I have a requirement where I need to send a reminder to the user who has not logged in past xx days eg(1) and after sending this reminder he will have 2 days to log in to avoid being disabled.
I wrote a batch but I don't know how may I implement a solution that he will be deactivated after these 3 days counting based on last received reminder.
So for example - User logged in yesterday eg(22 Sep) so today (23 Sep) should receive a reminder that after 2 days his account will be deactivated (25 Sep). But when he log in 24 Sep he should receive a notification on 25 Sep that he has again 2 days to log in.
This is my code - could someone help me out with how to implement it ?
global class UserLoginReminderBatch implements Database.Batchable<sObject>{
Date todayDate = System.today();
Integer getDay = todayDate.Day() + 2;
Date deactivateDate = todayDate.addDays(1);
Integer currentMonth = todayDate.month();
Map<Integer,String> monthNames = new Map<Integer,String>{
1 => 'January',
2 => 'February',
3 => 'March',
4 => 'April',
5 => 'May',
6 => 'June',
7 => 'July',
8 => 'August',
9 => 'September',
10 => 'October',
11 => 'November',
12 => 'December'
};
Set<String> profileNames = new Set<String>{
'System Administrator',
'Chatter Free User'};
String query = 'SELECT Id, Email, LastLoginDate, Profile.Name ' +
'FROM User ' +
'WHERE IsActive = TRUE AND LastLoginDate < NEXT_N_DAYS:1 AND Profile.Name NOT IN :profileNames';
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<User> scope){
User user = scope[0];
List<User> usersListToDeactivate = new List<User>();
for(User userRecord : scope){
User usr = (user)userRecord;
user.Ready_For_Deactivate__c = TRUE;
usersListToDeactivate.add(user);
}
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[] {user.Email});
email.setSubject('SFDC Reminder');
email.setTargetObjectId(user.Id);
email.setSaveAsActivity(false);
String emailBody = '<b> Hi, </b> <br>' +
'This is reminder because <b>you have not logged in for more than 1 day.</b>' +;
email.setHtmlBody(emailBody);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
if(todayDate == deactivateDate AND user.Ready_For_Deactivate__c == TRUE){
for(User us : usersListToDeactivate){
us.IsActive = FALSE;
us.Ready_For_Deactivate__c = FALSE;
}
}
update usersListToDeactivate;
}
global void finish(Database.BatchableContext BC){
}
}