Bug 19830: Add the Koha::Patron->old_checkouts method
[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 + old_checkouts' => sub {
434     plan tests => 12;
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                 itemlost      => 0,
446                 withdrawn     => 0,
447             }
448         }
449     );
450     my $item_2 = $builder->build(
451         {
452             source => 'Item',
453             value  => {
454                 homebranch    => $library->{branchcode},
455                 holdingbranch => $library->{branchcode},
456                 biblionumber  => $biblionumber_1,
457                 itemlost      => 0,
458                 withdrawn     => 0,
459             }
460         }
461     );
462     my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
463     my $item_3 = $builder->build(
464         {
465             source => 'Item',
466             value  => {
467                 homebranch    => $library->{branchcode},
468                 holdingbranch => $library->{branchcode},
469                 biblionumber  => $biblionumber_2,
470                 itemlost      => 0,
471                 withdrawn     => 0,
472             }
473         }
474     );
475     my $patron = $builder->build(
476         {
477             source => 'Borrower',
478             value  => { branchcode => $library->{branchcode} }
479         }
480     );
481
482     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
483     my $checkouts = $patron->checkouts;
484     is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
485     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
486     my $old_checkouts = $patron->old_checkouts;
487     is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
488     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
489
490     # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
491     $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
492
493     my $module = new Test::MockModule('C4::Context');
494     $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
495
496     AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
497     AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
498     AddIssue( $patron, $item_3->{barcode} );
499
500     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
501     $checkouts = $patron->checkouts;
502     is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
503     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
504
505     my $overdues = $patron->get_overdues;
506     is( $overdues->count, 2, 'Patron should have 2 overdues');
507     is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
508     is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
509     is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
510
511
512     C4::Circulation::AddReturn( $item_1->{barcode} );
513     C4::Circulation::AddReturn( $item_2->{barcode} );
514     $old_checkouts = $patron->old_checkouts;
515     is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
516     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
517
518     # Clean stuffs
519     Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
520     $patron->delete;
521     $module->unmock('userenv');
522 };
523
524 subtest 'get_age' => sub {
525     plan tests => 7;
526
527     my $patron = $builder->build( { source => 'Borrower' } );
528     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
529
530     my $today = dt_from_string;
531
532     $patron->dateofbirth( undef );
533     is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
534     $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1 ) );
535     is( $patron->get_age, 12, 'Patron should be 12' );
536     $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 1 ) );
537     is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
538     $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 0 ) );
539     is( $patron->get_age, 18, 'Patron should be 18' );
540     $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -31 ) );
541     is( $patron->get_age, 19, 'Patron should be 19' );
542     $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -30 ) );
543     is( $patron->get_age, 19, 'Patron should be 19 again' );
544     $patron->dateofbirth( $today->clone->add( years => 0,   months => -1, days => -1 ) );
545     is( $patron->get_age, 0, 'Patron is a newborn child' );
546
547     $patron->delete;
548 };
549
550 subtest 'account' => sub {
551     plan tests => 1;
552
553     my $patron = $builder->build({source => 'Borrower'});
554
555     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
556     my $account = $patron->account;
557     is( ref($account),   'Koha::Account', 'account should return a Koha::Account object' );
558
559     $patron->delete;
560 };
561
562 subtest 'search_upcoming_membership_expires' => sub {
563     plan tests => 9;
564
565     my $expiry_days = 15;
566     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
567     my $nb_of_days_before = 1;
568     my $nb_of_days_after = 2;
569
570     my $builder = t::lib::TestBuilder->new();
571
572     my $library = $builder->build({ source => 'Branch' });
573
574     # before we add borrowers to this branch, add the expires we have now
575     # note that this pertains to the current mocked setting of the pref
576     # for this reason we add the new branchcode to most of the tests
577     my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
578
579     my $patron_1 = $builder->build({
580         source => 'Borrower',
581         value  => {
582             branchcode              => $library->{branchcode},
583             dateexpiry              => dt_from_string->add( days => $expiry_days )
584         },
585     });
586
587     my $patron_2 = $builder->build({
588         source => 'Borrower',
589         value  => {
590             branchcode              => $library->{branchcode},
591             dateexpiry              => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
592         },
593     });
594
595     my $patron_3 = $builder->build({
596         source => 'Borrower',
597         value  => {
598             branchcode              => $library->{branchcode},
599             dateexpiry              => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
600         },
601     });
602
603     # Test without extra parameters
604     my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
605     is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
606
607     # Test with branch
608     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
609     is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
610     my $expired = $upcoming_mem_expires->next;
611     is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
612     is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
613     is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
614
615     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
616     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
617     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
618
619     # Test MembershipExpiryDaysNotice == undef
620     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
621     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
622     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
623
624     # Test the before parameter
625     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
626     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
627     is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
628     # Test after parameter also
629     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
630     is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
631     Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
632 };
633
634 subtest 'holds and old_holds' => sub {
635     plan tests => 6;
636
637     my $library = $builder->build( { source => 'Branch' } );
638     my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
639     my $item_1 = $builder->build(
640         {
641             source => 'Item',
642             value  => {
643                 homebranch    => $library->{branchcode},
644                 holdingbranch => $library->{branchcode},
645                 biblionumber  => $biblionumber_1
646             }
647         }
648     );
649     my $item_2 = $builder->build(
650         {
651             source => 'Item',
652             value  => {
653                 homebranch    => $library->{branchcode},
654                 holdingbranch => $library->{branchcode},
655                 biblionumber  => $biblionumber_1
656             }
657         }
658     );
659     my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
660     my $item_3 = $builder->build(
661         {
662             source => 'Item',
663             value  => {
664                 homebranch    => $library->{branchcode},
665                 holdingbranch => $library->{branchcode},
666                 biblionumber  => $biblionumber_2
667             }
668         }
669     );
670     my $patron = $builder->build(
671         {
672             source => 'Borrower',
673             value  => { branchcode => $library->{branchcode} }
674         }
675     );
676
677     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
678     my $holds = $patron->holds;
679     is( ref($holds), 'Koha::Holds',
680         'Koha::Patron->holds should return a Koha::Holds objects' );
681     is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
682
683     C4::Reserves::AddReserve( $library->{branchcode},
684         $patron->borrowernumber, $biblionumber_1 );
685     # In the future
686     C4::Reserves::AddReserve( $library->{branchcode},
687         $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
688
689     $holds = $patron->holds;
690     is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
691
692     my $old_holds = $patron->old_holds;
693     is( ref($old_holds), 'Koha::Old::Holds',
694         'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
695     is( $old_holds->count, 0, 'There should not be any old holds yet');
696
697     my $hold = $holds->next;
698     $hold->cancel;
699
700     $old_holds = $patron->old_holds;
701     is( $old_holds->count, 1, 'There should  be 1 old (cancelled) hold');
702
703     $old_holds->delete;
704     $holds->delete;
705     $patron->delete;
706 };
707
708 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
709     plan tests => 4;
710
711     # TODO create a subroutine in t::lib::Mocks
712     my $branch = $builder->build({ source => 'Branch' });
713     my $userenv_patron = $builder->build({
714         source => 'Borrower',
715         value  => { branchcode => $branch->{branchcode} },
716     });
717     C4::Context->_new_userenv('DUMMY SESSION');
718     C4::Context->set_userenv(
719         $userenv_patron->{borrowernumber},
720         $userenv_patron->{userid},
721         'usercnum', 'First name', 'Surname',
722         $branch->{branchcode},
723         $branch->{branchname},
724         0,
725     );
726     my $anonymous = $builder->build( { source => 'Borrower', }, );
727
728     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
729
730     subtest 'patron privacy is 1 (default)' => sub {
731         plan tests => 8;
732
733         t::lib::Mocks::mock_preference('IndependentBranches', 0);
734         my $patron = $builder->build(
735             {   source => 'Borrower',
736                 value  => { privacy => 1, }
737             }
738         );
739         my $item_1 = $builder->build(
740             {   source => 'Item',
741                 value  => {
742                     itemlost  => 0,
743                     withdrawn => 0,
744                 },
745             }
746         );
747         my $issue_1 = $builder->build(
748             {   source => 'Issue',
749                 value  => {
750                     borrowernumber => $patron->{borrowernumber},
751                     itemnumber     => $item_1->{itemnumber},
752                 },
753             }
754         );
755         my $item_2 = $builder->build(
756             {   source => 'Item',
757                 value  => {
758                     itemlost  => 0,
759                     withdrawn => 0,
760                 },
761             }
762         );
763         my $issue_2 = $builder->build(
764             {   source => 'Issue',
765                 value  => {
766                     borrowernumber => $patron->{borrowernumber},
767                     itemnumber     => $item_2->{itemnumber},
768                 },
769             }
770         );
771
772         my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, undef, '2010-10-10' );
773         my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, undef, '2011-11-11' );
774         is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
775
776         my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
777         is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
778
779         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
780         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
781
782         my $dbh = C4::Context->dbh;
783         my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
784         $sth->execute($item_1->{itemnumber});
785         my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
786         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
787         $sth->execute($item_2->{itemnumber});
788         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
789         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
790
791         $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
792         $sth->execute($item_2->{itemnumber});
793         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
794         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
795
796         my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
797         $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
798         $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
799         $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
800         $sth->execute($item_1->{itemnumber});
801         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
802         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
803         $sth->execute($item_2->{itemnumber});
804         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
805         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
806
807         Koha::Patrons->find( $patron->{borrowernumber})->delete;
808     };
809
810     subtest 'patron privacy is 0 (forever)' => sub {
811         plan tests => 3;
812
813         t::lib::Mocks::mock_preference('IndependentBranches', 0);
814         my $patron = $builder->build(
815             {   source => 'Borrower',
816                 value  => { privacy => 0, }
817             }
818         );
819         my $item = $builder->build(
820             {   source => 'Item',
821                 value  => {
822                     itemlost  => 0,
823                     withdrawn => 0,
824                 },
825             }
826         );
827         my $issue = $builder->build(
828             {   source => 'Issue',
829                 value  => {
830                     borrowernumber => $patron->{borrowernumber},
831                     itemnumber     => $item->{itemnumber},
832                 },
833             }
834         );
835
836         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
837         is( $returned, 1, 'The item should have been returned' );
838         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
839         ok( $rows_affected > 0, 'AnonymiseIssueHistory should not return any error if success' );
840
841         my $dbh = C4::Context->dbh;
842         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
843             SELECT borrowernumber FROM old_issues where itemnumber = ?
844         |, undef, $item->{itemnumber});
845         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
846         Koha::Patrons->find( $patron->{borrowernumber})->delete;
847     };
848
849     t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
850
851     subtest 'AnonymousPatron is not defined' => sub {
852         plan tests => 3;
853
854         t::lib::Mocks::mock_preference('IndependentBranches', 0);
855         my $patron = $builder->build(
856             {   source => 'Borrower',
857                 value  => { privacy => 1, }
858             }
859         );
860         my $item = $builder->build(
861             {   source => 'Item',
862                 value  => {
863                     itemlost  => 0,
864                     withdrawn => 0,
865                 },
866             }
867         );
868         my $issue = $builder->build(
869             {   source => 'Issue',
870                 value  => {
871                     borrowernumber => $patron->{borrowernumber},
872                     itemnumber     => $item->{itemnumber},
873                 },
874             }
875         );
876
877         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
878         is( $returned, 1, 'The item should have been returned' );
879         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
880         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
881
882         my $dbh = C4::Context->dbh;
883         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
884             SELECT borrowernumber FROM old_issues where itemnumber = ?
885         |, undef, $item->{itemnumber});
886         is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
887         Koha::Patrons->find( $patron->{borrowernumber})->delete;
888     };
889
890     subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
891         plan tests => 1;
892         t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
893         my $patron = $builder->build(
894             {   source => 'Borrower',
895                 value  => { privacy => 1 }    # Another branchcode than the logged in librarian
896             }
897         );
898         my $item = $builder->build(
899             {   source => 'Item',
900                 value  => {
901                     itemlost  => 0,
902                     withdrawn => 0,
903                 },
904             }
905         );
906         my $issue = $builder->build(
907             {   source => 'Issue',
908                 value  => {
909                     borrowernumber => $patron->{borrowernumber},
910                     itemnumber     => $item->{itemnumber},
911                 },
912             }
913         );
914
915         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
916         is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
917         Koha::Patrons->find( $patron->{borrowernumber})->delete;
918     };
919
920     Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
921     Koha::Patrons->find( $userenv_patron->{borrowernumber})->delete;
922 };
923
924 subtest 'account_locked' => sub {
925     plan tests => 8;
926     my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
927     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
928     for my $value ( undef, '', 0 ) {
929         t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
930         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
931         $patron->login_attempts(1)->store;
932         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
933     }
934
935     t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
936     $patron->login_attempts(2)->store;
937     is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
938     $patron->login_attempts(3)->store;
939     is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
940
941     $patron->delete;
942 };
943
944 $retrieved_patron_1->delete;
945 is( Koha::Patrons->search->count, $nb_of_patrons + 1, 'Delete should have deleted the patron' );
946
947 $schema->storage->txn_rollback;
948