Bug 18789: Add tests for is_adult and is_child
[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 => 25;
23 use Test::Warn;
24 use Time::Fake;
25 use DateTime;
26
27 use C4::Biblio;
28 use C4::Circulation;
29 use C4::Members;
30 use C4::Circulation;
31
32 use Koha::Holds;
33 use Koha::Patron;
34 use Koha::Patrons;
35 use Koha::Patron::Categories;
36 use Koha::Database;
37 use Koha::DateUtils;
38 use Koha::Virtualshelves;
39
40 use t::lib::TestBuilder;
41 use t::lib::Mocks;
42
43 my $schema = Koha::Database->new->schema;
44 $schema->storage->txn_begin;
45
46 my $builder       = t::lib::TestBuilder->new;
47 my $library = $builder->build({source => 'Branch' });
48 my $category = $builder->build({source => 'Category' });
49 my $nb_of_patrons = Koha::Patrons->search->count;
50 my $new_patron_1  = Koha::Patron->new(
51     {   cardnumber => 'test_cn_1',
52         branchcode => $library->{branchcode},
53         categorycode => $category->{categorycode},
54         surname => 'surname for patron1',
55         firstname => 'firstname for patron1',
56         userid => 'a_nonexistent_userid_1',
57         flags => 1, # Is superlibrarian
58     }
59 )->store;
60 my $new_patron_2  = Koha::Patron->new(
61     {   cardnumber => 'test_cn_2',
62         branchcode => $library->{branchcode},
63         categorycode => $category->{categorycode},
64         surname => 'surname for patron2',
65         firstname => 'firstname for patron2',
66         userid => 'a_nonexistent_userid_2',
67     }
68 )->store;
69
70 C4::Context->_new_userenv('xxx');
71 set_logged_in_user( $new_patron_1 );
72
73 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
74
75 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
76 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
77
78 subtest 'library' => sub {
79     plan tests => 2;
80     is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
81     is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
82 };
83
84 subtest 'guarantees' => sub {
85     plan tests => 8;
86     my $guarantees = $new_patron_1->guarantees;
87     is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
88     is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee' );
89     my @guarantees = $new_patron_1->guarantees;
90     is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
91     is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
92
93     my $guarantee_1 = $builder->build({ source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber }});
94     my $guarantee_2 = $builder->build({ source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber }});
95
96     $guarantees = $new_patron_1->guarantees;
97     is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
98     is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
99     @guarantees = $new_patron_1->guarantees;
100     is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
101     is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
102     $_->delete for @guarantees;
103 };
104
105 subtest 'category' => sub {
106     plan tests => 2;
107     my $patron_category = $new_patron_1->category;
108     is( ref( $patron_category), 'Koha::Patron::Category', );
109     is( $patron_category->categorycode, $category->{categorycode}, );
110 };
111
112 subtest 'siblings' => sub {
113     plan tests => 7;
114     my $siblings = $new_patron_1->siblings;
115     is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
116     my $guarantee_1 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
117     my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
118     $siblings = $retrieved_guarantee_1->siblings;
119     is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
120     my @siblings = $retrieved_guarantee_1->siblings;
121     is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
122     is( $siblings->count,  0,       'guarantee_1 should not have siblings yet' );
123     my $guarantee_2 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
124     my $guarantee_3 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
125     $siblings = $retrieved_guarantee_1->siblings;
126     is( $siblings->count,               2,                               'guarantee_1 should have 2 siblings' );
127     is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
128     is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
129     $_->delete for $retrieved_guarantee_1->siblings;
130     $retrieved_guarantee_1->delete;
131 };
132
133 subtest 'has_overdues' => sub {
134     plan tests => 3;
135
136     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
137     my $item_1 = $builder->build(
138         {   source => 'Item',
139             value  => {
140                 homebranch    => $library->{branchcode},
141                 holdingbranch => $library->{branchcode},
142                 notforloan    => 0,
143                 itemlost      => 0,
144                 withdrawn     => 0,
145                 biblionumber  => $biblioitem_1->{biblionumber}
146             }
147         }
148     );
149     my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
150     is( $retrieved_patron->has_overdues, 0, );
151
152     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
153     my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
154     is( $retrieved_patron->has_overdues, 0, );
155     $issue->delete();
156     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
157     $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
158     $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
159     is( $retrieved_patron->has_overdues, 1, );
160     $issue->delete();
161 };
162
163 subtest 'update_password' => sub {
164     plan tests => 7;
165
166     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
167     my $original_userid   = $new_patron_1->userid;
168     my $original_password = $new_patron_1->password;
169     warning_like { $retrieved_patron_1->update_password( $new_patron_2->userid, 'another_password' ) }
170     qr{Duplicate entry},
171       'Koha::Patron->update_password should warn if the userid is already used by another patron';
172     is( Koha::Patrons->find( $new_patron_1->borrowernumber )->userid,   $original_userid,   'Koha::Patron->update_password should not have updated the userid' );
173     is( Koha::Patrons->find( $new_patron_1->borrowernumber )->password, $original_password, 'Koha::Patron->update_password should not have updated the userid' );
174
175     $retrieved_patron_1->update_password( 'another_nonexistent_userid_1', 'another_password' );
176     is( Koha::Patrons->find( $new_patron_1->borrowernumber )->userid,   'another_nonexistent_userid_1', 'Koha::Patron->update_password should have updated the userid' );
177     is( Koha::Patrons->find( $new_patron_1->borrowernumber )->password, 'another_password',             'Koha::Patron->update_password should have updated the password' );
178
179     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $new_patron_1->borrowernumber } )->count;
180     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->update_password should have logged' );
181
182     t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
183     $retrieved_patron_1->update_password( 'yet_another_nonexistent_userid_1', 'another_password' );
184     $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $new_patron_1->borrowernumber } )->count;
185     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->update_password should not have logged' );
186 };
187
188 subtest 'is_expired' => sub {
189     plan tests => 5;
190     my $patron = $builder->build({ source => 'Borrower' });
191     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
192     $patron->dateexpiry( undef )->store->discard_changes;
193     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
194     $patron->dateexpiry( '0000-00-00' );
195     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is 0000-00-00');
196     $patron->dateexpiry( dt_from_string )->store->discard_changes;
197     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
198     $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
199     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
200     $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
201     is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
202
203     $patron->delete;
204 };
205
206 subtest 'is_going_to_expire' => sub {
207     plan tests => 9;
208     my $patron = $builder->build({ source => 'Borrower' });
209     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
210     $patron->dateexpiry( undef )->store->discard_changes;
211     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
212     $patron->dateexpiry( '0000-00-00' );
213     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 0000-00-00');
214
215     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
216     $patron->dateexpiry( dt_from_string )->store->discard_changes;
217     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
218
219     $patron->dateexpiry( dt_from_string )->store->discard_changes;
220     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
221
222     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
223     $patron->dateexpiry( dt_from_string->add( days => 11 ) )->store->discard_changes;
224     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');
225
226     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
227     $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
228     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');
229
230     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
231     $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
232     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');
233     $patron->delete;
234
235     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
236     $patron->dateexpiry( dt_from_string->add( days => 20 ) )->store->discard_changes;
237     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');
238
239     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
240     $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
241     is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
242
243     $patron->delete;
244 };
245
246
247 subtest 'renew_account' => sub {
248     plan tests => 36;
249
250     for my $date ( '2016-03-31', '2016-11-30', dt_from_string() ) {
251         my $dt = dt_from_string( $date, 'iso' );
252         Time::Fake->offset( $dt->epoch );
253         my $a_month_ago                = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
254         my $a_year_later               = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
255         my $a_year_later_minus_a_month = $dt->clone->add( months => 11, end_of_month => 'limit' )->truncate( to => 'day' );
256         my $a_month_later              = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
257         my $a_year_later_plus_a_month  = $dt->clone->add( months => 13, end_of_month => 'limit' )->truncate( to => 'day' );
258         my $patron_category = $builder->build(
259             {   source => 'Category',
260                 value  => {
261                     enrolmentperiod     => 12,
262                     enrolmentperioddate => undef,
263                 }
264             }
265         );
266         my $patron = $builder->build(
267             {   source => 'Borrower',
268                 value  => {
269                     dateexpiry   => $a_month_ago,
270                     categorycode => $patron_category->{categorycode},
271                     date_renewed => undef, # Force builder to not populate the column for new patron
272                 }
273             }
274         );
275         my $patron_2 = $builder->build(
276             {  source => 'Borrower',
277                value  => {
278                    dateexpiry => $a_month_ago,
279                    categorycode => $patron_category->{categorycode},
280                 }
281             }
282         );
283         my $patron_3 = $builder->build(
284             {  source => 'Borrower',
285                value  => {
286                    dateexpiry => $a_month_later,
287                    categorycode => $patron_category->{categorycode},
288                }
289             }
290         );
291         my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
292         my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
293         my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
294
295         is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
296
297         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
298         t::lib::Mocks::mock_preference( 'BorrowersLog',              1 );
299         my $expiry_date = $retrieved_patron->renew_account;
300         is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
301         my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
302         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" );
303         my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
304         is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
305
306         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
307         t::lib::Mocks::mock_preference( 'BorrowersLog',              0 );
308         $expiry_date = $retrieved_patron->renew_account;
309         is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
310         $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
311         is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
312         $retrieved_expiry_date = $retrieved_patron->dateexpiry;
313         is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
314         $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
315         is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
316
317         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
318         $expiry_date = $retrieved_patron_2->renew_account;
319         is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
320         $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
321         is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
322
323         $expiry_date = $retrieved_patron_3->renew_account;
324         is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
325         $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
326         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" );
327
328         $retrieved_patron->delete;
329         $retrieved_patron_2->delete;
330         $retrieved_patron_3->delete;
331     }
332     Time::Fake->reset;
333 };
334
335 subtest "move_to_deleted" => sub {
336     plan tests => 5;
337     my $originally_updated_on = '2016-01-01 12:12:12';
338     my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
339     my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
340     is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
341       ;    # FIXME This should be Koha::Deleted::Patron
342     my $deleted_patron = $schema->resultset('Deletedborrower')
343         ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
344         ->next;
345     ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
346     ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
347     isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
348     $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
349     is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
350     $retrieved_patron->delete( $patron->{borrowernumber} );    # Cleanup
351 };
352
353 subtest "delete" => sub {
354     plan tests => 5;
355     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
356     my $patron           = $builder->build( { source => 'Borrower' } );
357     my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
358     my $hold             = $builder->build(
359         {   source => 'Reserve',
360             value  => { borrowernumber => $patron->{borrowernumber} }
361         }
362     );
363     my $list = $builder->build(
364         {   source => 'Virtualshelve',
365             value  => { owner => $patron->{borrowernumber} }
366         }
367     );
368
369     my $deleted = $retrieved_patron->delete;
370     is( $deleted, 1, 'Koha::Patron->delete should return 1 if the patron has been correctly deleted' );
371
372     is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
373
374     is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's holds| );
375
376     is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
377
378     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
379     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
380 };
381
382 subtest 'add_enrolment_fee_if_needed' => sub {
383     plan tests => 4;
384
385     my $enrolmentfees = { K  => 5, J => 10, YA => 20 };
386     foreach( keys %{$enrolmentfees} ) {
387         ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
388     }
389     my $enrolmentfee_K  = $enrolmentfees->{K};
390     my $enrolmentfee_J  = $enrolmentfees->{J};
391     my $enrolmentfee_YA = $enrolmentfees->{YA};
392
393     my %borrower_data = (
394         firstname    => 'my firstname',
395         surname      => 'my surname',
396         categorycode => 'K',
397         branchcode   => $library->{branchcode},
398     );
399
400     my $borrowernumber = C4::Members::AddMember(%borrower_data);
401     $borrower_data{borrowernumber} = $borrowernumber;
402
403     my ($total) = C4::Members::GetMemberAccountRecords($borrowernumber);
404     is( $total, $enrolmentfee_K, "New kid pay $enrolmentfee_K" );
405
406     t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
407     $borrower_data{categorycode} = 'J';
408     C4::Members::ModMember(%borrower_data);
409     ($total) = C4::Members::GetMemberAccountRecords($borrowernumber);
410     is( $total, $enrolmentfee_K, "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
411
412     $borrower_data{categorycode} = 'K';
413     C4::Members::ModMember(%borrower_data);
414     t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
415
416     $borrower_data{categorycode} = 'J';
417     C4::Members::ModMember(%borrower_data);
418     ($total) = C4::Members::GetMemberAccountRecords($borrowernumber);
419     is( $total, $enrolmentfee_K + $enrolmentfee_J, "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
420
421     # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
422     my $patron = Koha::Patrons->find($borrowernumber);
423     $patron->categorycode('YA')->store;
424     my $fee = $patron->add_enrolment_fee_if_needed;
425     ($total) = C4::Members::GetMemberAccountRecords($borrowernumber);
426     is( $total,
427         $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA,
428         "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
429     );
430
431     $patron->delete;
432 };
433
434 subtest 'checkouts + get_overdues + old_checkouts' => sub {
435     plan tests => 12;
436
437     my $library = $builder->build( { source => 'Branch' } );
438     my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
439     my $item_1 = $builder->build(
440         {
441             source => 'Item',
442             value  => {
443                 homebranch    => $library->{branchcode},
444                 holdingbranch => $library->{branchcode},
445                 biblionumber  => $biblionumber_1,
446                 itemlost      => 0,
447                 withdrawn     => 0,
448             }
449         }
450     );
451     my $item_2 = $builder->build(
452         {
453             source => 'Item',
454             value  => {
455                 homebranch    => $library->{branchcode},
456                 holdingbranch => $library->{branchcode},
457                 biblionumber  => $biblionumber_1,
458                 itemlost      => 0,
459                 withdrawn     => 0,
460             }
461         }
462     );
463     my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
464     my $item_3 = $builder->build(
465         {
466             source => 'Item',
467             value  => {
468                 homebranch    => $library->{branchcode},
469                 holdingbranch => $library->{branchcode},
470                 biblionumber  => $biblionumber_2,
471                 itemlost      => 0,
472                 withdrawn     => 0,
473             }
474         }
475     );
476     my $patron = $builder->build(
477         {
478             source => 'Borrower',
479             value  => { branchcode => $library->{branchcode} }
480         }
481     );
482
483     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
484     my $checkouts = $patron->checkouts;
485     is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
486     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
487     my $old_checkouts = $patron->old_checkouts;
488     is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
489     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
490
491     # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
492     $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
493
494     my $module = new Test::MockModule('C4::Context');
495     $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
496
497     AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
498     AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
499     AddIssue( $patron, $item_3->{barcode} );
500
501     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
502     $checkouts = $patron->checkouts;
503     is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
504     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
505
506     my $overdues = $patron->get_overdues;
507     is( $overdues->count, 2, 'Patron should have 2 overdues');
508     is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
509     is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
510     is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
511
512
513     C4::Circulation::AddReturn( $item_1->{barcode} );
514     C4::Circulation::AddReturn( $item_2->{barcode} );
515     $old_checkouts = $patron->old_checkouts;
516     is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
517     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
518
519     # Clean stuffs
520     Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
521     $patron->delete;
522     $module->unmock('userenv');
523 };
524
525 subtest 'get_age' => sub {
526     plan tests => 7;
527
528     my $patron = $builder->build( { source => 'Borrower' } );
529     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
530
531     my $today = dt_from_string;
532
533     $patron->dateofbirth( undef );
534     is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
535     $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1 ) );
536     is( $patron->get_age, 12, 'Patron should be 12' );
537     $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 1 ) );
538     is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
539     $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 0 ) );
540     is( $patron->get_age, 18, 'Patron should be 18' );
541     $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -31 ) );
542     is( $patron->get_age, 19, 'Patron should be 19' );
543     $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -30 ) );
544     is( $patron->get_age, 19, 'Patron should be 19 again' );
545     $patron->dateofbirth( $today->clone->add( years => 0,   months => -1, days => -1 ) );
546     is( $patron->get_age, 0, 'Patron is a newborn child' );
547
548     $patron->delete;
549 };
550
551 subtest 'account' => sub {
552     plan tests => 1;
553
554     my $patron = $builder->build({source => 'Borrower'});
555
556     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
557     my $account = $patron->account;
558     is( ref($account),   'Koha::Account', 'account should return a Koha::Account object' );
559
560     $patron->delete;
561 };
562
563 subtest 'search_upcoming_membership_expires' => sub {
564     plan tests => 9;
565
566     my $expiry_days = 15;
567     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
568     my $nb_of_days_before = 1;
569     my $nb_of_days_after = 2;
570
571     my $builder = t::lib::TestBuilder->new();
572
573     my $library = $builder->build({ source => 'Branch' });
574
575     # before we add borrowers to this branch, add the expires we have now
576     # note that this pertains to the current mocked setting of the pref
577     # for this reason we add the new branchcode to most of the tests
578     my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
579
580     my $patron_1 = $builder->build({
581         source => 'Borrower',
582         value  => {
583             branchcode              => $library->{branchcode},
584             dateexpiry              => dt_from_string->add( days => $expiry_days )
585         },
586     });
587
588     my $patron_2 = $builder->build({
589         source => 'Borrower',
590         value  => {
591             branchcode              => $library->{branchcode},
592             dateexpiry              => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
593         },
594     });
595
596     my $patron_3 = $builder->build({
597         source => 'Borrower',
598         value  => {
599             branchcode              => $library->{branchcode},
600             dateexpiry              => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
601         },
602     });
603
604     # Test without extra parameters
605     my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
606     is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
607
608     # Test with branch
609     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
610     is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
611     my $expired = $upcoming_mem_expires->next;
612     is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
613     is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
614     is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
615
616     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
617     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
618     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
619
620     # Test MembershipExpiryDaysNotice == undef
621     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
622     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
623     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
624
625     # Test the before parameter
626     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
627     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
628     is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
629     # Test after parameter also
630     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
631     is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
632     Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
633 };
634
635 subtest 'holds and old_holds' => sub {
636     plan tests => 6;
637
638     my $library = $builder->build( { source => 'Branch' } );
639     my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
640     my $item_1 = $builder->build(
641         {
642             source => 'Item',
643             value  => {
644                 homebranch    => $library->{branchcode},
645                 holdingbranch => $library->{branchcode},
646                 biblionumber  => $biblionumber_1
647             }
648         }
649     );
650     my $item_2 = $builder->build(
651         {
652             source => 'Item',
653             value  => {
654                 homebranch    => $library->{branchcode},
655                 holdingbranch => $library->{branchcode},
656                 biblionumber  => $biblionumber_1
657             }
658         }
659     );
660     my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
661     my $item_3 = $builder->build(
662         {
663             source => 'Item',
664             value  => {
665                 homebranch    => $library->{branchcode},
666                 holdingbranch => $library->{branchcode},
667                 biblionumber  => $biblionumber_2
668             }
669         }
670     );
671     my $patron = $builder->build(
672         {
673             source => 'Borrower',
674             value  => { branchcode => $library->{branchcode} }
675         }
676     );
677
678     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
679     my $holds = $patron->holds;
680     is( ref($holds), 'Koha::Holds',
681         'Koha::Patron->holds should return a Koha::Holds objects' );
682     is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
683
684     C4::Reserves::AddReserve( $library->{branchcode},
685         $patron->borrowernumber, $biblionumber_1 );
686     # In the future
687     C4::Reserves::AddReserve( $library->{branchcode},
688         $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
689
690     $holds = $patron->holds;
691     is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
692
693     my $old_holds = $patron->old_holds;
694     is( ref($old_holds), 'Koha::Old::Holds',
695         'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
696     is( $old_holds->count, 0, 'There should not be any old holds yet');
697
698     my $hold = $holds->next;
699     $hold->cancel;
700
701     $old_holds = $patron->old_holds;
702     is( $old_holds->count, 1, 'There should  be 1 old (cancelled) hold');
703
704     $old_holds->delete;
705     $holds->delete;
706     $patron->delete;
707 };
708
709 subtest 'notice_email_address' => sub {
710     plan tests => 2;
711
712     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
713
714     t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
715     is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
716
717     t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
718     is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
719
720     $patron->delete;
721 };
722
723 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
724     plan tests => 4;
725
726     # TODO create a subroutine in t::lib::Mocks
727     my $branch = $builder->build({ source => 'Branch' });
728     my $userenv_patron = $builder->build({
729         source => 'Borrower',
730         value  => { branchcode => $branch->{branchcode} },
731     });
732     C4::Context->_new_userenv('DUMMY SESSION');
733     C4::Context->set_userenv(
734         $userenv_patron->{borrowernumber},
735         $userenv_patron->{userid},
736         'usercnum', 'First name', 'Surname',
737         $branch->{branchcode},
738         $branch->{branchname},
739         0,
740     );
741     my $anonymous = $builder->build( { source => 'Borrower', }, );
742
743     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
744
745     subtest 'patron privacy is 1 (default)' => sub {
746         plan tests => 8;
747
748         t::lib::Mocks::mock_preference('IndependentBranches', 0);
749         my $patron = $builder->build(
750             {   source => 'Borrower',
751                 value  => { privacy => 1, }
752             }
753         );
754         my $item_1 = $builder->build(
755             {   source => 'Item',
756                 value  => {
757                     itemlost  => 0,
758                     withdrawn => 0,
759                 },
760             }
761         );
762         my $issue_1 = $builder->build(
763             {   source => 'Issue',
764                 value  => {
765                     borrowernumber => $patron->{borrowernumber},
766                     itemnumber     => $item_1->{itemnumber},
767                 },
768             }
769         );
770         my $item_2 = $builder->build(
771             {   source => 'Item',
772                 value  => {
773                     itemlost  => 0,
774                     withdrawn => 0,
775                 },
776             }
777         );
778         my $issue_2 = $builder->build(
779             {   source => 'Issue',
780                 value  => {
781                     borrowernumber => $patron->{borrowernumber},
782                     itemnumber     => $item_2->{itemnumber},
783                 },
784             }
785         );
786
787         my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, undef, '2010-10-10' );
788         my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, undef, '2011-11-11' );
789         is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
790
791         my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
792         is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
793
794         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
795         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
796
797         my $dbh = C4::Context->dbh;
798         my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
799         $sth->execute($item_1->{itemnumber});
800         my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
801         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
802         $sth->execute($item_2->{itemnumber});
803         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
804         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
805
806         $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
807         $sth->execute($item_2->{itemnumber});
808         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
809         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
810
811         my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
812         $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
813         $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
814         $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
815         $sth->execute($item_1->{itemnumber});
816         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
817         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
818         $sth->execute($item_2->{itemnumber});
819         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
820         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
821
822         Koha::Patrons->find( $patron->{borrowernumber})->delete;
823     };
824
825     subtest 'patron privacy is 0 (forever)' => sub {
826         plan tests => 3;
827
828         t::lib::Mocks::mock_preference('IndependentBranches', 0);
829         my $patron = $builder->build(
830             {   source => 'Borrower',
831                 value  => { privacy => 0, }
832             }
833         );
834         my $item = $builder->build(
835             {   source => 'Item',
836                 value  => {
837                     itemlost  => 0,
838                     withdrawn => 0,
839                 },
840             }
841         );
842         my $issue = $builder->build(
843             {   source => 'Issue',
844                 value  => {
845                     borrowernumber => $patron->{borrowernumber},
846                     itemnumber     => $item->{itemnumber},
847                 },
848             }
849         );
850
851         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
852         is( $returned, 1, 'The item should have been returned' );
853         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
854         ok( $rows_affected > 0, 'AnonymiseIssueHistory should not return any error if success' );
855
856         my $dbh = C4::Context->dbh;
857         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
858             SELECT borrowernumber FROM old_issues where itemnumber = ?
859         |, undef, $item->{itemnumber});
860         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
861         Koha::Patrons->find( $patron->{borrowernumber})->delete;
862     };
863
864     t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
865
866     subtest 'AnonymousPatron is not defined' => sub {
867         plan tests => 3;
868
869         t::lib::Mocks::mock_preference('IndependentBranches', 0);
870         my $patron = $builder->build(
871             {   source => 'Borrower',
872                 value  => { privacy => 1, }
873             }
874         );
875         my $item = $builder->build(
876             {   source => 'Item',
877                 value  => {
878                     itemlost  => 0,
879                     withdrawn => 0,
880                 },
881             }
882         );
883         my $issue = $builder->build(
884             {   source => 'Issue',
885                 value  => {
886                     borrowernumber => $patron->{borrowernumber},
887                     itemnumber     => $item->{itemnumber},
888                 },
889             }
890         );
891
892         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
893         is( $returned, 1, 'The item should have been returned' );
894         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
895         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
896
897         my $dbh = C4::Context->dbh;
898         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
899             SELECT borrowernumber FROM old_issues where itemnumber = ?
900         |, undef, $item->{itemnumber});
901         is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
902         Koha::Patrons->find( $patron->{borrowernumber})->delete;
903     };
904
905     subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
906         plan tests => 1;
907         t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
908         my $patron = $builder->build(
909             {   source => 'Borrower',
910                 value  => { privacy => 1 }    # Another branchcode than the logged in librarian
911             }
912         );
913         my $item = $builder->build(
914             {   source => 'Item',
915                 value  => {
916                     itemlost  => 0,
917                     withdrawn => 0,
918                 },
919             }
920         );
921         my $issue = $builder->build(
922             {   source => 'Issue',
923                 value  => {
924                     borrowernumber => $patron->{borrowernumber},
925                     itemnumber     => $item->{itemnumber},
926                 },
927             }
928         );
929
930         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
931         is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
932         Koha::Patrons->find( $patron->{borrowernumber})->delete;
933     };
934
935     Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
936     Koha::Patrons->find( $userenv_patron->{borrowernumber})->delete;
937
938     # Reset IndependentBranches for further tests
939     t::lib::Mocks::mock_preference('IndependentBranches', 0);
940 };
941
942 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
943     plan tests => 3;
944
945     # group1
946     #   + library_11
947     #   + library_12
948     # group2
949     #   + library21
950     my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
951     my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
952     my $library_11 = $builder->build( { source => 'Branch' } );
953     my $library_12 = $builder->build( { source => 'Branch' } );
954     my $library_21 = $builder->build( { source => 'Branch' } );
955     $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
956     $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
957     $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
958     Koha::Library::Group->new(
959         { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
960     Koha::Library::Group->new(
961         { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
962     Koha::Library::Group->new(
963         { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
964
965     my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
966     # 2 patrons from library_11 (group1)
967     # patron_11_1 see patron's infos from outside its group
968     # Setting flags => undef to not be considered as superlibrarian
969     my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
970     $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
971     $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
972     $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
973     # patron_11_2 can only see patron's info from its group
974     my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
975     $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
976     $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
977     # 1 patron from library_12 (group1)
978     my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
979     $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
980     # 1 patron from library_21 (group2) can only see patron's info from its group
981     my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
982     $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
983     $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
984
985     # Pfiou, we can start now!
986     subtest 'libraries_where_can_see_patrons' => sub {
987         plan tests => 3;
988
989         my @branchcodes;
990
991         set_logged_in_user( $patron_11_1 );
992         @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
993         is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
994
995         set_logged_in_user( $patron_11_2 );
996         @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
997         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| );
998
999         set_logged_in_user( $patron_21 );
1000         @branchcodes = $patron_21->libraries_where_can_see_patrons;
1001         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| );
1002     };
1003     subtest 'can_see_patron_infos' => sub {
1004         plan tests => 6;
1005
1006         set_logged_in_user( $patron_11_1 );
1007         is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1008         is( $patron_11_1->can_see_patron_infos( $patron_12 ),   1, q|patron_11_1 can see patron_12, from its group| );
1009         is( $patron_11_1->can_see_patron_infos( $patron_21 ),   1, q|patron_11_1 can see patron_11_2, from another group| );
1010
1011         set_logged_in_user( $patron_11_2 );
1012         is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1013         is( $patron_11_2->can_see_patron_infos( $patron_12 ),   1, q|patron_11_2 can see patron_12, from its group| );
1014         is( $patron_11_2->can_see_patron_infos( $patron_21 ),   0, q|patron_11_2 can NOT see patron_21, from another group| );
1015     };
1016     subtest 'search_limited' => sub {
1017         plan tests => 6;
1018
1019         set_logged_in_user( $patron_11_1 );
1020         my $total_number_of_patrons = $nb_of_patrons + 6; # 2 created before + 4 for these subtests
1021         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1022         is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1023
1024         set_logged_in_user( $patron_11_2 );
1025         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1026         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' );
1027
1028         set_logged_in_user( $patron_21 );
1029         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1030         is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1031     };
1032     $patron_11_1->delete;
1033     $patron_11_2->delete;
1034     $patron_12->delete;
1035     $patron_21->delete;
1036 };
1037
1038 subtest 'account_locked' => sub {
1039     plan tests => 8;
1040     my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1041     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1042     for my $value ( undef, '', 0 ) {
1043         t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1044         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1045         $patron->login_attempts(1)->store;
1046         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1047     }
1048
1049     t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1050     $patron->login_attempts(2)->store;
1051     is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1052     $patron->login_attempts(3)->store;
1053     is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1054
1055     $patron->delete;
1056 };
1057
1058 subtest 'is_child | is_adult' => sub {
1059     plan tests => 8;
1060     my $category = $builder->build_object(
1061         {
1062             class => 'Koha::Patron::Categories',
1063             value => { category_type => 'A' }
1064         }
1065     );
1066     my $patron_adult = $builder->build_object(
1067         {
1068             class => 'Koha::Patrons',
1069             value => { categorycode => $category->categorycode }
1070         }
1071     );
1072     $category = $builder->build_object(
1073         {
1074             class => 'Koha::Patron::Categories',
1075             value => { category_type => 'I' }
1076         }
1077     );
1078     my $patron_adult_i = $builder->build_object(
1079         {
1080             class => 'Koha::Patrons',
1081             value => { categorycode => $category->categorycode }
1082         }
1083     );
1084     $category = $builder->build_object(
1085         {
1086             class => 'Koha::Patron::Categories',
1087             value => { category_type => 'C' }
1088         }
1089     );
1090     my $patron_child = $builder->build_object(
1091         {
1092             class => 'Koha::Patrons',
1093             value => { categorycode => $category->categorycode }
1094         }
1095     );
1096     $category = $builder->build_object(
1097         {
1098             class => 'Koha::Patron::Categories',
1099             value => { category_type => 'O' }
1100         }
1101     );
1102     my $patron_other = $builder->build_object(
1103         {
1104             class => 'Koha::Patrons',
1105             value => { categorycode => $category->categorycode }
1106         }
1107     );
1108     is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1109     is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1110     is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1111     is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1112
1113     is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1114     is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1115     is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1116     is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1117
1118     # Clean up
1119     $patron_adult->delete;
1120     $patron_adult_i->delete;
1121     $patron_child->delete;
1122     $patron_other->delete;
1123 };
1124
1125 $retrieved_patron_1->delete;
1126 is( Koha::Patrons->search->count, $nb_of_patrons + 1, 'Delete should have deleted the patron' );
1127
1128 $schema->storage->txn_rollback;
1129
1130 # TODO Move to t::lib::Mocks and reuse it!
1131 sub set_logged_in_user {
1132     my ($patron) = @_;
1133     C4::Context->set_userenv(
1134         $patron->borrowernumber, $patron->userid,
1135         $patron->cardnumber,     'firstname',
1136         'surname',               $patron->library->branchcode,
1137         'Midway Public Library', $patron->flags,
1138         '',                      ''
1139     );
1140 }