I am trying to add a trigger to route emails. The criteria are, if a case is opened from email-to-case and remains open while there are email messages being sent between representatives and customers the emails will attach to the open case. If the case is closed, any emails pertaining to that case will open a new case and while that case is open any correspondance will remain on that case.
My logic is working between messages being filtered between the first original open case. When that case is closed and a customer replies back it opens a new case successfully. I am running into an issue where a customer replies back to an email to the new open case that is created.
I think this is an email token issue. The email see's the closed case of the original case and creates a new case because the original is closed.
trigger EmailToCase on EmailMessage (before insert) {
List<EmailMessage> comments = new List<EmailMessage>();
for (EmailMessage message : trigger.new) {
Id caseId = message.ParentId;
//find the case in the system
String query = 'SELECT ' + Utilities.GetAllSelects('Case') + ' FROM CASE WHERE Id = :caseId';
List<Case> cases = System.Database.query(query);
//if this is an existing case it will see if it is open/closed
if(cases.size() > 0){
Case emailToCase = cases.get(0);
//if this case is closed it will open a new case
if(emailToCase.Status == 'Closed'){
emailToCase.Status = 'New';
sObject closedCase = emailToCase;
Sobject newCase = closedCase.clone(false, true);
insert newCase;
//setting email to open/new case
message.ParentId = newCase.id;
message.Subject = '';
}
}
}
}