Bug 21178: (QA follow-up) whitespace characters fix
[koha-equinox.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 => 33;
23 use Test::Warn;
24 use Test::Exception;
25 use Time::Fake;
26 use DateTime;
27 use JSON;
28
29 use C4::Circulation;
30 use C4::Biblio;
31
32 use Koha::Holds;
33 use Koha::Patrons;
34 use Koha::Patron::Categories;
35 use Koha::Database;
36 use Koha::DateUtils;
37 use Koha::Virtualshelves;
38
39 use t::lib::TestBuilder;
40 use t::lib::Mocks;
41
42 my $schema = Koha::Database->new->schema;
43 $schema->storage->txn_begin;
44
45 my $builder       = t::lib::TestBuilder->new;
46 my $library = $builder->build({source => 'Branch' });
47 my $category = $builder->build({source => 'Category' });
48 my $nb_of_patrons = Koha::Patrons->search->count;
49 my $new_patron_1  = Koha::Patron->new(
50     {   cardnumber => 'test_cn_1',
51         branchcode => $library->{branchcode},
52         categorycode => $category->{categorycode},
53         surname => 'surname for patron1',
54         firstname => 'firstname for patron1',
55         userid => 'a_nonexistent_userid_1',
56         flags => 1, # Is superlibrarian
57     }
58 )->store;
59 my $new_patron_2  = Koha::Patron->new(
60     {   cardnumber => 'test_cn_2',
61         branchcode => $library->{branchcode},
62         categorycode => $category->{categorycode},
63         surname => 'surname for patron2',
64         firstname => 'firstname for patron2',
65         userid => 'a_nonexistent_userid_2',
66     }
67 )->store;
68
69 C4::Context->_new_userenv('xxx');
70 set_logged_in_user( $new_patron_1 );
71
72 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
73
74 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
75 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
76
77 subtest 'library' => sub {
78     plan tests => 2;
79     is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
80     is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
81 };
82
83 subtest 'guarantees' => sub {
84     plan tests => 13;
85     my $guarantees = $new_patron_1->guarantees;
86     is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
87     is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee' );
88     my @guarantees = $new_patron_1->guarantees;
89     is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
90     is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
91
92     my $guarantee_1 = $builder->build({ source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber }});
93     my $guarantee_2 = $builder->build({ source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber }});
94
95     $guarantees = $new_patron_1->guarantees;
96     is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
97     is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
98     @guarantees = $new_patron_1->guarantees;
99     is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
100     is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
101     $_->delete for @guarantees;
102
103     #Test return order of guarantees BZ 18635
104     my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
105     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
106
107     my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
108
109     my $order_guarantee1 = $builder->build_object( { class => 'Koha::Patrons' ,  value => {
110             surname => 'Zebra',
111             guarantorid => $guarantor->borrowernumber
112         }
113     })->borrowernumber;
114
115     my $order_guarantee2 = $builder->build_object( { class => 'Koha::Patrons' ,  value => {
116             surname => 'Yak',
117             guarantorid => $guarantor->borrowernumber
118         }
119     })->borrowernumber;
120
121     my $order_guarantee3 = $builder->build_object( { class => 'Koha::Patrons' ,  value => {
122             surname => 'Xerus',
123             firstname => 'Walrus',
124             guarantorid => $guarantor->borrowernumber
125         }
126     })->borrowernumber;
127
128     my $order_guarantee4 = $builder->build_object( { class => 'Koha::Patrons' ,  value => {
129             surname => 'Xerus',
130             firstname => 'Vulture',
131             guarantorid => $guarantor->borrowernumber
132         }
133     })->borrowernumber;
134
135     my $order_guarantee5 = $builder->build_object( { class => 'Koha::Patrons' ,  value => {
136             surname => 'Xerus',
137             firstname => 'Unicorn',
138             guarantorid => $guarantor->borrowernumber
139         }
140     })->borrowernumber;
141
142     $guarantees = $guarantor->guarantees();
143
144     is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
145     is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
146     is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
147     is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
148     is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
149 };
150
151 subtest 'category' => sub {
152     plan tests => 2;
153     my $patron_category = $new_patron_1->category;
154     is( ref( $patron_category), 'Koha::Patron::Category', );
155     is( $patron_category->categorycode, $category->{categorycode}, );
156 };
157
158 subtest 'siblings' => sub {
159     plan tests => 7;
160     my $siblings = $new_patron_1->siblings;
161     is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
162     my $guarantee_1 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
163     my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
164     $siblings = $retrieved_guarantee_1->siblings;
165     is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
166     my @siblings = $retrieved_guarantee_1->siblings;
167     is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
168     is( $siblings->count,  0,       'guarantee_1 should not have siblings yet' );
169     my $guarantee_2 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
170     my $guarantee_3 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
171     $siblings = $retrieved_guarantee_1->siblings;
172     is( $siblings->count,               2,                               'guarantee_1 should have 2 siblings' );
173     is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
174     is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
175     $_->delete for $retrieved_guarantee_1->siblings;
176     $retrieved_guarantee_1->delete;
177 };
178
179 subtest 'has_overdues' => sub {
180     plan tests => 3;
181
182     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
183     my $item_1 = $builder->build(
184         {   source => 'Item',
185             value  => {
186                 homebranch    => $library->{branchcode},
187                 holdingbranch => $library->{branchcode},
188                 notforloan    => 0,
189                 itemlost      => 0,
190                 withdrawn     => 0,
191                 biblionumber  => $biblioitem_1->{biblionumber}
192             }
193         }
194     );
195     my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
196     is( $retrieved_patron->has_overdues, 0, );
197
198     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
199     my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
200     is( $retrieved_patron->has_overdues, 0, );
201     $issue->delete();
202     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
203     $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
204     $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
205     is( $retrieved_patron->has_overdues, 1, );
206     $issue->delete();
207 };
208
209 subtest 'update_password' => sub {
210     plan tests => 7;
211
212     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
213     my $original_userid   = $new_patron_1->userid;
214     my $original_password = $new_patron_1->password;
215     warning_like { $retrieved_patron_1->update_password( $new_patron_2->userid, 'another_password' ) }
216     qr{Duplicate entry},
217       'Koha::Patron->update_password should warn if the userid is already used by another patron';
218     is( Koha::Patrons->find( $new_patron_1->borrowernumber )->userid,   $original_userid,   'Koha::Patron->update_password should not have updated the userid' );
219     is( Koha::Patrons->find( $new_patron_1->borrowernumber )->password, $original_password, 'Koha::Patron->update_password should not have updated the userid' );
220
221     my $digest = $retrieved_patron_1->update_password( 'another_nonexistent_userid_1', 'another_password' );
222     is( Koha::Patrons->find( $new_patron_1->borrowernumber )->userid,   'another_nonexistent_userid_1', 'Koha::Patron->update_password should have updated the userid' );
223     is( Koha::Patrons->find( $new_patron_1->borrowernumber )->password, $digest,             'Koha::Patron->update_password should have updated the password' );
224
225     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $new_patron_1->borrowernumber } )->count;
226     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->update_password should have logged' );
227
228     t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
229     $retrieved_patron_1->update_password( 'yet_another_nonexistent_userid_1', 'another_password' );
230     $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $new_patron_1->borrowernumber } )->count;
231     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->update_password should not have logged' );
232 };
233
234 subtest 'is_expired' => sub {
235     plan tests => 4;
236     my $patron = $builder->build({ source => 'Borrower' });
237     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
238     $patron->dateexpiry( undef )->store->discard_changes;
239     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
240     $patron->dateexpiry( dt_from_string )->store->discard_changes;
241     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
242     $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
243     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
244     $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
245     is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
246
247     $patron->delete;
248 };
249
250 subtest 'is_going_to_expire' => sub {
251     plan tests => 8;
252     my $patron = $builder->build({ source => 'Borrower' });
253     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
254     $patron->dateexpiry( undef )->store->discard_changes;
255     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
256
257     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
258     $patron->dateexpiry( dt_from_string )->store->discard_changes;
259     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
260
261     $patron->dateexpiry( dt_from_string )->store->discard_changes;
262     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
263
264     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
265     $patron->dateexpiry( dt_from_string->add( days => 11 ) )->store->discard_changes;
266     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');
267
268     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
269     $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
270     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');
271
272     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
273     $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
274     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');
275     $patron->delete;
276
277     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
278     $patron->dateexpiry( dt_from_string->add( days => 20 ) )->store->discard_changes;
279     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');
280
281     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
282     $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
283     is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
284
285     $patron->delete;
286 };
287
288
289 subtest 'renew_account' => sub {
290     plan tests => 36;
291
292     for my $date ( '2016-03-31', '2016-11-30', dt_from_string() ) {
293         my $dt = dt_from_string( $date, 'iso' );
294         Time::Fake->offset( $dt->epoch );
295         my $a_month_ago                = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
296         my $a_year_later               = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
297         my $a_year_later_minus_a_month = $dt->clone->add( months => 11, end_of_month => 'limit' )->truncate( to => 'day' );
298         my $a_month_later              = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
299         my $a_year_later_plus_a_month  = $dt->clone->add( months => 13, end_of_month => 'limit' )->truncate( to => 'day' );
300         my $patron_category = $builder->build(
301             {   source => 'Category',
302                 value  => {
303                     enrolmentperiod     => 12,
304                     enrolmentperioddate => undef,
305                 }
306             }
307         );
308         my $patron = $builder->build(
309             {   source => 'Borrower',
310                 value  => {
311                     dateexpiry   => $a_month_ago,
312                     categorycode => $patron_category->{categorycode},
313                     date_renewed => undef, # Force builder to not populate the column for new patron
314                 }
315             }
316         );
317         my $patron_2 = $builder->build(
318             {  source => 'Borrower',
319                value  => {
320                    dateexpiry => $a_month_ago,
321                    categorycode => $patron_category->{categorycode},
322                 }
323             }
324         );
325         my $patron_3 = $builder->build(
326             {  source => 'Borrower',
327                value  => {
328                    dateexpiry => $a_month_later,
329                    categorycode => $patron_category->{categorycode},
330                }
331             }
332         );
333         my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
334         my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
335         my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
336
337         is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
338
339         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
340         t::lib::Mocks::mock_preference( 'BorrowersLog',              1 );
341         my $expiry_date = $retrieved_patron->renew_account;
342         is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
343         my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
344         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" );
345         my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
346         is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
347
348         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
349         t::lib::Mocks::mock_preference( 'BorrowersLog',              0 );
350         $expiry_date = $retrieved_patron->renew_account;
351         is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
352         $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
353         is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
354         $retrieved_expiry_date = $retrieved_patron->dateexpiry;
355         is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
356         $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
357         is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
358
359         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
360         $expiry_date = $retrieved_patron_2->renew_account;
361         is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
362         $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
363         is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
364
365         $expiry_date = $retrieved_patron_3->renew_account;
366         is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
367         $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
368         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" );
369
370         $retrieved_patron->delete;
371         $retrieved_patron_2->delete;
372         $retrieved_patron_3->delete;
373     }
374     Time::Fake->reset;
375 };
376
377 subtest "move_to_deleted" => sub {
378     plan tests => 5;
379     my $originally_updated_on = '2016-01-01 12:12:12';
380     my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
381     my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
382     is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
383       ;    # FIXME This should be Koha::Deleted::Patron
384     my $deleted_patron = $schema->resultset('Deletedborrower')
385         ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
386         ->next;
387     ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
388     ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
389     isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
390     $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
391     is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
392     $retrieved_patron->delete( $patron->{borrowernumber} );    # Cleanup
393 };
394
395 subtest "delete" => sub {
396     plan tests => 5;
397     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
398     my $patron           = $builder->build( { source => 'Borrower' } );
399     my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
400     my $hold             = $builder->build(
401         {   source => 'Reserve',
402             value  => { borrowernumber => $patron->{borrowernumber} }
403         }
404     );
405     my $list = $builder->build(
406         {   source => 'Virtualshelve',
407             value  => { owner => $patron->{borrowernumber} }
408         }
409     );
410
411     my $deleted = $retrieved_patron->delete;
412     is( $deleted, 1, 'Koha::Patron->delete should return 1 if the patron has been correctly deleted' );
413
414     is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
415
416     is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's holds| );
417
418     is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
419
420     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
421     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
422 };
423
424 subtest 'add_enrolment_fee_if_needed' => sub {
425     plan tests => 4;
426
427     my $enrolmentfees = { K  => 5, J => 10, YA => 20 };
428     foreach( keys %{$enrolmentfees} ) {
429         ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
430     }
431     my $enrolmentfee_K  = $enrolmentfees->{K};
432     my $enrolmentfee_J  = $enrolmentfees->{J};
433     my $enrolmentfee_YA = $enrolmentfees->{YA};
434
435     my %borrower_data = (
436         firstname    => 'my firstname',
437         surname      => 'my surname',
438         categorycode => 'K',
439         branchcode   => $library->{branchcode},
440     );
441
442     my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
443     $borrower_data{borrowernumber} = $borrowernumber;
444
445     my $patron = Koha::Patrons->find( $borrowernumber );
446     my $total = $patron->account->balance;
447     is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
448
449     t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
450     $borrower_data{categorycode} = 'J';
451     $patron->set(\%borrower_data)->store;
452     $total = $patron->account->balance;
453     is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
454
455     $borrower_data{categorycode} = 'K';
456     $patron->set(\%borrower_data)->store;
457     t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
458
459     $borrower_data{categorycode} = 'J';
460     $patron->set(\%borrower_data)->store;
461     $total = $patron->account->balance;
462     is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
463
464     # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
465     $patron->categorycode('YA')->store;
466     $total = $patron->account->balance;
467     is( int($total),
468         int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
469         "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
470     );
471
472     $patron->delete;
473 };
474
475 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
476     plan tests => 17;
477
478     my $library = $builder->build( { source => 'Branch' } );
479     my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
480     my $item_1 = $builder->build(
481         {
482             source => 'Item',
483             value  => {
484                 homebranch    => $library->{branchcode},
485                 holdingbranch => $library->{branchcode},
486                 biblionumber  => $biblionumber_1,
487                 itemlost      => 0,
488                 withdrawn     => 0,
489             }
490         }
491     );
492     my $item_2 = $builder->build(
493         {
494             source => 'Item',
495             value  => {
496                 homebranch    => $library->{branchcode},
497                 holdingbranch => $library->{branchcode},
498                 biblionumber  => $biblionumber_1,
499                 itemlost      => 0,
500                 withdrawn     => 0,
501             }
502         }
503     );
504     my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
505     my $item_3 = $builder->build(
506         {
507             source => 'Item',
508             value  => {
509                 homebranch    => $library->{branchcode},
510                 holdingbranch => $library->{branchcode},
511                 biblionumber  => $biblionumber_2,
512                 itemlost      => 0,
513                 withdrawn     => 0,
514             }
515         }
516     );
517     my $patron = $builder->build(
518         {
519             source => 'Borrower',
520             value  => { branchcode => $library->{branchcode} }
521         }
522     );
523
524     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
525     my $checkouts = $patron->checkouts;
526     is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
527     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
528     my $pending_checkouts = $patron->pending_checkouts;
529     is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
530     is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
531     my $old_checkouts = $patron->old_checkouts;
532     is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
533     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
534
535     # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
536     $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
537
538     my $module = new Test::MockModule('C4::Context');
539     $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
540
541     AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
542     AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
543     AddIssue( $patron, $item_3->{barcode} );
544
545     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
546     $checkouts = $patron->checkouts;
547     is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
548     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
549     $pending_checkouts = $patron->pending_checkouts;
550     is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
551     is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
552
553     my $first_checkout = $pending_checkouts->next;
554     is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
555
556     my $overdues = $patron->get_overdues;
557     is( $overdues->count, 2, 'Patron should have 2 overdues');
558     is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
559     is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
560     is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
561
562
563     C4::Circulation::AddReturn( $item_1->{barcode} );
564     C4::Circulation::AddReturn( $item_2->{barcode} );
565     $old_checkouts = $patron->old_checkouts;
566     is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
567     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
568
569     # Clean stuffs
570     Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
571     $patron->delete;
572     $module->unmock('userenv');
573 };
574
575 subtest 'get_routing_lists' => sub {
576     plan tests => 5;
577
578     my $biblio = Koha::Biblio->new()->store();
579     my $subscription = Koha::Subscription->new({
580         biblionumber => $biblio->biblionumber,
581         }
582     )->store;
583
584     my $patron = $builder->build( { source => 'Borrower' } );
585     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
586
587     is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
588
589     my $routinglist_count = Koha::Subscription::Routinglists->count;
590     my $routinglist = Koha::Subscription::Routinglist->new({
591         borrowernumber   => $patron->borrowernumber,
592         ranking          => 5,
593         subscriptionid   => $subscription->subscriptionid
594     })->store;
595
596     is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
597
598     my $routinglists = $patron->get_routing_lists;
599     is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
600     is( ref($routinglists),   'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
601
602     my $subscription2 = Koha::Subscription->new({
603         biblionumber => $biblio->biblionumber,
604         }
605     )->store;
606     my $routinglist2 = Koha::Subscription::Routinglist->new({
607         borrowernumber   => $patron->borrowernumber,
608         ranking          => 1,
609         subscriptionid   => $subscription2->subscriptionid
610     })->store;
611
612     is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
613
614     $patron->delete; # Clean up for later tests
615
616 };
617
618 subtest 'get_age' => sub {
619     plan tests => 7;
620
621     my $patron = $builder->build( { source => 'Borrower' } );
622     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
623
624     my $today = dt_from_string;
625
626     $patron->dateofbirth( undef );
627     is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
628     $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1, end_of_month => 'limit'  ) );
629     is( $patron->get_age, 12, 'Patron should be 12' );
630     $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 1, end_of_month => 'limit'  ) );
631     is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
632     $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 0, end_of_month => 'limit'  ) );
633     is( $patron->get_age, 18, 'Patron should be 18' );
634     $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -31, end_of_month => 'limit'  ) );
635     is( $patron->get_age, 19, 'Patron should be 19' );
636     $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -30, end_of_month => 'limit'  ) );
637     is( $patron->get_age, 19, 'Patron should be 19 again' );
638     $patron->dateofbirth( $today->clone->add( years => 0,   months => -1, days => -1, end_of_month => 'limit'  ) );
639     is( $patron->get_age, 0, 'Patron is a newborn child' );
640
641     $patron->delete;
642 };
643
644 subtest 'account' => sub {
645     plan tests => 1;
646
647     my $patron = $builder->build({source => 'Borrower'});
648
649     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
650     my $account = $patron->account;
651     is( ref($account),   'Koha::Account', 'account should return a Koha::Account object' );
652
653     $patron->delete;
654 };
655
656 subtest 'search_upcoming_membership_expires' => sub {
657     plan tests => 9;
658
659     my $expiry_days = 15;
660     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
661     my $nb_of_days_before = 1;
662     my $nb_of_days_after = 2;
663
664     my $builder = t::lib::TestBuilder->new();
665
666     my $library = $builder->build({ source => 'Branch' });
667
668     # before we add borrowers to this branch, add the expires we have now
669     # note that this pertains to the current mocked setting of the pref
670     # for this reason we add the new branchcode to most of the tests
671     my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
672
673     my $patron_1 = $builder->build({
674         source => 'Borrower',
675         value  => {
676             branchcode              => $library->{branchcode},
677             dateexpiry              => dt_from_string->add( days => $expiry_days )
678         },
679     });
680
681     my $patron_2 = $builder->build({
682         source => 'Borrower',
683         value  => {
684             branchcode              => $library->{branchcode},
685             dateexpiry              => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
686         },
687     });
688
689     my $patron_3 = $builder->build({
690         source => 'Borrower',
691         value  => {
692             branchcode              => $library->{branchcode},
693             dateexpiry              => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
694         },
695     });
696
697     # Test without extra parameters
698     my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
699     is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
700
701     # Test with branch
702     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
703     is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
704     my $expired = $upcoming_mem_expires->next;
705     is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
706     is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
707     is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
708
709     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
710     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
711     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
712
713     # Test MembershipExpiryDaysNotice == undef
714     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
715     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
716     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
717
718     # Test the before parameter
719     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
720     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
721     is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
722     # Test after parameter also
723     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
724     is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
725     Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
726 };
727
728 subtest 'holds and old_holds' => sub {
729     plan tests => 6;
730
731     my $library = $builder->build( { source => 'Branch' } );
732     my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
733     my $item_1 = $builder->build(
734         {
735             source => 'Item',
736             value  => {
737                 homebranch    => $library->{branchcode},
738                 holdingbranch => $library->{branchcode},
739                 biblionumber  => $biblionumber_1
740             }
741         }
742     );
743     my $item_2 = $builder->build(
744         {
745             source => 'Item',
746             value  => {
747                 homebranch    => $library->{branchcode},
748                 holdingbranch => $library->{branchcode},
749                 biblionumber  => $biblionumber_1
750             }
751         }
752     );
753     my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
754     my $item_3 = $builder->build(
755         {
756             source => 'Item',
757             value  => {
758                 homebranch    => $library->{branchcode},
759                 holdingbranch => $library->{branchcode},
760                 biblionumber  => $biblionumber_2
761             }
762         }
763     );
764     my $patron = $builder->build(
765         {
766             source => 'Borrower',
767             value  => { branchcode => $library->{branchcode} }
768         }
769     );
770
771     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
772     my $holds = $patron->holds;
773     is( ref($holds), 'Koha::Holds',
774         'Koha::Patron->holds should return a Koha::Holds objects' );
775     is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
776
777     C4::Reserves::AddReserve( $library->{branchcode},
778         $patron->borrowernumber, $biblionumber_1 );
779     # In the future
780     C4::Reserves::AddReserve( $library->{branchcode},
781         $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
782
783     $holds = $patron->holds;
784     is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
785
786     my $old_holds = $patron->old_holds;
787     is( ref($old_holds), 'Koha::Old::Holds',
788         'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
789     is( $old_holds->count, 0, 'There should not be any old holds yet');
790
791     my $hold = $holds->next;
792     $hold->cancel;
793
794     $old_holds = $patron->old_holds;
795     is( $old_holds->count, 1, 'There should  be 1 old (cancelled) hold');
796
797     $old_holds->delete;
798     $holds->delete;
799     $patron->delete;
800 };
801
802 subtest 'notice_email_address' => sub {
803     plan tests => 2;
804
805     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
806
807     t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
808     is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
809
810     t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
811     is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
812
813     $patron->delete;
814 };
815
816 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
817     plan tests => 4;
818
819     # TODO create a subroutine in t::lib::Mocks
820     my $branch = $builder->build({ source => 'Branch' });
821     my $userenv_patron = $builder->build({
822         source => 'Borrower',
823         value  => { branchcode => $branch->{branchcode} },
824     });
825     C4::Context->_new_userenv('DUMMY SESSION');
826     C4::Context->set_userenv(
827         $userenv_patron->{borrowernumber},
828         $userenv_patron->{userid},
829         'usercnum', 'First name', 'Surname',
830         $branch->{branchcode},
831         $branch->{branchname},
832         0,
833     );
834     my $anonymous = $builder->build( { source => 'Borrower', }, );
835
836     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
837
838     subtest 'patron privacy is 1 (default)' => sub {
839         plan tests => 8;
840
841         t::lib::Mocks::mock_preference('IndependentBranches', 0);
842         my $patron = $builder->build(
843             {   source => 'Borrower',
844                 value  => { privacy => 1, }
845             }
846         );
847         my $item_1 = $builder->build(
848             {   source => 'Item',
849                 value  => {
850                     itemlost  => 0,
851                     withdrawn => 0,
852                 },
853             }
854         );
855         my $issue_1 = $builder->build(
856             {   source => 'Issue',
857                 value  => {
858                     borrowernumber => $patron->{borrowernumber},
859                     itemnumber     => $item_1->{itemnumber},
860                 },
861             }
862         );
863         my $item_2 = $builder->build(
864             {   source => 'Item',
865                 value  => {
866                     itemlost  => 0,
867                     withdrawn => 0,
868                 },
869             }
870         );
871         my $issue_2 = $builder->build(
872             {   source => 'Issue',
873                 value  => {
874                     borrowernumber => $patron->{borrowernumber},
875                     itemnumber     => $item_2->{itemnumber},
876                 },
877             }
878         );
879
880         my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, undef, '2010-10-10' );
881         my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, undef, '2011-11-11' );
882         is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
883
884         my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
885         is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
886
887         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
888         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
889
890         my $dbh = C4::Context->dbh;
891         my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
892         $sth->execute($item_1->{itemnumber});
893         my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
894         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
895         $sth->execute($item_2->{itemnumber});
896         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
897         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
898
899         $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
900         $sth->execute($item_2->{itemnumber});
901         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
902         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
903
904         my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
905         $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
906         $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
907         $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
908         $sth->execute($item_1->{itemnumber});
909         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
910         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
911         $sth->execute($item_2->{itemnumber});
912         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
913         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
914
915         Koha::Patrons->find( $patron->{borrowernumber})->delete;
916     };
917
918     subtest 'patron privacy is 0 (forever)' => sub {
919         plan tests => 3;
920
921         t::lib::Mocks::mock_preference('IndependentBranches', 0);
922         my $patron = $builder->build(
923             {   source => 'Borrower',
924                 value  => { privacy => 0, }
925             }
926         );
927         my $item = $builder->build(
928             {   source => 'Item',
929                 value  => {
930                     itemlost  => 0,
931                     withdrawn => 0,
932                 },
933             }
934         );
935         my $issue = $builder->build(
936             {   source => 'Issue',
937                 value  => {
938                     borrowernumber => $patron->{borrowernumber},
939                     itemnumber     => $item->{itemnumber},
940                 },
941             }
942         );
943
944         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
945         is( $returned, 1, 'The item should have been returned' );
946         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
947         ok( $rows_affected > 0, 'AnonymiseIssueHistory should not return any error if success' );
948
949         my $dbh = C4::Context->dbh;
950         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
951             SELECT borrowernumber FROM old_issues where itemnumber = ?
952         |, undef, $item->{itemnumber});
953         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
954         Koha::Patrons->find( $patron->{borrowernumber})->delete;
955     };
956
957     t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
958
959     subtest 'AnonymousPatron is not defined' => sub {
960         plan tests => 3;
961
962         t::lib::Mocks::mock_preference('IndependentBranches', 0);
963         my $patron = $builder->build(
964             {   source => 'Borrower',
965                 value  => { privacy => 1, }
966             }
967         );
968         my $item = $builder->build(
969             {   source => 'Item',
970                 value  => {
971                     itemlost  => 0,
972                     withdrawn => 0,
973                 },
974             }
975         );
976         my $issue = $builder->build(
977             {   source => 'Issue',
978                 value  => {
979                     borrowernumber => $patron->{borrowernumber},
980                     itemnumber     => $item->{itemnumber},
981                 },
982             }
983         );
984
985         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
986         is( $returned, 1, 'The item should have been returned' );
987         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
988         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
989
990         my $dbh = C4::Context->dbh;
991         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
992             SELECT borrowernumber FROM old_issues where itemnumber = ?
993         |, undef, $item->{itemnumber});
994         is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
995         Koha::Patrons->find( $patron->{borrowernumber})->delete;
996     };
997
998     subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
999         plan tests => 1;
1000         t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1001         my $patron = $builder->build(
1002             {   source => 'Borrower',
1003                 value  => { privacy => 1 }    # Another branchcode than the logged in librarian
1004             }
1005         );
1006         my $item = $builder->build(
1007             {   source => 'Item',
1008                 value  => {
1009                     itemlost  => 0,
1010                     withdrawn => 0,
1011                 },
1012             }
1013         );
1014         my $issue = $builder->build(
1015             {   source => 'Issue',
1016                 value  => {
1017                     borrowernumber => $patron->{borrowernumber},
1018                     itemnumber     => $item->{itemnumber},
1019                 },
1020             }
1021         );
1022
1023         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
1024         is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1025         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1026     };
1027
1028     Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1029     Koha::Patrons->find( $userenv_patron->{borrowernumber})->delete;
1030
1031     # Reset IndependentBranches for further tests
1032     t::lib::Mocks::mock_preference('IndependentBranches', 0);
1033 };
1034
1035 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1036     plan tests => 3;
1037
1038     # group1
1039     #   + library_11
1040     #   + library_12
1041     # group2
1042     #   + library21
1043     $nb_of_patrons = Koha::Patrons->search->count;
1044     my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1045     my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1046     my $library_11 = $builder->build( { source => 'Branch' } );
1047     my $library_12 = $builder->build( { source => 'Branch' } );
1048     my $library_21 = $builder->build( { source => 'Branch' } );
1049     $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1050     $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1051     $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1052     Koha::Library::Group->new(
1053         { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1054     Koha::Library::Group->new(
1055         { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1056     Koha::Library::Group->new(
1057         { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1058
1059     my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1060     # 2 patrons from library_11 (group1)
1061     # patron_11_1 see patron's infos from outside its group
1062     # Setting flags => undef to not be considered as superlibrarian
1063     my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1064     $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1065     $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1066     $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1067     # patron_11_2 can only see patron's info from its group
1068     my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1069     $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1070     $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1071     # 1 patron from library_12 (group1)
1072     my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1073     $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1074     # 1 patron from library_21 (group2) can only see patron's info from its group
1075     my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1076     $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1077     $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1078
1079     # Pfiou, we can start now!
1080     subtest 'libraries_where_can_see_patrons' => sub {
1081         plan tests => 3;
1082
1083         my @branchcodes;
1084
1085         set_logged_in_user( $patron_11_1 );
1086         @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1087         is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1088
1089         set_logged_in_user( $patron_11_2 );
1090         @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1091         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| );
1092
1093         set_logged_in_user( $patron_21 );
1094         @branchcodes = $patron_21->libraries_where_can_see_patrons;
1095         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| );
1096     };
1097     subtest 'can_see_patron_infos' => sub {
1098         plan tests => 6;
1099
1100         set_logged_in_user( $patron_11_1 );
1101         is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1102         is( $patron_11_1->can_see_patron_infos( $patron_12 ),   1, q|patron_11_1 can see patron_12, from its group| );
1103         is( $patron_11_1->can_see_patron_infos( $patron_21 ),   1, q|patron_11_1 can see patron_11_2, from another group| );
1104
1105         set_logged_in_user( $patron_11_2 );
1106         is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1107         is( $patron_11_2->can_see_patron_infos( $patron_12 ),   1, q|patron_11_2 can see patron_12, from its group| );
1108         is( $patron_11_2->can_see_patron_infos( $patron_21 ),   0, q|patron_11_2 can NOT see patron_21, from another group| );
1109     };
1110     subtest 'search_limited' => sub {
1111         plan tests => 6;
1112
1113         set_logged_in_user( $patron_11_1 );
1114         my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1115         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1116         is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1117
1118         set_logged_in_user( $patron_11_2 );
1119         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1120         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' );
1121
1122         set_logged_in_user( $patron_21 );
1123         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1124         is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1125     };
1126     $patron_11_1->delete;
1127     $patron_11_2->delete;
1128     $patron_12->delete;
1129     $patron_21->delete;
1130 };
1131
1132 subtest 'account_locked' => sub {
1133     plan tests => 8;
1134     my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1135     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1136     for my $value ( undef, '', 0 ) {
1137         t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1138         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1139         $patron->login_attempts(1)->store;
1140         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1141     }
1142
1143     t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1144     $patron->login_attempts(2)->store;
1145     is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1146     $patron->login_attempts(3)->store;
1147     is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1148
1149     $patron->delete;
1150 };
1151
1152 subtest 'is_child | is_adult' => sub {
1153     plan tests => 8;
1154     my $category = $builder->build_object(
1155         {
1156             class => 'Koha::Patron::Categories',
1157             value => { category_type => 'A' }
1158         }
1159     );
1160     my $patron_adult = $builder->build_object(
1161         {
1162             class => 'Koha::Patrons',
1163             value => { categorycode => $category->categorycode }
1164         }
1165     );
1166     $category = $builder->build_object(
1167         {
1168             class => 'Koha::Patron::Categories',
1169             value => { category_type => 'I' }
1170         }
1171     );
1172     my $patron_adult_i = $builder->build_object(
1173         {
1174             class => 'Koha::Patrons',
1175             value => { categorycode => $category->categorycode }
1176         }
1177     );
1178     $category = $builder->build_object(
1179         {
1180             class => 'Koha::Patron::Categories',
1181             value => { category_type => 'C' }
1182         }
1183     );
1184     my $patron_child = $builder->build_object(
1185         {
1186             class => 'Koha::Patrons',
1187             value => { categorycode => $category->categorycode }
1188         }
1189     );
1190     $category = $builder->build_object(
1191         {
1192             class => 'Koha::Patron::Categories',
1193             value => { category_type => 'O' }
1194         }
1195     );
1196     my $patron_other = $builder->build_object(
1197         {
1198             class => 'Koha::Patrons',
1199             value => { categorycode => $category->categorycode }
1200         }
1201     );
1202     is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1203     is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1204     is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1205     is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1206
1207     is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1208     is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1209     is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1210     is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1211
1212     # Clean up
1213     $patron_adult->delete;
1214     $patron_adult_i->delete;
1215     $patron_child->delete;
1216     $patron_other->delete;
1217 };
1218
1219 subtest 'get_overdues' => sub {
1220     plan tests => 7;
1221
1222     my $library = $builder->build( { source => 'Branch' } );
1223     my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1224     my $item_1 = $builder->build(
1225         {
1226             source => 'Item',
1227             value  => {
1228                 homebranch    => $library->{branchcode},
1229                 holdingbranch => $library->{branchcode},
1230                 biblionumber  => $biblionumber_1
1231             }
1232         }
1233     );
1234     my $item_2 = $builder->build(
1235         {
1236             source => 'Item',
1237             value  => {
1238                 homebranch    => $library->{branchcode},
1239                 holdingbranch => $library->{branchcode},
1240                 biblionumber  => $biblionumber_1
1241             }
1242         }
1243     );
1244     my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1245     my $item_3 = $builder->build(
1246         {
1247             source => 'Item',
1248             value  => {
1249                 homebranch    => $library->{branchcode},
1250                 holdingbranch => $library->{branchcode},
1251                 biblionumber  => $biblionumber_2
1252             }
1253         }
1254     );
1255     my $patron = $builder->build(
1256         {
1257             source => 'Borrower',
1258             value  => { branchcode => $library->{branchcode} }
1259         }
1260     );
1261
1262     my $module = new Test::MockModule('C4::Context');
1263     $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
1264
1265     AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1266     AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1267     AddIssue( $patron, $item_3->{barcode} );
1268
1269     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1270     my $overdues = $patron->get_overdues;
1271     is( $overdues->count, 2, 'Patron should have 2 overdues');
1272     is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1273     is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1274
1275     my $o = $overdues->reset->next;
1276     my $unblessed_overdue = $o->unblessed_all_relateds;
1277     is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1278     is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1279     is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1280     is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1281
1282     # Clean stuffs
1283     $patron->checkouts->delete;
1284     $patron->delete;
1285 };
1286
1287 subtest 'userid_is_valid' => sub {
1288     plan tests => 8;
1289
1290     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1291     my $patron_category = $builder->build_object(
1292         {
1293             class => 'Koha::Patron::Categories',
1294             value => { category_type => 'P', enrolmentfee => 0 }
1295         }
1296     );
1297     my %data = (
1298         cardnumber   => "123456789",
1299         firstname    => "Tomasito",
1300         surname      => "None",
1301         categorycode => $patron_category->categorycode,
1302         branchcode   => $library->branchcode,
1303     );
1304
1305     my $expected_userid_patron_1 = 'tomasito.none';
1306     my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1307     my $patron_1       = Koha::Patrons->find($borrowernumber);
1308     is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1309
1310     $patron_1->userid( 'tomasito.non' );
1311     is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1312         1, 'recently created userid -> unique (borrowernumber passed)' );
1313
1314     $patron_1->userid( 'tomasitoxxx' );
1315     is( $patron_1->has_valid_userid,
1316         1, 'non-existent userid -> unique (borrowernumber passed)' );
1317     $patron_1->discard_changes; # We compare with the original userid later
1318
1319     my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1320     is( $patron_not_in_storage->has_valid_userid,
1321         0, 'userid exists for another patron, patron is not in storage yet' );
1322
1323     $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1324     is( $patron_not_in_storage->has_valid_userid,
1325         1, 'non-existent userid, patron is not in storage yet' );
1326
1327     # Regression tests for BZ12226
1328     my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1329     is( $db_patron->has_valid_userid,
1330         0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1331
1332     # Add a new borrower with the same userid but different cardnumber
1333     $data{cardnumber} = "987654321";
1334     my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1335     my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1336     $patron_2->userid($patron_1->userid);
1337     is( $patron_2->has_valid_userid,
1338         0, 'The userid is already in used, it cannot be used for another patron' );
1339
1340     my $new_userid = 'a_user_id';
1341     $data{cardnumber} = "234567890";
1342     $data{userid}     = 'a_user_id';
1343     $borrowernumber   = Koha::Patron->new(\%data)->store->borrowernumber;
1344     my $patron_3 = Koha::Patrons->find($borrowernumber);
1345     is( $patron_3->userid, $new_userid,
1346         'Koha::Patron->store should insert the given userid' );
1347
1348     # Cleanup
1349     $patron_1->delete;
1350     $patron_2->delete;
1351     $patron_3->delete;
1352 };
1353
1354 subtest 'generate_userid' => sub {
1355     plan tests => 7;
1356
1357     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1358     my $patron_category = $builder->build_object(
1359         {
1360             class => 'Koha::Patron::Categories',
1361             value => { category_type => 'P', enrolmentfee => 0 }
1362         }
1363     );
1364     my %data = (
1365         cardnumber   => "123456789",
1366         firstname    => "Tomasito",
1367         surname      => "None",
1368         categorycode => $patron_category->categorycode,
1369         branchcode   => $library->branchcode,
1370     );
1371
1372     my $expected_userid_patron_1 = 'tomasito.none';
1373     my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1374     $new_patron->generate_userid;
1375     my $userid = $new_patron->userid;
1376     is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1377     my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1378     my $patron_1 = Koha::Patrons->find($borrowernumber);
1379     is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1380
1381     $new_patron->generate_userid;
1382     $userid = $new_patron->userid;
1383     is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1384     $data{cardnumber} = '987654321';
1385     my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1386     my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1387     isnt( $patron_2->userid, 'tomasito',
1388         "Patron with duplicate userid has new userid generated" );
1389     is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1390         "Patron with duplicate userid has new userid generated (1 is appened" );
1391
1392     $new_patron->generate_userid;
1393     $userid = $new_patron->userid;
1394     is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1395
1396     $patron_1 = Koha::Patrons->find($borrowernumber);
1397     $patron_1->userid(undef);
1398     $patron_1->generate_userid;
1399     $userid = $patron_1->userid;
1400     is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1401
1402     # Cleanup
1403     $patron_1->delete;
1404     $patron_2->delete;
1405 };
1406
1407 $nb_of_patrons = Koha::Patrons->search->count;
1408 $retrieved_patron_1->delete;
1409 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1410
1411 subtest 'Log cardnumber change' => sub {
1412     plan tests => 3;
1413
1414     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1415     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1416
1417     my $cardnumber = $patron->cardnumber;
1418     $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1419     $patron->store;
1420
1421     my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1422     my $log_info = from_json( $logs[0]->info );
1423     is( $log_info->{cardnumber_replaced}->{new_cardnumber}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1424     is( $log_info->{cardnumber_replaced}->{previous_cardnumber}, $cardnumber, 'Got correct old cardnumber' );
1425     is( scalar @logs, 2, 'With BorrowerLogs, Change in cardnumber should be logged, as well as general alert of patron mod.' );
1426 };
1427
1428 $schema->storage->txn_rollback;
1429
1430 subtest 'Test Koha::Patrons::merge' => sub {
1431     plan tests => 110;
1432
1433     my $schema = Koha::Database->new()->schema();
1434
1435     my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1436
1437     $schema->storage->txn_begin;
1438
1439     my $keeper  = $builder->build_object({ class => 'Koha::Patrons' });
1440     my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1441     my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1442
1443     while (my ($r, $field) = each(%$resultsets)) {
1444         $builder->build({ source => $r, value => { $field => $keeper->id } });
1445         $builder->build({ source => $r, value => { $field => $loser_1 } });
1446         $builder->build({ source => $r, value => { $field => $loser_2 } });
1447
1448         my $keeper_rs =
1449           $schema->resultset($r)->search( { $field => $keeper->id } );
1450         is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1451
1452         my $loser_1_rs =
1453           $schema->resultset($r)->search( { $field => $loser_1 } );
1454         is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1455
1456         my $loser_2_rs =
1457           $schema->resultset($r)->search( { $field => $loser_2 } );
1458         is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1459     }
1460
1461     my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1462
1463     while (my ($r, $field) = each(%$resultsets)) {
1464         my $keeper_rs =
1465           $schema->resultset($r)->search( {$field => $keeper->id } );
1466         is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1467     }
1468
1469     is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1470     is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1471
1472     $schema->storage->txn_rollback;
1473 };
1474
1475 subtest '->store' => sub {
1476     plan tests => 3;
1477     my $schema = Koha::Database->new->schema;
1478     $schema->storage->txn_begin;
1479
1480     my $print_error = $schema->storage->dbh->{PrintError};
1481     $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1482
1483     my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1484     my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1485
1486     throws_ok
1487         { $patron_2->userid($patron_1->userid)->store; }
1488         'Koha::Exceptions::Object::DuplicateID',
1489         'Koha::Patron->store raises an exception on duplicate ID';
1490
1491     # Test password
1492     my $password = 'password';
1493     $patron_1->update_password($patron_1->userid, $password);
1494     like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1495     my $digest = $patron_1->password;
1496     $patron_1->surname('xxx')->store;
1497     is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1498
1499     $schema->storage->dbh->{PrintError} = $print_error;
1500     $schema->storage->txn_rollback;
1501 };
1502
1503 subtest '->set_password' => sub {
1504
1505     plan tests => 11;
1506
1507     $schema->storage->txn_begin;
1508
1509     my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1510
1511     # Disable logging password changes for this tests
1512     t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1513
1514     # Password-length tests
1515     t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1516     throws_ok { $patron->set_password('ab'); }
1517         'Koha::Exceptions::Password::TooShort',
1518         'minPasswordLength is undef, fall back to 3, fail test';
1519
1520     t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1521     throws_ok { $patron->set_password('ab'); }
1522         'Koha::Exceptions::Password::TooShort',
1523         'minPasswordLength is 2, fall back to 3, fail test';
1524
1525     t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1526     throws_ok { $patron->set_password('abcb'); }
1527         'Koha::Exceptions::Password::TooShort',
1528         'minPasswordLength is 5, fail test';
1529
1530     # Trailing spaces tests
1531     throws_ok { $patron->set_password('abcD12d   '); }
1532         'Koha::Exceptions::Password::WhitespaceCharacters',
1533         'Password contains trailing spaces, exception is thrown';
1534
1535     # Require strong password tests
1536     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1537     throws_ok { $patron->set_password('abcd   a'); }
1538         'Koha::Exceptions::Password::TooWeak',
1539         'Password is too weak, exception is thrown';
1540
1541     # Refresh patron from DB, just to make sure
1542     $patron->discard_changes;
1543     is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1544
1545     $patron->set_password('abcD12 34');
1546     $patron->discard_changes;
1547
1548     is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1549
1550     # Completeness
1551     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1552     $patron->login_attempts(3)->store;
1553     my $old_digest = $patron->password;
1554     $patron->set_password('abcd   a');
1555     $patron->discard_changes;
1556
1557     isnt( $patron->password, $old_digest, 'Password has been updated' );
1558     is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1559
1560     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1561     is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1562
1563     # Enable logging password changes
1564     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1565     $patron->set_password('abcd   b');
1566
1567     $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1568     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1569
1570     $schema->storage->txn_rollback;
1571 };
1572
1573
1574
1575 # TODO Move to t::lib::Mocks and reuse it!
1576 sub set_logged_in_user {
1577     my ($patron) = @_;
1578     C4::Context->set_userenv(
1579         $patron->borrowernumber, $patron->userid,
1580         $patron->cardnumber,     'firstname',
1581         'surname',               $patron->library->branchcode,
1582         'Midway Public Library', $patron->flags,
1583         '',                      ''
1584     );
1585 }