Bug 12532: (QA follow-up) Remove defunkt test
[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 qw( AddPatronList AddPatronsToList );
29 use Koha::Patrons;
30 use Koha::Patron::Relationship;
31
32 use t::lib::Mocks;
33 use t::lib::TestBuilder;
34
35 BEGIN {
36         use_ok('C4::Members', qw( GetBorrowersToExpunge DeleteUnverifiedOpacRegistrations DeleteExpiredOpacRegistrations ));
37 }
38
39 my $schema = Koha::Database->schema;
40 $schema->storage->txn_begin;
41 my $builder = t::lib::TestBuilder->new;
42 my $dbh = C4::Context->dbh;
43
44 my $library1 = $builder->build({
45     source => 'Branch',
46 });
47 my $library2 = $builder->build({
48     source => 'Branch',
49 });
50 my $patron_category = $builder->build({ source => 'Category' });
51 my $CARDNUMBER   = 'TESTCARD01';
52 my $FIRSTNAME    = 'Marie';
53 my $SURNAME      = 'Mcknight';
54 my $BRANCHCODE   = $library1->{branchcode};
55
56 my $CHANGED_FIRSTNAME = "Marry Ann";
57 my $EMAIL             = "Marie\@email.com";
58 my $EMAILPRO          = "Marie\@work.com";
59 my $PHONE             = "555-12123";
60
61 t::lib::Mocks::mock_userenv();
62
63 # Make a borrower for testing
64 my %data = (
65     cardnumber => $CARDNUMBER,
66     firstname =>  $FIRSTNAME . q{ },
67     surname => $SURNAME,
68     categorycode => $patron_category->{categorycode},
69     branchcode => $BRANCHCODE,
70     dateofbirth => '',
71     dateexpiry => '9999-12-31',
72     userid => 'tomasito'
73 );
74
75 my $addmem=Koha::Patron->new(\%data)->store->borrowernumber;
76 ok($addmem, "Koha::Patron->store()");
77
78 my $patron = Koha::Patrons->find( { cardnumber => $CARDNUMBER } )
79   or BAIL_OUT("Cannot read member with card $CARDNUMBER");
80 my $member = $patron->unblessed;
81
82 ok ( $member->{firstname}    eq $FIRSTNAME    &&
83      $member->{surname}      eq $SURNAME      &&
84      $member->{categorycode} eq $patron_category->{categorycode} &&
85      $member->{branchcode}   eq $BRANCHCODE
86      , "Got member")
87   or diag("Mismatching member details: ".Dumper(\%data, $member));
88
89 is($member->{dateofbirth}, undef, "Empty dates handled correctly");
90
91 $member->{firstname} = $CHANGED_FIRSTNAME . q{ };
92 $member->{email}     = $EMAIL;
93 $member->{phone}     = $PHONE;
94 $member->{emailpro}  = $EMAILPRO;
95 $patron->set($member)->store;
96 my $changedmember = Koha::Patrons->find( { cardnumber => $CARDNUMBER } )->unblessed;
97 ok ( $changedmember->{firstname} eq $CHANGED_FIRSTNAME &&
98      $changedmember->{email}     eq $EMAIL             &&
99      $changedmember->{phone}     eq $PHONE             &&
100      $changedmember->{emailpro}  eq $EMAILPRO
101      , "Member Changed")
102   or diag("Mismatching member details: ".Dumper($member, $changedmember));
103
104 # Add a new borrower
105 %data = (
106     cardnumber   => "123456789",
107     firstname    => "Tomasito",
108     surname      => "None",
109     categorycode => $patron_category->{categorycode},
110     branchcode   => $library2->{branchcode},
111     dateofbirth  => '',
112     debarred     => '',
113     dateexpiry   => '',
114     dateenrolled => '',
115 );
116 my $borrowernumber = Koha::Patron->new( \%data )->store->borrowernumber;
117 $patron = Koha::Patrons->find( $borrowernumber );
118 my $borrower = $patron->unblessed;
119 is( $borrower->{dateofbirth}, undef, 'Koha::Patron->store should undef dateofbirth if empty string is given');
120 is( $borrower->{debarred}, undef, 'Koha::Patron->store should undef debarred if empty string is given');
121 isnt( $borrower->{dateexpiry}, '0000-00-00', 'Koha::Patron->store should not set dateexpiry to 0000-00-00 if empty string is given');
122 isnt( $borrower->{dateenrolled}, '0000-00-00', 'Koha::Patron->store should not set dateenrolled to 0000-00-00 if empty string is given');
123
124 $patron->set({ dateofbirth => '', debarred => '', dateexpiry => '', dateenrolled => '' })->store;
125 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
126 is( $borrower->{dateofbirth}, undef, 'Koha::Patron->store should undef dateofbirth if empty string is given');
127 is( $borrower->{debarred}, undef, 'Koha::Patron->store should undef debarred if empty string is given');
128 isnt( $borrower->{dateexpiry}, '0000-00-00', 'Koha::Patron->store should not set dateexpiry to 0000-00-00 if empty string is given');
129 isnt( $borrower->{dateenrolled}, '0000-00-00', 'Koha::Patron->store should not set dateenrolled to 0000-00-00 if empty string is given');
130
131 $patron->set({ dateofbirth => '1970-01-01', debarred => '2042-01-01', dateexpiry => '9999-12-31', dateenrolled => '2015-09-06' })->store;
132 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
133 is( $borrower->{dateofbirth}, '1970-01-01', 'Koha::Patron->store should correctly set dateofbirth if a valid date is given');
134 is( $borrower->{debarred}, '2042-01-01', 'Koha::Patron->store should correctly set debarred if a valid date is given');
135 is( $borrower->{dateexpiry}, '9999-12-31', 'Koha::Patron->store should correctly set dateexpiry if a valid date is given');
136 is( $borrower->{dateenrolled}, '2015-09-06', 'Koha::Patron->store should correctly set dateenrolled if a valid date is given');
137
138 #Regression tests for bug 10612
139 my $library3 = $builder->build({
140     source => 'Branch',
141 });
142 $builder->build({
143         source => 'Category',
144         value => {
145             categorycode         => 'STAFFER',
146             description          => 'Staff dont batch del',
147             category_type        => 'S',
148         },
149 });
150
151 $builder->build({
152         source => 'Category',
153         value => {
154             categorycode         => 'CIVILIAN',
155             description          => 'Civilian batch del',
156             category_type        => 'A',
157         },
158 });
159
160 $builder->build({
161         source => 'Category',
162         value => {
163             categorycode         => 'KIDclamp',
164             description          => 'Kid to be guaranteed',
165             category_type        => 'C',
166         },
167 });
168
169 my $borrower1 = $builder->build({
170         source => 'Borrower',
171         value  => {
172             categorycode=>'STAFFER',
173             branchcode => $library3->{branchcode},
174             dateexpiry => '2015-01-01',
175             flags => undef,
176         },
177 });
178 my $bor1inlist = $borrower1->{borrowernumber};
179 my $borrower2 = $builder->build({
180         source => 'Borrower',
181         value  => {
182             categorycode=>'STAFFER',
183             branchcode => $library3->{branchcode},
184             dateexpiry => '2015-01-01',
185             flags => undef,
186         },
187 });
188
189 my $guarantee = $builder->build({
190         source => 'Borrower',
191         value  => {
192             categorycode=>'KIDclamp',
193             branchcode => $library3->{branchcode},
194             dateexpiry => '2015-01-01',
195             flags => undef,
196         },
197 });
198
199 my $bor2inlist = $borrower2->{borrowernumber};
200
201 $builder->build({
202         source => 'OldIssue',
203         value  => {
204             borrowernumber => $bor2inlist,
205             timestamp => '2016-01-01',
206         },
207 });
208
209 # The following calls to GetBorrowersToExpunge are assuming that the pref
210 # IndependentBranches is off.
211 t::lib::Mocks::mock_preference('IndependentBranches', 0);
212
213 my $anonymous_patron = Koha::Patron->new({ categorycode => 'CIVILIAN', branchcode => $library2->{branchcode} })->store->borrowernumber;
214 t::lib::Mocks::mock_preference('AnonymousPatron', $anonymous_patron);
215
216 my $owner = Koha::Patron->new({ categorycode => 'STAFFER', branchcode => $library2->{branchcode} })->store->borrowernumber;
217 my $list1 = AddPatronList( { name => 'Test List 1', owner => $owner } );
218
219 AddPatronsToList( { list => $list1, borrowernumbers => [$anonymous_patron] } );
220 my $patstodel = GetBorrowersToExpunge( { patron_list_id => $list1->patron_list_id() } );
221 is( scalar(@$patstodel), 0, 'Anonymous Patron not deleted from list' );
222
223 my @listpatrons = ($bor1inlist, $bor2inlist);
224 AddPatronsToList(  { list => $list1, borrowernumbers => \@listpatrons });
225 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id() } );
226 is( scalar(@$patstodel),0,'No staff deleted from list of all staff');
227 Koha::Patrons->find($bor2inlist)->set({ categorycode => 'CIVILIAN' })->store;
228 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
229 ok( scalar(@$patstodel)== 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted from list');
230 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
231 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by branchcode and list');
232 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } );
233 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by expirationdate and list');
234 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
235 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by last issue date');
236
237 Koha::Patrons->find($bor1inlist)->set({ categorycode => 'CIVILIAN' })->store;
238
239 t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test' );
240
241 my $relationship = Koha::Patron::Relationship->new( { guarantor_id => $bor1inlist, guarantee_id => $guarantee->{borrowernumber}, relationship => 'test' } )->store();
242
243 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
244 ok( scalar(@$patstodel)== 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted from list');
245 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
246 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by branchcode and list');
247 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } );
248 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by expirationdate and list');
249 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
250 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by last issue date');
251 $relationship->delete();
252
253 $builder->build({
254         source => 'Issue',
255         value  => {
256             borrowernumber => $bor2inlist,
257         },
258 });
259 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
260 is( scalar(@$patstodel),1,'Borrower with issue not deleted from list');
261 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
262 is( scalar(@$patstodel),1,'Borrower with issue not deleted by branchcode and list');
263 $patstodel = GetBorrowersToExpunge( {category_code => 'CIVILIAN',patron_list_id => $list1->patron_list_id() } );
264 is( scalar(@$patstodel),1,'Borrower with issue not deleted by category_code and list');
265 $patstodel = GetBorrowersToExpunge( {category_code => [], patron_list_id => $list1->patron_list_id() } );
266 is( scalar(@$patstodel),1,'category_code can contain an empty arrayref');
267 $patstodel = GetBorrowersToExpunge( {category_code => ['CIVILIAN','STAFFER'],patron_list_id => $list1->patron_list_id() } );
268 is( scalar(@$patstodel),1,'Borrower with issue not deleted by multiple category_code and list');
269 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02',patron_list_id => $list1->patron_list_id() } );
270 is( scalar(@$patstodel),1,'Borrower with issue not deleted by expiration_date and list');
271 $builder->schema->resultset( 'Issue' )->delete_all;
272 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
273 ok( scalar(@$patstodel)== 2,'Borrowers without issue deleted from list');
274 $patstodel = GetBorrowersToExpunge( {category_code => 'CIVILIAN',patron_list_id => $list1->patron_list_id() } );
275 is( scalar(@$patstodel),2,'Borrowers without issues deleted by category_code and list');
276 $patstodel = GetBorrowersToExpunge( {category_code => ['CIVILIAN','STAFFER'],patron_list_id => $list1->patron_list_id() } );
277 is( scalar(@$patstodel),2,'Borrowers without issues deleted by multiple category_code and list');
278 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02',patron_list_id => $list1->patron_list_id() } );
279 is( scalar(@$patstodel),2,'Borrowers without issues deleted by expiration_date and list');
280 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
281 is( scalar(@$patstodel),2,'Borrowers without issues deleted by last issue date');
282
283 # Test GetBorrowersToExpunge and TrackLastPatronActivity
284 $dbh->do(q|UPDATE borrowers SET lastseen=NULL|);
285 $builder->build({
286     source => 'Borrower',
287     value => {
288         lastseen => '2016-01-01 01:01:01',
289         categorycode => 'CIVILIAN',
290         flags => undef,
291     }
292 });
293 $builder->build({
294     source => 'Borrower',
295     value => {
296         lastseen => '2016-02-02 02:02:02',
297         categorycode => 'CIVILIAN',
298         flags => undef,
299     }
300 });
301 $builder->build({
302     source => 'Borrower',
303     value => {
304         lastseen => '2016-03-03 03:03:03',
305         categorycode => 'CIVILIAN',
306         flags => undef,
307     }
308 });
309 $patstodel = GetBorrowersToExpunge( { last_seen => '1999-12-12' });
310 is( scalar @$patstodel, 0, 'TrackLastPatronActivity - 0 patrons must be deleted' );
311 $patstodel = GetBorrowersToExpunge( { last_seen => '2016-02-15' });
312 is( scalar @$patstodel, 2, 'TrackLastPatronActivity - 2 patrons must be deleted' );
313 $patstodel = GetBorrowersToExpunge( { last_seen => '2016-04-04' });
314 is( scalar @$patstodel, 3, 'TrackLastPatronActivity - 3 patrons must be deleted' );
315 my $patron2 = $builder->build({
316     source => 'Borrower',
317     value => {
318         lastseen => undef,
319         flags => undef,
320     }
321 });
322 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
323 Koha::Patrons->find( $patron2->{borrowernumber} )->track_login;
324 is( Koha::Patrons->find( $patron2->{borrowernumber} )->lastseen, undef, 'Lastseen should not be changed' );
325 Koha::Patrons->find( $patron2->{borrowernumber} )->track_login({ force => 1 });
326 isnt( Koha::Patrons->find( $patron2->{borrowernumber} )->lastseen, undef, 'Lastseen should be changed now' );
327
328 # Test GetBorrowersToExpunge and regular patron with permission
329 $builder->build({
330         source => 'Category',
331         value => {
332             categorycode         => 'SMALLSTAFF',
333             description          => 'Small staff',
334             category_type        => 'A',
335         },
336 });
337 $borrowernumber = Koha::Patron->new({
338     categorycode => 'SMALLSTAFF',
339     branchcode => $library2->{branchcode},
340     flags => undef,
341 })->store->borrowernumber;
342 $patron = Koha::Patrons->find( $borrowernumber );
343 $patstodel = GetBorrowersToExpunge( {category_code => 'SMALLSTAFF' } );
344 is( scalar @$patstodel, 1, 'Regular patron with flags=undef can be deleted' );
345 $patron->set({ flags => 0 })->store;
346 $patstodel = GetBorrowersToExpunge( {category_code => 'SMALLSTAFF' } );
347 is( scalar @$patstodel, 1, 'Regular patron with flags=0 can be deleted' );
348 $patron->set({ flags => 4 })->store;
349 $patstodel = GetBorrowersToExpunge( {category_code => 'SMALLSTAFF' } );
350 is( scalar @$patstodel, 0, 'Regular patron with flags>0 can not be deleted' );
351
352 # Regression tests for BZ13502
353 ## Remove all entries with userid='' (should be only 1 max)
354 $dbh->do(q|DELETE FROM borrowers WHERE userid = ''|);
355 ## And create a patron with a userid=''
356 $borrowernumber = Koha::Patron->new({ categorycode => $patron_category->{categorycode}, branchcode => $library2->{branchcode} })->store->borrowernumber;
357 $dbh->do(q|UPDATE borrowers SET userid = '' WHERE borrowernumber = ?|, undef, $borrowernumber);
358 # Create another patron and verify the userid has been generated
359 $borrowernumber = Koha::Patron->new({ categorycode => $patron_category->{categorycode}, branchcode => $library2->{branchcode} })->store->borrowernumber;
360 ok( $borrowernumber > 0, 'Koha::Patron->store should have inserted the patron even if no userid is given' );
361 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
362 ok( $borrower->{userid},  'A userid should have been generated correctly' );
363
364 subtest 'purgeSelfRegistration' => sub {
365     plan tests => 8;
366
367     #purge unverified
368     my $d=360;
369     C4::Members::DeleteUnverifiedOpacRegistrations($d);
370     foreach(1..3) {
371         $dbh->do("INSERT INTO borrower_modifications (timestamp, borrowernumber, verification_token, changed_fields) VALUES ('2014-01-01 01:02:03',0,?,'firstname,surname')", undef, (scalar localtime)."_$_");
372     }
373     # Add a record with a borrowernumber which should not be deleted by DeleteUnverifiedOpacRegistrations
374     # NOTE: We are using the borrowernumber from the last test outside this subtest
375     $dbh->do( "INSERT INTO borrower_modifications (timestamp, borrowernumber, verification_token, changed_fields) VALUES ('2014-01-01 01:02:03', ?, '', 'firstname,surname' )", undef, $borrowernumber );
376     is( C4::Members::DeleteUnverifiedOpacRegistrations($d), 3, 'Test for DeleteUnverifiedOpacRegistrations' );
377
378     #purge members in temporary category
379     my $c= 'XYZ';
380     $dbh->do("INSERT IGNORE INTO categories (categorycode) VALUES ('$c')");
381     t::lib::Mocks::mock_preference('PatronSelfRegistrationDefaultCategory', $c );
382     C4::Members::DeleteExpiredOpacRegistrations();
383     my $self_reg = $builder->build_object({
384         class => 'Koha::Patrons',
385         value => {
386             dateenrolled => '2014-01-01 01:02:03',
387             categorycode => $c
388         }
389     });
390
391     # First test if empty PatronSelfRegistrationExpireTemporaryAccountsDelay returns zero
392     t::lib::Mocks::mock_preference('PatronSelfRegistrationExpireTemporaryAccountsDelay', q{} );
393     is( C4::Members::DeleteExpiredOpacRegistrations(), 0, "DeleteExpiredOpacRegistrations with empty delay" );
394     # Test zero too
395     t::lib::Mocks::mock_preference('PatronSelfRegistrationExpireTemporaryAccountsDelay', 0 );
396     is( C4::Members::DeleteExpiredOpacRegistrations(), 0, "DeleteExpiredOpacRegistrations with delay 0" );
397     # Also check empty category
398     t::lib::Mocks::mock_preference('PatronSelfRegistrationDefaultCategory', q{} );
399     t::lib::Mocks::mock_preference('PatronSelfRegistrationExpireTemporaryAccountsDelay', 360 );
400     is( C4::Members::DeleteExpiredOpacRegistrations(), 0, "DeleteExpiredOpacRegistrations with empty category" );
401     t::lib::Mocks::mock_preference('PatronSelfRegistrationDefaultCategory', $c );
402
403     my $checkout     = $builder->build_object({
404         class=>'Koha::Checkouts',
405         value=>{
406             borrowernumber=>$self_reg->borrowernumber
407         }
408     });
409     is( C4::Members::DeleteExpiredOpacRegistrations(), 0, "DeleteExpiredOpacRegistrations doesn't delete borrower with checkout");
410
411     my $account_line = $builder->build_object(
412         {
413             class => 'Koha::Account::Lines',
414             value => {
415                 borrowernumber    => $self_reg->borrowernumber,
416                 amountoutstanding => 5,
417             }
418         }
419     );
420     is( C4::Members::DeleteExpiredOpacRegistrations(), 0, "DeleteExpiredOpacRegistrations doesn't delete borrower with checkout and fine");
421
422     $checkout->delete;
423     is( C4::Members::DeleteExpiredOpacRegistrations(), 0, "DeleteExpiredOpacRegistrations doesn't delete borrower with fine and no checkout");
424
425     $account_line->delete;
426     is( C4::Members::DeleteExpiredOpacRegistrations(), 1, "DeleteExpiredOpacRegistrations does delete borrower with no fines and no checkouts");
427
428 };
429
430 sub _find_member {
431     my ($resultset) = @_;
432     my $found = $resultset && grep( { $_->{cardnumber} && $_->{cardnumber} eq $CARDNUMBER } @$resultset );
433     return $found;
434 }
435
436 $schema->storage->txn_rollback;
437
438 subtest 'Koha::Patron->store (invalid categorycode) tests' => sub {
439     plan tests => 1;
440     # TODO Move this to t/db_dependent/Koha/Patrons.t subtest ->store
441
442     $schema->storage->txn_begin;
443
444     my $category    = $builder->build_object({ class => 'Koha::Patron::Categories' });
445     my $category_id = $category->id;
446     # Remove category to make sure the id is not on the DB
447     $category->delete;
448
449     my $patron_data = {
450         categorycode => $category_id
451     };
452
453     throws_ok
454         { Koha::Patron->new( $patron_data )->store; }
455         'Koha::Exceptions::Object::FKConstraint',
456         'AddMember raises an exception on invalid categorycode';
457
458     $schema->storage->txn_rollback;
459 };