You should leverage Case Team functionality.
Basically, whenever Case ownership changes you should add the user to a case team as member and provide read/write access to that user.
Here is the logic:
- Define case team role.
- If previous case owner ownerId and new OwnerId are not same then add the user in the team. Also, put a check that, previous owner is a user and not a queue.
- Also verify that user is not previously exist as case team member of that case.
Refer this below code and use this in after update
trigger.
public void addCaseTeamMembersToCase(List<Case> lstNewCases, Map<Id,Case> mapOldCases)
{
for(Case objCase:lstNewCases)
{
String oldOwnerId = mapOldCases.get(objCase.Id).ownerId;
String newOwnerid = objCase.ownerId;
if(!newOwnerid.equalsIgnoreCase(mapOldCases.get(objCase.Id).ownerId)
&& oldOwnerId.subString(0,3) == '005')
{
//verify if the oldOwnerId ever exists as Case Team members
List<CaseTeamMember> lstCaseTeamMember = [SELECT MemberId FROM CaseTeamMember
WHERE ParentId =: objCase.Id
AND MemberId =: oldOwnerId];
if(lstCaseTeamMember.size() == 0)
{
mapMembersToAdd.put(objCase.Id,
new CaseTeamMember(
ParentId = objCase.Id,
MemberId = oldOwnerId
)
);
}
}
}
if (!mapMembersToAdd.isEmpty())
{
objCaseTeamRole = [SELECT Id
FROM CaseTeamRole
WHERE Name = '<my team role>' LIMIT 1];
for (CaseTeamMember objCaseTeamMember : mapMembersToAdd.values())
{
objCaseTeamMember.TeamRoleId = objCaseTeamRole.Id;
}
if (!mapMembersToAdd.isEmpty())
{
insert mapMembersToAdd.values();
}
}
}