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