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