I'm writing a Windows service that will poll my IMAP4 inbox for emails from clients and create new Cases in Salesforce based on them.
Sometimes emails come in with a Case reference code in the subject. Ex: "[ ref:00FFwxyz.500FFJJS5:ref ]". I'd like to assign such emails to the existing Case identified by the code rather than create a new one.
My questions is: Is there a definitive formula for extracting a unique Case identifier from the ref code? I've seen a few formulas that do the reverse, but they all look like guesswork: Blog post on KnowThyCloud.com, Force.com Discussion Board thread.
Found a decent enough solution. I was wrong in calling the post on KnowThyCloud.com guesswork. In the right context it works fine.
My solution is to create a new custom field on the Case record of type "Formula (Text)". The field's value is the formula mentioned in the blog post:
TRIM(" [ ref:" + LEFT( $Organization.Id, 4) + RIGHT($Organization.Id, 4) +"."+ LEFT( Id, 4) + SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(Id, RIGHT( Id, 4), ""), LEFT( Id, 4), ""), "0", "") + RIGHT( Id, 4) + ":ref ] ")
Now the value of the custom field for each Case record is the same as the reference Id in emails and I can simply query for it with the Salesforce API.
I implemented urig's solution and it works well.
Here is an Apex code solution that locates the Case without this field.
String emailSubject = 'FW: Re: RE: order 36000862A Case: 00028936 [ ref:00D7JFzw.5007Ju10k:ref ]';
String caseNumber = null;
/*
Extract the text after ref: and before the period. Could use this to locate the organization.
In the text after the period and before the :ref split into a 4 digit number and remaining number.
Insert 0's to get ref id.
*/
String patternString = '.*ref:(.{8}).(.{4})(.+):ref.*';
Pattern thePattern = Pattern.compile(patternString);
Matcher matcher = thePattern.matcher(emailSubject);
if (matcher.matches()) {
String caseId = matcher.group(2) + '000000' + matcher.group(3);
Case[] matchingCases = [Select CaseNumber from Case where Id = :caseId];
if(matchingCases.size() == 1) {
Case theCase = matchingCases[0];
caseNumber = theCase.CaseNumber;
}
}
I have modified Jan's code snippet above in order to support the new reference string containing underrscores (e.g. _00DC0PxQg._500C0KoOZS
).
String patternString = '.*ref:(.{11}).(.{5})(.+):ref.*';
Pattern thePattern = Pattern.compile(patternString);
Matcher matcher = thePattern.matcher(emailSubject);
if (matcher.matches()) {
String caseId = matcher.group(2) + '00000' + matcher.group(3);
system.debug('### '+caseId);
Case[] matchingCases = [Select CaseNumber from Case where Id = :caseId];
if(matchingCases.size() == 1) {
Case theCase = matchingCases[0];
caseNumber = theCase.CaseNumber;
}
}