Bug 17733: Fix Members.t
[koha.git] / t / db_dependent / Members.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use Test::More tests => 79;
21 use Test::MockModule;
22 use Data::Dumper;
23 use C4::Context;
24 use Koha::Database;
25 use Koha::Holds;
26 use Koha::List::Patron;
27 use Koha::Patrons;
28
29 use t::lib::Mocks;
30 use t::lib::TestBuilder;
31
32 BEGIN {
33         use_ok('C4::Members');
34 }
35
36 my $schema = Koha::Database->schema;
37 $schema->storage->txn_begin;
38 my $builder = t::lib::TestBuilder->new;
39 my $dbh = C4::Context->dbh;
40 $dbh->{RaiseError} = 1;
41
42 my $library1 = $builder->build({
43     source => 'Branch',
44 });
45 my $library2 = $builder->build({
46     source => 'Branch',
47 });
48 my $CARDNUMBER   = 'TESTCARD01';
49 my $FIRSTNAME    = 'Marie';
50 my $SURNAME      = 'Mcknight';
51 my $CATEGORYCODE = 'S';
52 my $BRANCHCODE   = $library1->{branchcode};
53
54 my $CHANGED_FIRSTNAME = "Marry Ann";
55 my $EMAIL             = "Marie\@email.com";
56 my $EMAILPRO          = "Marie\@work.com";
57 my $PHONE             = "555-12123";
58
59 # XXX should be randomised and checked against the database
60 my $IMPOSSIBLE_CARDNUMBER = "XYZZZ999";
61
62 #my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $branchname, $userflags, $emailaddress, $branchprinter)= @_;
63 my @USERENV = (
64     1,
65     'test',
66     'MASTERTEST',
67     'Test',
68     'Test',
69     't',
70     'Test',
71     0,
72 );
73 my $BRANCH_IDX = 5;
74
75 C4::Context->_new_userenv ('DUMMY_SESSION_ID');
76 C4::Context->set_userenv ( @USERENV );
77
78 my $userenv = C4::Context->userenv
79   or BAIL_OUT("No userenv");
80
81 # Make a borrower for testing
82 my %data = (
83     cardnumber => $CARDNUMBER,
84     firstname =>  $FIRSTNAME,
85     surname => $SURNAME,
86     categorycode => $CATEGORYCODE,
87     branchcode => $BRANCHCODE,
88     dateofbirth => '',
89     dateexpiry => '9999-12-31',
90     userid => 'tomasito'
91 );
92
93 testAgeAccessors(\%data); #Age accessor tests don't touch the db so it is safe to run them with just the object.
94
95 my $addmem=AddMember(%data);
96 ok($addmem, "AddMember()");
97
98 my $member=GetMemberDetails("",$CARDNUMBER)
99   or BAIL_OUT("Cannot read member with card $CARDNUMBER");
100
101 ok ( $member->{firstname}    eq $FIRSTNAME    &&
102      $member->{surname}      eq $SURNAME      &&
103      $member->{categorycode} eq $CATEGORYCODE &&
104      $member->{branchcode}   eq $BRANCHCODE
105      , "Got member")
106   or diag("Mismatching member details: ".Dumper(\%data, $member));
107
108 is($member->{dateofbirth}, undef, "Empty dates handled correctly");
109
110 $member->{firstname} = $CHANGED_FIRSTNAME;
111 $member->{email}     = $EMAIL;
112 $member->{phone}     = $PHONE;
113 $member->{emailpro}  = $EMAILPRO;
114 ModMember(%$member);
115 my $changedmember=GetMemberDetails("",$CARDNUMBER);
116 ok ( $changedmember->{firstname} eq $CHANGED_FIRSTNAME &&
117      $changedmember->{email}     eq $EMAIL             &&
118      $changedmember->{phone}     eq $PHONE             &&
119      $changedmember->{emailpro}  eq $EMAILPRO
120      , "Member Changed")
121   or diag("Mismatching member details: ".Dumper($member, $changedmember));
122
123 t::lib::Mocks::mock_preference( 'CardnumberLength', '' );
124 C4::Context->clear_syspref_cache();
125
126 my $checkcardnum=C4::Members::checkcardnumber($CARDNUMBER, "");
127 is ($checkcardnum, "1", "Card No. in use");
128
129 $checkcardnum=C4::Members::checkcardnumber($IMPOSSIBLE_CARDNUMBER, "");
130 is ($checkcardnum, "0", "Card No. not used");
131
132 t::lib::Mocks::mock_preference( 'CardnumberLength', '4' );
133 C4::Context->clear_syspref_cache();
134
135 $checkcardnum=C4::Members::checkcardnumber($IMPOSSIBLE_CARDNUMBER, "");
136 is ($checkcardnum, "2", "Card number is too long");
137
138
139
140 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
141 C4::Context->clear_syspref_cache();
142
143 my $notice_email = GetNoticeEmailAddress($member->{'borrowernumber'});
144 is ($notice_email, $EMAIL, "GetNoticeEmailAddress returns correct value when AutoEmailPrimaryAddress is off");
145
146 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
147 C4::Context->clear_syspref_cache();
148
149 $notice_email = GetNoticeEmailAddress($member->{'borrowernumber'});
150 is ($notice_email, $EMAILPRO, "GetNoticeEmailAddress returns correct value when AutoEmailPrimaryAddress is emailpro");
151
152 ok(!$member->{is_expired}, "GetMemberDetails() indicates that patron is not expired");
153 ModMember(borrowernumber => $member->{'borrowernumber'}, dateexpiry => '2001-01-1');
154 $member = GetMemberDetails($member->{'borrowernumber'});
155 ok($member->{is_expired}, "GetMemberDetails() indicates that patron is expired");
156
157 # Check_Userid tests
158 %data = (
159     cardnumber   => "123456789",
160     firstname    => "Tomasito",
161     surname      => "None",
162     categorycode => "S",
163     branchcode   => $library2->{branchcode},
164     dateofbirth  => '',
165     debarred     => '',
166     dateexpiry   => '',
167     dateenrolled => '',
168 );
169 # Add a new borrower
170 my $borrowernumber = AddMember( %data );
171 is( Check_Userid( 'tomasito.non', $borrowernumber ), 1,
172     'recently created userid -> unique (borrowernumber passed)' );
173 is( Check_Userid( 'tomasitoxxx', $borrowernumber ), 1,
174     'non-existent userid -> unique (borrowernumber passed)' );
175 is( Check_Userid( 'tomasito.none', '' ), 0,
176     'userid exists (blank borrowernumber)' );
177 is( Check_Userid( 'tomasitoxxx', '' ), 1,
178     'non-existent userid -> unique (blank borrowernumber)' );
179
180 my $borrower = GetMember( borrowernumber => $borrowernumber );
181 is( $borrower->{dateofbirth}, undef, 'AddMember should undef dateofbirth if empty string is given');
182 is( $borrower->{debarred}, undef, 'AddMember should undef debarred if empty string is given');
183 isnt( $borrower->{dateexpiry}, '0000-00-00', 'AddMember should not set dateexpiry to 0000-00-00 if empty string is given');
184 isnt( $borrower->{dateenrolled}, '0000-00-00', 'AddMember should not set dateenrolled to 0000-00-00 if empty string is given');
185
186 ModMember( borrowernumber => $borrowernumber, dateofbirth => '', debarred => '', dateexpiry => '', dateenrolled => '' );
187 $borrower = GetMember( borrowernumber => $borrowernumber );
188 is( $borrower->{dateofbirth}, undef, 'ModMember should undef dateofbirth if empty string is given');
189 is( $borrower->{debarred}, undef, 'ModMember should undef debarred if empty string is given');
190 isnt( $borrower->{dateexpiry}, '0000-00-00', 'ModMember should not set dateexpiry to 0000-00-00 if empty string is given');
191 isnt( $borrower->{dateenrolled}, '0000-00-00', 'ModMember should not set dateenrolled to 0000-00-00 if empty string is given');
192
193 ModMember( borrowernumber => $borrowernumber, dateofbirth => '1970-01-01', debarred => '2042-01-01', dateexpiry => '9999-12-31', dateenrolled => '2015-09-06' );
194 $borrower = GetMember( borrowernumber => $borrowernumber );
195 is( $borrower->{dateofbirth}, '1970-01-01', 'ModMember should correctly set dateofbirth if a valid date is given');
196 is( $borrower->{debarred}, '2042-01-01', 'ModMember should correctly set debarred if a valid date is given');
197 is( $borrower->{dateexpiry}, '9999-12-31', 'ModMember should correctly set dateexpiry if a valid date is given');
198 is( $borrower->{dateenrolled}, '2015-09-06', 'ModMember should correctly set dateenrolled if a valid date is given');
199
200 # Add a new borrower with the same userid but different cardnumber
201 $data{ cardnumber } = "987654321";
202 my $new_borrowernumber = AddMember( %data );
203 is( Check_Userid( 'tomasito.none', '' ), 0,
204     'userid not unique (blank borrowernumber)' );
205 is( Check_Userid( 'tomasito.none', $new_borrowernumber ), 0,
206     'userid not unique (second borrowernumber passed)' );
207 $borrower = GetMember( borrowernumber => $new_borrowernumber );
208 ok( $borrower->{userid} ne 'tomasito', "Borrower with duplicate userid has new userid generated" );
209
210 $data{ cardnumber } = "234567890";
211 $data{userid} = 'a_user_id';
212 $borrowernumber = AddMember( %data );
213 $borrower = GetMember( borrowernumber => $borrowernumber );
214 is( $borrower->{userid}, $data{userid}, 'AddMember should insert the given userid' );
215
216 subtest 'ModMember should not update userid if not true' => sub {
217     plan tests => 3;
218     ModMember( borrowernumber => $borrowernumber, firstname => 'Tomas', userid => '' );
219     $borrower = GetMember( borrowernumber => $borrowernumber );
220     is ( $borrower->{userid}, $data{userid}, 'ModMember should not update the userid with an empty string' );
221     ModMember( borrowernumber => $borrowernumber, firstname => 'Tomas', userid => 0 );
222     $borrower = GetMember( borrowernumber => $borrowernumber );
223     is ( $borrower->{userid}, $data{userid}, 'ModMember should not update the userid with an 0');
224     ModMember( borrowernumber => $borrowernumber, firstname => 'Tomas', userid => undef );
225     $borrower = GetMember( borrowernumber => $borrowernumber );
226     is ( $borrower->{userid}, $data{userid}, 'ModMember should not update the userid with an undefined value');
227 };
228
229 #Regression tests for bug 10612
230 my $library3 = $builder->build({
231     source => 'Branch',
232 });
233 $builder->build({
234         source => 'Category',
235         value => {
236             categorycode         => 'STAFFER',
237             description          => 'Staff dont batch del',
238             category_type        => 'S',
239         },
240 });
241
242 $builder->build({
243         source => 'Category',
244         value => {
245             categorycode         => 'CIVILIAN',
246             description          => 'Civilian batch del',
247             category_type        => 'A',
248         },
249 });
250
251 $builder->build({
252         source => 'Category',
253         value => {
254             categorycode         => 'KIDclamp',
255             description          => 'Kid to be guaranteed',
256             category_type        => 'C',
257         },
258 });
259
260 my $borrower1 = $builder->build({
261         source => 'Borrower',
262         value  => {
263             categorycode=>'STAFFER',
264             branchcode => $library3->{branchcode},
265             dateexpiry => '2015-01-01',
266         },
267 });
268 my $bor1inlist = $borrower1->{borrowernumber};
269 my $borrower2 = $builder->build({
270         source => 'Borrower',
271         value  => {
272             categorycode=>'STAFFER',
273             branchcode => $library3->{branchcode},
274             dateexpiry => '2015-01-01',
275         },
276 });
277
278 my $guarantee = $builder->build({
279         source => 'Borrower',
280         value  => {
281             categorycode=>'KIDclamp',
282             branchcode => $library3->{branchcode},
283             dateexpiry => '2015-01-01',
284         },
285 });
286
287 my $bor2inlist = $borrower2->{borrowernumber};
288
289 $builder->build({
290         source => 'OldIssue',
291         value  => {
292             borrowernumber => $bor2inlist,
293             timestamp => '2016-01-01',
294         },
295 });
296
297 # In some dirty DB, the guarantorid is set to a non existent patron id
298 # If we pick it, then the tests will fail
299 # This should not be needed, we should have a FK on the guarantorid instead
300 Koha::Patrons->search({ guarantorid => { -in => [ $borrower1->{borrowernumber}, $borrower2->{borrowernumber} ] }})->update({ guarantorid => undef });
301
302 my $owner = AddMember (categorycode => 'STAFFER', branchcode => $library2->{branchcode} );
303 my $list1 = AddPatronList( { name => 'Test List 1', owner => $owner } );
304 my @listpatrons = ($bor1inlist, $bor2inlist);
305 AddPatronsToList(  { list => $list1, borrowernumbers => \@listpatrons });
306 my $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id() } );
307 is( scalar(@$patstodel),0,'No staff deleted from list of all staff');
308 ModMember( borrowernumber => $bor2inlist, categorycode => 'CIVILIAN' );
309 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
310 ok( scalar(@$patstodel)== 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted from list');
311 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
312 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by branchcode and list');
313 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } );
314 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by expirationdate and list');
315 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
316 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by last issue date');
317
318 ModMember( borrowernumber => $bor1inlist, categorycode => 'CIVILIAN' );
319 ModMember( borrowernumber => $guarantee->{borrowernumber} ,guarantorid=>$bor1inlist );
320
321 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
322 ok( scalar(@$patstodel)== 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted from list');
323 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
324 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by branchcode and list');
325 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } );
326 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by expirationdate and list');
327 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
328 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by last issue date');
329 ModMember( borrowernumber => $guarantee->{borrowernumber}, guarantorid=>'' );
330
331 $builder->build({
332         source => 'Issue',
333         value  => {
334             borrowernumber => $bor2inlist,
335         },
336 });
337 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
338 is( scalar(@$patstodel),1,'Borrower with issue not deleted from list');
339 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
340 is( scalar(@$patstodel),1,'Borrower with issue not deleted by branchcode and list');
341 $patstodel = GetBorrowersToExpunge( {category_code => 'CIVILIAN',patron_list_id => $list1->patron_list_id() } );
342 is( scalar(@$patstodel),1,'Borrower with issue not deleted by category_code and list');
343 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02',patron_list_id => $list1->patron_list_id() } );
344 is( scalar(@$patstodel),1,'Borrower with issue not deleted by expiration_date and list');
345 $builder->schema->resultset( 'Issue' )->delete_all;
346 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
347 ok( scalar(@$patstodel)== 2,'Borrowers without issue deleted from list');
348 $patstodel = GetBorrowersToExpunge( {category_code => 'CIVILIAN',patron_list_id => $list1->patron_list_id() } );
349 is( scalar(@$patstodel),2,'Borrowers without issues deleted by category_code and list');
350 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02',patron_list_id => $list1->patron_list_id() } );
351 is( scalar(@$patstodel),2,'Borrowers without issues deleted by expiration_date and list');
352 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
353 is( scalar(@$patstodel),2,'Borrowers without issues deleted by last issue date');
354
355 # Test GetBorrowersToExpunge and TrackLastPatronActivity
356 $dbh->do(q|UPDATE borrowers SET lastseen=NULL|);
357 $builder->build({ source => 'Borrower', value => { lastseen => '2016-01-01 01:01:01', categorycode => 'CIVILIAN', guarantorid => undef } } );
358 $builder->build({ source => 'Borrower', value => { lastseen => '2016-02-02 02:02:02', categorycode => 'CIVILIAN', guarantorid => undef } } );
359 $builder->build({ source => 'Borrower', value => { lastseen => '2016-03-03 03:03:03', categorycode => 'CIVILIAN', guarantorid => undef } } );
360 $patstodel = GetBorrowersToExpunge( { last_seen => '1999-12-12' });
361 is( scalar @$patstodel, 0, 'TrackLastPatronActivity - 0 patrons must be deleted' );
362 $patstodel = GetBorrowersToExpunge( { last_seen => '2016-02-15' });
363 is( scalar @$patstodel, 2, 'TrackLastPatronActivity - 2 patrons must be deleted' );
364 $patstodel = GetBorrowersToExpunge( { last_seen => '2016-04-04' });
365 is( scalar @$patstodel, 3, 'TrackLastPatronActivity - 3 patrons must be deleted' );
366 my $patron2 = $builder->build({ source => 'Borrower', value => { lastseen => undef } });
367 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
368 Koha::Patrons->find( $patron2->{borrowernumber} )->track_login;
369 is( Koha::Patrons->find( $patron2->{borrowernumber} )->lastseen, undef, 'Lastseen should not be changed' );
370 Koha::Patrons->find( $patron2->{borrowernumber} )->track_login({ force => 1 });
371 isnt( Koha::Patrons->find( $patron2->{borrowernumber} )->lastseen, undef, 'Lastseen should be changed now' );
372
373 # Regression tests for BZ13502
374 ## Remove all entries with userid='' (should be only 1 max)
375 $dbh->do(q|DELETE FROM borrowers WHERE userid = ''|);
376 ## And create a patron with a userid=''
377 $borrowernumber = AddMember( categorycode => 'S', branchcode => $library2->{branchcode} );
378 $dbh->do(q|UPDATE borrowers SET userid = '' WHERE borrowernumber = ?|, undef, $borrowernumber);
379 # Create another patron and verify the userid has been generated
380 $borrowernumber = AddMember( categorycode => 'S', branchcode => $library2->{branchcode} );
381 ok( $borrowernumber > 0, 'AddMember should have inserted the patron even if no userid is given' );
382 $borrower = GetMember( borrowernumber => $borrowernumber );
383 ok( $borrower->{userid},  'A userid should have been generated correctly' );
384
385 # Regression tests for BZ12226
386 is( Check_Userid( C4::Context->config('user'), '' ), 0,
387     'Check_Userid should return 0 for the DB user (Bug 12226)');
388
389 subtest 'GetMemberAccountRecords' => sub {
390
391     plan tests => 2;
392
393     my $borrowernumber = $builder->build({ source => 'Borrower' })->{ borrowernumber };
394     my $accountline_1  = $builder->build({
395         source => 'Accountline',
396         value  => {
397             borrowernumber    => $borrowernumber,
398             amountoutstanding => 64.60
399         }
400     });
401
402     my ($total,undef,undef) = GetMemberAccountRecords( $borrowernumber );
403     is( $total , 64.60, "Rounding works correctly in total calculation (single value)" );
404
405     my $accountline_2 = $builder->build({
406         source => 'Accountline',
407         value  => {
408             borrowernumber    => $borrowernumber,
409             amountoutstanding => 10.65
410         }
411     });
412
413     ($total,undef,undef) = GetMemberAccountRecords( $borrowernumber );
414     is( $total , 75.25, "Rounding works correctly in total calculation (multiple values)" );
415
416 };
417
418 subtest 'GetMemberAccountBalance' => sub {
419
420     plan tests => 10;
421
422     my $members_mock = new Test::MockModule('C4::Members');
423     $members_mock->mock( 'GetMemberAccountRecords', sub {
424         my ($borrowernumber) = @_;
425         if ($borrowernumber) {
426             my @accountlines = (
427             { amountoutstanding => '7', accounttype => 'Rent' },
428             { amountoutstanding => '5', accounttype => 'Res' },
429             { amountoutstanding => '3', accounttype => 'Pay' } );
430             return ( 15, \@accountlines );
431         }
432         else {
433             my @accountlines;
434             return ( 0, \@accountlines );
435         }
436     });
437
438     my $person = GetMemberDetails(undef,undef);
439     ok( !$person , 'Expected no member details from undef,undef' );
440     $person = GetMemberDetails(undef,'987654321');
441     is( $person->{amountoutstanding}, 15,
442         'Expected 15 outstanding for cardnumber.');
443     $borrowernumber = $person->{borrowernumber};
444     $person = GetMemberDetails($borrowernumber,undef);
445     is( $person->{amountoutstanding}, 15,
446         'Expected 15 outstanding for borrowernumber.');
447     $person = GetMemberDetails($borrowernumber,'987654321');
448     is( $person->{amountoutstanding}, 15,
449         'Expected 15 outstanding for both borrowernumber and cardnumber.');
450
451     # do not count holds charges
452     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge', '1' );
453     t::lib::Mocks::mock_preference( 'ManInvInNoissuesCharge', '0' );
454     my ($total, $total_minus_charges,
455         $other_charges) = C4::Members::GetMemberAccountBalance(123);
456     is( $total, 15 , "Total calculated correctly");
457     is( $total_minus_charges, 15, "Holds charges are not count if HoldsInNoissuesCharge=1");
458     is( $other_charges, 0, "Holds charges are not considered if HoldsInNoissuesCharge=1");
459
460     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge', '0' );
461     ($total, $total_minus_charges,
462         $other_charges) = C4::Members::GetMemberAccountBalance(123);
463     is( $total, 15 , "Total calculated correctly");
464     is( $total_minus_charges, 10, "Holds charges are count if HoldsInNoissuesCharge=0");
465     is( $other_charges, 5, "Holds charges are considered if HoldsInNoissuesCharge=1");
466 };
467
468 subtest 'purgeSelfRegistration' => sub {
469     plan tests => 2;
470
471     #purge unverified
472     my $d=360;
473     C4::Members::DeleteUnverifiedOpacRegistrations($d);
474     foreach(1..3) {
475         $dbh->do("INSERT INTO borrower_modifications (timestamp, borrowernumber, verification_token) VALUES ('2014-01-01 01:02:03',0,?)", undef, (scalar localtime)."_$_");
476     }
477     is( C4::Members::DeleteUnverifiedOpacRegistrations($d), 3, 'Test for DeleteUnverifiedOpacRegistrations' );
478
479     #purge members in temporary category
480     my $c= 'XYZ';
481     $dbh->do("INSERT IGNORE INTO categories (categorycode) VALUES ('$c')");
482     t::lib::Mocks::mock_preference('PatronSelfRegistrationDefaultCategory', $c );
483     t::lib::Mocks::mock_preference('PatronSelfRegistrationExpireTemporaryAccountsDelay', 360);
484     C4::Members::DeleteExpiredOpacRegistrations();
485     $dbh->do("INSERT INTO borrowers (surname, address, city, branchcode, categorycode, dateenrolled) VALUES ('Testaabbcc', 'Street 1', 'CITY', ?, '$c', '2014-01-01 01:02:03')", undef, $library1->{branchcode});
486     is( C4::Members::DeleteExpiredOpacRegistrations(), 1, 'Test for DeleteExpiredOpacRegistrations');
487 };
488
489 sub _find_member {
490     my ($resultset) = @_;
491     my $found = $resultset && grep( { $_->{cardnumber} && $_->{cardnumber} eq $CARDNUMBER } @$resultset );
492     return $found;
493 }
494
495 # Regression tests for BZ15343
496 my $password="";
497 ( $borrowernumber, $password ) = AddMember_Opac(surname=>"Dick",firstname=>'Philip',branchcode => $library2->{branchcode});
498 is( $password =~ /^[a-zA-Z]{10}$/ , 1, 'Test for autogenerated password if none submitted');
499 ( $borrowernumber, $password ) = AddMember_Opac(surname=>"Deckard",firstname=>"Rick",password=>"Nexus-6",branchcode => $library2->{branchcode});
500 is( $password eq "Nexus-6", 1, 'Test password used if submitted');
501 $borrower = GetMember(borrowernumber => $borrowernumber);
502 my $hashed_up =  Koha::AuthUtils::hash_password("Nexus-6", $borrower->{password});
503 is( $borrower->{password} eq $hashed_up, 1, 'Check password hash equals hash of submitted password' );
504
505
506
507 ### ------------------------------------- ###
508 ### Testing GetAge() / SetAge() functions ###
509 ### ------------------------------------- ###
510 #USES the package $member-variable to mock a koha.borrowers-object
511 sub testAgeAccessors {
512     my ($member) = @_;
513     my $original_dateofbirth = $member->{dateofbirth};
514
515     ##Testing GetAge()
516     my $age=GetAge("1992-08-14", "2011-01-19");
517     is ($age, "18", "Age correct");
518
519     $age=GetAge("2011-01-19", "1992-01-19");
520     is ($age, "-19", "Birthday In the Future");
521
522     ##Testing SetAge() for now()
523     my $dt_now = DateTime->now();
524     $age = DateTime::Duration->new(years => 12, months => 6, days => 1);
525     C4::Members::SetAge( $member, $age );
526     $age = C4::Members::GetAge( $member->{dateofbirth} );
527     is ($age, '12', "SetAge 12 years");
528
529     $age = DateTime::Duration->new(years => 18, months => 12, days => 31);
530     C4::Members::SetAge( $member, $age );
531     $age = C4::Members::GetAge( $member->{dateofbirth} );
532     is ($age, '19', "SetAge 18+1 years"); #This is a special case, where months=>12 and days=>31 constitute one full year, hence we get age 19 instead of 18.
533
534     $age = DateTime::Duration->new(years => 18, months => 12, days => 30);
535     C4::Members::SetAge( $member, $age );
536     $age = C4::Members::GetAge( $member->{dateofbirth} );
537     is ($age, '19', "SetAge 18 years");
538
539     $age = DateTime::Duration->new(years => 0, months => 1, days => 1);
540     C4::Members::SetAge( $member, $age );
541     $age = C4::Members::GetAge( $member->{dateofbirth} );
542     is ($age, '0', "SetAge 0 years");
543
544     $age = '0018-12-31';
545     C4::Members::SetAge( $member, $age );
546     $age = C4::Members::GetAge( $member->{dateofbirth} );
547     is ($age, '19', "SetAge ISO_Date 18+1 years"); #This is a special case, where months=>12 and days=>31 constitute one full year, hence we get age 19 instead of 18.
548
549     $age = '0018-12-30';
550     C4::Members::SetAge( $member, $age );
551     $age = C4::Members::GetAge( $member->{dateofbirth} );
552     is ($age, '19', "SetAge ISO_Date 18 years");
553
554     $age = '18-1-1';
555     eval { C4::Members::SetAge( $member, $age ); };
556     is ((length $@ > 1), '1', "SetAge ISO_Date $age years FAILS");
557
558     $age = '0018-01-01';
559     eval { C4::Members::SetAge( $member, $age ); };
560     is ((length $@ == 0), '1', "SetAge ISO_Date $age years succeeds");
561
562     ##Testing SetAge() for relative_date
563     my $relative_date = DateTime->new(year => 3010, month => 3, day => 15);
564
565     $age = DateTime::Duration->new(years => 10, months => 3);
566     C4::Members::SetAge( $member, $age, $relative_date );
567     $age = C4::Members::GetAge( $member->{dateofbirth}, $relative_date->ymd() );
568     is ($age, '10', "SetAge, 10 years and 3 months old person was born on ".$member->{dateofbirth}." if todays is ".$relative_date->ymd());
569
570     $age = DateTime::Duration->new(years => 112, months => 1, days => 1);
571     C4::Members::SetAge( $member, $age, $relative_date );
572     $age = C4::Members::GetAge( $member->{dateofbirth}, $relative_date->ymd() );
573     is ($age, '112', "SetAge, 112 years, 1 months and 1 days old person was born on ".$member->{dateofbirth}." if today is ".$relative_date->ymd());
574
575     $age = '0112-01-01';
576     C4::Members::SetAge( $member, $age, $relative_date );
577     $age = C4::Members::GetAge( $member->{dateofbirth}, $relative_date->ymd() );
578     is ($age, '112', "SetAge ISO_Date, 112 years, 1 months and 1 days old person was born on ".$member->{dateofbirth}." if today is ".$relative_date->ymd());
579
580     $member->{dateofbirth} = $original_dateofbirth; #It is polite to revert made changes in the unit tests.
581 } #sub testAgeAccessors
582
583 # regression test for bug 16009
584 my $patron;
585 eval {
586     my $patron = GetMember(cardnumber => undef);
587 };
588 is($@, '', 'Bug 16009: GetMember(cardnumber => undef) works');
589 is($patron, undef, 'Bug 16009: GetMember(cardnumber => undef) returns undef');
590
591 1;