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