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