Bug 15504: Remove PatronLastActivity preference
[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 => 49;
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 TrackLastPatronActivityTriggers
284 my $new_category = $builder->build_object(
285     {
286         class => 'Koha::Patron::Categories',
287         value => { category_type => 'A' },     # should not be S for GetBorrowersToExpunge
288     }
289 );
290 $builder->build({
291     source => 'Borrower',
292     value => {
293         lastseen => '2016-01-01 01:01:01',
294         categorycode => $new_category->categorycode,
295         flags => undef,
296     }
297 });
298 $builder->build({
299     source => 'Borrower',
300     value => {
301         lastseen => '2016-02-02 02:02:02',
302         categorycode => $new_category->categorycode,
303         flags => undef,
304     }
305 });
306 $builder->build({
307     source => 'Borrower',
308     value => {
309         lastseen => '2016-03-03 03:03:03',
310         categorycode => $new_category->categorycode,
311         flags => undef,
312     }
313 });
314 $patstodel = GetBorrowersToExpunge( { category_code => $new_category->categorycode, last_seen => '1999-12-12' });
315 is( scalar @$patstodel, 0, 'TrackLastPatronActivityTriggers - 0 patrons must be deleted' );
316 $patstodel = GetBorrowersToExpunge( { category_code => $new_category->categorycode, last_seen => '2016-02-15' });
317 is( scalar @$patstodel, 2, 'TrackLastPatronActivityTriggers - 2 patrons must be deleted' );
318 $patstodel = GetBorrowersToExpunge( { category_code => $new_category->categorycode, last_seen => '2016-04-04' });
319 is( scalar @$patstodel, 3, 'TrackLastPatronActivityTriggers - 3 patrons must be deleted' );
320 my $patron2 = $builder->build({
321     source => 'Borrower',
322     value => {
323         lastseen => undef,
324         flags => undef,
325     }
326 });
327 t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', 'connection' );
328 Koha::Patrons->find( $patron2->{borrowernumber} )->update_lastseen('connection');
329 isnt( Koha::Patrons->find( $patron2->{borrowernumber} )->lastseen, undef, 'Lastseen should be changed now' );
330
331 # Test GetBorrowersToExpunge and regular patron with permission
332 $builder->build({
333         source => 'Category',
334         value => {
335             categorycode         => 'SMALLSTAFF',
336             description          => 'Small staff',
337             category_type        => 'A',
338         },
339 });
340 $borrowernumber = Koha::Patron->new({
341     categorycode => 'SMALLSTAFF',
342     branchcode => $library2->{branchcode},
343     flags => undef,
344 })->store->borrowernumber;
345 $patron = Koha::Patrons->find( $borrowernumber );
346 $patstodel = GetBorrowersToExpunge( {category_code => 'SMALLSTAFF' } );
347 is( scalar @$patstodel, 1, 'Regular patron with flags=undef can be deleted' );
348 $patron->set({ flags => 0 })->store;
349 $patstodel = GetBorrowersToExpunge( {category_code => 'SMALLSTAFF' } );
350 is( scalar @$patstodel, 1, 'Regular patron with flags=0 can be deleted' );
351 $patron->set({ flags => 4 })->store;
352 $patstodel = GetBorrowersToExpunge( {category_code => 'SMALLSTAFF' } );
353 is( scalar @$patstodel, 0, 'Regular patron with flags>0 can not be deleted' );
354
355 # Regression tests for BZ13502
356 ## Remove all entries with userid='' (should be only 1 max)
357 $dbh->do(q|DELETE FROM borrowers WHERE userid = ''|);
358 ## And create a patron with a userid=''
359 $borrowernumber = Koha::Patron->new({ categorycode => $patron_category->{categorycode}, branchcode => $library2->{branchcode} })->store->borrowernumber;
360 $dbh->do(q|UPDATE borrowers SET userid = '' WHERE borrowernumber = ?|, undef, $borrowernumber);
361 # Create another patron and verify the userid has been generated
362 $borrowernumber = Koha::Patron->new({ categorycode => $patron_category->{categorycode}, branchcode => $library2->{branchcode} })->store->borrowernumber;
363 ok( $borrowernumber > 0, 'Koha::Patron->store should have inserted the patron even if no userid is given' );
364 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
365 ok( $borrower->{userid},  'A userid should have been generated correctly' );
366
367 subtest 'purgeSelfRegistration' => sub {
368     plan tests => 8;
369
370     #purge unverified
371     my $d=360;
372     C4::Members::DeleteUnverifiedOpacRegistrations($d);
373     foreach(1..3) {
374         $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)."_$_");
375     }
376     # Add a record with a borrowernumber which should not be deleted by DeleteUnverifiedOpacRegistrations
377     # NOTE: We are using the borrowernumber from the last test outside this subtest
378     $dbh->do( "INSERT INTO borrower_modifications (timestamp, borrowernumber, verification_token, changed_fields) VALUES ('2014-01-01 01:02:03', ?, '', 'firstname,surname' )", undef, $borrowernumber );
379     is( C4::Members::DeleteUnverifiedOpacRegistrations($d), 3, 'Test for DeleteUnverifiedOpacRegistrations' );
380
381     #purge members in temporary category
382     my $c= 'XYZ';
383     $dbh->do("INSERT IGNORE INTO categories (categorycode) VALUES ('$c')");
384     t::lib::Mocks::mock_preference('PatronSelfRegistrationDefaultCategory', $c );
385     C4::Members::DeleteExpiredOpacRegistrations();
386     my $self_reg = $builder->build_object({
387         class => 'Koha::Patrons',
388         value => {
389             dateenrolled => '2014-01-01 01:02:03',
390             categorycode => $c
391         }
392     });
393
394     # First test if empty PatronSelfRegistrationExpireTemporaryAccountsDelay returns zero
395     t::lib::Mocks::mock_preference('PatronSelfRegistrationExpireTemporaryAccountsDelay', q{} );
396     is( C4::Members::DeleteExpiredOpacRegistrations(), 0, "DeleteExpiredOpacRegistrations with empty delay" );
397     # Test zero too
398     t::lib::Mocks::mock_preference('PatronSelfRegistrationExpireTemporaryAccountsDelay', 0 );
399     is( C4::Members::DeleteExpiredOpacRegistrations(), 0, "DeleteExpiredOpacRegistrations with delay 0" );
400     # Also check empty category
401     t::lib::Mocks::mock_preference('PatronSelfRegistrationDefaultCategory', q{} );
402     t::lib::Mocks::mock_preference('PatronSelfRegistrationExpireTemporaryAccountsDelay', 360 );
403     is( C4::Members::DeleteExpiredOpacRegistrations(), 0, "DeleteExpiredOpacRegistrations with empty category" );
404     t::lib::Mocks::mock_preference('PatronSelfRegistrationDefaultCategory', $c );
405
406     my $checkout     = $builder->build_object({
407         class=>'Koha::Checkouts',
408         value=>{
409             borrowernumber=>$self_reg->borrowernumber
410         }
411     });
412     is( C4::Members::DeleteExpiredOpacRegistrations(), 0, "DeleteExpiredOpacRegistrations doesn't delete borrower with checkout");
413
414     my $account_line = $builder->build_object(
415         {
416             class => 'Koha::Account::Lines',
417             value => {
418                 borrowernumber    => $self_reg->borrowernumber,
419                 amountoutstanding => 5,
420             }
421         }
422     );
423     is( C4::Members::DeleteExpiredOpacRegistrations(), 0, "DeleteExpiredOpacRegistrations doesn't delete borrower with checkout and fine");
424
425     $checkout->delete;
426     is( C4::Members::DeleteExpiredOpacRegistrations(), 0, "DeleteExpiredOpacRegistrations doesn't delete borrower with fine and no checkout");
427
428     $account_line->delete;
429     is( C4::Members::DeleteExpiredOpacRegistrations(), 1, "DeleteExpiredOpacRegistrations does delete borrower with no fines and no checkouts");
430
431 };
432
433 sub _find_member {
434     my ($resultset) = @_;
435     my $found = $resultset && grep( { $_->{cardnumber} && $_->{cardnumber} eq $CARDNUMBER } @$resultset );
436     return $found;
437 }
438
439 $schema->storage->txn_rollback;
440
441 subtest 'Koha::Patron->store (invalid categorycode) tests' => sub {
442     plan tests => 1;
443     # TODO Move this to t/db_dependent/Koha/Patrons.t subtest ->store
444
445     $schema->storage->txn_begin;
446
447     my $category    = $builder->build_object({ class => 'Koha::Patron::Categories' });
448     my $category_id = $category->id;
449     # Remove category to make sure the id is not on the DB
450     $category->delete;
451
452     my $patron_data = {
453         categorycode => $category_id
454     };
455
456     throws_ok
457         { Koha::Patron->new( $patron_data )->store; }
458         'Koha::Exceptions::Object::FKConstraint',
459         'AddMember raises an exception on invalid categorycode';
460
461     $schema->storage->txn_rollback;
462 };