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