Bug 16891: Move C4::Members::MoveMemberToDeleted to Koha::Patron->move_to_deleted
[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 => 82;
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 # Create a reserve for the patron
158 $builder->build({
159     source => 'Reserve',
160     value  => {
161         borrowernumber => $member->{ borrowernumber }
162     }
163 });
164 is( Koha::Holds->search({ borrowernumber => $member->{borrowernumber} })->count,
165     1, 'Hold created correctly' );
166 DelMember($member->{borrowernumber});
167 my $borrower = GetMember( cardnumber => $CARDNUMBER );
168 is( $borrower, undef, 'DelMember should remove the patron' );
169 is( Koha::Holds->search({ borrowernumber => $member->{borrowernumber} })->count,
170     0, 'Hold deleted correctly' );
171
172 # Check_Userid tests
173 %data = (
174     cardnumber   => "123456789",
175     firstname    => "Tomasito",
176     surname      => "None",
177     categorycode => "S",
178     branchcode   => $library2->{branchcode},
179     dateofbirth  => '',
180     debarred     => '',
181     dateexpiry   => '',
182     dateenrolled => '',
183 );
184 # Add a new borrower
185 my $borrowernumber = AddMember( %data );
186 is( Check_Userid( 'tomasito.non', $borrowernumber ), 1,
187     'recently created userid -> unique (borrowernumber passed)' );
188 is( Check_Userid( 'tomasitoxxx', $borrowernumber ), 1,
189     'non-existent userid -> unique (borrowernumber passed)' );
190 is( Check_Userid( 'tomasito.none', '' ), 0,
191     'userid exists (blank borrowernumber)' );
192 is( Check_Userid( 'tomasitoxxx', '' ), 1,
193     'non-existent userid -> unique (blank borrowernumber)' );
194
195 $borrower = GetMember( borrowernumber => $borrowernumber );
196 is( $borrower->{dateofbirth}, undef, 'AddMember should undef dateofbirth if empty string is given');
197 is( $borrower->{debarred}, undef, 'AddMember should undef debarred if empty string is given');
198 isnt( $borrower->{dateexpiry}, '0000-00-00', 'AddMember should not set dateexpiry to 0000-00-00 if empty string is given');
199 isnt( $borrower->{dateenrolled}, '0000-00-00', 'AddMember should not set dateenrolled to 0000-00-00 if empty string is given');
200
201 ModMember( borrowernumber => $borrowernumber, dateofbirth => '', debarred => '', dateexpiry => '', dateenrolled => '' );
202 $borrower = GetMember( borrowernumber => $borrowernumber );
203 is( $borrower->{dateofbirth}, undef, 'ModMember should undef dateofbirth if empty string is given');
204 is( $borrower->{debarred}, undef, 'ModMember should undef debarred if empty string is given');
205 isnt( $borrower->{dateexpiry}, '0000-00-00', 'ModMember should not set dateexpiry to 0000-00-00 if empty string is given');
206 isnt( $borrower->{dateenrolled}, '0000-00-00', 'ModMember should not set dateenrolled to 0000-00-00 if empty string is given');
207
208 ModMember( borrowernumber => $borrowernumber, dateofbirth => '1970-01-01', debarred => '2042-01-01', dateexpiry => '9999-12-31', dateenrolled => '2015-09-06' );
209 $borrower = GetMember( borrowernumber => $borrowernumber );
210 is( $borrower->{dateofbirth}, '1970-01-01', 'ModMember should correctly set dateofbirth if a valid date is given');
211 is( $borrower->{debarred}, '2042-01-01', 'ModMember should correctly set debarred if a valid date is given');
212 is( $borrower->{dateexpiry}, '9999-12-31', 'ModMember should correctly set dateexpiry if a valid date is given');
213 is( $borrower->{dateenrolled}, '2015-09-06', 'ModMember should correctly set dateenrolled if a valid date is given');
214
215 # Add a new borrower with the same userid but different cardnumber
216 $data{ cardnumber } = "987654321";
217 my $new_borrowernumber = AddMember( %data );
218 is( Check_Userid( 'tomasito.none', '' ), 0,
219     'userid not unique (blank borrowernumber)' );
220 is( Check_Userid( 'tomasito.none', $new_borrowernumber ), 0,
221     'userid not unique (second borrowernumber passed)' );
222 $borrower = GetMember( borrowernumber => $new_borrowernumber );
223 ok( $borrower->{userid} ne 'tomasito', "Borrower with duplicate userid has new userid generated" );
224
225 $data{ cardnumber } = "234567890";
226 $data{userid} = 'a_user_id';
227 $borrowernumber = AddMember( %data );
228 $borrower = GetMember( borrowernumber => $borrowernumber );
229 is( $borrower->{userid}, $data{userid}, 'AddMember should insert the given userid' );
230
231 subtest 'ModMember should not update userid if not true' => sub {
232     plan tests => 3;
233     ModMember( borrowernumber => $borrowernumber, firstname => 'Tomas', userid => '' );
234     $borrower = GetMember( borrowernumber => $borrowernumber );
235     is ( $borrower->{userid}, $data{userid}, 'ModMember should not update the userid with an empty string' );
236     ModMember( borrowernumber => $borrowernumber, firstname => 'Tomas', userid => 0 );
237     $borrower = GetMember( borrowernumber => $borrowernumber );
238     is ( $borrower->{userid}, $data{userid}, 'ModMember should not update the userid with an 0');
239     ModMember( borrowernumber => $borrowernumber, firstname => 'Tomas', userid => undef );
240     $borrower = GetMember( borrowernumber => $borrowernumber );
241     is ( $borrower->{userid}, $data{userid}, 'ModMember should not update the userid with an undefined value');
242 };
243
244 #Regression tests for bug 10612
245 my $library3 = $builder->build({
246     source => 'Branch',
247 });
248 $builder->build({
249         source => 'Category',
250         value => {
251             categorycode         => 'STAFFER',
252             description          => 'Staff dont batch del',
253             category_type        => 'S',
254         },
255 });
256
257 $builder->build({
258         source => 'Category',
259         value => {
260             categorycode         => 'CIVILIAN',
261             description          => 'Civilian batch del',
262             category_type        => 'A',
263         },
264 });
265
266 $builder->build({
267         source => 'Category',
268         value => {
269             categorycode         => 'KIDclamp',
270             description          => 'Kid to be guaranteed',
271             category_type        => 'C',
272         },
273 });
274
275 my $borrower1 = $builder->build({
276         source => 'Borrower',
277         value  => {
278             categorycode=>'STAFFER',
279             branchcode => $library3->{branchcode},
280             dateexpiry => '2015-01-01',
281         },
282 });
283 my $bor1inlist = $borrower1->{borrowernumber};
284 my $borrower2 = $builder->build({
285         source => 'Borrower',
286         value  => {
287             categorycode=>'STAFFER',
288             branchcode => $library3->{branchcode},
289             dateexpiry => '2015-01-01',
290         },
291 });
292
293 my $guarantee = $builder->build({
294         source => 'Borrower',
295         value  => {
296             categorycode=>'KIDclamp',
297             branchcode => $library3->{branchcode},
298             dateexpiry => '2015-01-01',
299         },
300 });
301
302 my $bor2inlist = $borrower2->{borrowernumber};
303
304 $builder->build({
305         source => 'OldIssue',
306         value  => {
307             borrowernumber => $bor2inlist,
308             timestamp => '2016-01-01',
309         },
310 });
311
312 my $owner = AddMember (categorycode => 'STAFFER', branchcode => $library2->{branchcode} );
313 my $list1 = AddPatronList( { name => 'Test List 1', owner => $owner } );
314 my @listpatrons = ($bor1inlist, $bor2inlist);
315 AddPatronsToList(  { list => $list1, borrowernumbers => \@listpatrons });
316 my $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id() } );
317 is( scalar(@$patstodel),0,'No staff deleted from list of all staff');
318 ModMember( borrowernumber => $bor2inlist, categorycode => 'CIVILIAN' );
319 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
320 ok( scalar(@$patstodel)== 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted from list');
321 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
322 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by branchcode and list');
323 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } );
324 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by expirationdate and list');
325 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
326 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by last issue date');
327
328 ModMember( borrowernumber => $bor1inlist, categorycode => 'CIVILIAN' );
329 ModMember( borrowernumber => $guarantee->{borrowernumber} ,guarantorid=>$bor1inlist );
330
331 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
332 ok( scalar(@$patstodel)== 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted from list');
333 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
334 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by branchcode and list');
335 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } );
336 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by expirationdate and list');
337 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
338 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by last issue date');
339 ModMember( borrowernumber => $guarantee->{borrowernumber}, guarantorid=>'' );
340
341 $builder->build({
342         source => 'Issue',
343         value  => {
344             borrowernumber => $bor2inlist,
345         },
346 });
347 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
348 is( scalar(@$patstodel),1,'Borrower with issue not deleted from list');
349 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
350 is( scalar(@$patstodel),1,'Borrower with issue not deleted by branchcode and list');
351 $patstodel = GetBorrowersToExpunge( {category_code => 'CIVILIAN',patron_list_id => $list1->patron_list_id() } );
352 is( scalar(@$patstodel),1,'Borrower with issue not deleted by category_code and list');
353 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02',patron_list_id => $list1->patron_list_id() } );
354 is( scalar(@$patstodel),1,'Borrower with issue not deleted by expiration_date and list');
355 $builder->schema->resultset( 'Issue' )->delete_all;
356 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
357 ok( scalar(@$patstodel)== 2,'Borrowers without issue deleted from list');
358 $patstodel = GetBorrowersToExpunge( {category_code => 'CIVILIAN',patron_list_id => $list1->patron_list_id() } );
359 is( scalar(@$patstodel),2,'Borrowers without issues deleted by category_code and list');
360 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02',patron_list_id => $list1->patron_list_id() } );
361 is( scalar(@$patstodel),2,'Borrowers without issues deleted by expiration_date and list');
362 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
363 is( scalar(@$patstodel),2,'Borrowers without issues deleted by last issue date');
364
365 # Test GetBorrowersToExpunge and TrackLastPatronActivity
366 $dbh->do(q|UPDATE borrowers SET lastseen=NULL|);
367 $builder->build({ source => 'Borrower', value => { lastseen => '2016-01-01 01:01:01', guarantorid => undef } } );
368 $builder->build({ source => 'Borrower', value => { lastseen => '2016-02-02 02:02:02', guarantorid => undef } } );
369 $builder->build({ source => 'Borrower', value => { lastseen => '2016-03-03 03:03:03', guarantorid => undef } } );
370 $patstodel = GetBorrowersToExpunge( { last_seen => '1999-12-12' });
371 is( scalar @$patstodel, 0, 'TrackLastPatronActivity - 0 patrons must be deleted' );
372 $patstodel = GetBorrowersToExpunge( { last_seen => '2016-02-15' });
373 is( scalar @$patstodel, 2, 'TrackLastPatronActivity - 2 patrons must be deleted' );
374 $patstodel = GetBorrowersToExpunge( { last_seen => '2016-04-04' });
375 is( scalar @$patstodel, 3, 'TrackLastPatronActivity - 3 patrons must be deleted' );
376 my $patron2 = $builder->build({ source => 'Borrower', value => { lastseen => undef } });
377 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
378 Koha::Patrons->find( $patron2->{borrowernumber} )->track_login;
379 is( Koha::Patrons->find( $patron2->{borrowernumber} )->lastseen, undef, 'Lastseen should not be changed' );
380 Koha::Patrons->find( $patron2->{borrowernumber} )->track_login({ force => 1 });
381 isnt( Koha::Patrons->find( $patron2->{borrowernumber} )->lastseen, undef, 'Lastseen should be changed now' );
382
383 # Regression tests for BZ13502
384 ## Remove all entries with userid='' (should be only 1 max)
385 $dbh->do(q|DELETE FROM borrowers WHERE userid = ''|);
386 ## And create a patron with a userid=''
387 $borrowernumber = AddMember( categorycode => 'S', branchcode => $library2->{branchcode} );
388 $dbh->do(q|UPDATE borrowers SET userid = '' WHERE borrowernumber = ?|, undef, $borrowernumber);
389 # Create another patron and verify the userid has been generated
390 $borrowernumber = AddMember( categorycode => 'S', branchcode => $library2->{branchcode} );
391 ok( $borrowernumber > 0, 'AddMember should have inserted the patron even if no userid is given' );
392 $borrower = GetMember( borrowernumber => $borrowernumber );
393 ok( $borrower->{userid},  'A userid should have been generated correctly' );
394
395 # Regression tests for BZ12226
396 is( Check_Userid( C4::Context->config('user'), '' ), 0,
397     'Check_Userid should return 0 for the DB user (Bug 12226)');
398
399 subtest 'GetMemberAccountRecords' => sub {
400
401     plan tests => 2;
402
403     my $borrowernumber = $builder->build({ source => 'Borrower' })->{ borrowernumber };
404     my $accountline_1  = $builder->build({
405         source => 'Accountline',
406         value  => {
407             borrowernumber    => $borrowernumber,
408             amountoutstanding => 64.60
409         }
410     });
411
412     my ($total,undef,undef) = GetMemberAccountRecords( $borrowernumber );
413     is( $total , 64.60, "Rounding works correctly in total calculation (single value)" );
414
415     my $accountline_2 = $builder->build({
416         source => 'Accountline',
417         value  => {
418             borrowernumber    => $borrowernumber,
419             amountoutstanding => 10.65
420         }
421     });
422
423     ($total,undef,undef) = GetMemberAccountRecords( $borrowernumber );
424     is( $total , 75.25, "Rounding works correctly in total calculation (multiple values)" );
425
426 };
427
428 subtest 'GetMemberAccountBalance' => sub {
429
430     plan tests => 10;
431
432     my $members_mock = new Test::MockModule('C4::Members');
433     $members_mock->mock( 'GetMemberAccountRecords', sub {
434         my ($borrowernumber) = @_;
435         if ($borrowernumber) {
436             my @accountlines = (
437             { amountoutstanding => '7', accounttype => 'Rent' },
438             { amountoutstanding => '5', accounttype => 'Res' },
439             { amountoutstanding => '3', accounttype => 'Pay' } );
440             return ( 15, \@accountlines );
441         }
442         else {
443             my @accountlines;
444             return ( 0, \@accountlines );
445         }
446     });
447
448     my $person = GetMemberDetails(undef,undef);
449     ok( !$person , 'Expected no member details from undef,undef' );
450     $person = GetMemberDetails(undef,'987654321');
451     is( $person->{amountoutstanding}, 15,
452         'Expected 15 outstanding for cardnumber.');
453     $borrowernumber = $person->{borrowernumber};
454     $person = GetMemberDetails($borrowernumber,undef);
455     is( $person->{amountoutstanding}, 15,
456         'Expected 15 outstanding for borrowernumber.');
457     $person = GetMemberDetails($borrowernumber,'987654321');
458     is( $person->{amountoutstanding}, 15,
459         'Expected 15 outstanding for both borrowernumber and cardnumber.');
460
461     # do not count holds charges
462     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge', '1' );
463     t::lib::Mocks::mock_preference( 'ManInvInNoissuesCharge', '0' );
464     my ($total, $total_minus_charges,
465         $other_charges) = C4::Members::GetMemberAccountBalance(123);
466     is( $total, 15 , "Total calculated correctly");
467     is( $total_minus_charges, 15, "Holds charges are not count if HoldsInNoissuesCharge=1");
468     is( $other_charges, 0, "Holds charges are not considered if HoldsInNoissuesCharge=1");
469
470     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge', '0' );
471     ($total, $total_minus_charges,
472         $other_charges) = C4::Members::GetMemberAccountBalance(123);
473     is( $total, 15 , "Total calculated correctly");
474     is( $total_minus_charges, 10, "Holds charges are count if HoldsInNoissuesCharge=0");
475     is( $other_charges, 5, "Holds charges are considered if HoldsInNoissuesCharge=1");
476 };
477
478 subtest 'purgeSelfRegistration' => sub {
479     plan tests => 2;
480
481     #purge unverified
482     my $d=360;
483     C4::Members::DeleteUnverifiedOpacRegistrations($d);
484     foreach(1..3) {
485         $dbh->do("INSERT INTO borrower_modifications (timestamp, borrowernumber, verification_token) VALUES ('2014-01-01 01:02:03',0,?)", undef, (scalar localtime)."_$_");
486     }
487     is( C4::Members::DeleteUnverifiedOpacRegistrations($d), 3, 'Test for DeleteUnverifiedOpacRegistrations' );
488
489     #purge members in temporary category
490     my $c= 'XYZ';
491     $dbh->do("INSERT IGNORE INTO categories (categorycode) VALUES ('$c')");
492     t::lib::Mocks::mock_preference('PatronSelfRegistrationDefaultCategory', $c );
493     t::lib::Mocks::mock_preference('PatronSelfRegistrationExpireTemporaryAccountsDelay', 360);
494     C4::Members::DeleteExpiredOpacRegistrations();
495     $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});
496     is( C4::Members::DeleteExpiredOpacRegistrations(), 1, 'Test for DeleteExpiredOpacRegistrations');
497 };
498
499 sub _find_member {
500     my ($resultset) = @_;
501     my $found = $resultset && grep( { $_->{cardnumber} && $_->{cardnumber} eq $CARDNUMBER } @$resultset );
502     return $found;
503 }
504
505 # Regression tests for BZ15343
506 my $password="";
507 ( $borrowernumber, $password ) = AddMember_Opac(surname=>"Dick",firstname=>'Philip',branchcode => $library2->{branchcode});
508 is( $password =~ /^[a-zA-Z]{10}$/ , 1, 'Test for autogenerated password if none submitted');
509 ( $borrowernumber, $password ) = AddMember_Opac(surname=>"Deckard",firstname=>"Rick",password=>"Nexus-6",branchcode => $library2->{branchcode});
510 is( $password eq "Nexus-6", 1, 'Test password used if submitted');
511 $borrower = GetMember(borrowernumber => $borrowernumber);
512 my $hashed_up =  Koha::AuthUtils::hash_password("Nexus-6", $borrower->{password});
513 is( $borrower->{password} eq $hashed_up, 1, 'Check password hash equals hash of submitted password' );
514
515
516
517 ### ------------------------------------- ###
518 ### Testing GetAge() / SetAge() functions ###
519 ### ------------------------------------- ###
520 #USES the package $member-variable to mock a koha.borrowers-object
521 sub testAgeAccessors {
522     my ($member) = @_;
523     my $original_dateofbirth = $member->{dateofbirth};
524
525     ##Testing GetAge()
526     my $age=GetAge("1992-08-14", "2011-01-19");
527     is ($age, "18", "Age correct");
528
529     $age=GetAge("2011-01-19", "1992-01-19");
530     is ($age, "-19", "Birthday In the Future");
531
532     ##Testing SetAge() for now()
533     my $dt_now = DateTime->now();
534     $age = DateTime::Duration->new(years => 12, months => 6, days => 1);
535     C4::Members::SetAge( $member, $age );
536     $age = C4::Members::GetAge( $member->{dateofbirth} );
537     is ($age, '12', "SetAge 12 years");
538
539     $age = DateTime::Duration->new(years => 18, months => 12, days => 31);
540     C4::Members::SetAge( $member, $age );
541     $age = C4::Members::GetAge( $member->{dateofbirth} );
542     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.
543
544     $age = DateTime::Duration->new(years => 18, months => 12, days => 30);
545     C4::Members::SetAge( $member, $age );
546     $age = C4::Members::GetAge( $member->{dateofbirth} );
547     is ($age, '19', "SetAge 18 years");
548
549     $age = DateTime::Duration->new(years => 0, months => 1, days => 1);
550     C4::Members::SetAge( $member, $age );
551     $age = C4::Members::GetAge( $member->{dateofbirth} );
552     is ($age, '0', "SetAge 0 years");
553
554     $age = '0018-12-31';
555     C4::Members::SetAge( $member, $age );
556     $age = C4::Members::GetAge( $member->{dateofbirth} );
557     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.
558
559     $age = '0018-12-30';
560     C4::Members::SetAge( $member, $age );
561     $age = C4::Members::GetAge( $member->{dateofbirth} );
562     is ($age, '19', "SetAge ISO_Date 18 years");
563
564     $age = '18-1-1';
565     eval { C4::Members::SetAge( $member, $age ); };
566     is ((length $@ > 1), '1', "SetAge ISO_Date $age years FAILS");
567
568     $age = '0018-01-01';
569     eval { C4::Members::SetAge( $member, $age ); };
570     is ((length $@ == 0), '1', "SetAge ISO_Date $age years succeeds");
571
572     ##Testing SetAge() for relative_date
573     my $relative_date = DateTime->new(year => 3010, month => 3, day => 15);
574
575     $age = DateTime::Duration->new(years => 10, months => 3);
576     C4::Members::SetAge( $member, $age, $relative_date );
577     $age = C4::Members::GetAge( $member->{dateofbirth}, $relative_date->ymd() );
578     is ($age, '10', "SetAge, 10 years and 3 months old person was born on ".$member->{dateofbirth}." if todays is ".$relative_date->ymd());
579
580     $age = DateTime::Duration->new(years => 112, months => 1, days => 1);
581     C4::Members::SetAge( $member, $age, $relative_date );
582     $age = C4::Members::GetAge( $member->{dateofbirth}, $relative_date->ymd() );
583     is ($age, '112', "SetAge, 112 years, 1 months and 1 days old person was born on ".$member->{dateofbirth}." if today is ".$relative_date->ymd());
584
585     $age = '0112-01-01';
586     C4::Members::SetAge( $member, $age, $relative_date );
587     $age = C4::Members::GetAge( $member->{dateofbirth}, $relative_date->ymd() );
588     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());
589
590     $member->{dateofbirth} = $original_dateofbirth; #It is polite to revert made changes in the unit tests.
591 } #sub testAgeAccessors
592
593 # regression test for bug 16009
594 my $patron;
595 eval {
596     my $patron = GetMember(cardnumber => undef);
597 };
598 is($@, '', 'Bug 16009: GetMember(cardnumber => undef) works');
599 is($patron, undef, 'Bug 16009: GetMember(cardnumber => undef) returns undef');
600
601 1;