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