-
ChatterFeed
-
0Best Answers
-
0Likes Received
-
0Likes Given
-
7Questions
-
3Replies
Can anyone help by writing the test class for this apex class. I am new in coding. need help.
Can anyone help by writing the test class for this apex class. I am new in coding. need help. Thanks
public class HSE_SecurityHealthCheckReport {
public List<List<String>> getSecurityHealthCheckRisks(){
List<List<String>> lstValues = new List<List<String>>();
String baseURL = System.URL.getSalesforceBaseUrl().toExternalForm();
String endpoint = baseURL+'/services/data/v56.0/tooling/query/?q=select+SettingRiskCategory,Setting,OrgValue,StandardValue,RiskType+from+SecurityHealthCheckRisks';
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
req.setHeader('Content-Type', 'application/json');
req.setEndpoint(endpoint);
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
String response = res.getBody();
List<HSE_SHCRWrapper> lstSHCRWpr = new List<HSE_SHCRWrapper>();
HSE_ResponseWrapper respWpr = new HSE_ResponseWrapper();
respWpr = (HSE_ResponseWrapper) JSON.deserialize(response, HSE_ResponseWrapper.Class);
List<String> lstString = new List<String>();
for(HSE_SHCRWrapper obj: respWpr.records){
lstString = new List<String>();
lstString.add(obj.SettingRiskCategory);
lstString.add(obj.Setting);
lstString.add(obj.OrgValue);
lstString.add(obj.StandardValue);
lstString.add(obj.RiskType);
lstValues.add(lstString);
}
return lstValues;
}
public static String getSecurityHealthCheck(Blob body){
List<List<String>> lstValues = new List<List<String>>();
String baseURL = System.URL.getSalesforceBaseUrl().toExternalForm();
String endpoint = baseURL+'/services/data/v56.0/tooling/query/?q=SELECT+Id,Score+FROM+SecurityHealthCheck';
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
req.setHeader('Content-Type', 'application/json');
req.setEndpoint(endpoint);
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
String response = res.getBody();
system.debug(response);
List<HSE_SHCWrapper> lstSHCRWpr = new List<HSE_SHCWrapper>();
HSE_SHCWRespWrapper respWpr = new HSE_SHCWRespWrapper();
respWpr = (HSE_SHCWRespWrapper) JSON.deserialize(response, HSE_SHCWRespWrapper.Class);
HSE_UtilityMethods.CreateCasewithAttchment(body,respWpr.records[0].Score, caseInfoPopulation(respWpr.records[0].Score)[0],caseInfoPopulation(respWpr.records[0].Score)[1]);
return respWpr.records[0].Score;
}
public static void sendEmailWithAttachment(){
PageReference excel = new pagereference('/apex/HSE_healthcheckOutputGenerator');
Blob body;
try {
body = excel.getContent();
} catch(Exception e){HSECustomException.logException(e);
body = Blob.valueOf('data');
}
String score = getSecurityHealthCheck(body);
Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
attach.setContentType('application/vnd.ms-excel');
attach.setFileName('SecurityRisk.xls');
attach.Body = body;
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<HSE_Security_Distribution_Channel__mdt> reptoaddresses= [Select Email__c from HSE_Security_Distribution_Channel__mdt];
List<String> toAddresses=new List<String>();
try{
for(HSE_Security_Distribution_Channel__mdt securitymail :reptoaddresses )
{
toAddresses.add(securitymail.Email__c);
}
List<emailtemplate> emailtemp=[SELECT Id, DeveloperName, Name, Subject, Body, HtmlValue FROM EmailTemplate where DeveloperName='HSE_Security_Email'];
String emailBody = emailtemp[0].HtmlValue.replace('{Datetime}',String.valueOf(System.Datetime.now()));
emailBody = emailBody.replace('{score}',Score);
mail.setToAddresses(toAddresses);//set from address
mail.setSenderDisplayName('No Reply');
mail.setSubject(emailtemp[0].Subject.replace('{Datetime}',String.valueOf(System.Datetime.now())));
mail.setPlainTextBody('HTML not supported..!');
mail.setHtmlBody(emailBody);
mail.setFileAttachments(new Messaging.EmailFileAttachment[] {attach});
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
}catch(Exception e){HSECustomException.logException(e);}
}
public static List<String> caseInfoPopulation(String score){
Integer scoreInt = Integer.valueOf(score);
List<HSE_HealthcheckThreshold__mdt> healthchkThreshold= [SELECT description__c,higherThreshold__c,lowerThreshold__c
FROM HSE_HealthcheckThreshold__mdt
WHERE lowerThreshold__c <=:scoreInt
AND higherThreshold__c >=:scoreInt];
String subject, description;
Subject= healthchkThreshold[0].description__c;
Description= healthchkThreshold[0].description__c;
return new List<String>{subject,description};
}
public class HSE_ResponseWrapper{
public list<HSE_SHCRWrapper> records = new list<HSE_SHCRWrapper>();
}
public class HSE_SHCWRespWrapper{
public list<HSE_SHCWrapper> records = new list<HSE_SHCWrapper>();
}
public class HSE_SHCRWrapper{
public String SettingRiskCategory;
public String Setting;
public String OrgValue;
public String StandardValue;
public String RiskType;
}
public class HSE_SHCWrapper{
public String Id;
public String DurableId;
public String Score;
}
}
public class HSE_SecurityHealthCheckReport {
public List<List<String>> getSecurityHealthCheckRisks(){
List<List<String>> lstValues = new List<List<String>>();
String baseURL = System.URL.getSalesforceBaseUrl().toExternalForm();
String endpoint = baseURL+'/services/data/v56.0/tooling/query/?q=select+SettingRiskCategory,Setting,OrgValue,StandardValue,RiskType+from+SecurityHealthCheckRisks';
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
req.setHeader('Content-Type', 'application/json');
req.setEndpoint(endpoint);
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
String response = res.getBody();
List<HSE_SHCRWrapper> lstSHCRWpr = new List<HSE_SHCRWrapper>();
HSE_ResponseWrapper respWpr = new HSE_ResponseWrapper();
respWpr = (HSE_ResponseWrapper) JSON.deserialize(response, HSE_ResponseWrapper.Class);
List<String> lstString = new List<String>();
for(HSE_SHCRWrapper obj: respWpr.records){
lstString = new List<String>();
lstString.add(obj.SettingRiskCategory);
lstString.add(obj.Setting);
lstString.add(obj.OrgValue);
lstString.add(obj.StandardValue);
lstString.add(obj.RiskType);
lstValues.add(lstString);
}
return lstValues;
}
public static String getSecurityHealthCheck(Blob body){
List<List<String>> lstValues = new List<List<String>>();
String baseURL = System.URL.getSalesforceBaseUrl().toExternalForm();
String endpoint = baseURL+'/services/data/v56.0/tooling/query/?q=SELECT+Id,Score+FROM+SecurityHealthCheck';
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
req.setHeader('Content-Type', 'application/json');
req.setEndpoint(endpoint);
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
String response = res.getBody();
system.debug(response);
List<HSE_SHCWrapper> lstSHCRWpr = new List<HSE_SHCWrapper>();
HSE_SHCWRespWrapper respWpr = new HSE_SHCWRespWrapper();
respWpr = (HSE_SHCWRespWrapper) JSON.deserialize(response, HSE_SHCWRespWrapper.Class);
HSE_UtilityMethods.CreateCasewithAttchment(body,respWpr.records[0].Score, caseInfoPopulation(respWpr.records[0].Score)[0],caseInfoPopulation(respWpr.records[0].Score)[1]);
return respWpr.records[0].Score;
}
public static void sendEmailWithAttachment(){
PageReference excel = new pagereference('/apex/HSE_healthcheckOutputGenerator');
Blob body;
try {
body = excel.getContent();
} catch(Exception e){HSECustomException.logException(e);
body = Blob.valueOf('data');
}
String score = getSecurityHealthCheck(body);
Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
attach.setContentType('application/vnd.ms-excel');
attach.setFileName('SecurityRisk.xls');
attach.Body = body;
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<HSE_Security_Distribution_Channel__mdt> reptoaddresses= [Select Email__c from HSE_Security_Distribution_Channel__mdt];
List<String> toAddresses=new List<String>();
try{
for(HSE_Security_Distribution_Channel__mdt securitymail :reptoaddresses )
{
toAddresses.add(securitymail.Email__c);
}
List<emailtemplate> emailtemp=[SELECT Id, DeveloperName, Name, Subject, Body, HtmlValue FROM EmailTemplate where DeveloperName='HSE_Security_Email'];
String emailBody = emailtemp[0].HtmlValue.replace('{Datetime}',String.valueOf(System.Datetime.now()));
emailBody = emailBody.replace('{score}',Score);
mail.setToAddresses(toAddresses);//set from address
mail.setSenderDisplayName('No Reply');
mail.setSubject(emailtemp[0].Subject.replace('{Datetime}',String.valueOf(System.Datetime.now())));
mail.setPlainTextBody('HTML not supported..!');
mail.setHtmlBody(emailBody);
mail.setFileAttachments(new Messaging.EmailFileAttachment[] {attach});
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
}catch(Exception e){HSECustomException.logException(e);}
}
public static List<String> caseInfoPopulation(String score){
Integer scoreInt = Integer.valueOf(score);
List<HSE_HealthcheckThreshold__mdt> healthchkThreshold= [SELECT description__c,higherThreshold__c,lowerThreshold__c
FROM HSE_HealthcheckThreshold__mdt
WHERE lowerThreshold__c <=:scoreInt
AND higherThreshold__c >=:scoreInt];
String subject, description;
Subject= healthchkThreshold[0].description__c;
Description= healthchkThreshold[0].description__c;
return new List<String>{subject,description};
}
public class HSE_ResponseWrapper{
public list<HSE_SHCRWrapper> records = new list<HSE_SHCRWrapper>();
}
public class HSE_SHCWRespWrapper{
public list<HSE_SHCWrapper> records = new list<HSE_SHCWrapper>();
}
public class HSE_SHCRWrapper{
public String SettingRiskCategory;
public String Setting;
public String OrgValue;
public String StandardValue;
public String RiskType;
}
public class HSE_SHCWrapper{
public String Id;
public String DurableId;
public String Score;
}
}
- KRITI LAHA 8
- August 23, 2023
- Like
- 0
How to populate user's other fields from map
Hello all,
I have this below code. The output of this code is like, I am getting UserId, Status and Permission set list and I need other fields of the user should be populated. Can anyone please help me on this? Thanks
public class UserService {
private static String profileName = 'Chatter Free User';
private static String ps7Name = 'Test Chatter Free7';
Public static List<UserDetail> userDetailList = new List<UserDetail>();
private static List<String> ps1_ps10NameList = new List<String>{
'Test Chatter Free1','Test Chatter Free2','Test Chatter Free3','Test Chatter Free4','Test Chatter Free5','Test Chatter Free6','Test Chatter Free7','Test Chatter Free8','Test Chatter Free9','Test Chatter Free10'};
public static List<UserDetail> getUserPermissionDetails(){
Map<Id, User> userMap = new Map<Id, User>([SELECT Id
FROM User
WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
//System.debug(usermap);
Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
for(PermissionSetAssignment psa : [SELECT AssigneeId,Assignee.FirstName, Assignee.LastName, Assignee.profile.name, Assignee.Username, Assignee.Email, Assignee.Division, Assignee.Department, PermissionSet.label
FROM PermissionSetAssignment
WHERE AssigneeId = : userMap.keySet()
AND (PermissionSet.label IN :ps1_ps10NameList
OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
ORDER BY AssigneeId, PermissionSet.label])
{
List<String> tempList = new List<String>();
if(permissionSetMap.containsKey(psa.AssigneeId))
tempList = permissionSetMap.get(psa.AssigneeId);
tempList.add(psa.PermissionSet.label);
permissionSetMap.put(psa.AssigneeId, tempList);
}
return evaluateUser(permissionSetMap);
}
private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){
Boolean additional;
List<UserDetail> userDetailList = new List<UserDetail>();
List<String> foundList = new List<String>();
for(Id id : permissionSetMap.keySet())
{
UserDetail ud = new UserDetail();
additional = false;
/*system.debug(permissionSetMap.get(id));*/
foundList.clear();
for(String str : permissionSetMap.get(id)){
if(!ps1_ps10NameList.contains(str)){
additional = true;
}else{
foundList.add(str);
}
/*system.debug(userDetailList);*/
}
ud.Id = id;
ud.permissionSetList = permissionSetMap.get(id);
if(additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change And Additional';
else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
ud.status = 'Missing And Additional';
else if(!additional && ps1_ps10NameList.size() != foundList.size())
ud.status = 'Missing';
else if(!additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change';
userDetailList.add(ud);
}
System.debug(JSON.serializePretty(userDetailList));
return userDetailList;
}
public class UserDetail {
public Id id;
public List<String> permissionSetList;
public String status;
}
}
I have this below code. The output of this code is like, I am getting UserId, Status and Permission set list and I need other fields of the user should be populated. Can anyone please help me on this? Thanks
public class UserService {
private static String profileName = 'Chatter Free User';
private static String ps7Name = 'Test Chatter Free7';
Public static List<UserDetail> userDetailList = new List<UserDetail>();
private static List<String> ps1_ps10NameList = new List<String>{
'Test Chatter Free1','Test Chatter Free2','Test Chatter Free3','Test Chatter Free4','Test Chatter Free5','Test Chatter Free6','Test Chatter Free7','Test Chatter Free8','Test Chatter Free9','Test Chatter Free10'};
public static List<UserDetail> getUserPermissionDetails(){
Map<Id, User> userMap = new Map<Id, User>([SELECT Id
FROM User
WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
//System.debug(usermap);
Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
for(PermissionSetAssignment psa : [SELECT AssigneeId,Assignee.FirstName, Assignee.LastName, Assignee.profile.name, Assignee.Username, Assignee.Email, Assignee.Division, Assignee.Department, PermissionSet.label
FROM PermissionSetAssignment
WHERE AssigneeId = : userMap.keySet()
AND (PermissionSet.label IN :ps1_ps10NameList
OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
ORDER BY AssigneeId, PermissionSet.label])
{
List<String> tempList = new List<String>();
if(permissionSetMap.containsKey(psa.AssigneeId))
tempList = permissionSetMap.get(psa.AssigneeId);
tempList.add(psa.PermissionSet.label);
permissionSetMap.put(psa.AssigneeId, tempList);
}
return evaluateUser(permissionSetMap);
}
private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){
Boolean additional;
List<UserDetail> userDetailList = new List<UserDetail>();
List<String> foundList = new List<String>();
for(Id id : permissionSetMap.keySet())
{
UserDetail ud = new UserDetail();
additional = false;
/*system.debug(permissionSetMap.get(id));*/
foundList.clear();
for(String str : permissionSetMap.get(id)){
if(!ps1_ps10NameList.contains(str)){
additional = true;
}else{
foundList.add(str);
}
/*system.debug(userDetailList);*/
}
ud.Id = id;
ud.permissionSetList = permissionSetMap.get(id);
if(additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change And Additional';
else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
ud.status = 'Missing And Additional';
else if(!additional && ps1_ps10NameList.size() != foundList.size())
ud.status = 'Missing';
else if(!additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change';
userDetailList.add(ud);
}
System.debug(JSON.serializePretty(userDetailList));
return userDetailList;
}
public class UserDetail {
public Id id;
public List<String> permissionSetList;
public String status;
}
}
- KRITI LAHA 8
- April 21, 2023
- Like
- 0
How to get other fields from below code
Hello,
I have beow code as per my requirement. Usecase is like that:
I have a list of permission sets (PS1-10) and one profile. Below are the steps which I need to execute:
First I need to find the users who have this particular profile and PS7.
Then I need to check if the users having PS7 and this profile have all the permission sets (PS1-10) assigned to them.
If there are less permission sets assigned, then return Missing, if the user has PS7 and any other permission set assigned to him, apart from PS1-10, then retuen Additional, else return No Change.
The final output should give me the userID, the permission sets assigned to them and Missing/Additional/No change. and also all the related fields of a user like firstname, last name etc..
Here I am sharing my code which I am using, it is giving me Id, status(Missing/additional), and permission list but I am facing error when I am adding other fields, As of now, I have tried with 'Division' field but it's throwing error : (Variable does not exist: division)
Can anyone please helpp me on this? I am shaing the code which I am using. Thanks
public class PersonaReport {
private static String profileName = 'HSE - Support';
private static String ps7Name = 'HSE - Omni Supervisor';
private static List<String> ps1_ps10NameList = new List<String>{
'Health Cloud Permission Set License','Multi-Factor Authentication Required','HSE - Omni Supervisor','Access Walkthroughs','myTrailhead Access','HSELIVE - Supervisor'};
public static List<UserDetail> getUserPermissionDetails(){
Map<Id, User> userMap = new Map<Id, User>([SELECT Id
FROM User
WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
//System.debug(usermap);
Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
system.debug('permissionSetMapTest'+permissionSetMap);
for(PermissionSetAssignment psa : [SELECT AssigneeId, Assignee.FirstName, Assignee.LastName, Assignee.profile.name, Assignee.Username, Assignee.Email, Assignee.Division, Assignee.Department, PermissionSet.label
FROM PermissionSetAssignment
WHERE AssigneeId = : userMap.keySet()
AND (PermissionSet.label IN :ps1_ps10NameList
OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
ORDER BY AssigneeId, PermissionSet.label])
{
List<String> tempList = new List<String>();
if(permissionSetMap.containsKey(psa.AssigneeId))
tempList = permissionSetMap.get(psa.AssigneeId);
tempList.add(psa.PermissionSet.label);
tempList.add(psa.Assignee.division);
permissionSetMap.put(psa.AssigneeId, tempList);
system.debug('tempdivision'+permissionSetMap );
}
return evaluateUser(permissionSetMap);
}
private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){
Boolean additional;
List<UserDetail> userDetailList = new List<UserDetail>();
List<String> foundList = new List<String>();
for(Id id : permissionSetMap.keySet())
{
UserDetail ud = new UserDetail();
additional = false;
foundList.clear();
for(String str : permissionSetMap.get(id)){
if(!ps1_ps10NameList.contains(str)){
additional = true;
}else{
foundList.add(str);
}
/*system.debug(userDetailList);*/
}
system.debug('permissionsetmaptest'+permissionSetMap);
ud.Id = id;
ud.permissionSetList = permissionSetMap.get(id);
Ud.Division=permissionSetMap.get(id).division;
system.debug('udinsideEU'+ ud);
if(additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change And Additional';
else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
ud.status = 'Missing And Additional';
else if(!additional && ps1_ps10NameList.size() != foundList.size())
ud.status = 'Missing';
else if(!additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change';
userDetailList.add(ud);
}
System.debug('evaluateUd details'+userDetailList);
return userDetailList;
}
public class UserDetail {
public Id id;
public List<String> permissionSetList;
public String status;
public String FirstName;
public String LastName;
public String Username;
public String Email;
public String Division;
public String Department;
}
public static void createcsv(){
List<UserDetail> theListReturnedFromMethod2 =getUserPermissionDetails();
system.debug('inside createcsv'+theListReturnedFromMethod2);
List<String> header= new List<String> {'AssigneeId','First Name','Last Name','Profile Name','User Name','Role Name','Email','Division','Department','Comapany Name','Last Login Date','Last Modified By','Created Date', 'PS Status' , 'Permissionset Name'};
// List<String> header= new List<String> {'AssigneeId','PS Status' , 'Permissionset Name', 'division'};
String csvColumnHeader = String.join(header,',') ;
List<String> csvRowValues = new List<String>();
csvRowValues.add(csvColumnHeader);
for(UserDetail currUser : theListReturnedFromMethod2){
String Id = currUser.Id != null ? String.valueOf(currUser.Id).escapeCsv() : '';
// String status = currUser.status != null ? String.valueOf(currUser.status).escapeCsv() : '';
String FirstName = currUser.FirstName != null ? String.valueOf(currUser.FirstName).escapeCsv() : '';
String LastName = currUser.LastName != null ? String.valueOf(currUser.LastName).escapeCsv() : '';
String Username = currUser.Username != null ? String.valueOf(currUser.Username).escapeCsv() : '';
String Email = currUser.Email != null ? String.valueOf(currUser.Email).escapeCsv() : '';
String Division = currUser.Division != null ? String.valueOf(currUser.Division).escapeCsv() : '';
system.debug('divisoncsv'+Division);
String Department = currUser.Department != null ? String.valueOf(currUser.Department).escapeCsv() : '';
String status = currUser.status != null ? String.valueOf(currUser.status).escapeCsv() : '';
String permissionSetList = currUser.permissionSetList != null ? String.join(currUser.permissionSetList,'\n').escapeCSV():'';
String rowStr = id + ',' + status + ',' + permissionSetList + ','+ Division ;
csvRowValues.add(rowStr);
}
String csvname='Persona Report'+'.csv';
String VersionData= String.join(csvRowValues,'\n');
ContentVersion cv = new ContentVersion();
cv.ContentLocation = 'S';
cv.Title = csvname;
cv.PathOnClient = csvname;
cv.VersionData = Blob.valueOf(versionData);
insert cv;
system.debug('personId'+ cv.id);
}
}
I have beow code as per my requirement. Usecase is like that:
I have a list of permission sets (PS1-10) and one profile. Below are the steps which I need to execute:
First I need to find the users who have this particular profile and PS7.
Then I need to check if the users having PS7 and this profile have all the permission sets (PS1-10) assigned to them.
If there are less permission sets assigned, then return Missing, if the user has PS7 and any other permission set assigned to him, apart from PS1-10, then retuen Additional, else return No Change.
The final output should give me the userID, the permission sets assigned to them and Missing/Additional/No change. and also all the related fields of a user like firstname, last name etc..
Here I am sharing my code which I am using, it is giving me Id, status(Missing/additional), and permission list but I am facing error when I am adding other fields, As of now, I have tried with 'Division' field but it's throwing error : (Variable does not exist: division)
Can anyone please helpp me on this? I am shaing the code which I am using. Thanks
public class PersonaReport {
private static String profileName = 'HSE - Support';
private static String ps7Name = 'HSE - Omni Supervisor';
private static List<String> ps1_ps10NameList = new List<String>{
'Health Cloud Permission Set License','Multi-Factor Authentication Required','HSE - Omni Supervisor','Access Walkthroughs','myTrailhead Access','HSELIVE - Supervisor'};
public static List<UserDetail> getUserPermissionDetails(){
Map<Id, User> userMap = new Map<Id, User>([SELECT Id
FROM User
WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
//System.debug(usermap);
Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
system.debug('permissionSetMapTest'+permissionSetMap);
for(PermissionSetAssignment psa : [SELECT AssigneeId, Assignee.FirstName, Assignee.LastName, Assignee.profile.name, Assignee.Username, Assignee.Email, Assignee.Division, Assignee.Department, PermissionSet.label
FROM PermissionSetAssignment
WHERE AssigneeId = : userMap.keySet()
AND (PermissionSet.label IN :ps1_ps10NameList
OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
ORDER BY AssigneeId, PermissionSet.label])
{
List<String> tempList = new List<String>();
if(permissionSetMap.containsKey(psa.AssigneeId))
tempList = permissionSetMap.get(psa.AssigneeId);
tempList.add(psa.PermissionSet.label);
tempList.add(psa.Assignee.division);
permissionSetMap.put(psa.AssigneeId, tempList);
system.debug('tempdivision'+permissionSetMap );
}
return evaluateUser(permissionSetMap);
}
private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){
Boolean additional;
List<UserDetail> userDetailList = new List<UserDetail>();
List<String> foundList = new List<String>();
for(Id id : permissionSetMap.keySet())
{
UserDetail ud = new UserDetail();
additional = false;
foundList.clear();
for(String str : permissionSetMap.get(id)){
if(!ps1_ps10NameList.contains(str)){
additional = true;
}else{
foundList.add(str);
}
/*system.debug(userDetailList);*/
}
system.debug('permissionsetmaptest'+permissionSetMap);
ud.Id = id;
ud.permissionSetList = permissionSetMap.get(id);
Ud.Division=permissionSetMap.get(id).division;
system.debug('udinsideEU'+ ud);
if(additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change And Additional';
else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
ud.status = 'Missing And Additional';
else if(!additional && ps1_ps10NameList.size() != foundList.size())
ud.status = 'Missing';
else if(!additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change';
userDetailList.add(ud);
}
System.debug('evaluateUd details'+userDetailList);
return userDetailList;
}
public class UserDetail {
public Id id;
public List<String> permissionSetList;
public String status;
public String FirstName;
public String LastName;
public String Username;
public String Email;
public String Division;
public String Department;
}
public static void createcsv(){
List<UserDetail> theListReturnedFromMethod2 =getUserPermissionDetails();
system.debug('inside createcsv'+theListReturnedFromMethod2);
List<String> header= new List<String> {'AssigneeId','First Name','Last Name','Profile Name','User Name','Role Name','Email','Division','Department','Comapany Name','Last Login Date','Last Modified By','Created Date', 'PS Status' , 'Permissionset Name'};
// List<String> header= new List<String> {'AssigneeId','PS Status' , 'Permissionset Name', 'division'};
String csvColumnHeader = String.join(header,',') ;
List<String> csvRowValues = new List<String>();
csvRowValues.add(csvColumnHeader);
for(UserDetail currUser : theListReturnedFromMethod2){
String Id = currUser.Id != null ? String.valueOf(currUser.Id).escapeCsv() : '';
// String status = currUser.status != null ? String.valueOf(currUser.status).escapeCsv() : '';
String FirstName = currUser.FirstName != null ? String.valueOf(currUser.FirstName).escapeCsv() : '';
String LastName = currUser.LastName != null ? String.valueOf(currUser.LastName).escapeCsv() : '';
String Username = currUser.Username != null ? String.valueOf(currUser.Username).escapeCsv() : '';
String Email = currUser.Email != null ? String.valueOf(currUser.Email).escapeCsv() : '';
String Division = currUser.Division != null ? String.valueOf(currUser.Division).escapeCsv() : '';
system.debug('divisoncsv'+Division);
String Department = currUser.Department != null ? String.valueOf(currUser.Department).escapeCsv() : '';
String status = currUser.status != null ? String.valueOf(currUser.status).escapeCsv() : '';
String permissionSetList = currUser.permissionSetList != null ? String.join(currUser.permissionSetList,'\n').escapeCSV():'';
String rowStr = id + ',' + status + ',' + permissionSetList + ','+ Division ;
csvRowValues.add(rowStr);
}
String csvname='Persona Report'+'.csv';
String VersionData= String.join(csvRowValues,'\n');
ContentVersion cv = new ContentVersion();
cv.ContentLocation = 'S';
cv.Title = csvname;
cv.PathOnClient = csvname;
cv.VersionData = Blob.valueOf(versionData);
insert cv;
system.debug('personId'+ cv.id);
}
}
- KRITI LAHA 8
- April 21, 2023
- Like
- 0
Batch job on SecurityHealthCheck
Hi all,
Can anyone help me to write a batch class on SecurityHealthCheck which will calculate the score and risk cateory and an email needs to be sent with the result?
Query:
1. SELECT SettingRiskCategory, RiskType, Setting, SettingGroup, OrgValue, StandardValue FROM SecurityHealthCheckRisks where RiskType != 'MEETS_STANDARD'
2. select score from SecurityHealthCheck
I have tried but getting below error: Invalid type: SecurityHealthCheck
Thanks
Can anyone help me to write a batch class on SecurityHealthCheck which will calculate the score and risk cateory and an email needs to be sent with the result?
Query:
1. SELECT SettingRiskCategory, RiskType, Setting, SettingGroup, OrgValue, StandardValue FROM SecurityHealthCheckRisks where RiskType != 'MEETS_STANDARD'
2. select score from SecurityHealthCheck
I have tried but getting below error: Invalid type: SecurityHealthCheck
Thanks
- KRITI LAHA 8
- April 19, 2023
- Like
- 0
Query on securityhealthcheck is not supported when using in APEX code
Hello all,
I was trying to write a batch job which will calculate score and risk types from SecurityHealthCheck,but I am getting below error :
Invalid type: Schema.SecurityHealthCheck
Invalid type: Schema.SecurityHealthCheckRisks
I am using below queries:
select Score from SecurityHealthCheck
SELECT SettingRiskCategory, RiskType, Setting, SettingGroup, OrgValue, StandardValue FROM SecurityHealthCheckRisks where RiskType != 'MEETS_STANDARD'
These two are running in Query editor.
Can anyone please give me solution how can I omit this error?
Thanks
I was trying to write a batch job which will calculate score and risk types from SecurityHealthCheck,but I am getting below error :
Invalid type: Schema.SecurityHealthCheck
Invalid type: Schema.SecurityHealthCheckRisks
I am using below queries:
select Score from SecurityHealthCheck
SELECT SettingRiskCategory, RiskType, Setting, SettingGroup, OrgValue, StandardValue FROM SecurityHealthCheckRisks where RiskType != 'MEETS_STANDARD'
These two are running in Query editor.
Can anyone please give me solution how can I omit this error?
Thanks
- KRITI LAHA 8
- April 18, 2023
- Like
- 0
Generate CSV with proper format
Hello, I have this below code,the CSV file is generating but not in proper format. How to generate the CSV file to show full list?
public class UserService {
private static String profileName = 'Chatter Free User';
private static String ps7Name = 'Test Chatter Free7';
private static List<String> ps1_ps10NameList = new List<String>{
'Test Chatter Free1','Test Chatter Free2','Test Chatter Free3','Test Chatter Free4','Test Chatter Free5','Test Chatter Free6','Test Chatter Free7','Test Chatter Free8','Test Chatter Free9','Test Chatter Free10'};
public static List<UserDetail> getUserPermissionDetails()
Map<Id, User> userMap = new Map<Id, User>([SELECT Id
FROM User
WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
//System.debug(usermap);
Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
for(PermissionSetAssignment psa : [SELECT AssigneeId, PermissionSet.label
FROM PermissionSetAssignment
WHERE AssigneeId = : userMap.keySet()
AND (PermissionSet.label IN :ps1_ps10NameList
OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
ORDER BY AssigneeId, PermissionSet.label])
{
List<String> tempList = new List<String>();
if(permissionSetMap.containsKey(psa.AssigneeId))
tempList = permissionSetMap.get(psa.AssigneeId);
tempList.add(psa.PermissionSet.label);
permissionSetMap.put(psa.AssigneeId, tempList);
}
return evaluateUser(permissionSetMap);
}
private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){
Boolean additional;
List<UserDetail> userDetailList = new List<UserDetail>();
List<String> foundList = new List<String>();
for(Id id : permissionSetMap.keySet())
{
UserDetail ud = new UserDetail();
additional = false;
/*system.debug(permissionSetMap.get(id));*/
foundList.clear();
for(String str : permissionSetMap.get(id)){
if(!ps1_ps10NameList.contains(str)){
additional = true;
}else{
foundList.add(str);
}
/*system.debug(userDetailList);*/
}
ud.Id = id;
ud.permissionSetList = permissionSetMap.get(id);
if(additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change And Additional';
else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
ud.status = 'Missing And Additional';
else if(!additional && ps1_ps10NameList.size() != foundList.size())
ud.status = 'Missing';
else if(!additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change';
userDetailList.add(ud);
}
System.debug(JSON.serializePretty(userDetailList));
return userDetailList;
}
public class UserDetail {
public Id id;
public List<String> permissionSetList;
public String status;
}
public static void createcsv(){
List<UserDetail> theListReturnedFromMethod2 =getUserPermissionDetails();
String req = json.serialize(theListReturnedFromMethod2);
Blob csvBlob = blob.valueOf(req);
String csvname='Persona Report'+'.xls';
Document doc= new document();
doc.name=csvname;
doc.folderId=[Select Id, Name from Folder where Name='Persona'].Id;
doc.body=csvBlob;
doc.description='Persona';
insert doc;
}
}
public class UserService {
private static String profileName = 'Chatter Free User';
private static String ps7Name = 'Test Chatter Free7';
private static List<String> ps1_ps10NameList = new List<String>{
'Test Chatter Free1','Test Chatter Free2','Test Chatter Free3','Test Chatter Free4','Test Chatter Free5','Test Chatter Free6','Test Chatter Free7','Test Chatter Free8','Test Chatter Free9','Test Chatter Free10'};
public static List<UserDetail> getUserPermissionDetails()
Map<Id, User> userMap = new Map<Id, User>([SELECT Id
FROM User
WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
//System.debug(usermap);
Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
for(PermissionSetAssignment psa : [SELECT AssigneeId, PermissionSet.label
FROM PermissionSetAssignment
WHERE AssigneeId = : userMap.keySet()
AND (PermissionSet.label IN :ps1_ps10NameList
OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
ORDER BY AssigneeId, PermissionSet.label])
{
List<String> tempList = new List<String>();
if(permissionSetMap.containsKey(psa.AssigneeId))
tempList = permissionSetMap.get(psa.AssigneeId);
tempList.add(psa.PermissionSet.label);
permissionSetMap.put(psa.AssigneeId, tempList);
}
return evaluateUser(permissionSetMap);
}
private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){
Boolean additional;
List<UserDetail> userDetailList = new List<UserDetail>();
List<String> foundList = new List<String>();
for(Id id : permissionSetMap.keySet())
{
UserDetail ud = new UserDetail();
additional = false;
/*system.debug(permissionSetMap.get(id));*/
foundList.clear();
for(String str : permissionSetMap.get(id)){
if(!ps1_ps10NameList.contains(str)){
additional = true;
}else{
foundList.add(str);
}
/*system.debug(userDetailList);*/
}
ud.Id = id;
ud.permissionSetList = permissionSetMap.get(id);
if(additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change And Additional';
else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
ud.status = 'Missing And Additional';
else if(!additional && ps1_ps10NameList.size() != foundList.size())
ud.status = 'Missing';
else if(!additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change';
userDetailList.add(ud);
}
System.debug(JSON.serializePretty(userDetailList));
return userDetailList;
}
public class UserDetail {
public Id id;
public List<String> permissionSetList;
public String status;
}
public static void createcsv(){
List<UserDetail> theListReturnedFromMethod2 =getUserPermissionDetails();
String req = json.serialize(theListReturnedFromMethod2);
Blob csvBlob = blob.valueOf(req);
String csvname='Persona Report'+'.xls';
Document doc= new document();
doc.name=csvname;
doc.folderId=[Select Id, Name from Folder where Name='Persona'].Id;
doc.body=csvBlob;
doc.description='Persona';
insert doc;
}
}
- KRITI LAHA 8
- March 16, 2023
- Like
- 0
generate csv file using apex
I have below code. I need to generate a csv file to show to results of 'userdetaillist'.
public class UserService {
private static String profileName = 'Chatter Free User';
private static String ps7Name = 'Test Chatter Free7';
Public static List<UserDetail> userDetailList = new List<UserDetail>();
private static List<String> ps1_ps10NameList = new List<String>{
'Test Chatter Free1','Test Chatter Free2','Test Chatter Free3','Test Chatter Free4','Test Chatter Free5','Test Chatter Free6','Test Chatter Free7','Test Chatter Free8','Test Chatter Free9','Test Chatter Free10'};
public static List<UserDetail> getUserPermissionDetails(){
Map<Id, User> userMap = new Map<Id, User>([SELECT Id
FROM User
WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
//System.debug(usermap);
Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
for(PermissionSetAssignment psa : [SELECT AssigneeId, PermissionSet.label
FROM PermissionSetAssignment
WHERE AssigneeId = : userMap.keySet()
AND (PermissionSet.label IN :ps1_ps10NameList
OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
ORDER BY AssigneeId, PermissionSet.label])
{
List<String> tempList = new List<String>();
if(permissionSetMap.containsKey(psa.AssigneeId))
tempList = permissionSetMap.get(psa.AssigneeId);
tempList.add(psa.PermissionSet.label);
permissionSetMap.put(psa.AssigneeId, tempList);
}
return evaluateUser(permissionSetMap);
}
private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){
Boolean additional;
List<UserDetail> userDetailList = new List<UserDetail>();
List<String> foundList = new List<String>();
for(Id id : permissionSetMap.keySet())
{
UserDetail ud = new UserDetail();
additional = false;
/*system.debug(permissionSetMap.get(id));*/
foundList.clear();
for(String str : permissionSetMap.get(id)){
if(!ps1_ps10NameList.contains(str)){
additional = true;
}else{
foundList.add(str);
}
/*system.debug(userDetailList);*/
}
ud.Id = id;
ud.permissionSetList = permissionSetMap.get(id);
if(additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change And Additional';
else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
ud.status = 'Missing And Additional';
else if(!additional && ps1_ps10NameList.size() != foundList.size())
ud.status = 'Missing';
else if(!additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change';
userDetailList.add(ud);
}
System.debug(JSON.serializePretty(userDetailList));
return userDetailList;
}
public class UserDetail {
public Id id;
public List<String> permissionSetList;
public String status;
}
}
public class UserService {
private static String profileName = 'Chatter Free User';
private static String ps7Name = 'Test Chatter Free7';
Public static List<UserDetail> userDetailList = new List<UserDetail>();
private static List<String> ps1_ps10NameList = new List<String>{
'Test Chatter Free1','Test Chatter Free2','Test Chatter Free3','Test Chatter Free4','Test Chatter Free5','Test Chatter Free6','Test Chatter Free7','Test Chatter Free8','Test Chatter Free9','Test Chatter Free10'};
public static List<UserDetail> getUserPermissionDetails(){
Map<Id, User> userMap = new Map<Id, User>([SELECT Id
FROM User
WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
//System.debug(usermap);
Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
for(PermissionSetAssignment psa : [SELECT AssigneeId, PermissionSet.label
FROM PermissionSetAssignment
WHERE AssigneeId = : userMap.keySet()
AND (PermissionSet.label IN :ps1_ps10NameList
OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
ORDER BY AssigneeId, PermissionSet.label])
{
List<String> tempList = new List<String>();
if(permissionSetMap.containsKey(psa.AssigneeId))
tempList = permissionSetMap.get(psa.AssigneeId);
tempList.add(psa.PermissionSet.label);
permissionSetMap.put(psa.AssigneeId, tempList);
}
return evaluateUser(permissionSetMap);
}
private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){
Boolean additional;
List<UserDetail> userDetailList = new List<UserDetail>();
List<String> foundList = new List<String>();
for(Id id : permissionSetMap.keySet())
{
UserDetail ud = new UserDetail();
additional = false;
/*system.debug(permissionSetMap.get(id));*/
foundList.clear();
for(String str : permissionSetMap.get(id)){
if(!ps1_ps10NameList.contains(str)){
additional = true;
}else{
foundList.add(str);
}
/*system.debug(userDetailList);*/
}
ud.Id = id;
ud.permissionSetList = permissionSetMap.get(id);
if(additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change And Additional';
else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
ud.status = 'Missing And Additional';
else if(!additional && ps1_ps10NameList.size() != foundList.size())
ud.status = 'Missing';
else if(!additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change';
userDetailList.add(ud);
}
System.debug(JSON.serializePretty(userDetailList));
return userDetailList;
}
public class UserDetail {
public Id id;
public List<String> permissionSetList;
public String status;
}
}
- KRITI LAHA 8
- March 08, 2023
- Like
- 0
Query on securityhealthcheck is not supported when using in APEX code
Hello all,
I was trying to write a batch job which will calculate score and risk types from SecurityHealthCheck,but I am getting below error :
Invalid type: Schema.SecurityHealthCheck
Invalid type: Schema.SecurityHealthCheckRisks
I am using below queries:
select Score from SecurityHealthCheck
SELECT SettingRiskCategory, RiskType, Setting, SettingGroup, OrgValue, StandardValue FROM SecurityHealthCheckRisks where RiskType != 'MEETS_STANDARD'
These two are running in Query editor.
Can anyone please give me solution how can I omit this error?
Thanks
I was trying to write a batch job which will calculate score and risk types from SecurityHealthCheck,but I am getting below error :
Invalid type: Schema.SecurityHealthCheck
Invalid type: Schema.SecurityHealthCheckRisks
I am using below queries:
select Score from SecurityHealthCheck
SELECT SettingRiskCategory, RiskType, Setting, SettingGroup, OrgValue, StandardValue FROM SecurityHealthCheckRisks where RiskType != 'MEETS_STANDARD'
These two are running in Query editor.
Can anyone please give me solution how can I omit this error?
Thanks
- KRITI LAHA 8
- April 18, 2023
- Like
- 0
Generate CSV with proper format
Hello, I have this below code,the CSV file is generating but not in proper format. How to generate the CSV file to show full list?
public class UserService {
private static String profileName = 'Chatter Free User';
private static String ps7Name = 'Test Chatter Free7';
private static List<String> ps1_ps10NameList = new List<String>{
'Test Chatter Free1','Test Chatter Free2','Test Chatter Free3','Test Chatter Free4','Test Chatter Free5','Test Chatter Free6','Test Chatter Free7','Test Chatter Free8','Test Chatter Free9','Test Chatter Free10'};
public static List<UserDetail> getUserPermissionDetails()
Map<Id, User> userMap = new Map<Id, User>([SELECT Id
FROM User
WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
//System.debug(usermap);
Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
for(PermissionSetAssignment psa : [SELECT AssigneeId, PermissionSet.label
FROM PermissionSetAssignment
WHERE AssigneeId = : userMap.keySet()
AND (PermissionSet.label IN :ps1_ps10NameList
OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
ORDER BY AssigneeId, PermissionSet.label])
{
List<String> tempList = new List<String>();
if(permissionSetMap.containsKey(psa.AssigneeId))
tempList = permissionSetMap.get(psa.AssigneeId);
tempList.add(psa.PermissionSet.label);
permissionSetMap.put(psa.AssigneeId, tempList);
}
return evaluateUser(permissionSetMap);
}
private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){
Boolean additional;
List<UserDetail> userDetailList = new List<UserDetail>();
List<String> foundList = new List<String>();
for(Id id : permissionSetMap.keySet())
{
UserDetail ud = new UserDetail();
additional = false;
/*system.debug(permissionSetMap.get(id));*/
foundList.clear();
for(String str : permissionSetMap.get(id)){
if(!ps1_ps10NameList.contains(str)){
additional = true;
}else{
foundList.add(str);
}
/*system.debug(userDetailList);*/
}
ud.Id = id;
ud.permissionSetList = permissionSetMap.get(id);
if(additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change And Additional';
else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
ud.status = 'Missing And Additional';
else if(!additional && ps1_ps10NameList.size() != foundList.size())
ud.status = 'Missing';
else if(!additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change';
userDetailList.add(ud);
}
System.debug(JSON.serializePretty(userDetailList));
return userDetailList;
}
public class UserDetail {
public Id id;
public List<String> permissionSetList;
public String status;
}
public static void createcsv(){
List<UserDetail> theListReturnedFromMethod2 =getUserPermissionDetails();
String req = json.serialize(theListReturnedFromMethod2);
Blob csvBlob = blob.valueOf(req);
String csvname='Persona Report'+'.xls';
Document doc= new document();
doc.name=csvname;
doc.folderId=[Select Id, Name from Folder where Name='Persona'].Id;
doc.body=csvBlob;
doc.description='Persona';
insert doc;
}
}
public class UserService {
private static String profileName = 'Chatter Free User';
private static String ps7Name = 'Test Chatter Free7';
private static List<String> ps1_ps10NameList = new List<String>{
'Test Chatter Free1','Test Chatter Free2','Test Chatter Free3','Test Chatter Free4','Test Chatter Free5','Test Chatter Free6','Test Chatter Free7','Test Chatter Free8','Test Chatter Free9','Test Chatter Free10'};
public static List<UserDetail> getUserPermissionDetails()
Map<Id, User> userMap = new Map<Id, User>([SELECT Id
FROM User
WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
//System.debug(usermap);
Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
for(PermissionSetAssignment psa : [SELECT AssigneeId, PermissionSet.label
FROM PermissionSetAssignment
WHERE AssigneeId = : userMap.keySet()
AND (PermissionSet.label IN :ps1_ps10NameList
OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
ORDER BY AssigneeId, PermissionSet.label])
{
List<String> tempList = new List<String>();
if(permissionSetMap.containsKey(psa.AssigneeId))
tempList = permissionSetMap.get(psa.AssigneeId);
tempList.add(psa.PermissionSet.label);
permissionSetMap.put(psa.AssigneeId, tempList);
}
return evaluateUser(permissionSetMap);
}
private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){
Boolean additional;
List<UserDetail> userDetailList = new List<UserDetail>();
List<String> foundList = new List<String>();
for(Id id : permissionSetMap.keySet())
{
UserDetail ud = new UserDetail();
additional = false;
/*system.debug(permissionSetMap.get(id));*/
foundList.clear();
for(String str : permissionSetMap.get(id)){
if(!ps1_ps10NameList.contains(str)){
additional = true;
}else{
foundList.add(str);
}
/*system.debug(userDetailList);*/
}
ud.Id = id;
ud.permissionSetList = permissionSetMap.get(id);
if(additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change And Additional';
else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
ud.status = 'Missing And Additional';
else if(!additional && ps1_ps10NameList.size() != foundList.size())
ud.status = 'Missing';
else if(!additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change';
userDetailList.add(ud);
}
System.debug(JSON.serializePretty(userDetailList));
return userDetailList;
}
public class UserDetail {
public Id id;
public List<String> permissionSetList;
public String status;
}
public static void createcsv(){
List<UserDetail> theListReturnedFromMethod2 =getUserPermissionDetails();
String req = json.serialize(theListReturnedFromMethod2);
Blob csvBlob = blob.valueOf(req);
String csvname='Persona Report'+'.xls';
Document doc= new document();
doc.name=csvname;
doc.folderId=[Select Id, Name from Folder where Name='Persona'].Id;
doc.body=csvBlob;
doc.description='Persona';
insert doc;
}
}
- KRITI LAHA 8
- March 16, 2023
- Like
- 0
generate csv file using apex
I have below code. I need to generate a csv file to show to results of 'userdetaillist'.
public class UserService {
private static String profileName = 'Chatter Free User';
private static String ps7Name = 'Test Chatter Free7';
Public static List<UserDetail> userDetailList = new List<UserDetail>();
private static List<String> ps1_ps10NameList = new List<String>{
'Test Chatter Free1','Test Chatter Free2','Test Chatter Free3','Test Chatter Free4','Test Chatter Free5','Test Chatter Free6','Test Chatter Free7','Test Chatter Free8','Test Chatter Free9','Test Chatter Free10'};
public static List<UserDetail> getUserPermissionDetails(){
Map<Id, User> userMap = new Map<Id, User>([SELECT Id
FROM User
WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
//System.debug(usermap);
Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
for(PermissionSetAssignment psa : [SELECT AssigneeId, PermissionSet.label
FROM PermissionSetAssignment
WHERE AssigneeId = : userMap.keySet()
AND (PermissionSet.label IN :ps1_ps10NameList
OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
ORDER BY AssigneeId, PermissionSet.label])
{
List<String> tempList = new List<String>();
if(permissionSetMap.containsKey(psa.AssigneeId))
tempList = permissionSetMap.get(psa.AssigneeId);
tempList.add(psa.PermissionSet.label);
permissionSetMap.put(psa.AssigneeId, tempList);
}
return evaluateUser(permissionSetMap);
}
private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){
Boolean additional;
List<UserDetail> userDetailList = new List<UserDetail>();
List<String> foundList = new List<String>();
for(Id id : permissionSetMap.keySet())
{
UserDetail ud = new UserDetail();
additional = false;
/*system.debug(permissionSetMap.get(id));*/
foundList.clear();
for(String str : permissionSetMap.get(id)){
if(!ps1_ps10NameList.contains(str)){
additional = true;
}else{
foundList.add(str);
}
/*system.debug(userDetailList);*/
}
ud.Id = id;
ud.permissionSetList = permissionSetMap.get(id);
if(additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change And Additional';
else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
ud.status = 'Missing And Additional';
else if(!additional && ps1_ps10NameList.size() != foundList.size())
ud.status = 'Missing';
else if(!additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change';
userDetailList.add(ud);
}
System.debug(JSON.serializePretty(userDetailList));
return userDetailList;
}
public class UserDetail {
public Id id;
public List<String> permissionSetList;
public String status;
}
}
public class UserService {
private static String profileName = 'Chatter Free User';
private static String ps7Name = 'Test Chatter Free7';
Public static List<UserDetail> userDetailList = new List<UserDetail>();
private static List<String> ps1_ps10NameList = new List<String>{
'Test Chatter Free1','Test Chatter Free2','Test Chatter Free3','Test Chatter Free4','Test Chatter Free5','Test Chatter Free6','Test Chatter Free7','Test Chatter Free8','Test Chatter Free9','Test Chatter Free10'};
public static List<UserDetail> getUserPermissionDetails(){
Map<Id, User> userMap = new Map<Id, User>([SELECT Id
FROM User
WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
//System.debug(usermap);
Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
for(PermissionSetAssignment psa : [SELECT AssigneeId, PermissionSet.label
FROM PermissionSetAssignment
WHERE AssigneeId = : userMap.keySet()
AND (PermissionSet.label IN :ps1_ps10NameList
OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
ORDER BY AssigneeId, PermissionSet.label])
{
List<String> tempList = new List<String>();
if(permissionSetMap.containsKey(psa.AssigneeId))
tempList = permissionSetMap.get(psa.AssigneeId);
tempList.add(psa.PermissionSet.label);
permissionSetMap.put(psa.AssigneeId, tempList);
}
return evaluateUser(permissionSetMap);
}
private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){
Boolean additional;
List<UserDetail> userDetailList = new List<UserDetail>();
List<String> foundList = new List<String>();
for(Id id : permissionSetMap.keySet())
{
UserDetail ud = new UserDetail();
additional = false;
/*system.debug(permissionSetMap.get(id));*/
foundList.clear();
for(String str : permissionSetMap.get(id)){
if(!ps1_ps10NameList.contains(str)){
additional = true;
}else{
foundList.add(str);
}
/*system.debug(userDetailList);*/
}
ud.Id = id;
ud.permissionSetList = permissionSetMap.get(id);
if(additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change And Additional';
else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
ud.status = 'Missing And Additional';
else if(!additional && ps1_ps10NameList.size() != foundList.size())
ud.status = 'Missing';
else if(!additional && ps1_ps10NameList.size() == foundList.size())
ud.status = 'No Change';
userDetailList.add(ud);
}
System.debug(JSON.serializePretty(userDetailList));
return userDetailList;
}
public class UserDetail {
public Id id;
public List<String> permissionSetList;
public String status;
}
}
- KRITI LAHA 8
- March 08, 2023
- Like
- 0