CSV Reader in LWC – Salesforce

This article will full fill following requirements 

  1. Upload and Read CSV in LWC – Salesforce
  2. Provide access (assigning permission set and public group) to multiple users.
  3. Update user fields .
  4. Download Sample CSV Template.
  5. Upload CSV template with users data.
  6. Error handling while uploading template.
  7. Show proper response status (Success/Fail) on Page.
  8. Sending Email to Users after modification and Permission assignment.

Please follow below Steps for above requirement Implementation:

1. Create Two Permission set AD Manager and AD Senior Employee as shown in below screenshot.

2. Create, Setup and Verify Org Wide Email Id as shown in below Screenshot. Here you please setup your valid email address so that you can easily verify it.

3. Create below additional fields into User Object

  • Sales_Code__c – Text(255)
  • AD_Transfer_Codes__c – Text(255)
  • SRS_Account_Number__c – Text(255)
  • Sales_Rep_ID__c – Text(255)

4. Email Deliverability should be as below (Access Level = All email)

5. Create Email template AD Grant Access as shown below

6. Crete Apex Class AD_UAMInfo and copy paste below code
--------------------------------------------------------

public class AD_UAMInfo {
@AuraEnabled public string Username{get;set;}
@AuraEnabled public string Email{get;set;}
@AuraEnabled public string SRS{get;set;}
@AuraEnabled public string RepId{get;set;}
@AuraEnabled public string Permissionset{get;set;}
@AuraEnabled public string Publicgroup{get;set;}
@AuraEnabled public string Status{get;set;}
@AuraEnabled public string Comments{get;set;}
}
7. Create Apex Class AD_UAMController and copy paste below code
---------------------------------------------------------------
public class AD_UAMController {
public static  Map<String,String> mapEmailNameOfUser=new Map<String,String>();
public static String DocumentId;
@AuraEnabled
    public static list<AD_UAMInfo> readCSVFile(Id idContentDocument){
        DocumentId = idContentDocument;         
        list<AD_UAMInfo> lstUAMInfo = new list<AD_UAMInfo>();
        if(idContentDocument != null) {            
            // getting File Data based on document id 
            ContentVersion objVersion = [SELECT Id, VersionData FROM ContentVersion WHERE ContentDocumentId =:idContentDocument];
            // split the file data
            list<String> lstCSVLines = objVersion.VersionData.toString().split('\n');
            system.debug('====='+objVersion.VersionData.toString().split('\n'));
            List<String> Emails=new List<String>();
            for(Integer i = 1; i < lstCSVLines.size(); i++){
                AD_UAMInfo objUAMInfo = new AD_UAMInfo();
                list<String> csvRowData = lstCSVLines[i].split(',');
                System.debug('csvRowData====> '+csvRowData);    
                Emails.add(csvRowData[0]);
                objUAMInfo.Email = csvRowData[0]; // accName
                objUAMInfo.SRS = csvRowData[1];
                objUAMInfo.RepId = csvRowData[2];
                objUAMInfo.Permissionset = csvRowData[3];
                objUAMInfo.Publicgroup = csvRowData[4];
                objUAMInfo.Status = 'Success';
                objUAMInfo.Comments = 'Grant Successfully';
                lstUAMInfo.add(objUAMInfo);
            }
            
            try{    
                if(!lstUAMInfo.isEmpty()) {                   
                    Map<String,User> mapofNameUser= new Map<String,user>();
                    mapofNameUser= getUsers(Emails);                   
                    List<User> lstUserToUpdate= new List<User>();
                    
                    Map<String,String> mapOfNameIdPermissionSet= new Map<String,String>();
                    mapOfNameIdPermissionSet=GetPermissionSetNameIdMap();
                    List<PermissionSetAssignment> lstPerSetAssign=new List<PermissionSetAssignment>();
                    
                    Map<String,String> mapOfNameIdPublicGroup= new Map<String,String>();
                    mapOfNameIdPublicGroup=GetPublicGroupNameIdMap();
                    List<GroupMember> lstPubGrpMem=new List<GroupMember>();
                    
                    Map<String, String> mapOfAssigneeIdPermissionSetId = new Map<String,String>();
                    mapOfAssigneeIdPermissionSetId = GetUserPermissionSetId(Emails);
                    
                    for(AD_UAMInfo objUsr : lstUAMInfo )
                    {
                        User objuser=mapofNameUser.get(objUsr.Email);
                        objuser.SRS_Account_Number__c = objUsr.SRS;
                        objuser.Sales_Rep_ID__c = objUsr.RepId;
                        lstUserToUpdate.add(objuser);
                        if(mapOfNameIdPermissionSet.get(objUsr.Permissionset) != null)
                        {
                            PermissionSetAssignment objPer=new PermissionSetAssignment();
                            objPer.AssigneeId= mapofNameUser.get(objUsr.Email).Id;
                            objPer.PermissionSetId = mapOfNameIdPermissionSet.get(objUsr.Permissionset);
                            if(mapOfAssigneeIdPermissionSetId.get(objPer.AssigneeId) != objPer.PermissionSetId )
                            lstPerSetAssign.add(objPer);
                        }
                        
                        if(mapOfNameIdPublicGroup.get(objUsr.Publicgroup) != null)
                        {
                            GroupMember objGrpMem=new GroupMember();
                            objGrpMem.UserOrGroupId= mapofNameUser.get(objUsr.Email).Id;
                            objGrpMem.GroupId = mapOfNameIdPublicGroup.get(objUsr.Publicgroup);
                            lstPubGrpMem.add(objGrpMem);
                        }                       
                        
                    }
                    if(lstUserToUpdate.size()>0)
                        UpdateUsers(lstUserToUpdate);
                    if(lstPerSetAssign.size()>0)
                        AssignPermissionSet(lstPerSetAssign);
                    if(lstPubGrpMem.size()>0)
                        AssigPublicGroup(lstPubGrpMem);
                    deleteTemplate(DocumentId);
                    
                }
            }
            catch (Exception ex) {
                throw new AuraHandledException(ex.getMessage());
            } 
        }        
        return lstUAMInfo;    
    }
@AuraEnabled(Cacheable=true)
    public static String getTemplateDownloadLink(){
        try {
            //TODO this should ideally be stored in Custom Settings
            String contentDocumentId = System.Label.CSVTemplateId;
            
            //Query the ContentDistribution object to retrieve the Downloadable url
            List<ContentDistribution> contentDistributions = [
                SELECT Id, ContentDownloadUrl, DistributionPublicUrl
                FROM ContentDistribution
                WHERE ContentDocumentId =: contentDocumentId
                LIMIT 1
            ];
            
            if(!contentDistributions.isEmpty() && String.isNotBlank(contentDistributions[0].ContentDownloadUrl)){
                return contentDistributions[0].ContentDownloadUrl;
            }
        } catch (Exception e) {
            System.debug('Some excellent error messaging');
        }
        
        return null;
    }
     public static Map<String,User> getUsers(List<String> Emails) {
        system.debug('===Emails==='+Emails);
        Set<String> emailSet=new Set<String>();
        for(String emailStr : Emails)
        {
            emailSet.add('%'+emailStr+'%');
        }
        Map<String,User> mapuserNameUser= new Map<String,User>();
        for(User usr: [Select Id,Name, Username, Email, SRS_Account_Number__c, Sales_Rep_ID__c, Sales_Code__c, 
                       FederationIdentifier, AD_Transfer_Codes__c, 
                       Country, ProfileId, Profile.Name, Region__c  
                       from User where IsActive = true and username like : emailSet])
        { 
            mapuserNameUser.put(usr.Email, usr);
            mapEmailNameOfUser.put(usr.Email,usr.Name);
        }
        system.debug('===mapuserNameUser==='+mapuserNameUser);
        return mapuserNameUser;
    }
     public static List<PermissionSetAssignment> AssignPermissionSet(List<PermissionSetAssignment> lstPerSetAssignment) {
        
        try{ Database.insert(lstPerSetAssignment);sendEmailNotification(mapEmailNameOfUser);}catch(exception ex){}
        return lstPerSetAssignment;
        
    }
    public static List<GroupMember> AssigPublicGroup(List<GroupMember> lstGrpMember) {
        try{ Database.insert(lstGrpMember);}catch(exception ex){}
        return lstGrpMember;
    }
    public static List<User> RevokePermissionSet(Map<String,String> MapUserPermissionSet) {
        List<User> lstResUsers= new List<User>();
        return lstResUsers;
    }
    public static List<User> RevokePublicGroup(Map<String,String> MapUserPublicGroup) {
        List<User> lstResUsers= new List<User>();
        return lstResUsers;
    }
    public static Map<String,String> GetPermissionSetNameIdMap(){
        Map<String,String> mapPermissionSetNameId = new Map<String, String>();
        //Select Id, Assignee.Name, AssigneeId, PermissionSet.Name, PermissionSetId from PermissionSetAssignment where PermissionSet.Name like 'SH_FIM%'
        for( PermissionSet ps :[Select Id, Name, Label from PermissionSet where Name like 'AD_%']){
            mapPermissionSetNameId.put(ps.Name,ps.Id);
        }
        return mapPermissionSetNameId;
    }
    public static Map<String,String> GetPublicGroupNameIdMap(){
        Map<String,String> mapPublicGroupNameId = new Map<String, String>();
        for(Group grp :[Select Id, Name from Group  where Name like 'AD_%'])
        {
            mapPublicGroupNameId.put(grp.Name,grp.Id);
        }
        return mapPublicGroupNameId;
    }
    public static Map<String,String> GetUserPermissionSetId(List<String> Emails) {
        Map<String,String> mapOfUserIdPermissionSetId=new Map<String,String>();
        for( PermissionSetAssignment psa :[Select AssigneeId, PermissionSetId 
                                           from PermissionSetAssignment where Assignee.Email  in: Emails ])
        {
            mapOfUserIdPermissionSetId.put(psa.AssigneeId, psa.PermissionSetId);
        }
        return mapOfUserIdPermissionSetId;
    }
     @future
    public static void deleteTemplate(String DocumentId)
    {
        List<ContentDocument> lstContent=new List<ContentDocument>();
        for(ContentVersion conver: [SELECT Id,ContentDocumentId FROM ContentVersion where ContentDocumentId =:DocumentId])
        {
            
            lstContent.add(new ContentDocument(
                Id = conver.ContentDocumentId
            ));
        }
        delete lstContent;
    }
     public static List<User> UpdateUsers(List<User> lstUser) {
        List<User> lstResUsers= new List<User>();
        update lstUser;
        return lstResUsers;
    }
     @future
    public static void sendEmailNotification(Map<String,String> mapEmailNameOfUser)
    {
        List<Messaging.SingleEmailMessage> emailNotifications = new List<Messaging.SingleEmailMessage>();
        String DeveloperName= 'AD_Grant_Access';
      
        EmailTemplate eTemplate=[Select Id, DeveloperName, body, subject, htmlValue from EmailTemplate 
                                 where developername =: DeveloperName WITH SECURITY_ENFORCED limit 1];
        
        //Get orgwide email id for sender email
        Id orgwdId= getOrgWideEmailId();
        if(eTemplate != null && String.isNotBlank(eTemplate.HtmlValue) && orgwdId != null)
        {  
            for(String emailId : mapEmailNameOfUser.keySet())
            {   
                Messaging.SingleEmailMessage email= new Messaging.SingleEmailMessage();
                //system.debug('==='+emailId);
                email.setToAddresses(new String[]{emailId});
                email.setHtmlBody(eTemplate.HtmlValue);
                email.setHtmlBody(email.getHtmlBody().replace('User_name',String.valueOf(mapEmailNameOfUser.get(emailId))));
                email.setOrgWideEmailAddressId(orgwdId);
                emailNotifications.add(email);
            }
            if(!emailNotifications.isEmpty())
            {
                //Send bulk emails
                Messaging.sendEmail(emailNotifications);
            }
        }
        
    }
     //This Method will return Org Wide Email id
    public static Id getOrgWideEmailId()
    {
        OrgWideEmailAddress[] owea =[Select Id from OrgWideEmailAddress where Address =: '[email protected]' WITH SECURITY_ENFORCED];
        if(owea.size()>0)
        {
            return owea.get(0).Id;
        }
        return null;
    }

}