Bug 33070: Remove use of can_edit_items
[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 => 45;
23 use Test::Warn;
24 use Test::Exception;
25 use Test::MockModule;
26 use Time::Fake;
27 use DateTime;
28 use JSON;
29 use utf8;
30
31 use C4::Circulation qw( AddIssue AddReturn );
32 use C4::Biblio;
33 use C4::Auth qw( checkpw checkpw_hash );
34
35 use Koha::ActionLogs;
36 use Koha::Holds;
37 use Koha::Old::Holds;
38 use Koha::Patrons;
39 use Koha::Old::Patrons;
40 use Koha::Patron::Attribute::Types;
41 use Koha::Patron::Categories;
42 use Koha::Patron::Relationship;
43 use Koha::Database;
44 use Koha::DateUtils qw( dt_from_string output_pref );
45 use Koha::Virtualshelf;
46 use Koha::Virtualshelves;
47 use Koha::Notice::Messages;
48
49 use t::lib::TestBuilder;
50 use t::lib::Mocks;
51
52 my $schema = Koha::Database->new->schema;
53 $schema->storage->txn_begin;
54
55 my $builder       = t::lib::TestBuilder->new;
56 my $library = $builder->build({source => 'Branch' });
57 my $category = $builder->build({source => 'Category' });
58 my $nb_of_patrons = Koha::Patrons->search->count;
59 my $new_patron_1  = Koha::Patron->new(
60     {   cardnumber => 'test_cn_1',
61         branchcode => $library->{branchcode},
62         categorycode => $category->{categorycode},
63         surname => 'surname for patron1',
64         firstname => 'firstname for patron1',
65         userid => 'a_nonexistent_userid_1',
66         flags => 1, # Is superlibrarian
67     }
68 )->store;
69 my $new_patron_2  = Koha::Patron->new(
70     {   cardnumber => 'test_cn_2',
71         branchcode => $library->{branchcode},
72         categorycode => $category->{categorycode},
73         surname => 'surname for patron2',
74         firstname => 'firstname for patron2',
75         userid => 'a_nonexistent_userid_2',
76     }
77 )->store;
78
79 t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
80
81 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
82
83 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
84 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
85
86 subtest 'library' => sub {
87     plan tests => 2;
88     is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
89     is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
90 };
91
92 subtest 'sms_provider' => sub {
93     plan tests => 3;
94     my $sms_provider = $builder->build({source => 'SmsProvider' });
95     is( $retrieved_patron_1->sms_provider, undef, '->sms_provider should return undef if none defined' );
96     $retrieved_patron_1->sms_provider_id( $sms_provider->{id} )->store;
97     is_deeply( $retrieved_patron_1->sms_provider->unblessed, $sms_provider, 'Koha::Patron->sms_provider returns the correct SMS provider' );
98     is( ref($retrieved_patron_1->sms_provider), 'Koha::SMS::Provider', 'Koha::Patron->sms_provider should return a Koha::SMS::Provider object' );
99 };
100
101 subtest 'guarantees' => sub {
102
103     plan tests => 9;
104
105     t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test|test2' );
106
107     my $guarantees = $new_patron_1->guarantee_relationships;
108     is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
109     is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee relationships' );
110
111     my $guarantee_1 = $builder->build({ source => 'Borrower' });
112     my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
113     my $guarantee_2 = $builder->build({ source => 'Borrower' });
114     my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
115
116     $guarantees = $new_patron_1->guarantee_relationships;
117     is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' );
118     is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
119
120     $guarantees->delete;
121
122     #Test return order of guarantees BZ 18635
123     my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
124     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
125
126     my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
127
128     my $order_guarantee1 = $builder->build_object(
129         {
130             class => 'Koha::Patrons',
131             value => {
132                 surname     => 'Zebra',
133             }
134         }
135     )->borrowernumber;
136     $builder->build_object(
137         {
138             class => 'Koha::Patron::Relationships',
139             value => {
140                 guarantor_id  => $guarantor->id,
141                 guarantee_id => $order_guarantee1,
142                 relationship => 'test',
143             }
144         }
145     );
146
147     my $order_guarantee2 = $builder->build_object(
148         {
149             class => 'Koha::Patrons',
150             value => {
151                 surname     => 'Yak',
152             }
153         }
154     )->borrowernumber;
155     $builder->build_object(
156         {
157             class => 'Koha::Patron::Relationships',
158             value => {
159                 guarantor_id  => $guarantor->id,
160                 guarantee_id => $order_guarantee2,
161                 relationship => 'test',
162             }
163         }
164     );
165
166     my $order_guarantee3 = $builder->build_object(
167         {
168             class => 'Koha::Patrons',
169             value => {
170                 surname     => 'Xerus',
171                 firstname   => 'Walrus',
172             }
173         }
174     )->borrowernumber;
175     $builder->build_object(
176         {
177             class => 'Koha::Patron::Relationships',
178             value => {
179                 guarantor_id  => $guarantor->id,
180                 guarantee_id => $order_guarantee3,
181                 relationship => 'test',
182             }
183         }
184     );
185
186     my $order_guarantee4 = $builder->build_object(
187         {
188             class => 'Koha::Patrons',
189             value => {
190                 surname     => 'Xerus',
191                 firstname   => 'Vulture',
192             }
193         }
194     )->borrowernumber;
195     $builder->build_object(
196         {
197             class => 'Koha::Patron::Relationships',
198             value => {
199                 guarantor_id  => $guarantor->id,
200                 guarantee_id => $order_guarantee4,
201                 relationship => 'test',
202             }
203         }
204     );
205
206     my $order_guarantee5 = $builder->build_object(
207         {
208             class => 'Koha::Patrons',
209             value => {
210                 surname     => 'Xerus',
211                 firstname   => 'Unicorn',
212             }
213         }
214     )->borrowernumber;
215     my $r = $builder->build_object(
216         {
217             class => 'Koha::Patron::Relationships',
218             value => {
219                 guarantor_id  => $guarantor->id,
220                 guarantee_id => $order_guarantee5,
221                 relationship => 'test',
222             }
223         }
224     );
225
226     $guarantees = $guarantor->guarantee_relationships->guarantees;
227
228     is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
229     is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
230     is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
231     is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
232     is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
233 };
234
235 subtest 'category' => sub {
236     plan tests => 2;
237     my $patron_category = $new_patron_1->category;
238     is( ref( $patron_category), 'Koha::Patron::Category', );
239     is( $patron_category->categorycode, $category->{categorycode}, );
240 };
241
242 subtest 'siblings' => sub {
243
244     plan tests => 6;
245
246     my $siblings = $new_patron_1->siblings;
247     is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
248     my $guarantee_1 = $builder->build( { source => 'Borrower' } );
249     my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
250     my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
251     $siblings = $retrieved_guarantee_1->siblings;
252     is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
253     is( $siblings->count,  0,       'guarantee_1 should not have siblings yet' );
254     my $guarantee_2 = $builder->build( { source => 'Borrower' } );
255     my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
256     my $guarantee_3 = $builder->build( { source => 'Borrower' } );
257     my $relationship_3 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, relationship => 'test' } )->store();
258     $siblings = $retrieved_guarantee_1->siblings;
259     is( $siblings->count,               2,                               'guarantee_1 should have 2 siblings' );
260     is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
261     is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
262     $_->delete for $retrieved_guarantee_1->siblings;
263     $retrieved_guarantee_1->delete;
264 };
265
266 subtest 'has_overdues' => sub {
267     plan tests => 3;
268
269     my $item_1 = $builder->build_sample_item;
270     my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
271     is( $retrieved_patron->has_overdues, 0, );
272
273     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
274     my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
275     is( $retrieved_patron->has_overdues, 0, );
276     $issue->delete();
277     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
278     $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
279     $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
280     is( $retrieved_patron->has_overdues, 1, );
281     $issue->delete();
282 };
283
284 subtest 'is_expired' => sub {
285     plan tests => 4;
286     my $patron = $builder->build({ source => 'Borrower' });
287     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
288     $patron->dateexpiry( undef )->store->discard_changes;
289     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
290     $patron->dateexpiry( dt_from_string )->store->discard_changes;
291     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
292     $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
293     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
294     $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
295     is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
296
297     $patron->delete;
298 };
299
300 subtest 'is_going_to_expire' => sub {
301     plan tests => 9;
302
303     my $today = dt_from_string(undef, undef, 'floating');
304     my $patron = $builder->build({ source => 'Borrower' });
305     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
306     $patron->dateexpiry( undef )->store->discard_changes;
307     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
308
309     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
310     $patron->dateexpiry( $today )->store->discard_changes;
311     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
312
313     $patron->dateexpiry( $today )->store->discard_changes;
314     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
315
316     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
317     $patron->dateexpiry( $today->clone->add( days => 11 ) )->store->discard_changes;
318     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');
319
320     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
321     $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
322     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');
323
324     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
325     $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
326     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');
327     $patron->delete;
328
329     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
330     $patron->dateexpiry( $today->clone->add( days => 20 ) )->store->discard_changes;
331     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');
332
333     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
334     $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
335     is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
336
337     { # Testing invalid is going to expiry date
338         t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 30);
339         # mock_config does not work here, because of tz vs timezone subroutines
340         my $context = Test::MockModule->new('C4::Context');
341         $context->mock( 'tz', sub {
342             'America/Sao_Paulo';
343         });
344         $patron->dateexpiry(DateTime->new( year => 2019, month => 12, day => 3 ))->store;
345         eval { $patron->is_going_to_expire };
346         is( $@, '', 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"');
347         $context->unmock('tz');
348     };
349
350     $patron->delete;
351 };
352
353
354 subtest 'renew_account' => sub {
355     plan tests => 48;
356
357     for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
358         my $dt = dt_from_string( $date, 'iso' );
359         Time::Fake->offset( $dt->epoch );
360         my $a_month_ago                = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
361         my $a_year_later               = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
362         my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
363         my $a_month_later              = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
364         my $a_year_later_plus_a_month  = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
365         my $patron_category = $builder->build(
366             {   source => 'Category',
367                 value  => {
368                     enrolmentperiod     => 12,
369                     enrolmentperioddate => undef,
370                 }
371             }
372         );
373         my $patron = $builder->build(
374             {   source => 'Borrower',
375                 value  => {
376                     dateexpiry   => $a_month_ago,
377                     categorycode => $patron_category->{categorycode},
378                     date_renewed => undef, # Force builder to not populate the column for new patron
379                 }
380             }
381         );
382         my $patron_2 = $builder->build(
383             {  source => 'Borrower',
384                value  => {
385                    dateexpiry => $a_month_ago,
386                    categorycode => $patron_category->{categorycode},
387                 }
388             }
389         );
390         my $patron_3 = $builder->build(
391             {  source => 'Borrower',
392                value  => {
393                    dateexpiry => $a_month_later,
394                    categorycode => $patron_category->{categorycode},
395                }
396             }
397         );
398         my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
399         my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
400         my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
401
402         is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
403
404         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
405         t::lib::Mocks::mock_preference( 'BorrowersLog',              1 );
406         my $expiry_date = $retrieved_patron->renew_account;
407         is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
408         my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
409         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" );
410         my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
411         is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
412
413         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
414         t::lib::Mocks::mock_preference( 'BorrowersLog',              0 );
415         $expiry_date = $retrieved_patron->renew_account;
416         is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
417         $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
418         is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
419         $retrieved_expiry_date = $retrieved_patron->dateexpiry;
420         is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
421         $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
422         is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
423
424         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
425         $expiry_date = $retrieved_patron_2->renew_account;
426         is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
427         $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
428         is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
429
430         $expiry_date = $retrieved_patron_3->renew_account;
431         is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
432         $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
433         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" );
434
435         $retrieved_patron->delete;
436         $retrieved_patron_2->delete;
437         $retrieved_patron_3->delete;
438     }
439     Time::Fake->reset;
440 };
441
442 subtest "move_to_deleted" => sub {
443     plan tests => 5;
444     my $originally_updated_on = '2016-01-01 12:12:12';
445     my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
446     my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
447     is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
448       ;    # FIXME This should be Koha::Deleted::Patron
449     my $deleted_patron = $schema->resultset('Deletedborrower')
450         ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
451         ->next;
452     ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
453     ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
454     isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
455     $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
456     is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
457     $retrieved_patron->delete( $patron->{borrowernumber} );    # Cleanup
458 };
459
460 subtest "delete" => sub {
461     plan tests => 16;
462     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
463     t::lib::Mocks::mock_preference( 'ListOwnershipUponPatronDeletion', 'transfer' );
464     t::lib::Mocks::mock_preference( 'ListOwnerDesignated', undef );
465     Koha::Virtualshelves->delete;
466
467     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
468     my $patron_for_sharing = $builder->build_object({ class => 'Koha::Patrons' });
469     my $staff_patron = $builder->build_object({ class => 'Koha::Patrons' });
470     t::lib::Mocks::mock_userenv({ patron => $staff_patron });
471
472     my $hold = $builder->build_object({ class => 'Koha::Holds', value => { borrowernumber => $patron->borrowernumber } });
473     my $modification = $builder->build_object({ class => 'Koha::Patron::Modifications', value => { borrowernumber => $patron->borrowernumber } });
474     my $private_list = Koha::Virtualshelf->new({
475         shelfname => "private",
476         owner => $patron->borrowernumber,
477         public => 0,
478     })->store;
479     my $public_list = Koha::Virtualshelf->new({
480         shelfname => "public",
481         owner => $patron->borrowernumber,
482         public => 1,
483     })->store;
484     my $list_to_share = Koha::Virtualshelf->new({
485         shelfname => "shared",
486         owner => $patron->borrowernumber,
487         public => 0,
488     })->store;
489
490     $list_to_share->share("valid key")->accept( "valid key", $patron_for_sharing->borrowernumber );
491     $list_to_share->share("valid key")->accept( "valid key", $staff_patron->borrowernumber ); # this share should be removed at deletion too
492     my $deleted = $patron->delete;
493     is( ref($deleted), 'Koha::Patron', 'Koha::Patron->delete should return the deleted patron object if the patron has been correctly deleted' );
494     ok( $patron->borrowernumber, 'Still have the deleted borrowernumber' );
495
496     is( Koha::Patrons->find( $patron->borrowernumber ), undef, 'Koha::Patron->delete should have deleted the patron' );
497
498     is (Koha::Old::Holds->search({ reserve_id => $hold->reserve_id })->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
499
500     is( Koha::Holds->search( { borrowernumber => $patron->borrowernumber } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| );
501
502     my $transferred_lists = Koha::Virtualshelves->search({ owner => $staff_patron->borrowernumber })->count;
503     is( $transferred_lists, 2, 'Public and shared lists should stay in database under a different owner with a unique name, while private lists delete, with ListOwnershipPatronDeletion set to Transfer');
504     is( Koha::Virtualshelfshares->search({ borrowernumber => $staff_patron->borrowernumber })->count, 0, "New owner of list should have shares removed" );
505     is( Koha::Virtualshelfshares->search({ borrowernumber => $patron_for_sharing->borrowernumber })->count, 1, "But the other share is still there" );
506     is( Koha::Virtualshelves->search({ owner => $patron->borrowernumber })->count, 0, q|Koha::Patron->delete should have deleted patron's lists/removed their ownership| );
507
508     is( Koha::Patron::Modifications->search( { borrowernumber => $patron->borrowernumber } )->count, 0, q|Koha::Patron->delete should have deleted patron's modifications| );
509
510     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $patron->borrowernumber } )->count;
511     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
512
513     # Test deletion with designated fallback owner
514     my $designated_owner = $builder->build_object({ class => 'Koha::Patrons' });
515     t::lib::Mocks::mock_preference( 'ListOwnerDesignated', $designated_owner->id );
516     $patron = $builder->build_object({ class => 'Koha::Patrons' });
517     $private_list = Koha::Virtualshelf->new({ shelfname => "PR1", owner => $patron->id })->store;
518     $public_list = Koha::Virtualshelf->new({ shelfname => "PU1", public => 1, owner => $patron->id })->store;
519     $list_to_share = Koha::Virtualshelf->new({ shelfname => "SH1", owner => $patron->id })->store;
520     $list_to_share->share("valid key")->accept( "valid key", $patron_for_sharing->id );
521     $patron->delete;
522     is( Koha::Virtualshelves->find( $private_list->id ), undef, 'Private list gone' );
523     is( $public_list->discard_changes->get_column('owner'), $designated_owner->id, 'Public list transferred' );
524     is( $list_to_share->discard_changes->get_column('owner'), $designated_owner->id, 'Shared list transferred' );
525
526     # Finally test deleting lists
527     t::lib::Mocks::mock_preference( 'ListOwnershipUponPatronDeletion', 'delete' );
528     Koha::Virtualshelves->delete;
529     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
530     my $private_list2 = Koha::Virtualshelf->new({
531          shelfname => "private",
532          owner => $patron2->borrowernumber,
533          public => 0,
534     })->store;
535     my $public_list2 = Koha::Virtualshelf->new({
536         shelfname => "public",
537         owner => $patron2->borrowernumber,
538         public => 1,
539     })->store;
540     my $list_to_share2 = Koha::Virtualshelf->new({
541         shelfname => "shared",
542         owner => $patron2->borrowernumber,
543         public => 0,
544     })->store;
545     $list_to_share2->share("valid key")->accept( "valid key", $patron_for_sharing->borrowernumber );
546
547     # Delete patron2, check if shelves and shares are now empty
548     $patron2->delete;
549     is( Koha::Virtualshelves->count, 0, 'All lists should be gone now' );
550     is( Koha::Virtualshelfshares->count, 0, 'All shares should be gone too' );
551 };
552
553 subtest 'Koha::Patrons->delete' => sub {
554     plan tests => 3;
555
556     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
557     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
558     my $id1 = $patron1->borrowernumber;
559     my $set = Koha::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
560     is( $set->count, 2, 'Two patrons found as expected' );
561     is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
562     my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
563     is( $deleted_patrons->count, 2, 'Patrons moved to deletedborrowers' );
564
565     # See other tests in t/db_dependent/Koha/Objects.t
566 };
567
568 subtest 'add_enrolment_fee_if_needed' => sub {
569     plan tests => 4;
570
571     my $enrolmentfees = { K  => 5, J => 10, YA => 20 };
572     foreach( keys %{$enrolmentfees} ) {
573         ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
574     }
575     my $enrolmentfee_K  = $enrolmentfees->{K};
576     my $enrolmentfee_J  = $enrolmentfees->{J};
577     my $enrolmentfee_YA = $enrolmentfees->{YA};
578
579     my %borrower_data = (
580         firstname    => 'my firstname',
581         surname      => 'my surname',
582         categorycode => 'K',
583         branchcode   => $library->{branchcode},
584     );
585
586     my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
587     $borrower_data{borrowernumber} = $borrowernumber;
588
589     my $patron = Koha::Patrons->find( $borrowernumber );
590     my $total = $patron->account->balance;
591     is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
592
593     t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
594     $borrower_data{categorycode} = 'J';
595     $patron->set(\%borrower_data)->store;
596     $total = $patron->account->balance;
597     is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
598
599     $borrower_data{categorycode} = 'K';
600     $patron->set(\%borrower_data)->store;
601     t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
602
603     $borrower_data{categorycode} = 'J';
604     $patron->set(\%borrower_data)->store;
605     $total = $patron->account->balance;
606     is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
607
608     # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
609     $patron->categorycode('YA')->store;
610     $total = $patron->account->balance;
611     is( int($total),
612         int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
613         "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
614     );
615
616     $patron->delete;
617 };
618
619 subtest 'checkouts + pending_checkouts + overdues + old_checkouts' => sub {
620     plan tests => 17;
621
622     my $library = $builder->build( { source => 'Branch' } );
623     my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
624     my $item_1 = $builder->build_sample_item(
625         {
626             library      => $library->{branchcode},
627             biblionumber => $biblionumber_1,
628         }
629     );
630     my $item_2 = $builder->build_sample_item(
631         {
632             library      => $library->{branchcode},
633             biblionumber => $biblionumber_1,
634         }
635     );
636     my $biblionumber_2 = $builder->build_sample_biblio->biblionumber;
637     my $item_3 = $builder->build_sample_item(
638         {
639             library      => $library->{branchcode},
640             biblionumber => $biblionumber_2,
641         }
642     );
643     my $patron = $builder->build(
644         {
645             source => 'Borrower',
646             value  => { branchcode => $library->{branchcode} }
647         }
648     );
649
650     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
651     my $checkouts = $patron->checkouts;
652     is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
653     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
654     my $pending_checkouts = $patron->pending_checkouts;
655     is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
656     is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
657     my $old_checkouts = $patron->old_checkouts;
658     is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
659     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
660
661     # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
662     $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
663
664     t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
665
666     AddIssue( $patron, $item_1->barcode, DateTime->now->subtract( days => 1 ) );
667     AddIssue( $patron, $item_2->barcode, DateTime->now->subtract( days => 5 ) );
668     AddIssue( $patron, $item_3->barcode );
669
670     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
671     $checkouts = $patron->checkouts;
672     is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
673     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
674     $pending_checkouts = $patron->pending_checkouts;
675     is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
676     is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
677
678     my $first_checkout = $pending_checkouts->next;
679     is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->biblionumber, 'pending_checkouts should prefetch values from other tables (here biblio)' );
680
681     my $overdues = $patron->overdues;
682     is( $overdues->count, 2, 'Patron should have 2 overdues');
683     is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->overdues should return Koha::Checkouts' );
684     is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' );
685     is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' );
686
687
688     C4::Circulation::AddReturn( $item_1->barcode );
689     C4::Circulation::AddReturn( $item_2->barcode );
690     $old_checkouts = $patron->old_checkouts;
691     is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
692     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
693
694     # Clean stuffs
695     Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
696     $patron->delete;
697 };
698
699 subtest 'get_routing_lists' => sub {
700     plan tests => 5;
701
702     my $biblio = Koha::Biblio->new()->store();
703     my $subscription = Koha::Subscription->new({
704         biblionumber => $biblio->biblionumber,
705         }
706     )->store;
707
708     my $patron = $builder->build( { source => 'Borrower' } );
709     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
710
711     is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
712
713     my $routinglist_count = Koha::Subscription::Routinglists->count;
714     my $routinglist = Koha::Subscription::Routinglist->new({
715         borrowernumber   => $patron->borrowernumber,
716         ranking          => 5,
717         subscriptionid   => $subscription->subscriptionid
718     })->store;
719
720     is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
721
722     my $routinglists = $patron->get_routing_lists;
723     is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
724     is( ref($routinglists),   'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
725
726     my $subscription2 = Koha::Subscription->new({
727         biblionumber => $biblio->biblionumber,
728         }
729     )->store;
730     my $routinglist2 = Koha::Subscription::Routinglist->new({
731         borrowernumber   => $patron->borrowernumber,
732         ranking          => 1,
733         subscriptionid   => $subscription2->subscriptionid
734     })->store;
735
736     is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
737
738     $patron->delete; # Clean up for later tests
739
740 };
741
742 subtest 'get_age' => sub {
743     plan tests => 31;
744
745     my $patron = $builder->build( { source => 'Borrower' } );
746     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
747
748     my @dates = (
749         {
750             today            => '2020-02-28',
751             has_12           => { date => '2007-08-27', expected_age => 12 },
752             almost_18        => { date => '2002-03-01', expected_age => 17 },
753             has_18_today     => { date => '2002-02-28', expected_age => 18 },
754             had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
755             almost_16        => { date => '2004-02-29', expected_age => 15 },
756             has_16_today     => { date => '2004-02-28', expected_age => 16 },
757             had_16_yesterday => { date => '2004-02-27', expected_age => 16 },
758             new_born         => { date => '2020-01-27', expected_age => 0 },
759         },
760         {
761             today            => '2020-02-29',
762             has_12           => { date => '2007-08-27', expected_age => 12 },
763             almost_18        => { date => '2002-03-01', expected_age => 17 },
764             has_18_today     => { date => '2002-02-28', expected_age => 18 },
765             had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
766             almost_16        => { date => '2004-03-01', expected_age => 15 },
767             has_16_today     => { date => '2004-02-29', expected_age => 16 },
768             had_16_yesterday => { date => '2004-02-28', expected_age => 16 },
769             new_born         => { date => '2020-01-27', expected_age => 0 },
770         },
771         {
772             today            => '2020-03-01',
773             has_12           => { date => '2007-08-27', expected_age => 12 },
774             almost_18        => { date => '2002-03-02', expected_age => 17 },
775             has_18_today     => { date => '2002-03-01', expected_age => 18 },
776             had_18_yesterday => { date => '2002-02-28', expected_age => 18 },
777             almost_16        => { date => '2004-03-02', expected_age => 15 },
778             has_16_today     => { date => '2004-03-01', expected_age => 16 },
779             had_16_yesterday => { date => '2004-02-29', expected_age => 16 },
780         },
781         {
782             today            => '2019-01-31',
783             has_12           => { date => '2006-08-27', expected_age => 12 },
784             almost_18        => { date => '2001-02-01', expected_age => 17 },
785             has_18_today     => { date => '2001-01-31', expected_age => 18 },
786             had_18_yesterday => { date => '2001-01-30', expected_age => 18 },
787             almost_16        => { date => '2003-02-01', expected_age => 15 },
788             has_16_today     => { date => '2003-01-31', expected_age => 16 },
789             had_16_yesterday => { date => '2003-01-30', expected_age => 16 },
790         },
791     );
792
793     $patron->dateofbirth( undef );
794     is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
795
796     for my $date ( @dates ) {
797
798         my $dt = dt_from_string($date->{today});
799
800         Time::Fake->offset( $dt->epoch );
801
802         for my $k ( keys %$date ) {
803             next if $k eq 'today';
804
805             my $dob = $date->{$k};
806             $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
807             is(
808                 $patron->get_age,
809                 $dob->{expected_age},
810                 sprintf(
811                     "Today=%s, dob=%s, should be %d",
812                     $date->{today}, $dob->{date}, $dob->{expected_age}
813                 )
814             );
815         }
816
817         Time::Fake->reset;
818
819     }
820
821     $patron->delete;
822 };
823
824 subtest 'is_valid_age' => sub {
825     plan tests => 10;
826
827     my $dt = dt_from_string('2020-02-28');
828
829     Time::Fake->offset( $dt->epoch );
830
831     my $category = $builder->build({
832         source => 'Category',
833         value => {
834             categorycode        => 'AGE_5_10',
835             dateofbirthrequired => 5,
836             upperagelimit       => 10
837         }
838     });
839     $category = Koha::Patron::Categories->find( $category->{categorycode} );
840
841     my $patron = $builder->build({
842         source => 'Borrower',
843         value => {
844             categorycode        => $category->categorycode
845         }
846     });
847     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
848
849
850     $patron->dateofbirth( undef );
851     is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
852
853     my @dates = (
854         {
855             today => '2020-02-28',
856             add_m12_m6_m1 =>
857               { date => '2007-08-27', expected_age => 12, valid => 0 },
858             add_m3_m6_m1 =>
859               { date => '2016-08-27', expected_age => 3, valid => 0 },
860             add_m7_m6_m1 =>
861               { date => '2013-02-28', expected_age => 7, valid => 1 },
862             add_m5_0_0 =>
863               { date => '2015-02-28', expected_age => 5, valid => 1 },
864             add_m5_0_p1 =>
865               { date => '2015-03-01', expected_age => 4, valid => 0 },
866             add_m5_0_m1 =>
867               { date => '2015-02-27', expected_age => 5, valid => 1 },
868             add_m11_0_0 =>
869               { date => '2009-02-28', expected_age => 11, valid => 0 },
870             add_m11_0_p1 =>
871               { date => '2009-03-01', expected_age => 10, valid => 1 },
872             add_m11_0_m1 =>
873               { date => '2009-02-27', expected_age => 11, valid => 0 },
874         },
875     );
876
877     for my $date ( @dates ) {
878
879         my $dt = dt_from_string($date->{today});
880
881         Time::Fake->offset( $dt->epoch );
882
883         for my $k ( sort keys %$date ) {
884             next if $k eq 'today';
885
886             my $dob = $date->{$k};
887             $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
888             is(
889                 $patron->is_valid_age,
890                 $dob->{valid},
891                 sprintf(
892                     "Today=%s, dob=%s, is %s, should be valid=%s in category %s",
893                     $date->{today}, $dob->{date}, $dob->{expected_age}, $dob->{valid}, $category->categorycode
894                 )
895             );
896         }
897
898         Time::Fake->reset;
899
900     }
901
902     $patron->delete;
903     $category->delete;
904 };
905
906 subtest 'account' => sub {
907     plan tests => 1;
908
909     my $patron = $builder->build({source => 'Borrower'});
910
911     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
912     my $account = $patron->account;
913     is( ref($account),   'Koha::Account', 'account should return a Koha::Account object' );
914
915     $patron->delete;
916 };
917
918 subtest 'search_upcoming_membership_expires' => sub {
919     plan tests => 9;
920
921     my $expiry_days = 15;
922     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
923     my $nb_of_days_before = 1;
924     my $nb_of_days_after = 2;
925
926     my $builder = t::lib::TestBuilder->new();
927
928     my $library = $builder->build({ source => 'Branch' });
929
930     # before we add borrowers to this branch, add the expires we have now
931     # note that this pertains to the current mocked setting of the pref
932     # for this reason we add the new branchcode to most of the tests
933     my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
934
935     my $patron_1 = $builder->build({
936         source => 'Borrower',
937         value  => {
938             branchcode              => $library->{branchcode},
939             dateexpiry              => dt_from_string->add( days => $expiry_days )
940         },
941     });
942
943     my $patron_2 = $builder->build({
944         source => 'Borrower',
945         value  => {
946             branchcode              => $library->{branchcode},
947             dateexpiry              => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
948         },
949     });
950
951     my $patron_3 = $builder->build({
952         source => 'Borrower',
953         value  => {
954             branchcode              => $library->{branchcode},
955             dateexpiry              => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
956         },
957     });
958
959     # Test without extra parameters
960     my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
961     is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
962
963     # Test with branch
964     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
965     is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
966     my $expired = $upcoming_mem_expires->next;
967     is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
968     is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
969     is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
970
971     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
972     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
973     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
974
975     # Test MembershipExpiryDaysNotice == undef
976     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
977     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
978     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
979
980     # Test the before parameter
981     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
982     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
983     is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
984     # Test after parameter also
985     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
986     is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
987     Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
988 };
989
990 subtest 'holds and old_holds' => sub {
991     plan tests => 6;
992
993     my $library = $builder->build( { source => 'Branch' } );
994     my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
995     my $item_1 = $builder->build_sample_item(
996         {
997             library      => $library->{branchcode},
998             biblionumber => $biblionumber_1,
999         }
1000     );
1001     my $item_2 = $builder->build_sample_item(
1002         {
1003             library      => $library->{branchcode},
1004             biblionumber => $biblionumber_1,
1005         }
1006     );
1007     my $biblionumber_2 = $builder->build_sample_biblio->biblionumber;
1008     my $item_3 = $builder->build_sample_item(
1009         {
1010             library      => $library->{branchcode},
1011             biblionumber => $biblionumber_2,
1012         }
1013     );
1014
1015     my $patron = $builder->build(
1016         {
1017             source => 'Borrower',
1018             value  => { branchcode => $library->{branchcode} }
1019         }
1020     );
1021
1022     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1023     my $holds = $patron->holds;
1024     is( ref($holds), 'Koha::Holds',
1025         'Koha::Patron->holds should return a Koha::Holds objects' );
1026     is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
1027
1028     C4::Reserves::AddReserve(
1029         {
1030             branchcode     => $library->{branchcode},
1031             borrowernumber => $patron->borrowernumber,
1032             biblionumber   => $biblionumber_1
1033         }
1034     );
1035     # In the future
1036     C4::Reserves::AddReserve(
1037         {
1038             branchcode      => $library->{branchcode},
1039             borrowernumber  => $patron->borrowernumber,
1040             biblionumber    => $biblionumber_2,
1041             expiration_date => dt_from_string->add( days => 2 )
1042         }
1043     );
1044
1045     $holds = $patron->holds;
1046     is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
1047
1048     my $old_holds = $patron->old_holds;
1049     is( ref($old_holds), 'Koha::Old::Holds',
1050         'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
1051     is( $old_holds->count, 0, 'There should not be any old holds yet');
1052
1053     my $hold = $holds->next;
1054     $hold->cancel;
1055
1056     $old_holds = $patron->old_holds;
1057     is( $old_holds->count, 1, 'There should  be 1 old (cancelled) hold');
1058
1059     $old_holds->delete;
1060     $holds->delete;
1061     $patron->delete;
1062 };
1063
1064 subtest 'notice_email_address' => sub {
1065     plan tests => 2;
1066
1067     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1068
1069     t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
1070     is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
1071
1072     t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
1073     is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
1074
1075     $patron->delete;
1076 };
1077
1078 subtest 'search_patrons_to_anonymise' => sub {
1079
1080     plan tests => 5;
1081
1082     # TODO create a subroutine in t::lib::Mocks
1083     my $branch = $builder->build({ source => 'Branch' });
1084     my $userenv_patron = $builder->build_object({
1085         class  => 'Koha::Patrons',
1086         value  => { branchcode => $branch->{branchcode}, flags => 0 },
1087     });
1088     t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
1089
1090     my $anonymous = $builder->build( { source => 'Borrower', }, );
1091
1092     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
1093
1094     subtest 'Anonymous Patron should be undeleteable' => sub {
1095         plan tests => 2;
1096
1097         my $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} );
1098         throws_ok { $anonymous_patron->delete(); }
1099             'Koha::Exceptions::Patron::FailedDeleteAnonymousPatron',
1100             'Attempt to delete anonymous patron throws exception.';
1101         $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} );
1102         is( $anonymous_patron->id, $anonymous->{borrowernumber}, "Anonymous Patron was not deleted" );
1103     };
1104
1105     subtest 'patron privacy is 1 (default)' => sub {
1106         plan tests => 9;
1107
1108         t::lib::Mocks::mock_preference('IndependentBranches', 0);
1109         my $patron = $builder->build(
1110             {   source => 'Borrower',
1111                 value  => { privacy => 1, }
1112             }
1113         );
1114         my $item_1 = $builder->build_sample_item;
1115         my $issue_1 = $builder->build(
1116             {   source => 'Issue',
1117                 value  => {
1118                     borrowernumber => $patron->{borrowernumber},
1119                     itemnumber     => $item_1->itemnumber,
1120                 },
1121             }
1122         );
1123         my $item_2 = $builder->build_sample_item;
1124         my $issue_2 = $builder->build(
1125             {   source => 'Issue',
1126                 value  => {
1127                     borrowernumber => $patron->{borrowernumber},
1128                     itemnumber     => $item_2->itemnumber,
1129                 },
1130             }
1131         );
1132
1133         my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->barcode, undef, undef, dt_from_string('2010-10-10') );
1134         my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->barcode, undef, undef, dt_from_string('2011-11-11') );
1135         is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1136
1137         my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1138         is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1139
1140         my $rows_affected = Koha::Old::Checkouts->search(
1141             {
1142                 borrowernumber => [
1143                     Koha::Patrons->search_patrons_to_anonymise(
1144                         { before => '2011-11-12' }
1145                     )->get_column('borrowernumber')
1146                 ],
1147                 returndate => { '<' => '2011-10-11', }
1148             }
1149         )->anonymize;
1150         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1151
1152         $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1153         is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1154
1155         my $dbh = C4::Context->dbh;
1156         my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1157         $sth->execute($item_1->itemnumber);
1158         my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1159         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1160         $sth->execute($item_2->itemnumber);
1161         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1162         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1163
1164         $rows_affected = Koha::Old::Checkouts->search(
1165             {
1166                 borrowernumber => [
1167                     Koha::Patrons->search_patrons_to_anonymise(
1168                         { before => '2011-11-12' }
1169                     )->get_column('borrowernumber')
1170                 ],
1171                 returndate => { '<' => '2011-11-12', }
1172             }
1173         )->anonymize;
1174         $sth->execute($item_2->itemnumber);
1175         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1176         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1177
1178         my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1179         $sth_reset->execute( $patron->{borrowernumber}, $item_1->itemnumber );
1180         $sth_reset->execute( $patron->{borrowernumber}, $item_2->itemnumber );
1181         $rows_affected = Koha::Old::Checkouts->search(
1182             {
1183                 borrowernumber => [
1184                     Koha::Patrons->search_patrons_to_anonymise->get_column(
1185                         'borrowernumber')
1186                 ]
1187             }
1188         )->anonymize;
1189         $sth->execute($item_1->itemnumber);
1190         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1191         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1192         $sth->execute($item_2->itemnumber);
1193         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1194         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1195
1196         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1197     };
1198
1199     subtest 'patron privacy is 0 (forever)' => sub {
1200         plan tests => 2;
1201
1202         t::lib::Mocks::mock_preference('IndependentBranches', 0);
1203         my $patron = $builder->build(
1204             {   source => 'Borrower',
1205                 value  => { privacy => 0, }
1206             }
1207         );
1208         my $item = $builder->build_sample_item;
1209         my $issue = $builder->build(
1210             {   source => 'Issue',
1211                 value  => {
1212                     borrowernumber => $patron->{borrowernumber},
1213                     itemnumber     => $item->itemnumber,
1214                 },
1215             }
1216         );
1217
1218         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1219         is( $returned, 1, 'The item should have been returned' );
1220
1221         my $dbh = C4::Context->dbh;
1222         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1223             SELECT borrowernumber FROM old_issues where itemnumber = ?
1224         |, undef, $item->itemnumber);
1225         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1226         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1227     };
1228
1229     t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1230
1231     subtest 'AnonymousPatron is not defined' => sub {
1232
1233         plan tests => 2;
1234
1235         t::lib::Mocks::mock_preference('IndependentBranches', 0);
1236         my $patron = $builder->build(
1237             {   source => 'Borrower',
1238                 value  => { privacy => 1, }
1239             }
1240         );
1241         my $item = $builder->build_sample_item;
1242         my $issue = $builder->build(
1243             {   source => 'Issue',
1244                 value  => {
1245                     borrowernumber => $patron->{borrowernumber},
1246                     itemnumber     => $item->itemnumber,
1247                 },
1248             }
1249         );
1250
1251         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1252         is( $returned, 1, 'The item should have been returned' );
1253         my $patrons_to_anonymize = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1254         ok( $patrons_to_anonymize->count > 0, 'search_patrons_to_anonymize' );
1255
1256         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1257     };
1258
1259     subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1260         plan tests => 1;
1261         t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1262         my $patron = $builder->build(
1263             {   source => 'Borrower',
1264                 value  => { privacy => 1 }    # Another branchcode than the logged in librarian
1265             }
1266         );
1267         my $item = $builder->build_sample_item;
1268         my $issue = $builder->build(
1269             {   source => 'Issue',
1270                 value  => {
1271                     borrowernumber => $patron->{borrowernumber},
1272                     itemnumber     => $item->itemnumber,
1273                 },
1274             }
1275         );
1276
1277         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1278         is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1279         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1280     };
1281
1282     Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1283     $userenv_patron->delete;
1284
1285     # Reset IndependentBranches for further tests
1286     t::lib::Mocks::mock_preference('IndependentBranches', 0);
1287 };
1288
1289 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1290     plan tests => 3;
1291
1292     # group1
1293     #   + library_11
1294     #   + library_12
1295     # group2
1296     #   + library21
1297     $nb_of_patrons = Koha::Patrons->search->count;
1298     my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1299     my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1300     my $library_11 = $builder->build( { source => 'Branch' } );
1301     my $library_12 = $builder->build( { source => 'Branch' } );
1302     my $library_21 = $builder->build( { source => 'Branch' } );
1303     $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1304     $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1305     $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1306     Koha::Library::Group->new(
1307         { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1308     Koha::Library::Group->new(
1309         { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1310     Koha::Library::Group->new(
1311         { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1312
1313     my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1314     # 2 patrons from library_11 (group1)
1315     # patron_11_1 see patron's infos from outside its group
1316     # Setting flags => undef to not be considered as superlibrarian
1317     my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1318     $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1319     $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1320     $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1321     # patron_11_2 can only see patron's info from its group
1322     my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1323     $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1324     $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1325     # 1 patron from library_12 (group1)
1326     my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1327     $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1328     # 1 patron from library_21 (group2) can only see patron's info from its group
1329     my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1330     $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1331     $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1332
1333     # Pfiou, we can start now!
1334     subtest 'libraries_where_can_see_patrons' => sub {
1335         plan tests => 3;
1336
1337         my @branchcodes;
1338
1339         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1340         @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1341         is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1342
1343         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1344         @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1345         is_deeply( \@branchcodes, [ sort ( $library_11->branchcode, $library_12->branchcode ) ], q|patron_11_2 has not view_borrower_infos_from_any_libraries => Can only see patron's from its group| );
1346
1347         t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1348         @branchcodes = $patron_21->libraries_where_can_see_patrons;
1349         is_deeply( \@branchcodes, [$library_21->branchcode], q|patron_21 has not view_borrower_infos_from_any_libraries => Can only see patron's from its group| );
1350     };
1351     subtest 'can_see_patron_infos' => sub {
1352         plan tests => 6;
1353
1354         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1355         is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1356         is( $patron_11_1->can_see_patron_infos( $patron_12 ),   1, q|patron_11_1 can see patron_12, from its group| );
1357         is( $patron_11_1->can_see_patron_infos( $patron_21 ),   1, q|patron_11_1 can see patron_11_2, from another group| );
1358
1359         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1360         is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1361         is( $patron_11_2->can_see_patron_infos( $patron_12 ),   1, q|patron_11_2 can see patron_12, from its group| );
1362         is( $patron_11_2->can_see_patron_infos( $patron_21 ),   0, q|patron_11_2 can NOT see patron_21, from another group| );
1363     };
1364     subtest 'search_limited' => sub {
1365         plan tests => 6;
1366
1367         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1368         my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1369         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1370         is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1371
1372         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1373         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1374         is( Koha::Patrons->search_limited->count, 3, 'patron_12_1 is not allowed to see patrons from other groups, only patron_11_1, patron_11_2 and patron_12' );
1375
1376         t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1377         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1378         is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1379     };
1380     $patron_11_1->delete;
1381     $patron_11_2->delete;
1382     $patron_12->delete;
1383     $patron_21->delete;
1384 };
1385
1386 subtest 'account_locked' => sub {
1387     plan tests => 13;
1388     my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1389     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1390     for my $value ( undef, '', 0 ) {
1391         t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1392         $patron->login_attempts(0)->store;
1393         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1394         $patron->login_attempts(1)->store;
1395         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1396         $patron->login_attempts(-1)->store;
1397         is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1398     }
1399
1400     t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1401     $patron->login_attempts(2)->store;
1402     is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1403     $patron->login_attempts(3)->store;
1404     is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1405     $patron->login_attempts(4)->store;
1406     is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1407     $patron->login_attempts(-1)->store;
1408     is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1409
1410     $patron->delete;
1411 };
1412
1413 subtest 'is_child | is_adult' => sub {
1414     plan tests => 8;
1415     my $category = $builder->build_object(
1416         {
1417             class => 'Koha::Patron::Categories',
1418             value => { category_type => 'A' }
1419         }
1420     );
1421     my $patron_adult = $builder->build_object(
1422         {
1423             class => 'Koha::Patrons',
1424             value => { categorycode => $category->categorycode }
1425         }
1426     );
1427     $category = $builder->build_object(
1428         {
1429             class => 'Koha::Patron::Categories',
1430             value => { category_type => 'I' }
1431         }
1432     );
1433     my $patron_adult_i = $builder->build_object(
1434         {
1435             class => 'Koha::Patrons',
1436             value => { categorycode => $category->categorycode }
1437         }
1438     );
1439     $category = $builder->build_object(
1440         {
1441             class => 'Koha::Patron::Categories',
1442             value => { category_type => 'C' }
1443         }
1444     );
1445     my $patron_child = $builder->build_object(
1446         {
1447             class => 'Koha::Patrons',
1448             value => { categorycode => $category->categorycode }
1449         }
1450     );
1451     $category = $builder->build_object(
1452         {
1453             class => 'Koha::Patron::Categories',
1454             value => { category_type => 'O' }
1455         }
1456     );
1457     my $patron_other = $builder->build_object(
1458         {
1459             class => 'Koha::Patrons',
1460             value => { categorycode => $category->categorycode }
1461         }
1462     );
1463     is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1464     is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1465     is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1466     is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1467
1468     is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1469     is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1470     is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1471     is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1472
1473     # Clean up
1474     $patron_adult->delete;
1475     $patron_adult_i->delete;
1476     $patron_child->delete;
1477     $patron_other->delete;
1478 };
1479
1480 subtest 'overdues' => sub {
1481     plan tests => 7;
1482
1483     my $library = $builder->build( { source => 'Branch' } );
1484     my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
1485     my $item_1 = $builder->build_sample_item(
1486         {
1487             library      => $library->{branchcode},
1488             biblionumber => $biblionumber_1,
1489         }
1490     );
1491     my $item_2 = $builder->build_sample_item(
1492         {
1493             library      => $library->{branchcode},
1494             biblionumber => $biblionumber_1,
1495         }
1496     );
1497     my $item_3 = $builder->build_sample_item(
1498         {
1499             library      => $library->{branchcode},
1500         }
1501     );
1502
1503     my $patron = $builder->build(
1504         {
1505             source => 'Borrower',
1506             value  => { branchcode => $library->{branchcode} }
1507         }
1508     );
1509
1510     t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1511
1512     AddIssue( $patron, $item_1->barcode, DateTime->now->subtract( days => 1 ) );
1513     AddIssue( $patron, $item_2->barcode, DateTime->now->subtract( days => 5 ) );
1514     AddIssue( $patron, $item_3->barcode );
1515
1516     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1517     my $overdues = $patron->overdues;
1518     is( $overdues->count, 2, 'Patron should have 2 overdues');
1519     is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' );
1520     is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' );
1521
1522     my $o = $overdues->reset->next;
1523     my $unblessed_overdue = $o->unblessed_all_relateds;
1524     is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1525     is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1526     is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1527     is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1528
1529     # Clean stuffs
1530     $patron->checkouts->delete;
1531     $patron->delete;
1532 };
1533
1534 subtest 'userid_is_valid' => sub {
1535     plan tests => 9;
1536
1537     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1538     my $patron_category = $builder->build_object(
1539         {
1540             class => 'Koha::Patron::Categories',
1541             value => { category_type => 'P', enrolmentfee => 0 }
1542         }
1543     );
1544     my %data = (
1545         cardnumber   => "123456789",
1546         firstname    => "Tomasito",
1547         surname      => "None",
1548         categorycode => $patron_category->categorycode,
1549         branchcode   => $library->branchcode,
1550     );
1551
1552     my $expected_userid_patron_1 = 'tomasito.none';
1553     my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1554     my $patron_1       = Koha::Patrons->find($borrowernumber);
1555     is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1556     is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1557
1558     $patron_1->userid( 'tomasito.non' );
1559     is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1560         1, 'recently created userid -> unique (borrowernumber passed)' );
1561
1562     $patron_1->userid( 'tomasitoxxx' );
1563     is( $patron_1->has_valid_userid,
1564         1, 'non-existent userid -> unique (borrowernumber passed)' );
1565     $patron_1->discard_changes; # We compare with the original userid later
1566
1567     my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1568     is( $patron_not_in_storage->has_valid_userid,
1569         0, 'userid exists for another patron, patron is not in storage yet' );
1570
1571     $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1572     is( $patron_not_in_storage->has_valid_userid,
1573         1, 'non-existent userid, patron is not in storage yet' );
1574
1575     # Regression tests for BZ12226
1576     my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1577     is( $db_patron->has_valid_userid,
1578         0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1579
1580     # Add a new borrower with the same userid but different cardnumber
1581     $data{cardnumber} = "987654321";
1582     my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1583     my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1584     $patron_2->userid($patron_1->userid);
1585     is( $patron_2->has_valid_userid,
1586         0, 'The userid is already in used, it cannot be used for another patron' );
1587
1588     my $new_userid = 'a_user_id';
1589     $data{cardnumber} = "234567890";
1590     $data{userid}     = 'a_user_id';
1591     $borrowernumber   = Koha::Patron->new(\%data)->store->borrowernumber;
1592     my $patron_3 = Koha::Patrons->find($borrowernumber);
1593     is( $patron_3->userid, $new_userid,
1594         'Koha::Patron->store should insert the given userid' );
1595
1596     # Cleanup
1597     $patron_1->delete;
1598     $patron_2->delete;
1599     $patron_3->delete;
1600 };
1601
1602 subtest 'generate_userid' => sub {
1603     plan tests => 7;
1604
1605     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1606     my $patron_category = $builder->build_object(
1607         {
1608             class => 'Koha::Patron::Categories',
1609             value => { category_type => 'P', enrolmentfee => 0 }
1610         }
1611     );
1612     my %data = (
1613         cardnumber   => "123456789",
1614         firstname    => "Tômàsító",
1615         surname      => "Ñoné",
1616         categorycode => $patron_category->categorycode,
1617         branchcode   => $library->branchcode,
1618     );
1619
1620     my $expected_userid_patron_1 = 'tomasito.none';
1621     my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1622     $new_patron->generate_userid;
1623     my $userid = $new_patron->userid;
1624     is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1625     my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1626     my $patron_1 = Koha::Patrons->find($borrowernumber);
1627     is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1628
1629     $new_patron->generate_userid;
1630     $userid = $new_patron->userid;
1631     is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1632     $data{cardnumber} = '987654321';
1633     my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1634     my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1635     isnt( $patron_2->userid, 'tomasito',
1636         "Patron with duplicate userid has new userid generated" );
1637     is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1638         "Patron with duplicate userid has new userid generated (1 is appened" );
1639
1640     $new_patron->generate_userid;
1641     $userid = $new_patron->userid;
1642     is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1643
1644     $patron_1 = Koha::Patrons->find($borrowernumber);
1645     $patron_1->userid(undef);
1646     $patron_1->generate_userid;
1647     $userid = $patron_1->userid;
1648     is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1649
1650     # Cleanup
1651     $patron_1->delete;
1652     $patron_2->delete;
1653 };
1654
1655 $nb_of_patrons = Koha::Patrons->search->count;
1656 $retrieved_patron_1->delete;
1657 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1658
1659 subtest 'BorrowersLog tests' => sub {
1660     plan tests => 4;
1661
1662     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1663     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1664
1665     my $cardnumber = $patron->cardnumber;
1666     $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1667     $patron->store;
1668
1669     my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1670     my $log_info = from_json( $logs[0]->info );
1671     is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1672     is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1673     is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1674
1675     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1676     $patron->track_login();
1677     @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1678     is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1679 };
1680
1681 $schema->storage->txn_rollback;
1682
1683 subtest 'Test Koha::Patrons::merge' => sub {
1684     plan tests => 110;
1685
1686     my $schema = Koha::Database->new()->schema();
1687
1688     my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1689
1690     $schema->storage->txn_begin;
1691
1692     my $keeper  = $builder->build_object({ class => 'Koha::Patrons' });
1693     my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1694     my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1695
1696     my $anonymous_patron_orig = C4::Context->preference('AnonymousPatron');
1697     my $anonymous_patron = $builder->build({ source => 'Borrower' })->{borrowernumber};
1698     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron );
1699
1700     while (my ($r, $field) = each(%$resultsets)) {
1701         $builder->build({ source => $r, value => { $field => $keeper->id } });
1702         $builder->build({ source => $r, value => { $field => $loser_1 } });
1703         $builder->build({ source => $r, value => { $field => $loser_2 } });
1704
1705         my $keeper_rs =
1706           $schema->resultset($r)->search( { $field => $keeper->id } );
1707         is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1708
1709         my $loser_1_rs =
1710           $schema->resultset($r)->search( { $field => $loser_1 } );
1711         is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1712
1713         my $loser_2_rs =
1714           $schema->resultset($r)->search( { $field => $loser_2 } );
1715         is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1716     }
1717
1718     my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1719
1720     while (my ($r, $field) = each(%$resultsets)) {
1721         my $keeper_rs =
1722           $schema->resultset($r)->search( {$field => $keeper->id } );
1723         is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1724     }
1725
1726     is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1727     is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1728     is( ref Koha::Patrons->find($anonymous_patron), 'Koha::Patron', 'Anonymous Patron was not deleted' );
1729
1730     $anonymous_patron = Koha::Patrons->find($anonymous_patron);
1731     $results = $anonymous_patron->merge_with( [ $keeper->id ] );
1732     is( $results, undef, "Anonymous patron cannot have other patrons merged into it" );
1733     is( Koha::Patrons->search( { borrowernumber => $keeper->id } )->count, 1, "Patron from attempted merge with AnonymousPatron still exists" );
1734
1735     subtest 'extended attributes' => sub {
1736         plan tests => 8;
1737
1738         my $keep_patron =
1739           $builder->build_object( { class => 'Koha::Patrons' } );
1740         my $merge_patron =
1741           $builder->build_object( { class => 'Koha::Patrons' } );
1742
1743         my $attribute_type_normal_1 = $builder->build_object(
1744             {
1745                 class => 'Koha::Patron::Attribute::Types',
1746                 value => { repeatable => 0, unique_id => 0 }
1747             }
1748         );
1749         my $attribute_type_normal_2 = $builder->build_object(
1750             {
1751                 class => 'Koha::Patron::Attribute::Types',
1752                 value => { repeatable => 0, unique_id => 0 }
1753             }
1754         );
1755
1756         my $attribute_type_repeatable = $builder->build_object(
1757             {
1758                 class => 'Koha::Patron::Attribute::Types',
1759                 value => { repeatable => 1, unique_id => 0 }
1760             }
1761         );
1762
1763         my $attr_keep = [
1764             {
1765                 code      => $attribute_type_normal_1->code,
1766                 attribute => 'from attr 1'
1767             },
1768             {
1769                 code      => $attribute_type_repeatable->code,
1770                 attribute => 'from attr repeatable'
1771             }
1772         ];
1773
1774         my $attr_merge = [
1775             {
1776                 code      => $attribute_type_normal_2->code,
1777                 attribute => 'to attr 2'
1778             },
1779             {
1780                 code      => $attribute_type_repeatable->code,
1781                 attribute => 'to attr repeatable'
1782             },
1783         ];
1784
1785         $keep_patron->extended_attributes($attr_keep);
1786         $merge_patron->extended_attributes($attr_merge);
1787
1788         $keep_patron->merge_with( [ $merge_patron->borrowernumber ] );
1789         my $merged_attributes = $keep_patron->extended_attributes;
1790         is( $merged_attributes->count, 4 );
1791
1792         sub compare_attributes {
1793             my ( $got, $expected, $code ) = @_;
1794
1795             is_deeply(
1796                 [
1797                     sort $got->search( { code => $code } )
1798                       ->get_column('attribute')
1799                 ],
1800                 $expected
1801             );
1802         }
1803         compare_attributes(
1804             $merged_attributes,
1805             ['from attr 1'],
1806             $attribute_type_normal_1->code
1807         );
1808         compare_attributes(
1809             $merged_attributes,
1810             ['to attr 2'],
1811             $attribute_type_normal_2->code
1812         );
1813         compare_attributes(
1814             $merged_attributes,
1815             [ 'from attr repeatable', 'to attr repeatable' ],
1816             $attribute_type_repeatable->code
1817         );
1818
1819         # Cleanup
1820         $keep_patron->delete;
1821         $merge_patron->delete;
1822
1823         # Recreate but don't expect an exception if 2 non-repeatable attributes exist, pick the one from the patron we keep
1824         $keep_patron =
1825           $builder->build_object( { class => 'Koha::Patrons' } );
1826         $merge_patron =
1827           $builder->build_object( { class => 'Koha::Patrons' } );
1828
1829         $keep_patron->extended_attributes($attr_keep);
1830         $merge_patron->extended_attributes(
1831             [
1832                 @$attr_merge,
1833                 {
1834                     code      => $attribute_type_normal_1->code,
1835                     attribute => 'yet another attribute for non-repeatable'
1836                 }
1837             ]
1838         );
1839
1840         $keep_patron->merge_with( [ $merge_patron->borrowernumber ] );
1841         $merged_attributes = $keep_patron->extended_attributes;
1842         is( $merged_attributes->count, 4 );
1843         compare_attributes(
1844             $merged_attributes,
1845             ['from attr 1'],
1846             $attribute_type_normal_1->code
1847         );
1848         compare_attributes(
1849             $merged_attributes,
1850             ['to attr 2'],
1851             $attribute_type_normal_2->code
1852         );
1853         compare_attributes(
1854             $merged_attributes,
1855             [ 'from attr repeatable', 'to attr repeatable' ],
1856             $attribute_type_repeatable->code
1857         );
1858
1859     };
1860
1861     t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1862     $schema->storage->txn_rollback;
1863 };
1864
1865 subtest '->store' => sub {
1866     plan tests => 8;
1867     my $schema = Koha::Database->new->schema;
1868     $schema->storage->txn_begin;
1869
1870     my $print_error = $schema->storage->dbh->{PrintError};
1871     $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1872
1873     my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1874     my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1875
1876     {
1877         local *STDERR;
1878         open STDERR, '>', '/dev/null';
1879         throws_ok { $patron_2->userid( $patron_1->userid )->store; }
1880         'Koha::Exceptions::Object::DuplicateID',
1881           'Koha::Patron->store raises an exception on duplicate ID';
1882         close STDERR;
1883     }
1884
1885     # Test password
1886     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1887     my $password = 'password';
1888     $patron_1->set_password({ password => $password });
1889     like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1890     my $digest = $patron_1->password;
1891     $patron_1->surname('xxx')->store;
1892     is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1893
1894     # Test uppercasesurnames
1895     t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1896     my $surname = lc $patron_1->surname;
1897     $patron_1->surname($surname)->store;
1898     isnt( $patron_1->surname, $surname,
1899         'Surname converts to uppercase on store.');
1900     t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1901     $patron_1->surname($surname)->store;
1902     is( $patron_1->surname, $surname,
1903         'Surname remains unchanged on store.');
1904
1905     # Test relationship
1906     $patron_1->relationship("")->store;
1907     is( $patron_1->relationship, undef, );
1908
1909     $schema->storage->dbh->{PrintError} = $print_error;
1910     $schema->storage->txn_rollback;
1911
1912     subtest 'skip updated_on for BorrowersLog' => sub {
1913         plan tests => 1;
1914         $schema->storage->txn_begin;
1915         t::lib::Mocks::mock_preference('BorrowersLog', 1);
1916         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1917         $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1918         my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1919         is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1920         $schema->storage->txn_rollback;
1921     };
1922
1923     subtest 'create user usage' => sub {
1924         plan tests => 1;
1925         $schema->storage->txn_begin;
1926
1927         my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1928         my $patron_category = $builder->build_object(
1929             {
1930                 class => 'Koha::Patron::Categories',
1931                 value => { category_type => 'P', enrolmentfee => 0 }
1932             }
1933         );
1934         my %data = (
1935             cardnumber   => "123456789",
1936             firstname    => "Tômàsító",
1937             surname      => "Ñoné",
1938             password     => 'Funk3y',
1939             categorycode => $patron_category->categorycode,
1940             branchcode   => $library->branchcode,
1941         );
1942
1943         # Enable notifying patrons of password changes for these tests
1944         t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 1 );
1945         my $new_patron     = Koha::Patron->new( \%data )->store();
1946         my $queued_notices = Koha::Notice::Messages->search(
1947             { borrowernumber => $new_patron->borrowernumber }
1948         );
1949         is(
1950             $queued_notices->count, 0,
1951             "No notice queued when NotifyPasswordChange enabled and this is a new patron"
1952         );
1953
1954         $schema->storage->txn_rollback;
1955     };
1956 };
1957
1958 subtest '->set_password' => sub {
1959
1960     plan tests => 16;
1961
1962     $schema->storage->txn_begin;
1963
1964     my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1965
1966     # Disable logging password changes for these tests
1967     t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1968
1969     # Disable notifying patrons of password changes for these tests
1970     t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 0 );
1971
1972     # Password-length tests
1973     t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1974     throws_ok { $patron->set_password({ password => 'ab' }); }
1975         'Koha::Exceptions::Password::TooShort',
1976         'minPasswordLength is undef, fall back to 3, fail test';
1977     is( "$@",
1978         'Password length (2) is shorter than required (3)',
1979         'Exception parameters passed correctly'
1980     );
1981
1982     t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1983     throws_ok { $patron->set_password({ password => 'ab' }); }
1984         'Koha::Exceptions::Password::TooShort',
1985         'minPasswordLength is 2, fall back to 3, fail test';
1986
1987     t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1988     throws_ok { $patron->set_password({ password => 'abcb' }); }
1989         'Koha::Exceptions::Password::TooShort',
1990         'minPasswordLength is 5, fail test';
1991
1992     # Trailing spaces tests
1993     throws_ok { $patron->set_password({ password => 'abcD12d   ' }); }
1994         'Koha::Exceptions::Password::WhitespaceCharacters',
1995         'Password contains trailing spaces, exception is thrown';
1996
1997     # Require strong password tests
1998     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1999     throws_ok { $patron->set_password({ password => 'abcd   a' }); }
2000         'Koha::Exceptions::Password::TooWeak',
2001         'Password is too weak, exception is thrown';
2002
2003     # Refresh patron from DB, just to make sure
2004     $patron->discard_changes;
2005     is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
2006
2007     $patron->set_password({ password => 'abcD12 34' });
2008     $patron->discard_changes;
2009
2010     is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
2011
2012     lives_ok { $patron->set_password({ password => 'abcd   a', skip_validation => 1 }) }
2013         'Password is weak, but skip_validation was passed, so no exception thrown';
2014
2015     # Completeness
2016     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
2017     $patron->login_attempts(3)->store;
2018     my $old_digest = $patron->password;
2019     $patron->set_password({ password => 'abcd   a' });
2020     $patron->discard_changes;
2021
2022     isnt( $patron->password, $old_digest, 'Password has been updated' );
2023     ok( checkpw_hash('abcd   a', $patron->password), 'Password hash is correct' );
2024     is( $patron->login_attempts, 0, 'Login attemps have been reset' );
2025
2026     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
2027     is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
2028
2029     # Enable logging password changes
2030     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
2031     $patron->set_password({ password => 'abcd   b' });
2032
2033     $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
2034     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
2035
2036     # Enable notifying patrons of password changes
2037     t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 1 );
2038     $patron->set_password({ password => 'abcd   c' });
2039     my $queued_notices = Koha::Notice::Messages->search({ borrowernumber => $patron->borrowernumber });
2040     is( $queued_notices->count, 1, "One notice queued when NotifyPasswordChange enabled" );
2041     my $THE_notice = $queued_notices->next;
2042     is( $THE_notice->status, 'failed', "The notice was handled immediately and failed on wrong email address."); #FIXME Mock sending mail
2043     $schema->storage->txn_rollback;
2044 };
2045
2046 $schema->storage->txn_begin;
2047 subtest 'filter_by_expiration_date' => sub {
2048     plan tests => 3;
2049     my $count1 = Koha::Patrons->filter_by_expiration_date({ days => 28 })->count;
2050     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2051     $patron1->dateexpiry( dt_from_string->subtract(days => 27) )->store;
2052     is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1, 'No more expired' );
2053     $patron1->dateexpiry( dt_from_string->subtract(days => 28) )->store;
2054     is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'One more expired' );
2055     $patron1->dateexpiry( dt_from_string->subtract(days => 29) )->store;
2056     is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'Same number again' );
2057 };
2058
2059 subtest 'search_unsubscribed' => sub {
2060     plan tests => 4;
2061
2062     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2063     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
2064     is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
2065
2066     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2067     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2068
2069     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
2070     Koha::Patron::Consents->delete; # for correct counts
2071     Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING',  refused_on => dt_from_string })->store;
2072     is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
2073
2074     # Add another refusal but shift the period
2075     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
2076     Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING',  refused_on => dt_from_string->subtract(days=>2) })->store;
2077     is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
2078
2079     # Try another (special) attempts setting
2080     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
2081     # Lockout is now disabled
2082     # Patron2 still matches: refused earlier, not locked
2083     is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
2084 };
2085
2086 subtest 'search_anonymize_candidates' => sub {
2087     plan tests => 7;
2088     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2089     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2090     $patron1->anonymized(0);
2091     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2092     $patron2->anonymized(0);
2093     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2094
2095     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
2096     is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
2097
2098     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
2099     my $cnt = Koha::Patrons->search_anonymize_candidates->count;
2100     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2101     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2102     is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
2103
2104     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
2105     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2106     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2107     $cnt = Koha::Patrons->search_anonymize_candidates->count;
2108     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2109     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2110     is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
2111
2112     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
2113     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2114     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2115     $cnt = Koha::Patrons->search_anonymize_candidates->count;
2116     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2117     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2118     is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
2119
2120     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2121     $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
2122     $patron1->login_attempts(0)->store;
2123     $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
2124     $patron2->login_attempts(0)->store;
2125     $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
2126     $patron1->login_attempts(3)->store;
2127     is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2128         $cnt+1, 'Locked flag' );
2129
2130     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
2131     # Patron 1 still on 3 == locked
2132     is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2133         $cnt+1, 'Still expect same number for FailedLoginAttempts empty' );
2134     $patron1->login_attempts(0)->store;
2135     # Patron 1 unlocked
2136     is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2137         $cnt, 'Patron 1 unlocked' );
2138 };
2139
2140 subtest 'search_anonymized' => sub {
2141     plan tests => 3;
2142     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2143
2144     t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
2145     is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
2146
2147     t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
2148     $patron1->dateexpiry( dt_from_string );
2149     $patron1->anonymized(0)->store;
2150     my $cnt = Koha::Patrons->search_anonymized->count;
2151     $patron1->anonymized(1)->store;
2152     is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
2153     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2154     is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
2155 };
2156
2157 subtest 'lock' => sub {
2158     plan tests => 8;
2159
2160     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2161     my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2162     my $hold = $builder->build_object({
2163         class => 'Koha::Holds',
2164         value => { borrowernumber => $patron1->borrowernumber },
2165     });
2166
2167     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2168     my $expiry = dt_from_string->add(days => 1);
2169     $patron1->dateexpiry( $expiry );
2170     $patron1->lock;
2171     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
2172     is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
2173     is( $patron1->holds->count, 1, 'No holds removed' );
2174
2175     $patron1->lock({ expire => 1, remove => 1});
2176     isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
2177     is( $patron1->holds->count, 0, 'Holds removed' );
2178
2179     # Disable lockout feature
2180     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
2181     $patron1->login_attempts(0);
2182     $patron1->dateexpiry( $expiry );
2183     $patron1->store;
2184     $patron1->lock;
2185     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
2186
2187     # Trivial wrapper test (Koha::Patrons->lock)
2188     $patron1->login_attempts(0)->store;
2189     Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
2190     $patron1->discard_changes; # refresh
2191     $patron2->discard_changes;
2192     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
2193     is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
2194 };
2195
2196 subtest 'anonymize' => sub {
2197     plan tests => 10;
2198
2199     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2200     my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2201
2202     # First try patron with issues
2203     my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
2204     warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
2205     $issue->delete;
2206
2207     t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
2208     my $surname = $patron1->surname; # expect change, no clear
2209     my $branchcode = $patron1->branchcode; # expect skip
2210     $patron1->anonymize;
2211     is($patron1->anonymized, 1, 'Check flag' );
2212
2213     is( $patron1->dateofbirth, undef, 'Birth date cleared' );
2214     is( $patron1->firstname, undef, 'First name cleared' );
2215     isnt( $patron1->surname, $surname, 'Surname changed' );
2216     ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
2217     is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
2218     is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
2219
2220     # Test wrapper in Koha::Patrons
2221     $patron1->surname($surname)->store; # restore
2222     my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
2223     $patron1->discard_changes; # refresh
2224     isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
2225     $patron2->discard_changes; # refresh
2226     is( $patron2->firstname, undef, 'First name patron2 cleared' );
2227 };
2228
2229 subtest 'queue_notice' => sub {
2230     plan tests => 11;
2231
2232     my $dbh = C4::Context->dbh;
2233     t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'email' );
2234     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2235     my $branch = $builder->build_object( { class => 'Koha::Libraries' } );
2236     my $letter_e = $builder->build_object( {
2237         class => 'Koha::Notice::Templates',
2238         value => {
2239             branchcode => $branch->branchcode,
2240             message_transport_type => 'email',
2241             lang => 'default'
2242         }
2243     });
2244     my $letter_p = $builder->build_object( {
2245         class => 'Koha::Notice::Templates',
2246         value => {
2247             code => $letter_e->code,
2248             module => $letter_e->module,
2249             branchcode => $branch->branchcode,
2250             message_transport_type => 'print',
2251             lang => 'default'
2252         }
2253     });
2254     my $letter_s = $builder->build_object( {
2255         class => 'Koha::Notice::Templates',
2256         value => {
2257             code => $letter_e->code,
2258             module => $letter_e->module,
2259             branchcode => $branch->branchcode,
2260             message_transport_type => 'sms',
2261             lang => 'default'
2262         }
2263     });
2264
2265     my $letter_params = {
2266         letter_code => $letter_e->code,
2267         branchcode  => $letter_e->branchcode,
2268         module      => $letter_e->module,
2269         borrowernumber => $patron->borrowernumber,
2270         tables => {
2271             borrowers => $patron->borrowernumber,
2272         }
2273     };
2274     my @mtts = ('email');
2275
2276     is( $patron->queue_notice(), undef, "Nothing is done if no params passed");
2277     is( $patron->queue_notice({ letter_params => $letter_params }),undef, "Nothing done if only letter");
2278     is_deeply(
2279         $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2280         {sent => ['email'] }, "Email sent"
2281     );
2282     $patron->email("")->store;
2283     is_deeply(
2284         $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2285         {sent => ['print'],fallback => ['email']}, "Email fallsback to print if no email"
2286     );
2287     push @mtts, 'sms';
2288     is_deeply(
2289         $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2290         {sent => ['print','sms'],fallback => ['email']}, "Email fallsback to print if no email, sms sent"
2291     );
2292     $patron->smsalertnumber("")->store;
2293     my $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count;
2294     is_deeply(
2295         $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2296         {sent => ['print'],fallback => ['email','sms']}, "Email fallsback to print if no emai, sms fallsback to print if no sms, only one print sent"
2297     );
2298     is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter+1,"Count of queued notices went up by one");
2299
2300     # Enable notification for Hold_Filled - Things are hardcoded here but should work with default data
2301     $dbh->do(q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ?)|, undef, $patron->borrowernumber, 4 );
2302     my $borrower_message_preference_id = $dbh->last_insert_id(undef, undef, "borrower_message_preferences", undef);
2303     $dbh->do(q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' );
2304
2305     is( $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts, message_name => 'Hold_Filled' }),undef, "Nothing done if transports and name sent");
2306
2307     $patron->email(q|awesome@ismymiddle.name|)->store;
2308     is_deeply(
2309         $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled' }),
2310         {sent => ['email'] }, "Email sent when using borrower preferences"
2311     );
2312     $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count;
2313     is_deeply(
2314         $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled', test_mode => 1 }),
2315         {sent => ['email'] }, "Report that email sent when using borrower preferences in test_mode"
2316     );
2317     is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter,"Count of queued notices not increased in test mode");
2318 };
2319
2320 subtest 'filter_by_amount_owed' => sub {
2321     plan tests => 6;
2322
2323     my $library = $builder->build({source => 'Branch' });
2324     my $category = $builder->build({source => 'Category' });
2325
2326     my $new_patron_cf_1 = Koha::Patron->new(
2327         {
2328             cardnumber   => 'test_cn_cf_1',
2329             branchcode   => $library->{branchcode},
2330             categorycode => $category->{categorycode},
2331             surname      => 'surname for patron1',
2332             firstname    => 'firstname for patron1',
2333             userid       => 'a_nonexistent_userid_cf_1',
2334         }
2335     )->store;
2336     my $new_patron_cf_2 = Koha::Patron->new(
2337         {
2338             cardnumber   => 'test_cn_cf_2',
2339             branchcode   => $library->{branchcode},
2340             categorycode => $category->{categorycode},
2341             surname      => 'surname for patron2',
2342             firstname    => 'firstname for patron2',
2343             userid       => 'a_nonexistent_userid_cf_2',
2344         }
2345     )->store;
2346     my $new_patron_cf_3 = Koha::Patron->new(
2347         {
2348             cardnumber   => 'test_cn_cf_3',
2349             branchcode   => $library->{branchcode},
2350             categorycode => $category->{categorycode},
2351             surname      => 'surname for patron3',
2352             firstname    => 'firstname for patron3',
2353             userid       => 'a_nonexistent_userid_cf_3',
2354         }
2355     )->store;
2356
2357     my $results = Koha::Patrons->search(
2358         {
2359             'me.borrowernumber' => [
2360                 $new_patron_cf_1->borrowernumber,
2361                 $new_patron_cf_2->borrowernumber,
2362                 $new_patron_cf_3->borrowernumber
2363             ]
2364         }
2365     );
2366
2367     my $fine1 = $builder->build(
2368         {
2369             source => 'Accountline',
2370             value  => {
2371                 borrowernumber    => $new_patron_cf_1->borrowernumber,
2372                 amountoutstanding => 12.00,
2373                 amount            => 12.00,
2374                 debit_type_code   => 'OVERDUE',
2375                 branchcode        => $library->{branchcode}
2376             },
2377         }
2378     );
2379     my $fine2 = $builder->build(
2380         {
2381             source => 'Accountline',
2382             value  => {
2383                 borrowernumber    => $new_patron_cf_2->borrowernumber,
2384                 amountoutstanding => 8.00,
2385                 amount            => 8.00,
2386                 debit_type_code   => 'OVERDUE',
2387                 branchcode        => $library->{branchcode}
2388
2389             },
2390         }
2391     );
2392     my $fine3 = $builder->build(
2393         {
2394             source => 'Accountline',
2395             value  => {
2396                 borrowernumber    => $new_patron_cf_2->borrowernumber,
2397                 amountoutstanding => 10.00,
2398                 amount            => 10.00,
2399                 debit_type_code   => 'OVERDUE',
2400                 branchcode        => $library->{branchcode}
2401             },
2402         }
2403     );
2404
2405     my $filtered = $results->filter_by_amount_owed();
2406     is( ref($filtered), 'Koha::Patrons',
2407 'Koha::Patrons->filter_by_amount_owed should return a Koha::Patrons result set in a scalar context'
2408     );
2409
2410     my $lower_limit = 12.00;
2411     my $upper_limit = 16.00;
2412
2413     # Catch user with 1 x 12.00 fine and user with no fines.
2414     $filtered =
2415       $results->filter_by_amount_owed( { less_than => $upper_limit } );
2416     is( $filtered->_resultset->as_subselect_rs->count, 2,
2417 "filter_by_amount_owed({ less_than => $upper_limit }) found two patrons"
2418     );
2419
2420     # Catch user with 1 x 8.00 and 1 x 10.00 fine
2421     $filtered =
2422       $results->filter_by_amount_owed( { more_than => $lower_limit } );
2423     is( $filtered->_resultset->as_subselect_rs->count, 1,
2424 "filter_by_amount_owed({ more_than => $lower_limit }) found two patrons"
2425     );
2426
2427     # User with 2 fines falls above upper limit - Excluded,
2428     # user with 1 fine falls below lower limit - Excluded
2429     # and user with no fines falls below lower limit - Excluded.
2430     $filtered = $results->filter_by_amount_owed(
2431         { more_than => $lower_limit, less_than => $upper_limit } );
2432     is( $filtered->_resultset->as_subselect_rs->count, 0,
2433 "filter_by_amount_owed({ more_than => $lower_limit, less_than => $upper_limit }) found zero patrons"
2434     );
2435
2436     my $library2 = $builder->build({source => 'Branch' });
2437     my $fine4 = $builder->build(
2438         {
2439             source => 'Accountline',
2440             value  => {
2441                 borrowernumber    => $new_patron_cf_2->borrowernumber,
2442                 amountoutstanding => 10.00,
2443                 amount            => 10.00,
2444                 debit_type_code   => 'HOLD',
2445                 branchcode        => $library2->{branchcode}
2446             },
2447         }
2448     );
2449
2450     # Catch only the user with a HOLD fee over 6.00
2451     $filtered = $results->filter_by_amount_owed( { more_than => 6.00, debit_type => 'HOLD' } );
2452     is( $filtered->_resultset->as_subselect_rs->count, 1,
2453 "filter_by_amount_owed({ more_than => 6.00, debit_type => 'HOLD' }) found one patron"
2454     );
2455
2456     # Catch only the user with a fee over 6.00 at the specified library
2457     $filtered = $results->filter_by_amount_owed( { more_than => 6.00, library => $library2->{branchcode} } );
2458     is( $filtered->_resultset->as_subselect_rs->count, 1,
2459 "filter_by_amount_owed({ more_than => 6.00, library => $library2->{branchcode} }) found one patron"
2460     );
2461 };
2462
2463 subtest 'libraries_where_can_edit_items() and can_edit_items_from() tests' => sub {
2464     plan tests => 2;
2465
2466     $schema->storage->txn_begin;
2467     my $dbh = $schema->storage->dbh;
2468
2469     $dbh->do("DELETE FROM library_groups");
2470
2471     # group1
2472     #   library_1A
2473     #   library_1B
2474     # group2
2475     #   library_2A
2476     my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_limit_item_editing => 1 } )->store;
2477     my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_limit_item_editing => 1 } )->store;
2478     my $library_1A = $builder->build( { source => 'Branch' } );
2479     my $library_1B = $builder->build( { source => 'Branch' } );
2480     my $library_2A = $builder->build( { source => 'Branch' } );
2481     $library_1A = Koha::Libraries->find( $library_1A->{branchcode} );
2482     $library_1B = Koha::Libraries->find( $library_1B->{branchcode} );
2483     $library_2A = Koha::Libraries->find( $library_2A->{branchcode} );
2484     Koha::Library::Group->new( { branchcode => $library_1A->branchcode, parent_id => $group_1->id } )->store;
2485     Koha::Library::Group->new( { branchcode => $library_1B->branchcode, parent_id => $group_1->id } )->store;
2486     Koha::Library::Group->new( { branchcode => $library_2A->branchcode, parent_id => $group_2->id } )->store;
2487
2488     my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 9, ?)|); # 9 for editcatalogue
2489     # 2 patrons from library_1A (group1)
2490     # patron_1A_1 see patron's infos from outside its group
2491     # Setting flags => undef to not be considered as superlibrarian
2492     my $patron_1A_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_1A->branchcode, flags => undef, }});
2493     $patron_1A_1 = Koha::Patrons->find( $patron_1A_1->{borrowernumber} );
2494     $sth->execute( $patron_1A_1->borrowernumber, 'edit_items' );
2495     $sth->execute( $patron_1A_1->borrowernumber, 'edit_any_item' );
2496     # patron_1A_2 can only see patron's info from its group
2497     my $patron_1A_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_1A->branchcode, flags => undef, }});
2498     $patron_1A_2 = Koha::Patrons->find( $patron_1A_2->{borrowernumber} );
2499     $sth->execute( $patron_1A_2->borrowernumber, 'edit_items' );
2500     # 1 patron from library_1B (group1)
2501     my $patron_1B = $builder->build({ source => 'Borrower', value => { branchcode => $library_1B->branchcode, flags => undef, }});
2502     $patron_1B = Koha::Patrons->find( $patron_1B->{borrowernumber} );
2503     # 1 patron from library_2A (group2) can only see patron's info from its group
2504     my $patron_2A = $builder->build({ source => 'Borrower', value => { branchcode => $library_2A->branchcode, flags => undef, }});
2505     $patron_2A = Koha::Patrons->find( $patron_2A->{borrowernumber} );
2506     $sth->execute( $patron_2A->borrowernumber, 'edit_items' );
2507
2508     subtest 'libraries_where_can_edit_items' => sub {
2509         plan tests => 3;
2510
2511         my @branchcodes;
2512
2513         @branchcodes = $patron_1A_1->libraries_where_can_edit_items;
2514         is_deeply( \@branchcodes, [], "patron_1A_1 has edit_any_item => No restrictions" );
2515
2516         @branchcodes = $patron_1A_2->libraries_where_can_edit_items;
2517         is_deeply( \@branchcodes, [ sort ( $library_1A->branchcode, $library_1B->branchcode ) ], "patron_1A_2 doesn't have edit_any_item => Can only edit items from its group" );
2518
2519         @branchcodes = $patron_2A->libraries_where_can_edit_items;
2520         is_deeply( \@branchcodes, [$library_2A->branchcode], "patron_2A doesn't have edit_any_item => Can only see patron's from its group" );
2521     };
2522
2523     subtest 'can_edit_items_from' => sub {
2524         plan tests => 6;
2525
2526         t::lib::Mocks::mock_userenv({ patron => $patron_1A_1 });
2527         is( $patron_1A_1->can_edit_items_from( $library_1A->id ), 1, "patron_1A_1 can see patron_1A_2, from its library" );
2528         is( $patron_1A_1->can_edit_items_from( $library_1B->id ),   1, "patron_1A_1 can see patron_1B, from its group" );
2529         is( $patron_1A_1->can_edit_items_from( $library_2A->id ),   1, "patron_1A_1 can see patron_1A_2, from another group" );
2530
2531         t::lib::Mocks::mock_userenv({ patron => $patron_1A_2 });
2532         is( $patron_1A_2->can_edit_items_from( $library_1A->id ),   1, "patron_1A_2 can see patron_1A_1, from its library" );
2533         is( $patron_1A_2->can_edit_items_from( $library_1B->id ),   1, "patron_1A_2 can see patron_1B, from its group" );
2534         is( $patron_1A_2->can_edit_items_from( $library_2A->id ),   0, "patron_1A_2 can NOT see patron_2A, from another group" );
2535     };
2536 };
2537
2538 subtest 'filter_by_have_permission' => sub {
2539     plan tests => 5;
2540
2541     $schema->storage->txn_begin;
2542
2543     my $library  = $builder->build_object( { class => 'Koha::Libraries' } );
2544     my $patron_1 = $builder->build_object(
2545         {
2546             class => 'Koha::Patrons',
2547             value => { flags => 1, branchcode => $library->branchcode }
2548         }
2549     );
2550
2551     my $patron_2 = $builder->build_object( # 4096 = 1 << 12 for suggestions
2552         {
2553             class => 'Koha::Patrons',
2554             value => { flags => 4096, branchcode => $library->branchcode }
2555         }
2556     );
2557
2558     my $patron_3 = $builder->build_object(
2559         {
2560             class => 'Koha::Patrons',
2561             value => { flags => 0, branchcode => $library->branchcode }
2562         }
2563     );
2564     $builder->build(
2565         {
2566             source => 'UserPermission',
2567             value  => {
2568                 borrowernumber => $patron_3->borrowernumber,
2569                 module_bit     => 11,
2570                 code           => 'order_manage',
2571             },
2572         }
2573     );
2574
2575     is_deeply(
2576         [
2577             Koha::Patrons->search( { branchcode => $library->branchcode } )
2578               ->filter_by_have_permission('suggestions.suggestions_manage')
2579               ->get_column('borrowernumber')
2580         ],
2581         [ $patron_1->borrowernumber, $patron_2->borrowernumber ],
2582         'Superlibrarian and patron with suggestions.suggestions_manage'
2583     );
2584
2585     is_deeply(
2586         [
2587             Koha::Patrons->search( { branchcode => $library->branchcode } )
2588               ->filter_by_have_permission('acquisition.order_manage')
2589               ->get_column('borrowernumber')
2590         ],
2591         [ $patron_1->borrowernumber, $patron_3->borrowernumber ],
2592         'Superlibrarian and patron with acquisition.order_manage'
2593     );
2594
2595     is_deeply(
2596         [
2597             Koha::Patrons->search( { branchcode => $library->branchcode } )
2598               ->filter_by_have_permission('parameters.manage_cities')
2599               ->get_column('borrowernumber')
2600         ],
2601         [ $patron_1->borrowernumber ],
2602         'Only Superlibrarian is returned'
2603     );
2604
2605     is_deeply(
2606         [
2607             Koha::Patrons->search( { branchcode => $library->branchcode } )
2608               ->filter_by_have_permission('suggestions')
2609               ->get_column('borrowernumber')
2610         ],
2611         [ $patron_1->borrowernumber, $patron_2->borrowernumber ],
2612         'Superlibrarian and patron with suggestions'
2613     );
2614
2615     throws_ok {
2616         Koha::Patrons->search( { branchcode => $library->branchcode } )
2617           ->filter_by_have_permission('dont_exist.subperm');
2618     } 'Koha::Exceptions::ObjectNotFound';
2619
2620
2621     $schema->storage->txn_rollback;
2622 };
2623
2624 $schema->storage->txn_rollback;