Created
December 23, 2017 17:25
-
-
Save dsilvadeepal/7096154ebf85af19c636306339b7cfa9 to your computer and use it in GitHub Desktop.
Move new contacts to the matching account based on domain. Contact email domain should match the website domain. Ex. john@fastco.com matches only to an account with website www.fastco.com Should also match with the following websites: http://www.fastco.com https://www.fastco.com fastco.com fastco.com.au fastco.com.ca
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Move new contacts to the matching account based on domain. Contact email domain should match the website domain. | |
Ex. john@fastco.com matches only to an account with website www.fastco.com | |
Should also match with the following websites: http://www.fastco.com https://www.fastco.com | |
fastco.com fastco.com.au fastco.com.ca | |
*/ | |
trigger AccountMatcherChallenge on Contact (before insert, before update) { | |
for(Contact con : Trigger.New) { | |
if(con.Email != null) { | |
//Construct various website patterns for the email domain | |
String domain = con.Email.split('@').get(1); | |
String website = 'www.' + domain; | |
String httpWebsite = 'http://www.' + domain; | |
String httpsWebsite = 'https://www.' + domain; | |
String internationalDomain = domain + '.%'; | |
List<Account> matchingAccounts = [SELECT Id | |
FROM Account | |
WHERE Website = :domain | |
OR Website = :website | |
OR Website = :httpWebsite | |
OR Website = :httpsWebsite | |
OR Website LIKE :internationalDomain]; | |
System.debug('matchingAccounts ' + matchingAccounts.size()); | |
//If only one matching Account | |
if(matchingAccounts.size() == 1) { | |
con.AccountId = matchingAccounts.get(0).Id; | |
} | |
} | |
} | |
} | |
//Test Class | |
@isTest | |
private class AccountMatcherChallengeTest { | |
@isTest static void noAccountMatches() { | |
Contact myCon = new Contact(); | |
myCon.FirstName = 'Jim'; | |
myCon.LastName = 'Tran'; | |
myCon.Email = 'jtran@waterfordhotels.com'; | |
insert myCon; | |
Contact updatedCon = [SELECT AccountId | |
FROM Contact | |
WHERE Id = :myCon.Id]; | |
System.assertEquals(null, updatedCon.AccountId); | |
} | |
@isTest static void accountMatchFound() { | |
String domain = 'waterfordhotels.com'; | |
Account acc = new Account(); | |
acc.Name = 'Waterford Hotels'; | |
acc.Website = domain + '.ca'; | |
insert acc; | |
Contact myCon = new Contact(); | |
myCon.FirstName = 'Matt'; | |
myCon.LastName = 'Tran'; | |
myCon.Email = 'mtran@' + domain; | |
insert myCon; | |
Contact updatedCon = [SELECT AccountId | |
FROM Contact | |
WHERE Id = :myCon.Id]; | |
System.assertEquals(acc.Id, updatedCon.AccountId); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment