Bug 31503: (follow-up) Remove OPACCustomConsentTypes
[koha.git] / t / db_dependent / Koha / Patron.t
1 #!/usr/bin/perl
2
3 # Copyright 2019 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 => 29;
23 use Test::Exception;
24 use Test::Warn;
25 use Time::Fake;
26
27 use Koha::CirculationRules;
28 use Koha::Database;
29 use Koha::DateUtils qw(dt_from_string);
30 use Koha::ArticleRequests;
31 use Koha::Patrons;
32 use Koha::Patron::Relationships;
33 use C4::Circulation qw( AddIssue AddReturn );
34
35 use t::lib::TestBuilder;
36 use t::lib::Mocks;
37
38 my $schema  = Koha::Database->new->schema;
39 my $builder = t::lib::TestBuilder->new;
40
41 subtest 'Accessor tests' => sub {
42     plan tests => 9;
43     $schema->storage->txn_begin;
44
45     my $object = Koha::Patron->new( { surname => 'Test Patron' } );
46     is( $object->surname(), 'Test Patron', "Accessor returns correct value" );
47     $object->surname('Test Patron Surname');
48     is( $object->surname(), 'Test Patron Surname', "Accessor returns correct value after set" );
49
50     my $object2 = Koha::Patron->new( { surname => 'Test Patron 2' } );
51     is( $object2->surname(), 'Test Patron 2', "Accessor returns correct value" );
52     $object2->surname('Test Patron Surname 2');
53     is( $object2->surname(), 'Test Patron Surname 2', "Accessor returns correct value after set" );
54
55     my $ret;
56     $ret = $object2->set( { surname => "Test Patron Surname 3", firstname => "Test Firstname" } );
57     ok( ref($ret) eq 'Koha::Patron', "Set returns object on success" );
58     is( $object2->surname(),   "Test Patron Surname 3", "Set sets first field correctly" );
59     is( $object2->firstname(), "Test Firstname",        "Set sets second field correctly" );
60
61     our $patron = Koha::Patron->new(
62         {
63             borrowernumber      => '12345',
64             cardnumber          => '1234567890',
65             surname             => 'mySurname',
66             firstname           => 'myFirstname',
67             title               => 'Mr.',
68             othernames          => 'myOthernames',
69             initials            => 'MM',
70             streetnumber        => '100',
71             streettype          => 'Blvd',
72             address             => 'my personal address',
73             address2            => 'my adress2',
74             city                => 'Marseille',
75             state               => 'mystate',
76             zipcode             => '13006',
77             country             => 'France',
78             email               => 'mySurname.myFirstname@email.com',
79             phone               => '0402872934',
80             mobile              => '0627884632',
81             fax                 => '0402872935',
82             emailpro            => 'myEmailPro@email.com',
83             phonepro            => '0402873334',
84             B_streetnumber      => '101',
85             B_streettype        => 'myB_streettype',
86             B_address           => 'myB_address',
87             B_address2          => 'myB_address2',
88             B_city              => 'myB_city',
89             B_state             => 'myB_state',
90             B_zipcode           => '23456',
91             B_country           => 'myB_country',
92             B_email             => 'myB_email',
93             B_phone             => '0678353935',
94             dateofbirth         => '1990-07-16',
95             branchcode          => 'myBranCode',
96             categorycode        => 'myCatCode',
97             dateenrolled        => '2015-03-19',
98             dateexpiry          => '2016-03-19',
99             gonenoaddress       => '0',
100             lost                => '0',
101             debarred            => '2015-04-19',
102             debarredcomment     => 'You are debarred',
103             borrowernotes       => 'borrowernotes',
104             sex                 => 'M',
105             password            => 'hfkurhfe976634èj!',
106             flags               => '55555',
107             userid              => '87987',
108             opacnote            => 'myOpacnote',
109             contactnote         => 'myContactnote',
110             sort1               => 'mySort1',
111             sort2               => 'mySort2',
112             altcontactfirstname => 'myAltcontactfirstname',
113             altcontactsurname   => 'myAltcontactsurname',
114             altcontactaddress1  => 'myAltcontactaddress1',
115             altcontactaddress2  => 'myAltcontactaddress2',
116             altcontactaddress3  => 'myAltcontactaddress3',
117             altcontactstate     => 'myAltcontactstate',
118             altcontactzipcode   => '465843',
119             altcontactcountry   => 'myOtherCountry',
120             altcontactphone     => 'myOtherphone',
121             smsalertnumber      => '0683027346',
122             privacy             => '667788',
123         }
124     );
125
126     subtest 'Accessor tests after new' => sub {
127         plan tests => 60;
128         is( $patron->borrowernumber, '12345',               'borrowernumber accessor returns correct value' );
129         is( $patron->cardnumber,     '1234567890',          'cardnumber accessor returns correct value' );
130         is( $patron->surname,        'mySurname',           'surname accessor returns correct value' );
131         is( $patron->firstname,      'myFirstname',         'firstname accessor returns correct value' );
132         is( $patron->title,          'Mr.',                 'title accessor returns correct value' );
133         is( $patron->othernames,     'myOthernames',        'othernames accessor returns correct value' );
134         is( $patron->initials,       'MM',                  'initials accessor returns correct value' );
135         is( $patron->streetnumber,   '100',                 'streetnumber accessor returns correct value' );
136         is( $patron->streettype,     'Blvd',                'streettype accessor returns correct value' );
137         is( $patron->address,        'my personal address', 'address accessor returns correct value' );
138         is( $patron->address2,       'my adress2',          'address2 accessor returns correct value' );
139         is( $patron->city,           'Marseille',           'city accessor returns correct value' );
140         is( $patron->state,          'mystate',             'state accessor returns correct value' );
141         is( $patron->zipcode,        '13006',               'zipcode accessor returns correct value' );
142         is( $patron->country,        'France',              'country accessor returns correct value' );
143         is( $patron->email,    'mySurname.myFirstname@email.com', 'email accessor returns correct value' );
144         is( $patron->phone,    '0402872934',                      'phone accessor returns correct value' );
145         is( $patron->mobile,   '0627884632',                      'mobile accessor returns correct value' );
146         is( $patron->fax,      '0402872935',                      'fax accessor returns correct value' );
147         is( $patron->emailpro, 'myEmailPro@email.com',            'emailpro accessor returns correct value' );
148         is( $patron->phonepro, '0402873334',                      'phonepro accessor returns correct value' );
149         is( $patron->B_streetnumber,  '101',               'B_streetnumber accessor returns correct value' );
150         is( $patron->B_streettype,    'myB_streettype',    'B_streettype accessor returns correct value' );
151         is( $patron->B_address,       'myB_address',       'B_address accessor returns correct value' );
152         is( $patron->B_address2,      'myB_address2',      'B_address2 accessor returns correct value' );
153         is( $patron->B_city,          'myB_city',          'B_city accessor returns correct value' );
154         is( $patron->B_state,         'myB_state',         'B_state accessor returns correct value' );
155         is( $patron->B_zipcode,       '23456',             'B_zipcode accessor returns correct value' );
156         is( $patron->B_country,       'myB_country',       'B_country accessor returns correct value' );
157         is( $patron->B_email,         'myB_email',         'B_email accessor returns correct value' );
158         is( $patron->B_phone,         '0678353935',        'B_phone accessor returns correct value' );
159         is( $patron->dateofbirth,     '1990-07-16',        'dateofbirth accessor returns correct value' );
160         is( $patron->branchcode,      'myBranCode',        'branchcode accessor returns correct value' );
161         is( $patron->categorycode,    'myCatCode',         'categorycode accessor returns correct value' );
162         is( $patron->dateenrolled,    '2015-03-19',        'dateenrolled accessor returns correct value' );
163         is( $patron->dateexpiry,      '2016-03-19',        'dateexpiry accessor returns correct value' );
164         is( $patron->gonenoaddress,   '0',                 'gonenoaddress accessor returns correct value' );
165         is( $patron->lost,            '0',                 'lost accessor returns correct value' );
166         is( $patron->debarred,        '2015-04-19',        'debarred accessor returns correct value' );
167         is( $patron->debarredcomment, 'You are debarred',  'debarredcomment accessor returns correct value' );
168         is( $patron->borrowernotes,   'borrowernotes',     'borrowernotes accessor returns correct value' );
169         is( $patron->sex,             'M',                 'sex accessor returns correct value' );
170         is( $patron->password,        'hfkurhfe976634èj!', 'password accessor returns correct value' );
171         is( $patron->flags,           '55555',             'flags accessor returns correct value' );
172         is( $patron->userid,          '87987',             'userid accessor returns correct value' );
173         is( $patron->opacnote,        'myOpacnote',        'opacnote accessor returns correct value' );
174         is( $patron->contactnote,     'myContactnote',     'contactnote accessor returns correct value' );
175         is( $patron->sort1,           'mySort1',           'sort1 accessor returns correct value' );
176         is( $patron->sort2,           'mySort2',           'sort2 accessor returns correct value' );
177         is(
178             $patron->altcontactfirstname, 'myAltcontactfirstname',
179             'altcontactfirstname accessor returns correct value'
180         );
181         is( $patron->altcontactsurname,  'myAltcontactsurname',  'altcontactsurname accessor returns correct value' );
182         is( $patron->altcontactaddress1, 'myAltcontactaddress1', 'altcontactaddress1 accessor returns correct value' );
183         is( $patron->altcontactaddress2, 'myAltcontactaddress2', 'altcontactaddress2 accessor returns correct value' );
184         is( $patron->altcontactaddress3, 'myAltcontactaddress3', 'altcontactaddress3 accessor returns correct value' );
185         is( $patron->altcontactstate,    'myAltcontactstate',    'altcontactstate accessor returns correct value' );
186         is( $patron->altcontactzipcode,  '465843',               'altcontactzipcode accessor returns correct value' );
187         is( $patron->altcontactcountry,  'myOtherCountry',       'altcontactcountry accessor returns correct value' );
188         is( $patron->altcontactphone,    'myOtherphone',         'altcontactphone accessor returns correct value' );
189         is( $patron->smsalertnumber,     '0683027346',           'smsalertnumber accessor returns correct value' );
190         is( $patron->privacy,            '667788',               'privacy accessor returns correct value' );
191     };
192
193     subtest 'Accessor tests after set' => sub {
194         plan tests => 60;
195
196         $patron->set(
197             {
198                 borrowernumber      => '12346',
199                 cardnumber          => '1234567891',
200                 surname             => 'SmySurname',
201                 firstname           => 'SmyFirstname',
202                 title               => 'Mme.',
203                 othernames          => 'SmyOthernames',
204                 initials            => 'SS',
205                 streetnumber        => '200',
206                 streettype          => 'Rue',
207                 address             => 'Smy personal address',
208                 address2            => 'Smy adress2',
209                 city                => 'Lyon',
210                 state               => 'Smystate',
211                 zipcode             => '69000',
212                 country             => 'France',
213                 email               => 'SmySurname.myFirstname@email.com',
214                 phone               => '0402872935',
215                 mobile              => '0627884633',
216                 fax                 => '0402872936',
217                 emailpro            => 'SmyEmailPro@email.com',
218                 phonepro            => '0402873335',
219                 B_streetnumber      => '102',
220                 B_streettype        => 'SmyB_streettype',
221                 B_address           => 'SmyB_address',
222                 B_address2          => 'SmyB_address2',
223                 B_city              => 'SmyB_city',
224                 B_state             => 'SmyB_state',
225                 B_zipcode           => '12333',
226                 B_country           => 'SmyB_country',
227                 B_email             => 'SmyB_email',
228                 B_phone             => '0678353936',
229                 dateofbirth         => '1991-07-16',
230                 branchcode          => 'SmyBranCode',
231                 categorycode        => 'SmyCatCode',
232                 dateenrolled        => '2014-03-19',
233                 dateexpiry          => '2017-03-19',
234                 gonenoaddress       => '1',
235                 lost                => '1',
236                 debarred            => '2016-04-19',
237                 debarredcomment     => 'You are still debarred',
238                 borrowernotes       => 'Sborrowernotes',
239                 sex                 => 'F',
240                 password            => 'zerzerzer#',
241                 flags               => '666666',
242                 userid              => '98233',
243                 opacnote            => 'SmyOpacnote',
244                 contactnote         => 'SmyContactnote',
245                 sort1               => 'SmySort1',
246                 sort2               => 'SmySort2',
247                 altcontactfirstname => 'SmyAltcontactfirstname',
248                 altcontactsurname   => 'SmyAltcontactsurname',
249                 altcontactaddress1  => 'SmyAltcontactaddress1',
250                 altcontactaddress2  => 'SmyAltcontactaddress2',
251                 altcontactaddress3  => 'SmyAltcontactaddress3',
252                 altcontactstate     => 'SmyAltcontactstate',
253                 altcontactzipcode   => '565843',
254                 altcontactcountry   => 'SmyOtherCountry',
255                 altcontactphone     => 'SmyOtherphone',
256                 smsalertnumber      => '0683027347',
257                 privacy             => '667789'
258             }
259         );
260
261         is( $patron->borrowernumber,      '12346',                            'borrowernumber field set ok' );
262         is( $patron->cardnumber,          '1234567891',                       'cardnumber field set ok' );
263         is( $patron->surname,             'SmySurname',                       'surname field set ok' );
264         is( $patron->firstname,           'SmyFirstname',                     'firstname field set ok' );
265         is( $patron->title,               'Mme.',                             'title field set ok' );
266         is( $patron->othernames,          'SmyOthernames',                    'othernames field set ok' );
267         is( $patron->initials,            'SS',                               'initials field set ok' );
268         is( $patron->streetnumber,        '200',                              'streetnumber field set ok' );
269         is( $patron->streettype,          'Rue',                              'streettype field set ok' );
270         is( $patron->address,             'Smy personal address',             'address field set ok' );
271         is( $patron->address2,            'Smy adress2',                      'address2 field set ok' );
272         is( $patron->city,                'Lyon',                             'city field set ok' );
273         is( $patron->state,               'Smystate',                         'state field set ok' );
274         is( $patron->zipcode,             '69000',                            'zipcode field set ok' );
275         is( $patron->country,             'France',                           'country field set ok' );
276         is( $patron->email,               'SmySurname.myFirstname@email.com', 'email field set ok' );
277         is( $patron->phone,               '0402872935',                       'phone field set ok' );
278         is( $patron->mobile,              '0627884633',                       'mobile field set ok' );
279         is( $patron->fax,                 '0402872936',                       'fax field set ok' );
280         is( $patron->emailpro,            'SmyEmailPro@email.com',            'emailpro field set ok' );
281         is( $patron->phonepro,            '0402873335',                       'phonepro field set ok' );
282         is( $patron->B_streetnumber,      '102',                              'B_streetnumber field set ok' );
283         is( $patron->B_streettype,        'SmyB_streettype',                  'B_streettype field set ok' );
284         is( $patron->B_address,           'SmyB_address',                     'B_address field set ok' );
285         is( $patron->B_address2,          'SmyB_address2',                    'B_address2 field set ok' );
286         is( $patron->B_city,              'SmyB_city',                        'B_city field set ok' );
287         is( $patron->B_state,             'SmyB_state',                       'B_state field set ok' );
288         is( $patron->B_zipcode,           '12333',                            'B_zipcode field set ok' );
289         is( $patron->B_country,           'SmyB_country',                     'B_country field set ok' );
290         is( $patron->B_email,             'SmyB_email',                       'B_email field set ok' );
291         is( $patron->B_phone,             '0678353936',                       'B_phone field set ok' );
292         is( $patron->dateofbirth,         '1991-07-16',                       'dateofbirth field set ok' );
293         is( $patron->branchcode,          'SmyBranCode',                      'branchcode field set ok' );
294         is( $patron->categorycode,        'SmyCatCode',                       'categorycode field set ok' );
295         is( $patron->dateenrolled,        '2014-03-19',                       'dateenrolled field set ok' );
296         is( $patron->dateexpiry,          '2017-03-19',                       'dateexpiry field set ok' );
297         is( $patron->gonenoaddress,       '1',                                'gonenoaddress field set ok' );
298         is( $patron->lost,                '1',                                'lost field set ok' );
299         is( $patron->debarred,            '2016-04-19',                       'debarred field set ok' );
300         is( $patron->debarredcomment,     'You are still debarred',           'debarredcomment field set ok' );
301         is( $patron->borrowernotes,       'Sborrowernotes',                   'borrowernotes field set ok' );
302         is( $patron->sex,                 'F',                                'sex field set ok' );
303         is( $patron->password,            'zerzerzer#',                       'password field set ok' );
304         is( $patron->flags,               '666666',                           'flags field set ok' );
305         is( $patron->userid,              '98233',                            'userid field set ok' );
306         is( $patron->opacnote,            'SmyOpacnote',                      'opacnote field set ok' );
307         is( $patron->contactnote,         'SmyContactnote',                   'contactnote field set ok' );
308         is( $patron->sort1,               'SmySort1',                         'sort1 field set ok' );
309         is( $patron->sort2,               'SmySort2',                         'sort2 field set ok' );
310         is( $patron->altcontactfirstname, 'SmyAltcontactfirstname',           'altcontactfirstname field set ok' );
311         is( $patron->altcontactsurname,   'SmyAltcontactsurname',             'altcontactsurname field set ok' );
312         is( $patron->altcontactaddress1,  'SmyAltcontactaddress1',            'altcontactaddress1 field set ok' );
313         is( $patron->altcontactaddress2,  'SmyAltcontactaddress2',            'altcontactaddress2 field set ok' );
314         is( $patron->altcontactaddress3,  'SmyAltcontactaddress3',            'altcontactaddress3 field set ok' );
315         is( $patron->altcontactstate,     'SmyAltcontactstate',               'altcontactstate field set ok' );
316         is( $patron->altcontactzipcode,   '565843',                           'altcontactzipcode field set ok' );
317         is( $patron->altcontactcountry,   'SmyOtherCountry',                  'altcontactcountry field set ok' );
318         is( $patron->altcontactphone,     'SmyOtherphone',                    'altcontactphone field set ok' );
319         is( $patron->smsalertnumber,      '0683027347',                       'smsalertnumber field set ok' );
320         is( $patron->privacy,             '667789',                           'privacy field set ok' );
321     };
322 };
323
324 subtest 'is_active' => sub {
325     plan tests => 12;
326     $schema->storage->txn_begin;
327
328     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
329     throws_ok { $patron->is_active } 'Koha::Exceptions::MissingParameter', 'Called without params';
330
331     # Check expiry
332     $patron->dateexpiry( dt_from_string->subtract( days => 1 ) )->lastseen(undef)->store;
333     is( $patron->is_active( { days => 1 } ), 0, 'Expired patron is not active' );
334     $patron->dateexpiry(undef)->store;
335     is( $patron->is_active( { days => 1 } ), 1, 'Expiry date removed' );
336
337     # Check anonymized
338     $patron->anonymized(1)->store;
339     is( $patron->is_active( { days => 1 } ), 0, 'Anonymized patron is not active' );
340     $patron->anonymized(0)->store;
341
342     # Change enrolled date now
343     $patron->dateenrolled('2020-01-01')->store;
344     is( $patron->is_active( { days => 1 } ), 0, 'No recent enrollment and lastseen still empty: not active' );
345     $patron->dateenrolled( dt_from_string() )->store;
346     is( $patron->is_active( { days => 1 } ), 1, 'Enrolled today: active' );
347
348     # Check lastseen, test days parameter
349     t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', 'login' );
350     $patron->dateenrolled('2020-01-01')->store;
351     $patron->update_lastseen('login');
352     is( $patron->is_active( { days => 1 } ), 1, 'Just logged in' );
353     my $ago = dt_from_string->subtract( days => 2 );
354     $patron->lastseen($ago)->store;
355     is( $patron->is_active( { days => 1 } ), 0, 'Not active since yesterday' );
356     is( $patron->is_active( { days => 3 } ), 1, 'Active within last 3 days' );
357     # test since parameter
358     my $dt = $ago->clone->add( hours => 1 );
359     is( $patron->is_active( { since => $dt } ), 0, 'Inactive since ago + 1 hour' );
360     $dt = $ago->clone->subtract( hours => 1 );
361     is( $patron->is_active( { since => $dt } ), 1, 'Active since ago - 1 hour' );
362     # test weeks parameter
363     is( $patron->is_active( { weeks => 1 } ), 1, 'Active within last week' );
364
365     $schema->storage->txn_rollback;
366 };
367
368 subtest 'add_guarantor() tests' => sub {
369
370     plan tests => 6;
371
372     $schema->storage->txn_begin;
373
374     t::lib::Mocks::mock_preference( 'borrowerRelationship', 'father1|father2' );
375
376     my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' });
377     my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
378
379     throws_ok
380         { $patron_1->add_guarantor({ guarantor_id => $patron_2->borrowernumber }); }
381         'Koha::Exceptions::Patron::Relationship::InvalidRelationship',
382         'Exception is thrown as no relationship passed';
383
384     is( $patron_1->guarantee_relationships->count, 0, 'No guarantors added' );
385
386     throws_ok
387         { $patron_1->add_guarantor({ guarantor_id => $patron_2->borrowernumber, relationship => 'father' }); }
388         'Koha::Exceptions::Patron::Relationship::InvalidRelationship',
389         'Exception is thrown as a wrong relationship was passed';
390
391     is( $patron_1->guarantee_relationships->count, 0, 'No guarantors added' );
392
393     $patron_1->add_guarantor({ guarantor_id => $patron_2->borrowernumber, relationship => 'father1' });
394
395     my $guarantors = $patron_1->guarantor_relationships;
396
397     is( $guarantors->count, 1, 'No guarantors added' );
398
399     {
400         local *STDERR;
401         open STDERR, '>', '/dev/null';
402         throws_ok
403             { $patron_1->add_guarantor({ guarantor_id => $patron_2->borrowernumber, relationship => 'father2' }); }
404             'Koha::Exceptions::Patron::Relationship::DuplicateRelationship',
405             'Exception is thrown for duplicated relationship';
406         close STDERR;
407     }
408
409     $schema->storage->txn_rollback;
410 };
411
412 subtest 'relationships_debt() tests' => sub {
413
414     plan tests => 168;
415
416     $schema->storage->txn_begin;
417
418     t::lib::Mocks::mock_preference( 'borrowerRelationship', 'parent' );
419
420     my $parent_1 = $builder->build_object({ class => 'Koha::Patrons', value => { firstname => "Parent 1" } });
421     my $parent_2 = $builder->build_object({ class => 'Koha::Patrons', value => { firstname => "Parent 2" } });
422     my $child_1 = $builder->build_object({ class => 'Koha::Patrons', value => { firstname => " Child 1" } });
423     my $child_2 = $builder->build_object({ class => 'Koha::Patrons', value => { firstname => " Child 2" } });
424
425     $child_1->add_guarantor({ guarantor_id => $parent_1->borrowernumber, relationship => 'parent' });
426     $child_1->add_guarantor({ guarantor_id => $parent_2->borrowernumber, relationship => 'parent' });
427     $child_2->add_guarantor({ guarantor_id => $parent_1->borrowernumber, relationship => 'parent' });
428     $child_2->add_guarantor({ guarantor_id => $parent_2->borrowernumber, relationship => 'parent' });
429
430     is( $child_1->guarantor_relationships->guarantors->count, 2, 'Child 1 has correct number of guarantors' );
431     is( $child_2->guarantor_relationships->guarantors->count, 2, 'Child 2 has correct number of guarantors' );
432     is( $parent_1->guarantee_relationships->guarantees->count, 2, 'Parent 1 has correct number of guarantees' );
433     is( $parent_2->guarantee_relationships->guarantees->count, 2, 'Parent 2 has correct number of guarantees' );
434
435     my $patrons = [ $parent_1, $parent_2, $child_1, $child_2 ];
436
437     # First test: No debt
438     my ($parent1_debt, $parent2_debt, $child1_debt, $child2_debt) = (0,0,0,0);
439     _test_combinations($patrons, $parent1_debt,$parent2_debt,$child1_debt,$child2_debt);
440
441     # Add debt to child_2
442     $child2_debt = 2;
443     $child_2->account->add_debit({ type => 'ACCOUNT', amount => $child2_debt, interface => 'commandline' });
444     is( $child_2->account->non_issues_charges, $child2_debt, 'Debt added to Child 2' );
445     _test_combinations($patrons, $parent1_debt,$parent2_debt,$child1_debt,$child2_debt);
446
447     $parent1_debt = 3;
448     $parent_1->account->add_debit({ type => 'ACCOUNT', amount => $parent1_debt, interface => 'commandline' });
449     is( $parent_1->account->non_issues_charges, $parent1_debt, 'Debt added to Parent 1' );
450     _test_combinations($patrons, $parent1_debt,$parent2_debt,$child1_debt,$child2_debt);
451
452     $parent2_debt = 5;
453     $parent_2->account->add_debit({ type => 'ACCOUNT', amount => $parent2_debt, interface => 'commandline' });
454     is( $parent_2->account->non_issues_charges, $parent2_debt, 'Parent 2 owes correct amount' );
455     _test_combinations($patrons, $parent1_debt,$parent2_debt,$child1_debt,$child2_debt);
456
457     $child1_debt = 7;
458     $child_1->account->add_debit({ type => 'ACCOUNT', amount => $child1_debt, interface => 'commandline' });
459     is( $child_1->account->non_issues_charges, $child1_debt, 'Child 1 owes correct amount' );
460     _test_combinations($patrons, $parent1_debt,$parent2_debt,$child1_debt,$child2_debt);
461
462     $schema->storage->txn_rollback;
463 };
464
465 sub _test_combinations {
466     my ( $patrons, $parent1_debt, $parent2_debt, $child1_debt, $child2_debt ) = @_;
467     note("Testing with parent 1 debt $parent1_debt | Parent 2 debt $parent2_debt | Child 1 debt $child1_debt | Child 2 debt $child2_debt");
468     # Options
469     # P1 => P1 + C1 + C2 ( - P1 ) ( + P2 )
470     # P2 => P2 + C1 + C2 ( - P2 ) ( + P1 )
471     # C1 => P1 + P2 + C1 + C2 ( - C1 )
472     # C2 => P1 + P2 + C1 + C2 ( - C2 )
473
474 # 3 params, count from 0 to 7 in binary ( 3 places ) to get the set of switches, then do that 4 times, one for each parent and child
475     for my $i ( 0 .. 7 ) {
476         my ( $only_this_guarantor, $include_guarantors, $include_this_patron )
477           = split '', sprintf( "%03b", $i );
478         note("---------------------");
479         for my $patron ( @$patrons ) {
480             if ( $only_this_guarantor
481                 && !$patron->guarantee_relationships->count )
482             {
483                 throws_ok {
484                     $patron->relationships_debt(
485                         {
486                             only_this_guarantor => $only_this_guarantor,
487                             include_guarantors  => $include_guarantors,
488                             include_this_patron => $include_this_patron
489                         }
490                     );
491                 }
492                 'Koha::Exceptions::BadParameter',
493                   'Exception is thrown as patron is not a guarantor';
494
495             }
496             else {
497
498                 my $debt = 0;
499                 if ( $patron->firstname eq 'Parent 1' ) {
500                     $debt += $parent1_debt if ($include_this_patron && $include_guarantors);
501                     $debt += $child1_debt + $child2_debt;
502                     $debt += $parent2_debt unless ($only_this_guarantor || !$include_guarantors);
503                 }
504                 elsif ( $patron->firstname eq 'Parent 2' ) {
505                     $debt += $parent2_debt if ($include_this_patron & $include_guarantors);
506                     $debt += $child1_debt + $child2_debt;
507                     $debt += $parent1_debt unless ($only_this_guarantor || !$include_guarantors);
508                 }
509                 elsif ( $patron->firstname eq ' Child 1' ) {
510                     $debt += $child1_debt if ($include_this_patron);
511                     $debt += $child2_debt;
512                     $debt += $parent1_debt + $parent2_debt if ($include_guarantors);
513                 }
514                 else {
515                     $debt += $child2_debt if ($include_this_patron);
516                     $debt += $child1_debt;
517                     $debt += $parent1_debt + $parent2_debt if ($include_guarantors);
518                 }
519
520                 is(
521                     $patron->relationships_debt(
522                         {
523                             only_this_guarantor => $only_this_guarantor,
524                             include_guarantors  => $include_guarantors,
525                             include_this_patron => $include_this_patron
526                         }
527                     ),
528                     $debt,
529                     $patron->firstname
530                       . " debt of " . sprintf('%02d',$debt) . " calculated correctly for ( only_this_guarantor: $only_this_guarantor, include_guarantors: $include_guarantors, include_this_patron: $include_this_patron)"
531                 );
532             }
533         }
534     }
535 }
536
537 subtest 'add_enrolment_fee_if_needed() tests' => sub {
538
539     plan tests => 2;
540
541     subtest 'category has enrolment fee' => sub {
542         plan tests => 7;
543
544         $schema->storage->txn_begin;
545
546         my $category = $builder->build_object(
547             {
548                 class => 'Koha::Patron::Categories',
549                 value => {
550                     enrolmentfee => 20
551                 }
552             }
553         );
554
555         my $patron = $builder->build_object(
556             {
557                 class => 'Koha::Patrons',
558                 value => {
559                     categorycode => $category->categorycode
560                 }
561             }
562         );
563
564         my $enrollment_fee = $patron->add_enrolment_fee_if_needed();
565         is( $enrollment_fee * 1, 20, 'Enrolment fee amount is correct' );
566         my $account = $patron->account;
567         is( $patron->account->balance * 1, 20, 'Patron charged the enrolment fee' );
568         # second enrolment fee, new
569         $enrollment_fee = $patron->add_enrolment_fee_if_needed(0);
570         # third enrolment fee, renewal
571         $enrollment_fee = $patron->add_enrolment_fee_if_needed(1);
572         is( $patron->account->balance * 1, 60, 'Patron charged the enrolment fees' );
573
574         my @debits = $account->outstanding_debits->as_list;
575         is( scalar @debits, 3, '3 enrolment fees' );
576         is( $debits[0]->debit_type_code, 'ACCOUNT', 'Account type set correctly' );
577         is( $debits[1]->debit_type_code, 'ACCOUNT', 'Account type set correctly' );
578         is( $debits[2]->debit_type_code, 'ACCOUNT_RENEW', 'Account type set correctly' );
579
580         $schema->storage->txn_rollback;
581     };
582
583     subtest 'no enrolment fee' => sub {
584
585         plan tests => 3;
586
587         $schema->storage->txn_begin;
588
589         my $category = $builder->build_object(
590             {
591                 class => 'Koha::Patron::Categories',
592                 value => {
593                     enrolmentfee => 0
594                 }
595             }
596         );
597
598         my $patron = $builder->build_object(
599             {
600                 class => 'Koha::Patrons',
601                 value => {
602                     categorycode => $category->categorycode
603                 }
604             }
605         );
606
607         my $enrollment_fee = $patron->add_enrolment_fee_if_needed();
608         is( $enrollment_fee * 1, 0, 'No enrolment fee' );
609         my $account = $patron->account;
610         is( $patron->account->balance, 0, 'Patron not charged anything' );
611
612         my @debits = $account->outstanding_debits->as_list;
613         is( scalar @debits, 0, 'no debits' );
614
615         $schema->storage->txn_rollback;
616     };
617 };
618
619 subtest 'messaging_preferences() tests' => sub {
620     plan tests => 5;
621
622     $schema->storage->txn_begin;
623
624     my $mtt = $builder->build_object({
625         class => 'Koha::Patron::MessagePreference::Transport::Types'
626     });
627     my $attribute = $builder->build_object({
628         class => 'Koha::Patron::MessagePreference::Attributes'
629     });
630     my $branchcode     = $builder->build({
631         source => 'Branch' })->{branchcode};
632     my $letter = $builder->build_object({
633         class => 'Koha::Notice::Templates',
634         value => {
635             branchcode => '',
636             is_html => 0,
637             message_transport_type => $mtt->message_transport_type
638         }
639     });
640
641     Koha::Patron::MessagePreference::Transport->new({
642         message_attribute_id   => $attribute->message_attribute_id,
643         message_transport_type => $mtt->message_transport_type,
644         is_digest              => 0,
645         letter_module          => $letter->module,
646         letter_code            => $letter->code,
647     })->store;
648
649     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
650
651     my $preference = Koha::Patron::MessagePreference->new({
652         borrowernumber => $patron->borrowernumber,
653         message_attribute_id => $attribute->message_attribute_id,
654         wants_digest => 0,
655         days_in_advance => undef,
656     })->store;
657
658     my $messaging_preferences = $patron->messaging_preferences();
659     is($messaging_preferences->count, 1, 'Found one preference');
660
661     my $messaging_preference = $messaging_preferences->next;
662     is($messaging_preference->borrowernumber, $patron->borrowernumber);
663     is($messaging_preference->message_attribute_id, $attribute->message_attribute_id);
664     is($messaging_preference->wants_digest, 0);
665     is($messaging_preference->days_in_advance, undef);
666
667     $schema->storage->txn_rollback;
668 };
669
670 subtest 'to_api() tests' => sub {
671
672     plan tests => 6;
673
674     $schema->storage->txn_begin;
675
676     my $patron_class = Test::MockModule->new('Koha::Patron');
677     $patron_class->mock(
678         'algo',
679         sub { return 'algo' }
680     );
681
682     my $patron = $builder->build_object(
683         {
684             class => 'Koha::Patrons',
685             value => {
686                 debarred => undef
687             }
688         }
689     );
690
691     my $restricted = $patron->to_api->{restricted};
692     ok( defined $restricted, 'restricted is defined' );
693     ok( !$restricted, 'debarred is undef, restricted evaluates to false' );
694
695     $patron->debarred( dt_from_string->add( days => 1 ) )->store->discard_changes;
696     $restricted = $patron->to_api->{restricted};
697     ok( defined $restricted, 'restricted is defined' );
698     ok( $restricted, 'debarred is defined, restricted evaluates to true' );
699
700     my $patron_json = $patron->to_api({ embed => { algo => {} } });
701     ok( exists $patron_json->{algo} );
702     is( $patron_json->{algo}, 'algo' );
703
704     $schema->storage->txn_rollback;
705 };
706
707 subtest 'login_attempts tests' => sub {
708     plan tests => 1;
709
710     $schema->storage->txn_begin;
711
712     my $patron = $builder->build_object(
713         {
714             class => 'Koha::Patrons',
715         }
716     );
717     my $patron_info = $patron->unblessed;
718     $patron->delete;
719     delete $patron_info->{login_attempts};
720     my $new_patron = Koha::Patron->new($patron_info)->store;
721     is( $new_patron->discard_changes->login_attempts, 0, "login_attempts defaults to 0 as expected");
722
723     $schema->storage->txn_rollback;
724 };
725
726 subtest 'is_superlibrarian() tests' => sub {
727
728     plan tests => 3;
729
730     $schema->storage->txn_begin;
731
732     my $patron = $builder->build_object(
733         {
734             class => 'Koha::Patrons',
735
736             value => {
737                 flags => 16
738             }
739         }
740     );
741
742     is( $patron->is_superlibrarian, 0, 'Patron is not a superlibrarian and the method returns the correct value' );
743
744     $patron->flags(1)->store->discard_changes;
745     is( $patron->is_superlibrarian, 1, 'Patron is a superlibrarian and the method returns the correct value' );
746
747     $patron->flags(0)->store->discard_changes;
748     is( $patron->is_superlibrarian, 0, 'Patron is not a superlibrarian and the method returns the correct value' );
749
750     $schema->storage->txn_rollback;
751 };
752
753 subtest 'extended_attributes' => sub {
754
755     plan tests => 16;
756
757     my $schema = Koha::Database->new->schema;
758     $schema->storage->txn_begin;
759
760     Koha::Patron::Attribute::Types->search->delete;
761
762     my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
763     my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
764
765     t::lib::Mocks::mock_userenv({ patron => $patron_1 });
766
767     my $attribute_type1 = Koha::Patron::Attribute::Type->new(
768         {
769             code        => 'my code1',
770             description => 'my description1',
771             unique_id   => 1
772         }
773     )->store;
774     my $attribute_type2 = Koha::Patron::Attribute::Type->new(
775         {
776             code             => 'my code2',
777             description      => 'my description2',
778             opac_display     => 1,
779             staff_searchable => 1
780         }
781     )->store;
782
783     my $new_library = $builder->build( { source => 'Branch' } );
784     my $attribute_type_limited = Koha::Patron::Attribute::Type->new(
785         { code => 'my code3', description => 'my description3' } )->store;
786     $attribute_type_limited->library_limits( [ $new_library->{branchcode} ] );
787
788     my $attributes_for_1 = [
789         {
790             attribute => 'my attribute1',
791             code => $attribute_type1->code(),
792         },
793         {
794             attribute => 'my attribute2',
795             code => $attribute_type2->code(),
796         },
797         {
798             attribute => 'my attribute limited',
799             code => $attribute_type_limited->code(),
800         }
801     ];
802
803     my $attributes_for_2 = [
804         {
805             attribute => 'my attribute12',
806             code => $attribute_type1->code(),
807         },
808         {
809             attribute => 'my attribute limited 2',
810             code => $attribute_type_limited->code(),
811         }
812     ];
813
814     my $extended_attributes = $patron_1->extended_attributes;
815     is( ref($extended_attributes), 'Koha::Patron::Attributes', 'Koha::Patron->extended_attributes must return a Koha::Patron::Attribute set' );
816     is( $extended_attributes->count, 0, 'There should not be attribute yet');
817
818     $patron_1->extended_attributes->filter_by_branch_limitations->delete;
819     $patron_2->extended_attributes->filter_by_branch_limitations->delete;
820     $patron_1->extended_attributes($attributes_for_1);
821     $patron_2->extended_attributes($attributes_for_2);
822
823     my $extended_attributes_for_1 = $patron_1->extended_attributes;
824     is( $extended_attributes_for_1->count, 3, 'There should be 3 attributes now for patron 1');
825
826     my $extended_attributes_for_2 = $patron_2->extended_attributes;
827     is( $extended_attributes_for_2->count, 2, 'There should be 2 attributes now for patron 2');
828
829     my $attribute_12 = $extended_attributes_for_2->search({ code => $attribute_type1->code })->next;
830     is( $attribute_12->attribute, 'my attribute12', 'search by code should return the correct attribute' );
831
832     $attribute_12 = $patron_2->get_extended_attribute( $attribute_type1->code );
833     is( $attribute_12->attribute, 'my attribute12', 'Koha::Patron->get_extended_attribute should return the correct attribute value' );
834
835     my $expected_attributes_for_2 = [
836         {
837             code      => $attribute_type1->code(),
838             attribute => 'my attribute12',
839         },
840         {
841             code      => $attribute_type_limited->code(),
842             attribute => 'my attribute limited 2',
843         }
844     ];
845     # Sorting them by code
846     $expected_attributes_for_2 = [ sort { $a->{code} cmp $b->{code} } @$expected_attributes_for_2 ];
847     my @extended_attributes_for_2 = $extended_attributes_for_2->as_list;
848
849     is_deeply(
850         [
851             {
852                 code      => $extended_attributes_for_2[0]->code,
853                 attribute => $extended_attributes_for_2[0]->attribute
854             },
855             {
856                 code      => $extended_attributes_for_2[1]->code,
857                 attribute => $extended_attributes_for_2[1]->attribute
858             }
859         ],
860         $expected_attributes_for_2
861     );
862
863     # TODO - What about multiple? POD explains the problem
864     my $non_existent = $patron_2->get_extended_attribute( 'not_exist' );
865     is( $non_existent, undef, 'Koha::Patron->get_extended_attribute must return undef if the attribute does not exist' );
866
867     # Test branch limitations
868     t::lib::Mocks::mock_userenv({ patron => $patron_2 });
869     # Return all
870     $extended_attributes_for_1 = $patron_1->extended_attributes;
871     is( $extended_attributes_for_1->count, 3, 'There should be 2 attributes for patron 1, the limited one should be returned');
872
873     # Return filtered
874     $extended_attributes_for_1 = $patron_1->extended_attributes->filter_by_branch_limitations;
875     is( $extended_attributes_for_1->count, 2, 'There should be 2 attributes for patron 1, the limited one should be returned');
876
877     # Not filtered
878     my $limited_value = $patron_1->get_extended_attribute( $attribute_type_limited->code );
879     is( $limited_value->attribute, 'my attribute limited', );
880
881     ## Do we need a filtered?
882     #$limited_value = $patron_1->get_extended_attribute( $attribute_type_limited->code );
883     #is( $limited_value, undef, );
884
885     $schema->storage->txn_rollback;
886
887     subtest 'non-repeatable attributes tests' => sub {
888
889         plan tests => 3;
890
891         $schema->storage->txn_begin;
892         Koha::Patron::Attribute::Types->search->delete;
893
894         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
895         my $attribute_type = $builder->build_object(
896             {
897                 class => 'Koha::Patron::Attribute::Types',
898                 value => { repeatable => 0 }
899             }
900         );
901
902         is( $patron->extended_attributes->count, 0, 'Patron has no extended attributes' );
903
904         throws_ok
905             {
906                 $patron->extended_attributes(
907                     [
908                         { code => $attribute_type->code, attribute => 'a' },
909                         { code => $attribute_type->code, attribute => 'b' }
910                     ]
911                 );
912             }
913             'Koha::Exceptions::Patron::Attribute::NonRepeatable',
914             'Exception thrown on non-repeatable attribute';
915
916         is( $patron->extended_attributes->count, 0, 'Extended attributes storing rolled back' );
917
918         $schema->storage->txn_rollback;
919
920     };
921
922     subtest 'unique attributes tests' => sub {
923
924         plan tests => 5;
925
926         $schema->storage->txn_begin;
927         Koha::Patron::Attribute::Types->search->delete;
928
929         my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' });
930         my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
931
932         my $attribute_type_1 = $builder->build_object(
933             {
934                 class => 'Koha::Patron::Attribute::Types',
935                 value => { unique_id => 1 }
936             }
937         );
938
939         my $attribute_type_2 = $builder->build_object(
940             {
941                 class => 'Koha::Patron::Attribute::Types',
942                 value => { unique_id => 0 }
943             }
944         );
945
946         is( $patron_1->extended_attributes->count, 0, 'patron_1 has no extended attributes' );
947         is( $patron_2->extended_attributes->count, 0, 'patron_2 has no extended attributes' );
948
949         $patron_1->extended_attributes(
950             [
951                 { code => $attribute_type_1->code, attribute => 'a' },
952                 { code => $attribute_type_2->code, attribute => 'a' }
953             ]
954         );
955
956         throws_ok
957             {
958                 $patron_2->extended_attributes(
959                     [
960                         { code => $attribute_type_1->code, attribute => 'a' },
961                         { code => $attribute_type_2->code, attribute => 'a' }
962                     ]
963                 );
964             }
965             'Koha::Exceptions::Patron::Attribute::UniqueIDConstraint',
966             'Exception thrown on unique attribute';
967
968         is( $patron_1->extended_attributes->count, 2, 'Extended attributes stored' );
969         is( $patron_2->extended_attributes->count, 0, 'Extended attributes storing rolled back' );
970
971         $schema->storage->txn_rollback;
972
973     };
974
975     subtest 'invalid type attributes tests' => sub {
976
977         plan tests => 3;
978
979         $schema->storage->txn_begin;
980         Koha::Patron::Attribute::Types->search->delete;
981
982         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
983
984         my $attribute_type_1 = $builder->build_object(
985             {
986                 class => 'Koha::Patron::Attribute::Types',
987                 value => { repeatable => 0 }
988             }
989         );
990
991         my $attribute_type_2 = $builder->build_object(
992             {
993                 class => 'Koha::Patron::Attribute::Types'
994             }
995         );
996
997         my $type_2 = $attribute_type_2->code;
998         $attribute_type_2->delete;
999
1000         is( $patron->extended_attributes->count, 0, 'Patron has no extended attributes' );
1001
1002         throws_ok
1003             {
1004                 $patron->extended_attributes(
1005                     [
1006                         { code => $attribute_type_1->code, attribute => 'a' },
1007                         { code => $attribute_type_2->code, attribute => 'b' }
1008                     ]
1009                 );
1010             }
1011             'Koha::Exceptions::Patron::Attribute::InvalidType',
1012             'Exception thrown on invalid attribute type';
1013
1014         is( $patron->extended_attributes->count, 0, 'Extended attributes storing rolled back' );
1015
1016         $schema->storage->txn_rollback;
1017
1018     };
1019
1020     subtest 'globally mandatory attributes tests' => sub {
1021
1022         plan tests => 5;
1023
1024         $schema->storage->txn_begin;
1025         Koha::Patron::Attribute::Types->search->delete;
1026
1027         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1028
1029         my $attribute_type_1 = $builder->build_object(
1030             {
1031                 class => 'Koha::Patron::Attribute::Types',
1032                 value => { mandatory => 1, class => 'a', category_code => undef }
1033             }
1034         );
1035
1036         my $attribute_type_2 = $builder->build_object(
1037             {
1038                 class => 'Koha::Patron::Attribute::Types',
1039                 value => { mandatory => 0, class => 'a', category_code => undef }
1040             }
1041         );
1042
1043         is( $patron->extended_attributes->count, 0, 'Patron has no extended attributes' );
1044
1045         throws_ok
1046             {
1047                 $patron->extended_attributes(
1048                     [
1049                         { code => $attribute_type_2->code, attribute => 'b' }
1050                     ]
1051                 );
1052             }
1053             'Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute',
1054             'Exception thrown on missing mandatory attribute type';
1055
1056         is( $@->type, $attribute_type_1->code, 'Exception parameters are correct' );
1057
1058         is( $patron->extended_attributes->count, 0, 'Extended attributes storing rolled back' );
1059
1060         $patron->extended_attributes(
1061             [
1062                 { code => $attribute_type_1->code, attribute => 'b' }
1063             ]
1064         );
1065
1066         is( $patron->extended_attributes->count, 1, 'Extended attributes succeeded' );
1067
1068         $schema->storage->txn_rollback;
1069
1070     };
1071
1072     subtest 'limited category mandatory attributes tests' => sub {
1073
1074         plan tests => 2;
1075
1076         $schema->storage->txn_begin;
1077         Koha::Patron::Attribute::Types->search->delete;
1078
1079         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1080
1081         my $attribute_type_1 = $builder->build_object(
1082             {
1083                 class => 'Koha::Patron::Attribute::Types',
1084                 value => { mandatory => 1, class => 'a', category_code => $patron->categorycode }
1085             }
1086         );
1087
1088         $patron->extended_attributes(
1089             [
1090                 { code => $attribute_type_1->code, attribute => 'a' }
1091             ]
1092         );
1093
1094         is( $patron->extended_attributes->count, 1, 'Extended attributes succeeded' );
1095
1096         $patron = $builder->build_object({ class => 'Koha::Patrons' });
1097         # new patron, new category - they shouldn't be required to have any attributes
1098
1099
1100         ok( $patron->extended_attributes([]), "We can set no attributes, mandatory attribute for other category not required");
1101
1102
1103     };
1104
1105
1106
1107 };
1108
1109 subtest 'can_log_into() tests' => sub {
1110
1111     plan tests => 5;
1112
1113     $schema->storage->txn_begin;
1114
1115     my $patron = $builder->build_object(
1116         {
1117             class => 'Koha::Patrons',
1118             value => {
1119                 flags => undef
1120             }
1121         }
1122     );
1123     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1124
1125     t::lib::Mocks::mock_preference('IndependentBranches', 1);
1126
1127     ok( $patron->can_log_into( $patron->library ), 'Patron can log into its own library' );
1128     ok( !$patron->can_log_into( $library ), 'Patron cannot log into different library, IndependentBranches on' );
1129
1130     # make it a superlibrarian
1131     $patron->set({ flags => 1 })->store->discard_changes;
1132     ok( $patron->can_log_into( $library ), 'Superlibrarian can log into different library, IndependentBranches on' );
1133
1134     t::lib::Mocks::mock_preference('IndependentBranches', 0);
1135
1136     # No special permissions
1137     $patron->set({ flags => undef })->store->discard_changes;
1138     ok( $patron->can_log_into( $patron->library ), 'Patron can log into its own library' );
1139     ok( $patron->can_log_into( $library ), 'Patron can log into any library' );
1140
1141     $schema->storage->txn_rollback;
1142 };
1143
1144 subtest 'can_request_article() tests' => sub {
1145
1146     plan tests => 4;
1147
1148     $schema->storage->txn_begin;
1149
1150     t::lib::Mocks::mock_preference( 'ArticleRequests', 1 );
1151
1152     my $item = $builder->build_sample_item;
1153
1154     my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
1155     my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
1156     my $patron    = $builder->build_object( { class => 'Koha::Patrons' } );
1157
1158     t::lib::Mocks::mock_userenv( { branchcode => $library_2->id } );
1159
1160     Koha::CirculationRules->set_rule(
1161         {
1162             categorycode => undef,
1163             branchcode   => $library_1->id,
1164             rule_name    => 'open_article_requests_limit',
1165             rule_value   => 4,
1166         }
1167     );
1168
1169     $builder->build_object(
1170         {
1171             class => 'Koha::ArticleRequests',
1172             value => { status => 'REQUESTED', borrowernumber => $patron->id }
1173         }
1174     );
1175     $builder->build_object(
1176         {
1177             class => 'Koha::ArticleRequests',
1178             value => { status => 'PENDING', borrowernumber => $patron->id }
1179         }
1180     );
1181     $builder->build_object(
1182         {
1183             class => 'Koha::ArticleRequests',
1184             value => { status => 'PROCESSING', borrowernumber => $patron->id }
1185         }
1186     );
1187     $builder->build_object(
1188         {
1189             class => 'Koha::ArticleRequests',
1190             value => { status => 'CANCELED', borrowernumber => $patron->id }
1191         }
1192     );
1193
1194     ok(
1195         $patron->can_request_article( $library_1->id ),
1196         '3 current requests, 4 is the limit: allowed'
1197     );
1198
1199     # Completed request, same day
1200     my $completed = $builder->build_object(
1201         {
1202             class => 'Koha::ArticleRequests',
1203             value => {
1204                 status         => 'COMPLETED',
1205                 borrowernumber => $patron->id
1206             }
1207         }
1208     );
1209
1210     ok( !$patron->can_request_article( $library_1->id ),
1211         '3 current requests and a completed one the same day: denied' );
1212
1213     $completed->updated_on(
1214         dt_from_string->add( days => -1 )->set(
1215             hour   => 23,
1216             minute => 59,
1217             second => 59,
1218         )
1219     )->store;
1220
1221     ok( $patron->can_request_article( $library_1->id ),
1222         '3 current requests and a completed one the day before: allowed' );
1223
1224     Koha::CirculationRules->set_rule(
1225         {
1226             categorycode => undef,
1227             branchcode   => $library_2->id,
1228             rule_name    => 'open_article_requests_limit',
1229             rule_value   => 3,
1230         }
1231     );
1232
1233     ok( !$patron->can_request_article,
1234         'Not passing the library_id param makes it fallback to userenv: denied'
1235     );
1236
1237     $schema->storage->txn_rollback;
1238 };
1239
1240 subtest 'article_requests() tests' => sub {
1241
1242     plan tests => 3;
1243
1244     $schema->storage->txn_begin;
1245
1246     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1247     t::lib::Mocks::mock_userenv( { branchcode => $library->id } );
1248
1249     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1250
1251     my $article_requests = $patron->article_requests;
1252     is( ref($article_requests), 'Koha::ArticleRequests',
1253         'In scalar context, type is correct' );
1254     is( $article_requests->count, 0, 'No article requests' );
1255
1256     foreach my $i ( 0 .. 3 ) {
1257
1258         my $item = $builder->build_sample_item;
1259
1260         Koha::ArticleRequest->new(
1261             {
1262                 borrowernumber => $patron->id,
1263                 biblionumber   => $item->biblionumber,
1264                 itemnumber     => $item->id,
1265                 title          => "Title",
1266             }
1267         )->request;
1268     }
1269
1270     $article_requests = $patron->article_requests;
1271     is( $article_requests->count, 4, '4 article requests' );
1272
1273     $schema->storage->txn_rollback;
1274
1275 };
1276
1277 subtest 'can_patron_change_staff_only_lists() tests' => sub {
1278
1279     plan tests => 3;
1280
1281     $schema->storage->txn_begin;
1282
1283     # make a user with no special permissions
1284     my $patron = $builder->build_object(
1285         {
1286             class => 'Koha::Patrons',
1287             value => {
1288                 flags => undef
1289             }
1290         }
1291     );
1292     is( $patron->can_patron_change_staff_only_lists(), 0, 'Patron without permissions cannot change staff only lists');
1293
1294     # make it a 'Catalogue' permission
1295     $patron->set({ flags => 4 })->store->discard_changes;
1296     is( $patron->can_patron_change_staff_only_lists(), 1, 'Catalogue patron can change staff only lists');
1297
1298
1299     # make it a superlibrarian
1300     $patron->set({ flags => 1 })->store->discard_changes;
1301     is( $patron->can_patron_change_staff_only_lists(), 1, 'Superlibrarian patron can change staff only lists');
1302
1303     $schema->storage->txn_rollback;
1304 };
1305
1306 subtest 'can_patron_change_permitted_staff_lists() tests' => sub {
1307
1308     plan tests => 4;
1309
1310     $schema->storage->txn_begin;
1311
1312     # make a user with no special permissions
1313     my $patron = $builder->build_object(
1314         {
1315             class => 'Koha::Patrons',
1316             value => {
1317                 flags => undef
1318             }
1319         }
1320     );
1321     is( $patron->can_patron_change_permitted_staff_lists(), 0, 'Patron without permissions cannot change permitted staff lists');
1322
1323     # make it a 'Catalogue' permission
1324     $patron->set({ flags => 4 })->store->discard_changes;
1325     is( $patron->can_patron_change_permitted_staff_lists(), 0, 'Catalogue patron cannot change permitted staff lists');
1326
1327     # make it a 'Catalogue' permission and 'edit_public_list_contents' sub-permission
1328     $patron->set({ flags => 4 })->store->discard_changes;
1329     $builder->build(
1330         {
1331             source => 'UserPermission',
1332             value  => {
1333                 borrowernumber => $patron->borrowernumber,
1334                 module_bit     => 20,                            # lists
1335                 code           => 'edit_public_list_contents',
1336             },
1337         }
1338     );
1339     is( $patron->can_patron_change_permitted_staff_lists(), 1, 'Catalogue and "edit_public_list_contents" patron can change permitted staff lists');
1340
1341     # make it a superlibrarian
1342     $patron->set({ flags => 1 })->store->discard_changes;
1343     is( $patron->can_patron_change_permitted_staff_lists(), 1, 'Superlibrarian patron can change permitted staff lists');
1344
1345     $schema->storage->txn_rollback;
1346 };
1347
1348 subtest 'password expiration tests' => sub {
1349
1350     plan tests => 5;
1351
1352     $schema->storage->txn_begin;
1353     my $date = dt_from_string();
1354     my $category = $builder->build_object({ class => 'Koha::Patron::Categories', value => {
1355             password_expiry_days => 10,
1356             require_strong_password => 0,
1357         }
1358     });
1359     my $patron = $builder->build_object({ class=> 'Koha::Patrons', value => {
1360             categorycode => $category->categorycode,
1361             password => 'hats'
1362         }
1363     });
1364
1365     $patron->delete()->store()->discard_changes(); # Make sure we are storing a 'new' patron
1366
1367     is( $patron->password_expiration_date(), $date->add( days => 10 )->ymd() , "Password expiration date set correctly on patron creation");
1368
1369     $patron = $builder->build_object({ class => 'Koha::Patrons', value => {
1370             categorycode => $category->categorycode,
1371             password => undef
1372         }
1373     });
1374     $patron->delete()->store()->discard_changes();
1375
1376     is( $patron->password_expiration_date(), undef, "Password expiration date is not set if patron does not have a password");
1377
1378     $category->password_expiry_days(undef)->store();
1379     $patron = $builder->build_object({ class => 'Koha::Patrons', value => {
1380             categorycode => $category->categorycode
1381         }
1382     });
1383     $patron->delete()->store()->discard_changes();
1384     is( $patron->password_expiration_date(), undef, "Password expiration date is not set if category does not have expiry days set");
1385
1386     $schema->storage->txn_rollback;
1387
1388     subtest 'password_expired' => sub {
1389
1390         plan tests => 3;
1391
1392         $schema->storage->txn_begin;
1393         my $date = dt_from_string();
1394         $patron = $builder->build_object({ class => 'Koha::Patrons', value => {
1395                 password_expiration_date => undef
1396             }
1397         });
1398         is( $patron->password_expired, 0, "Patron with no password expiration date, password not expired");
1399         $patron->password_expiration_date( $date )->store;
1400         $patron->discard_changes();
1401         is( $patron->password_expired, 1, "Patron with password expiration date of today, password expired");
1402         $date->subtract( days => 1 );
1403         $patron->password_expiration_date( $date )->store;
1404         $patron->discard_changes();
1405         is( $patron->password_expired, 1, "Patron with password expiration date in past, password expired");
1406
1407         $schema->storage->txn_rollback;
1408     };
1409
1410     subtest 'set_password' => sub {
1411
1412         plan tests => 4;
1413
1414         $schema->storage->txn_begin;
1415
1416         my $date = dt_from_string();
1417         my $category = $builder->build_object({ class => 'Koha::Patron::Categories', value => {
1418                 password_expiry_days => 10
1419             }
1420         });
1421         my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {
1422                 categorycode => $category->categorycode,
1423                 password_expiration_date =>  $date->subtract( days => 1 )
1424             }
1425         });
1426         is( $patron->password_expired, 1, "Patron password is expired");
1427
1428         $date = dt_from_string();
1429         $patron->set_password({ password => "kitten", skip_validation => 1 })->discard_changes();
1430         is( $patron->password_expired, 0, "Patron password no longer expired when new password set");
1431         is( $patron->password_expiration_date(), $date->add( days => 10 )->ymd(), "Password expiration date set correctly on patron creation");
1432
1433
1434         $category->password_expiry_days( undef )->store();
1435         $patron->set_password({ password => "puppies", skip_validation => 1 })->discard_changes();
1436         is( $patron->password_expiration_date(), undef, "Password expiration date is unset if category does not have expiry days");
1437
1438         $schema->storage->txn_rollback;
1439     };
1440
1441 };
1442
1443 subtest 'safe_to_delete() tests' => sub {
1444
1445     plan tests => 14;
1446
1447     $schema->storage->txn_begin;
1448
1449     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1450
1451     ## Make it the anonymous
1452     t::lib::Mocks::mock_preference( 'AnonymousPatron', $patron->id );
1453
1454     ok( !$patron->safe_to_delete, 'Cannot delete, it is the anonymous patron' );
1455     my $message = $patron->safe_to_delete->messages->[0];
1456     is( $message->type, 'error', 'Type is error' );
1457     is( $message->message, 'is_anonymous_patron', 'Cannot delete, it is the anonymous patron' );
1458     # cleanup
1459     t::lib::Mocks::mock_preference( 'AnonymousPatron', 0 );
1460
1461     ## Make it have a checkout
1462     my $checkout = $builder->build_object(
1463         {
1464             class => 'Koha::Checkouts',
1465             value => { borrowernumber => $patron->id }
1466         }
1467     );
1468
1469     ok( !$patron->safe_to_delete, 'Cannot delete, has checkouts' );
1470     $message = $patron->safe_to_delete->messages->[0];
1471     is( $message->type, 'error', 'Type is error' );
1472     is( $message->message, 'has_checkouts', 'Cannot delete, has checkouts' );
1473     # cleanup
1474     $checkout->delete;
1475
1476     ## Make it have a guarantee
1477     t::lib::Mocks::mock_preference( 'borrowerRelationship', 'parent' );
1478     $builder->build_object({ class => 'Koha::Patrons' })
1479             ->add_guarantor({ guarantor_id => $patron->id, relationship => 'parent' });
1480
1481     ok( !$patron->safe_to_delete, 'Cannot delete, has guarantees' );
1482     $message = $patron->safe_to_delete->messages->[0];
1483     is( $message->type, 'error', 'Type is error' );
1484     is( $message->message, 'has_guarantees', 'Cannot delete, has guarantees' );
1485
1486     # cleanup
1487     $patron->guarantee_relationships->delete;
1488
1489     ## Make it have debt
1490     my $debit = $patron->account->add_debit({ amount => 10, interface => 'intranet', type => 'MANUAL' });
1491
1492     ok( !$patron->safe_to_delete, 'Cannot delete, has debt' );
1493     $message = $patron->safe_to_delete->messages->[0];
1494     is( $message->type, 'error', 'Type is error' );
1495     is( $message->message, 'has_debt', 'Cannot delete, has debt' );
1496     # cleanup
1497     my $manager = $builder->build_object( { class => 'Koha::Patrons' } );
1498     t::lib::Mocks::mock_userenv( { borrowernumber => $manager->id } );
1499     $patron->account->pay({ amount => 10, debits => [ $debit ] });
1500
1501     ## Happy case :-D
1502     ok( $patron->safe_to_delete, 'Can delete, all conditions met' );
1503     my $messages = $patron->safe_to_delete->messages;
1504     is_deeply( $messages, [], 'Patron can be deleted, no messages' );
1505
1506     $schema->storage->txn_rollback;
1507 };
1508
1509 subtest 'article_request_fee() tests' => sub {
1510
1511     plan tests => 3;
1512
1513     $schema->storage->txn_begin;
1514
1515     # Cleanup, to avoid interference
1516     Koha::CirculationRules->search( { rule_name => 'article_request_fee' } )->delete;
1517
1518     t::lib::Mocks::mock_preference( 'ArticleRequests', 1 );
1519
1520     my $item = $builder->build_sample_item;
1521
1522     my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
1523     my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
1524     my $patron    = $builder->build_object( { class => 'Koha::Patrons' } );
1525
1526     # Rule that should never be picked, because the patron's category is always picked
1527     Koha::CirculationRules->set_rule(
1528         {   categorycode => undef,
1529             branchcode   => undef,
1530             rule_name    => 'article_request_fee',
1531             rule_value   => 1,
1532         }
1533     );
1534
1535     is( $patron->article_request_fee( { library_id => $library_2->id } ), 1, 'library_id used correctly' );
1536
1537     Koha::CirculationRules->set_rule(
1538         {   categorycode => $patron->categorycode,
1539             branchcode   => undef,
1540             rule_name    => 'article_request_fee',
1541             rule_value   => 2,
1542         }
1543     );
1544
1545     Koha::CirculationRules->set_rule(
1546         {   categorycode => $patron->categorycode,
1547             branchcode   => $library_1->id,
1548             rule_name    => 'article_request_fee',
1549             rule_value   => 3,
1550         }
1551     );
1552
1553     is( $patron->article_request_fee( { library_id => $library_2->id } ), 2, 'library_id used correctly' );
1554
1555     t::lib::Mocks::mock_userenv( { branchcode => $library_1->id } );
1556
1557     is( $patron->article_request_fee(), 3, 'env used correctly' );
1558
1559     $schema->storage->txn_rollback;
1560 };
1561
1562 subtest 'add_article_request_fee_if_needed() tests' => sub {
1563
1564     plan tests => 12;
1565
1566     $schema->storage->txn_begin;
1567
1568     my $amount = 0;
1569
1570     my $patron_mock = Test::MockModule->new('Koha::Patron');
1571     $patron_mock->mock( 'article_request_fee', sub { return $amount; } );
1572
1573     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1574
1575     is( $patron->article_request_fee, $amount, 'article_request_fee mocked' );
1576
1577     my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
1578     my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
1579     my $staff     = $builder->build_object( { class => 'Koha::Patrons' } );
1580     my $item      = $builder->build_sample_item;
1581
1582     t::lib::Mocks::mock_userenv(
1583         { branchcode => $library_1->id, patron => $staff } );
1584
1585     my $debit = $patron->add_article_request_fee_if_needed();
1586     is( $debit, undef, 'No fee, no debit line' );
1587
1588     # positive value
1589     $amount = 1;
1590
1591     $debit = $patron->add_article_request_fee_if_needed({ item_id => $item->id });
1592     is( ref($debit), 'Koha::Account::Line', 'Debit object type correct' );
1593     is( $debit->amount, $amount,
1594         'amount set to $patron->article_request_fee value' );
1595     is( $debit->manager_id, $staff->id,
1596         'manager_id set to userenv session user' );
1597     is( $debit->branchcode, $library_1->id,
1598         'branchcode set to userenv session library' );
1599     is( $debit->debit_type_code, 'ARTICLE_REQUEST',
1600         'debit_type_code set correctly' );
1601     is( $debit->itemnumber, $item->id,
1602         'itemnumber set correctly' );
1603
1604     $amount = 100;
1605
1606     $debit = $patron->add_article_request_fee_if_needed({ library_id => $library_2->id });
1607     is( ref($debit), 'Koha::Account::Line', 'Debit object type correct' );
1608     is( $debit->amount, $amount,
1609         'amount set to $patron->article_request_fee value' );
1610     is( $debit->branchcode, $library_2->id,
1611         'branchcode set to userenv session library' );
1612     is( $debit->itemnumber, undef,
1613         'itemnumber set correctly to undef' );
1614
1615     $schema->storage->txn_rollback;
1616 };
1617
1618 subtest 'messages' => sub {
1619     plan tests => 4;
1620
1621     $schema->storage->txn_begin;
1622
1623     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1624     my $messages = $patron->messages;
1625     is( $messages->count, 0, "No message yet" );
1626     my $message_1 = $builder->build_object(
1627         {
1628             class => 'Koha::Patron::Messages',
1629             value => { borrowernumber => $patron->borrowernumber }
1630         }
1631     );
1632     my $message_2 = $builder->build_object(
1633         {
1634             class => 'Koha::Patron::Messages',
1635             value => { borrowernumber => $patron->borrowernumber }
1636         }
1637     );
1638
1639     $messages = $patron->messages;
1640     is( $messages->count, 2, "There are two messages for this patron" );
1641     is( $messages->next->message, $message_1->message );
1642     is( $messages->next->message, $message_2->message );
1643     $schema->storage->txn_rollback;
1644 };
1645
1646 subtest 'recalls() tests' => sub {
1647
1648     plan tests => 3;
1649
1650     $schema->storage->txn_begin;
1651
1652     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1653     my $biblio1 = $builder->build_object({ class => 'Koha::Biblios' });
1654     my $item1 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $biblio1->biblionumber } });
1655     my $biblio2 = $builder->build_object({ class => 'Koha::Biblios' });
1656     my $item2 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $biblio2->biblionumber } });
1657
1658     Koha::Recall->new(
1659         {   biblio_id         => $biblio1->biblionumber,
1660             patron_id         => $patron->borrowernumber,
1661             item_id           => $item1->itemnumber,
1662             pickup_library_id => $patron->branchcode,
1663             created_date      => \'NOW()',
1664             item_level        => 1,
1665         }
1666     )->store;
1667     Koha::Recall->new(
1668         {   biblio_id         => $biblio2->biblionumber,
1669             patron_id         => $patron->borrowernumber,
1670             item_id           => $item2->itemnumber,
1671             pickup_library_id => $patron->branchcode,
1672             created_date      => \'NOW()',
1673             item_level        => 1,
1674         }
1675     )->store;
1676     Koha::Recall->new(
1677         {   biblio_id         => $biblio1->biblionumber,
1678             patron_id         => $patron->borrowernumber,
1679             item_id           => undef,
1680             pickup_library_id => $patron->branchcode,
1681             created_date      => \'NOW()',
1682             item_level        => 0,
1683         }
1684     )->store;
1685     my $recall = Koha::Recall->new(
1686         {   biblio_id         => $biblio1->biblionumber,
1687             patron_id         => $patron->borrowernumber,
1688             item_id           => undef,
1689             pickup_library_id => $patron->branchcode,
1690             created_date      => \'NOW()',
1691             item_level        => 0,
1692         }
1693     )->store;
1694     $recall->set_cancelled;
1695
1696     is( $patron->recalls->count,                                                                       4, "Correctly gets this patron's recalls" );
1697     is( $patron->recalls->filter_by_current->count,                                                    3, "Correctly gets this patron's active recalls" );
1698     is( $patron->recalls->filter_by_current->search( { biblio_id => $biblio1->biblionumber } )->count, 2, "Correctly gets this patron's active recalls on a specific biblio" );
1699
1700     $schema->storage->txn_rollback;
1701 };
1702
1703 subtest 'encode_secret and decoded_secret' => sub {
1704     plan tests => 5;
1705     $schema->storage->txn_begin;
1706
1707     t::lib::Mocks::mock_config('encryption_key', 't0P_secret');
1708
1709     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1710     is( $patron->decoded_secret, undef, 'TestBuilder does not initialize it' );
1711     $patron->secret(q{});
1712     is( $patron->decoded_secret, q{}, 'Empty string case' );
1713
1714     $patron->encode_secret('encrypt_me'); # Note: lazy testing; should be base32 string normally.
1715     is( length($patron->secret) > 0, 1, 'Secret length' );
1716     isnt( $patron->secret, 'encrypt_me', 'Encrypted column' );
1717     is( $patron->decoded_secret, 'encrypt_me', 'Decrypted column' );
1718
1719     $schema->storage->txn_rollback;
1720 };
1721
1722 subtest 'notify_library_of_registration()' => sub {
1723
1724     plan tests => 6;
1725
1726     $schema->storage->txn_begin;
1727     my $dbh = C4::Context->dbh;
1728
1729     my $library = $builder->build_object(
1730         {
1731             class => 'Koha::Libraries',
1732             value => {
1733                 branchemail   => 'from@mybranch.com',
1734                 branchreplyto => 'to@mybranch.com'
1735             }
1736         }
1737     );
1738     my $patron = $builder->build_object(
1739         {
1740             class => 'Koha::Patrons',
1741             value => {
1742                 branchcode => $library->branchcode
1743             }
1744         }
1745     );
1746
1747     t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'root@localhost' );
1748     t::lib::Mocks::mock_preference( 'EmailAddressForPatronRegistrations', 'library@localhost' );
1749
1750     # Test when EmailPatronRegistrations equals BranchEmailAddress
1751     t::lib::Mocks::mock_preference( 'EmailPatronRegistrations', 'BranchEmailAddress' );
1752     is( $patron->notify_library_of_registration(C4::Context->preference('EmailPatronRegistrations')), 1, 'OPAC_REG email is queued if EmailPatronRegistration syspref equals BranchEmailAddress');
1753     my $sth = $dbh->prepare("SELECT to_address FROM message_queue where borrowernumber = ?");
1754     $sth->execute( $patron->borrowernumber );
1755     my $to_address = $sth->fetchrow_array;
1756     is( $to_address, 'to@mybranch.com', 'OPAC_REG email queued to go to branchreplyto address when EmailPatronRegistration equals BranchEmailAddress' );
1757     $dbh->do(q|DELETE FROM message_queue|);
1758
1759     # Test when EmailPatronRegistrations equals EmailAddressForPatronRegistrations
1760     t::lib::Mocks::mock_preference( 'EmailPatronRegistrations', 'EmailAddressForPatronRegistrations' );
1761     is( $patron->notify_library_of_registration(C4::Context->preference('EmailPatronRegistrations')), 1, 'OPAC_REG email is queued if EmailPatronRegistration syspref equals EmailAddressForPatronRegistrations');
1762     $sth->execute( $patron->borrowernumber );
1763     $to_address = $sth->fetchrow_array;
1764     is( $to_address, 'library@localhost', 'OPAC_REG email queued to go to EmailAddressForPatronRegistrations syspref when EmailPatronRegistration equals EmailAddressForPatronRegistrations' );
1765     $dbh->do(q|DELETE FROM message_queue|);
1766
1767     # Test when EmailPatronRegistrations equals KohaAdminEmailAddress
1768     t::lib::Mocks::mock_preference( 'EmailPatronRegistrations', 'KohaAdminEmailAddress' );
1769     t::lib::Mocks::mock_preference( 'ReplyToDefault', 'root@localhost' ); # FIXME Remove localhost
1770     is( $patron->notify_library_of_registration(C4::Context->preference('EmailPatronRegistrations')), 1, 'OPAC_REG email is queued if EmailPatronRegistration syspref equals KohaAdminEmailAddress');
1771     $sth->execute( $patron->borrowernumber );
1772     $to_address = $sth->fetchrow_array;
1773     is( $to_address, 'root@localhost', 'OPAC_REG email queued to go to KohaAdminEmailAddress syspref when EmailPatronRegistration equals KohaAdminEmailAddress' );
1774     $dbh->do(q|DELETE FROM message_queue|);
1775
1776     $schema->storage->txn_rollback;
1777 };
1778
1779 subtest 'notice_email_address' => sub {
1780     plan tests => 2;
1781     $schema->storage->txn_begin;
1782
1783     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1784
1785     t::lib::Mocks::mock_preference( 'EmailFieldPrecedence', 'email|emailpro' );
1786     t::lib::Mocks::mock_preference( 'EmailFieldPrimary', 'OFF' );
1787     is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when EmailFieldPrimary is off");
1788
1789     t::lib::Mocks::mock_preference( 'EmailFieldPrimary', 'emailpro' );
1790     is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when EmailFieldPrimary is emailpro");
1791
1792     $patron->delete;
1793     $schema->storage->txn_rollback;
1794 };
1795
1796 subtest 'first_valid_email_address' => sub {
1797     plan tests => 1;
1798     $schema->storage->txn_begin;
1799
1800     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { emailpro => ''}});
1801
1802     t::lib::Mocks::mock_preference( 'EmailFieldPrecedence', 'emailpro|email' );
1803     is ($patron->first_valid_email_address, $patron->email, "Koha::Patron->first_valid_email_address returns correct value when EmailFieldPrecedence is 'emailpro|email' and emailpro is empty");
1804
1805     $patron->delete;
1806     $schema->storage->txn_rollback;
1807 };
1808
1809 subtest 'get_savings tests' => sub {
1810
1811     plan tests => 4;
1812
1813     $schema->storage->txn_begin;
1814
1815     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1816     my $patron = $builder->build_object({ class => 'Koha::Patrons' }, { value => { branchcode => $library->branchcode } });
1817
1818     t::lib::Mocks::mock_userenv({ patron => $patron, branchcode => $library->branchcode });
1819
1820     my $biblio = $builder->build_sample_biblio;
1821     my $item1 = $builder->build_sample_item(
1822         {
1823             biblionumber     => $biblio->biblionumber,
1824             library          => $library->branchcode,
1825             replacementprice => rand(20),
1826         }
1827     );
1828     my $item2 = $builder->build_sample_item(
1829         {
1830             biblionumber     => $biblio->biblionumber,
1831             library          => $library->branchcode,
1832             replacementprice => rand(20),
1833         }
1834     );
1835
1836     is( $patron->get_savings, 0, 'No checkouts, no savings' );
1837
1838     # Add an old checkout with deleted itemnumber
1839     $builder->build_object({ class => 'Koha::Old::Checkouts', value => { itemnumber => undef, borrowernumber => $patron->id } });
1840
1841     is( $patron->get_savings, 0, 'No checkouts with itemnumber, no savings' );
1842
1843     AddIssue( $patron, $item1->barcode );
1844     AddIssue( $patron, $item2->barcode );
1845
1846     my $savings = $patron->get_savings;
1847     is( $savings + 0, $item1->replacementprice + $item2->replacementprice, "Savings correctly calculated from current issues" );
1848
1849     AddReturn( $item2->barcode, $item2->homebranch );
1850
1851     $savings = $patron->get_savings;
1852     is( $savings + 0, $item1->replacementprice + $item2->replacementprice, "Savings correctly calculated from current and old issues" );
1853
1854     $schema->storage->txn_rollback;
1855 };
1856
1857 subtest 'update privacy tests' => sub {
1858     $schema->storage->txn_begin;
1859
1860     plan tests => 5;
1861
1862     $schema->storage->txn_begin;
1863     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { privacy => 1 } });
1864
1865     my $old_checkout = $builder->build_object({ class => 'Koha::Old::Checkouts', value => { borrowernumber => $patron->id } });
1866
1867     t::lib::Mocks::mock_preference( 'AnonymousPatron', '0' );
1868
1869     $patron->privacy(2); #set to never
1870
1871     throws_ok{ $patron->store } 'Koha::Exceptions::Patron::FailedAnonymizing', 'We throw an exception when anonymizing fails';
1872
1873     $old_checkout->discard_changes; #refresh from db
1874     $patron->discard_changes;
1875
1876     is( $old_checkout->borrowernumber, $patron->id, "When anonymizing fails, we don't clear the checkouts");
1877     is( $patron->privacy(), 1, "When anonymizing fails, we don't chaneg the privacy");
1878
1879     my $anon_patron = $builder->build_object({ class => 'Koha::Patrons'});
1880     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anon_patron->id );
1881
1882     $patron->privacy(2)->store(); #set to never
1883
1884     $old_checkout->discard_changes; #refresh from db
1885     $patron->discard_changes;
1886
1887     is( $old_checkout->borrowernumber, $anon_patron->id, "Checkout is successfully anonymized");
1888     is( $patron->privacy(), 2, "Patron privacy is successfully updated");
1889
1890     $schema->storage->txn_rollback;
1891 };
1892
1893 subtest 'alert_subscriptions tests' => sub {
1894
1895     plan tests => 3;
1896     $schema->storage->txn_begin;
1897
1898     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1899
1900     my $subscription1 = $builder->build_object( { class => 'Koha::Subscriptions' } );
1901     $subscription1->add_subscriber($patron);
1902
1903     my $subscription2 = $builder->build_object( { class => 'Koha::Subscriptions' } );
1904     $subscription2->add_subscriber($patron);
1905
1906     my @subscriptions = $patron->alert_subscriptions->as_list;
1907
1908     is( @subscriptions, 2, "Number of patron's subscribed alerts successfully fetched" );
1909     is( $subscriptions[0]->subscriptionid, $subscription1->subscriptionid, "First subscribed alert is correct" );
1910     is( $subscriptions[1]->subscriptionid, $subscription2->subscriptionid, "Second subscribed alert is correct" );
1911
1912     $patron->discard_changes;
1913     $schema->storage->txn_rollback;
1914 };
1915
1916 subtest 'test patron_consent' => sub {
1917     plan tests => 4;
1918     $schema->storage->txn_begin;
1919
1920     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1921     throws_ok { $patron->consent } 'Koha::Exceptions::MissingParameter', 'missing type';
1922
1923     my $consent = $patron->consent('GDPR_PROCESSING');
1924     is( ref $consent, 'Koha::Patron::Consent', 'return type check' );
1925     $consent->given_on('2021-02-03')->store;
1926     undef $consent;
1927     is( $patron->consent('GDPR_PROCESSING')->given_on, '2021-02-03 00:00:00', 'check date' );
1928
1929     is( $patron->consent('NOT_EXIST')->refused_on, undef, 'New empty object for new type' );
1930
1931     $schema->storage->txn_rollback;
1932 };
1933
1934 subtest 'update_lastseen tests' => sub {
1935
1936     plan tests => 24;
1937     $schema->storage->txn_begin;
1938
1939     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1940     my $userid = $patron->userid;
1941
1942     $patron->lastseen(undef);
1943     $patron->store();
1944
1945     my $cache     = Koha::Caches->get_instance();
1946     my $cache_key = "track_activity_" . $patron->borrowernumber;
1947     $cache->clear_from_cache($cache_key);
1948
1949     t::lib::Mocks::mock_preference(
1950         'TrackLastPatronActivityTriggers',
1951         'login,connection,check_in,check_out,renewal,hold,article'
1952     );
1953
1954     is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
1955
1956     my $now = dt_from_string();
1957     Time::Fake->offset( $now->epoch );
1958
1959     $patron->update_lastseen('login');
1960     $patron->_result()->discard_changes();
1961     isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivityTriggers contains values' );
1962     my $last_seen = $patron->lastseen;
1963
1964     Time::Fake->offset( $now->epoch + 5 );
1965
1966     # Test that lastseen isn't updated more than once in a day (regardless of activity passed)
1967     $patron->update_lastseen('login');
1968     $patron->_result()->discard_changes();
1969     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged after a login' );
1970     $patron->update_lastseen('connection');
1971     $patron->_result()->discard_changes();
1972     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged after a SIP/ILSDI connection' );
1973     $patron->update_lastseen('check_out');
1974     $patron->_result()->discard_changes();
1975     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged after a check out' );
1976     $patron->update_lastseen('check_in');
1977     $patron->_result()->discard_changes();
1978     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged after a check in' );
1979     $patron->update_lastseen('renewal');
1980     $patron->_result()->discard_changes();
1981     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged after a renewal' );
1982     $patron->update_lastseen('hold');
1983     $patron->_result()->discard_changes();
1984     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged after a hold' );
1985     $patron->update_lastseen('article');
1986     $patron->_result()->discard_changes();
1987     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged after a article' );
1988
1989     # Check that tracking is disabled when the activity isn't listed
1990     t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', '' );
1991     $cache->clear_from_cache($cache_key);    # Rule out the more than once day prevention above
1992
1993     $patron->update_lastseen('login');
1994     $patron->_result()->discard_changes();
1995     is(
1996         $patron->lastseen, $last_seen,
1997         'Patron last seen should be unchanged after a login if login is not selected as an option and the cache has been cleared'
1998     );
1999
2000     $patron->update_lastseen('connection');
2001     $patron->_result()->discard_changes();
2002     is(
2003         $patron->lastseen, $last_seen,
2004         'Patron last seen should be unchanged after a connection if connection is not selected as an option and the cache has been cleared'
2005     );
2006
2007     $patron->update_lastseen('check_in');
2008     $patron->_result()->discard_changes();
2009     is(
2010         $patron->lastseen, $last_seen,
2011         'Patron last seen should be unchanged after a check_in if check_in is not selected as an option and the cache has been cleared'
2012     );
2013
2014     $patron->update_lastseen('check_out');
2015     $patron->_result()->discard_changes();
2016     is(
2017         $patron->lastseen, $last_seen,
2018         'Patron last seen should be unchanged after a check_out if check_out is not selected as an option and the cache has been cleared'
2019     );
2020
2021     $patron->update_lastseen('renewal');
2022     $patron->_result()->discard_changes();
2023     is(
2024         $patron->lastseen, $last_seen,
2025         'Patron last seen should be unchanged after a renewal if renewal is not selected as an option and the cache has been cleared'
2026     );
2027     $patron->update_lastseen('hold');
2028     $patron->_result()->discard_changes();
2029     is(
2030         $patron->lastseen, $last_seen,
2031         'Patron last seen should be unchanged after a hold if hold is not selected as an option and the cache has been cleared'
2032     );
2033     $patron->update_lastseen('article');
2034     $patron->_result()->discard_changes();
2035     is(
2036         $patron->lastseen, $last_seen,
2037         'Patron last seen should be unchanged after an article request if article is not selected as an option and the cache has been cleared'
2038     );
2039
2040     # Check tracking for each activity
2041     t::lib::Mocks::mock_preference(
2042         'TrackLastPatronActivityTriggers',
2043         'login,connection,check_in,check_out,renewal,hold,article'
2044     );
2045
2046     $cache->clear_from_cache($cache_key);
2047     $patron->update_lastseen('login');
2048     $patron->_result()->discard_changes();
2049     isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed after a login if we cleared the cache' );
2050
2051     $cache->clear_from_cache($cache_key);
2052     $patron->update_lastseen('connection');
2053     $patron->_result()->discard_changes();
2054     isnt(
2055         $patron->lastseen, $last_seen,
2056         'Patron last seen should be changed after a connection if we cleared the cache'
2057     );
2058
2059     $cache->clear_from_cache($cache_key);
2060     $patron->update_lastseen('check_out');
2061     $patron->_result()->discard_changes();
2062     isnt(
2063         $patron->lastseen, $last_seen,
2064         'Patron last seen should be changed after a check_out if we cleared the cache'
2065     );
2066
2067     $cache->clear_from_cache($cache_key);
2068     $patron->update_lastseen('check_in');
2069     $patron->_result()->discard_changes();
2070     isnt(
2071         $patron->lastseen, $last_seen,
2072         'Patron last seen should be changed after a check_in if we cleared the cache'
2073     );
2074
2075     $cache->clear_from_cache($cache_key);
2076     $patron->update_lastseen('hold');
2077     $patron->_result()->discard_changes();
2078     isnt(
2079         $patron->lastseen, $last_seen,
2080         'Patron last seen should be changed after a hold if we cleared the cache'
2081     );
2082     $patron->update_lastseen('article');
2083     $patron->_result()->discard_changes();
2084     isnt(
2085         $patron->lastseen, $last_seen,
2086         'Patron last seen should be changed after a article if we cleared the cache'
2087     );
2088
2089     $cache->clear_from_cache($cache_key);
2090     $patron->update_lastseen('renewal');
2091     $patron->_result()->discard_changes();
2092     isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed after a renewal if we cleared the cache' );
2093
2094     # Check that the preference takes effect
2095     t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', '' );
2096     $patron->lastseen(undef)->store;
2097     $cache->clear_from_cache($cache_key);
2098     $patron->update_lastseen('login');
2099     $patron->_result()->discard_changes();
2100     is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivityTriggers is unset' );
2101
2102     Time::Fake->reset;
2103     $schema->storage->txn_rollback;
2104 };