da5d70bbec225604f7e25d4a499247343f1da7fc
[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 => 50;
21 use Test::MockModule;
22 use Test::Exception;
23
24 use Data::Dumper qw/Dumper/;
25 use C4::Context;
26 use Koha::Database;
27 use Koha::Holds;
28 use Koha::List::Patron;
29 use Koha::Patrons;
30
31 use t::lib::Mocks;
32 use t::lib::TestBuilder;
33
34 BEGIN {
35         use_ok('C4::Members');
36 }
37
38 my $schema = Koha::Database->schema;
39 $schema->storage->txn_begin;
40 my $builder = t::lib::TestBuilder->new;
41 my $dbh = C4::Context->dbh;
42
43 # Remove invalid guarantorid's as long as we have no FK
44 $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");
45
46 my $library1 = $builder->build({
47     source => 'Branch',
48 });
49 my $library2 = $builder->build({
50     source => 'Branch',
51 });
52 my $patron_category = $builder->build({ source => 'Category' });
53 my $CARDNUMBER   = 'TESTCARD01';
54 my $FIRSTNAME    = 'Marie';
55 my $SURNAME      = 'Mcknight';
56 my $BRANCHCODE   = $library1->{branchcode};
57
58 my $CHANGED_FIRSTNAME = "Marry Ann";
59 my $EMAIL             = "Marie\@email.com";
60 my $EMAILPRO          = "Marie\@work.com";
61 my $PHONE             = "555-12123";
62
63 # XXX should be randomised and checked against the database
64 my $IMPOSSIBLE_CARDNUMBER = "XYZZZ999";
65
66 #my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $branchname, $userflags, $emailaddress, $branchprinter)= @_;
67 my @USERENV = (
68     1,
69     'test',
70     'MASTERTEST',
71     'Test',
72     'Test',
73     't',
74     'Test',
75     0,
76 );
77 my $BRANCH_IDX = 5;
78
79 C4::Context->_new_userenv ('DUMMY_SESSION_ID');
80 C4::Context->set_userenv ( @USERENV );
81
82 my $userenv = C4::Context->userenv
83   or BAIL_OUT("No userenv");
84
85 # Make a borrower for testing
86 my %data = (
87     cardnumber => $CARDNUMBER,
88     firstname =>  $FIRSTNAME . q{ },
89     surname => $SURNAME,
90     categorycode => $patron_category->{categorycode},
91     branchcode => $BRANCHCODE,
92     dateofbirth => '',
93     dateexpiry => '9999-12-31',
94     userid => 'tomasito'
95 );
96
97 my $addmem=Koha::Patron->new(\%data)->store->borrowernumber;
98 ok($addmem, "Koha::Patron->store()");
99
100 my $member = Koha::Patrons->find( { cardnumber => $CARDNUMBER } )
101   or BAIL_OUT("Cannot read member with card $CARDNUMBER");
102 $member = $member->unblessed;
103
104 ok ( $member->{firstname}    eq $FIRSTNAME    &&
105      $member->{surname}      eq $SURNAME      &&
106      $member->{categorycode} eq $patron_category->{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 . q{ };
114 $member->{email}     = $EMAIL;
115 $member->{phone}     = $PHONE;
116 $member->{emailpro}  = $EMAILPRO;
117 ModMember(%$member);
118 my $changedmember = Koha::Patrons->find( { cardnumber => $CARDNUMBER } )->unblessed;
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 # Add a new borrower
143 %data = (
144     cardnumber   => "123456789",
145     firstname    => "Tomasito",
146     surname      => "None",
147     categorycode => $patron_category->{categorycode},
148     branchcode   => $library2->{branchcode},
149     dateofbirth  => '',
150     debarred     => '',
151     dateexpiry   => '',
152     dateenrolled => '',
153 );
154 my $borrowernumber = Koha::Patron->new( \%data )->store->borrowernumber;
155 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
156 is( $borrower->{dateofbirth}, undef, 'Koha::Patron->store should undef dateofbirth if empty string is given');
157 is( $borrower->{debarred}, undef, 'Koha::Patron->store should undef debarred if empty string is given');
158 isnt( $borrower->{dateexpiry}, '0000-00-00', 'Koha::Patron->store should not set dateexpiry to 0000-00-00 if empty string is given');
159 isnt( $borrower->{dateenrolled}, '0000-00-00', 'Koha::Patron->store should not set dateenrolled to 0000-00-00 if empty string is given');
160
161 ModMember( borrowernumber => $borrowernumber, dateofbirth => '', debarred => '', dateexpiry => '', dateenrolled => '' );
162 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
163 is( $borrower->{dateofbirth}, undef, 'ModMember should undef dateofbirth if empty string is given');
164 is( $borrower->{debarred}, undef, 'ModMember should undef debarred if empty string is given');
165 isnt( $borrower->{dateexpiry}, '0000-00-00', 'ModMember should not set dateexpiry to 0000-00-00 if empty string is given');
166 isnt( $borrower->{dateenrolled}, '0000-00-00', 'ModMember should not set dateenrolled to 0000-00-00 if empty string is given');
167
168 ModMember( borrowernumber => $borrowernumber, dateofbirth => '1970-01-01', debarred => '2042-01-01', dateexpiry => '9999-12-31', dateenrolled => '2015-09-06' );
169 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
170 is( $borrower->{dateofbirth}, '1970-01-01', 'ModMember should correctly set dateofbirth if a valid date is given');
171 is( $borrower->{debarred}, '2042-01-01', 'ModMember should correctly set debarred if a valid date is given');
172 is( $borrower->{dateexpiry}, '9999-12-31', 'ModMember should correctly set dateexpiry if a valid date is given');
173 is( $borrower->{dateenrolled}, '2015-09-06', 'ModMember should correctly set dateenrolled if a valid date is given');
174
175 subtest 'ModMember should not update userid if not true' => sub {
176     plan tests => 3;
177
178     $data{ cardnumber } = "234567890";
179     $data{userid} = 'a_user_id';
180     $borrowernumber = Koha::Patron->new( \%data )->store->borrowernumber;
181     $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
182
183     ModMember( borrowernumber => $borrowernumber, firstname => 'Tomas', userid => '' );
184     $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
185     is ( $borrower->{userid}, $data{userid}, 'ModMember should not update the userid with an empty string' );
186     ModMember( borrowernumber => $borrowernumber, firstname => 'Tomas', userid => 0 );
187     $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
188     is ( $borrower->{userid}, $data{userid}, 'ModMember should not update the userid with an 0');
189     ModMember( borrowernumber => $borrowernumber, firstname => 'Tomas', userid => undef );
190     $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
191     is ( $borrower->{userid}, $data{userid}, 'ModMember should not update the userid with an undefined value');
192 };
193
194 #Regression tests for bug 10612
195 my $library3 = $builder->build({
196     source => 'Branch',
197 });
198 $builder->build({
199         source => 'Category',
200         value => {
201             categorycode         => 'STAFFER',
202             description          => 'Staff dont batch del',
203             category_type        => 'S',
204         },
205 });
206
207 $builder->build({
208         source => 'Category',
209         value => {
210             categorycode         => 'CIVILIAN',
211             description          => 'Civilian batch del',
212             category_type        => 'A',
213         },
214 });
215
216 $builder->build({
217         source => 'Category',
218         value => {
219             categorycode         => 'KIDclamp',
220             description          => 'Kid to be guaranteed',
221             category_type        => 'C',
222         },
223 });
224
225 my $borrower1 = $builder->build({
226         source => 'Borrower',
227         value  => {
228             categorycode=>'STAFFER',
229             branchcode => $library3->{branchcode},
230             dateexpiry => '2015-01-01',
231             guarantorid=> undef,
232         },
233 });
234 my $bor1inlist = $borrower1->{borrowernumber};
235 my $borrower2 = $builder->build({
236         source => 'Borrower',
237         value  => {
238             categorycode=>'STAFFER',
239             branchcode => $library3->{branchcode},
240             dateexpiry => '2015-01-01',
241             guarantorid=> undef,
242         },
243 });
244
245 my $guarantee = $builder->build({
246         source => 'Borrower',
247         value  => {
248             categorycode=>'KIDclamp',
249             branchcode => $library3->{branchcode},
250             dateexpiry => '2015-01-01',
251             guarantorid=> undef, # will be filled later
252         },
253 });
254
255 my $bor2inlist = $borrower2->{borrowernumber};
256
257 $builder->build({
258         source => 'OldIssue',
259         value  => {
260             borrowernumber => $bor2inlist,
261             timestamp => '2016-01-01',
262         },
263 });
264
265 # The following calls to GetBorrowersToExpunge are assuming that the pref
266 # IndependentBranches is off.
267 t::lib::Mocks::mock_preference('IndependentBranches', 0);
268
269 my $owner = Koha::Patron->new({ categorycode => 'STAFFER', branchcode => $library2->{branchcode} })->store->borrowernumber;
270 my $list1 = AddPatronList( { name => 'Test List 1', owner => $owner } );
271 my @listpatrons = ($bor1inlist, $bor2inlist);
272 AddPatronsToList(  { list => $list1, borrowernumbers => \@listpatrons });
273 my $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id() } );
274 is( scalar(@$patstodel),0,'No staff deleted from list of all staff');
275 ModMember( borrowernumber => $bor2inlist, categorycode => 'CIVILIAN' );
276 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
277 ok( scalar(@$patstodel)== 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted from list');
278 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
279 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by branchcode and list');
280 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } );
281 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by expirationdate and list');
282 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
283 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by last issue date');
284
285 ModMember( borrowernumber => $bor1inlist, categorycode => 'CIVILIAN' );
286 ModMember( borrowernumber => $guarantee->{borrowernumber} ,guarantorid=>$bor1inlist );
287
288 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
289 ok( scalar(@$patstodel)== 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted from list');
290 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
291 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by branchcode and list');
292 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } );
293 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by expirationdate and list');
294 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
295 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by last issue date');
296 ModMember( borrowernumber => $guarantee->{borrowernumber}, guarantorid=>'' );
297
298 $builder->build({
299         source => 'Issue',
300         value  => {
301             borrowernumber => $bor2inlist,
302         },
303 });
304 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
305 is( scalar(@$patstodel),1,'Borrower with issue not deleted from list');
306 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
307 is( scalar(@$patstodel),1,'Borrower with issue not deleted by branchcode and list');
308 $patstodel = GetBorrowersToExpunge( {category_code => 'CIVILIAN',patron_list_id => $list1->patron_list_id() } );
309 is( scalar(@$patstodel),1,'Borrower with issue not deleted by category_code and list');
310 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02',patron_list_id => $list1->patron_list_id() } );
311 is( scalar(@$patstodel),1,'Borrower with issue not deleted by expiration_date and list');
312 $builder->schema->resultset( 'Issue' )->delete_all;
313 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
314 ok( scalar(@$patstodel)== 2,'Borrowers without issue deleted from list');
315 $patstodel = GetBorrowersToExpunge( {category_code => 'CIVILIAN',patron_list_id => $list1->patron_list_id() } );
316 is( scalar(@$patstodel),2,'Borrowers without issues deleted by category_code and list');
317 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02',patron_list_id => $list1->patron_list_id() } );
318 is( scalar(@$patstodel),2,'Borrowers without issues deleted by expiration_date and list');
319 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
320 is( scalar(@$patstodel),2,'Borrowers without issues deleted by last issue date');
321
322 # Test GetBorrowersToExpunge and TrackLastPatronActivity
323 $dbh->do(q|UPDATE borrowers SET lastseen=NULL|);
324 $builder->build({ source => 'Borrower', value => { lastseen => '2016-01-01 01:01:01', categorycode => 'CIVILIAN', guarantorid => undef } } );
325 $builder->build({ source => 'Borrower', value => { lastseen => '2016-02-02 02:02:02', categorycode => 'CIVILIAN', guarantorid => undef } } );
326 $builder->build({ source => 'Borrower', value => { lastseen => '2016-03-03 03:03:03', categorycode => 'CIVILIAN', guarantorid => undef } } );
327 $patstodel = GetBorrowersToExpunge( { last_seen => '1999-12-12' });
328 is( scalar @$patstodel, 0, 'TrackLastPatronActivity - 0 patrons must be deleted' );
329 $patstodel = GetBorrowersToExpunge( { last_seen => '2016-02-15' });
330 is( scalar @$patstodel, 2, 'TrackLastPatronActivity - 2 patrons must be deleted' );
331 $patstodel = GetBorrowersToExpunge( { last_seen => '2016-04-04' });
332 is( scalar @$patstodel, 3, 'TrackLastPatronActivity - 3 patrons must be deleted' );
333 my $patron2 = $builder->build({ source => 'Borrower', value => { lastseen => undef } });
334 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
335 Koha::Patrons->find( $patron2->{borrowernumber} )->track_login;
336 is( Koha::Patrons->find( $patron2->{borrowernumber} )->lastseen, undef, 'Lastseen should not be changed' );
337 Koha::Patrons->find( $patron2->{borrowernumber} )->track_login({ force => 1 });
338 isnt( Koha::Patrons->find( $patron2->{borrowernumber} )->lastseen, undef, 'Lastseen should be changed now' );
339
340 # Regression tests for BZ13502
341 ## Remove all entries with userid='' (should be only 1 max)
342 $dbh->do(q|DELETE FROM borrowers WHERE userid = ''|);
343 ## And create a patron with a userid=''
344 $borrowernumber = Koha::Patron->new({ categorycode => $patron_category->{categorycode}, branchcode => $library2->{branchcode} })->store->borrowernumber;
345 $dbh->do(q|UPDATE borrowers SET userid = '' WHERE borrowernumber = ?|, undef, $borrowernumber);
346 # Create another patron and verify the userid has been generated
347 $borrowernumber = Koha::Patron->new({ categorycode => $patron_category->{categorycode}, branchcode => $library2->{branchcode} })->store->borrowernumber;
348 ok( $borrowernumber > 0, 'Koha::Patron->store should have inserted the patron even if no userid is given' );
349 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
350 ok( $borrower->{userid},  'A userid should have been generated correctly' );
351
352 subtest 'purgeSelfRegistration' => sub {
353     plan tests => 2;
354
355     #purge unverified
356     my $d=360;
357     C4::Members::DeleteUnverifiedOpacRegistrations($d);
358     foreach(1..3) {
359         $dbh->do("INSERT INTO borrower_modifications (timestamp, borrowernumber, verification_token) VALUES ('2014-01-01 01:02:03',0,?)", undef, (scalar localtime)."_$_");
360     }
361     is( C4::Members::DeleteUnverifiedOpacRegistrations($d), 3, 'Test for DeleteUnverifiedOpacRegistrations' );
362
363     #purge members in temporary category
364     my $c= 'XYZ';
365     $dbh->do("INSERT IGNORE INTO categories (categorycode) VALUES ('$c')");
366     t::lib::Mocks::mock_preference('PatronSelfRegistrationDefaultCategory', $c );
367     t::lib::Mocks::mock_preference('PatronSelfRegistrationExpireTemporaryAccountsDelay', 360);
368     C4::Members::DeleteExpiredOpacRegistrations();
369     $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});
370     is( C4::Members::DeleteExpiredOpacRegistrations(), 1, 'Test for DeleteExpiredOpacRegistrations');
371 };
372
373 sub _find_member {
374     my ($resultset) = @_;
375     my $found = $resultset && grep( { $_->{cardnumber} && $_->{cardnumber} eq $CARDNUMBER } @$resultset );
376     return $found;
377 }
378
379 # Regression tests for BZ15343
380 my $password="";
381 ( $borrowernumber, $password ) = AddMember_Opac(surname=>"Dick",firstname=>'Philip',branchcode => $library2->{branchcode});
382 is( $password =~ /^[a-zA-Z]{10}$/ , 1, 'Test for autogenerated password if none submitted');
383 ( $borrowernumber, $password ) = AddMember_Opac(surname=>"Deckard",firstname=>"Rick",password=>"Nexus-6",branchcode => $library2->{branchcode});
384 is( $password eq "Nexus-6", 1, 'Test password used if submitted');
385 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
386 my $hashed_up =  Koha::AuthUtils::hash_password("Nexus-6", $borrower->{password});
387 is( $borrower->{password} eq $hashed_up, 1, 'Check password hash equals hash of submitted password' );
388
389 $schema->storage->txn_rollback;
390
391 subtest 'Koha::Patron->store (invalid categorycode) tests' => sub {
392     plan tests => 1;
393
394     $schema->storage->txn_begin;
395
396     my $category    = $builder->build_object({ class => 'Koha::Patron::Categories' });
397     my $category_id = $category->id;
398     # Remove category to make sure the id is not on the DB
399     $category->delete;
400
401     my $patron_data = {
402         categorycode => $category_id
403     };
404
405     throws_ok
406         { Koha::Patron->new( $patron_data )->store; }
407         'Koha::Exceptions::Object::FKConstraint',
408         'AddMember raises an exception on invalid categorycode';
409
410     $schema->storage->txn_rollback;
411 };