Skip to content

Instantly share code, notes, and snippets.

@dsilvadeepal
Last active December 23, 2017 16:56
Show Gist options
  • Save dsilvadeepal/521aea9dcdf6f27e76f6e7f415b7aa23 to your computer and use it in GitHub Desktop.
Save dsilvadeepal/521aea9dcdf6f27e76f6e7f415b7aa23 to your computer and use it in GitHub Desktop.
Moves new contacts to the matching account based on domain. Contact email domain should match the website domain.
/*
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
*/
trigger AccountMatcherHw on Contact (before insert) {
for (Contact con : Trigger.new) {
if(con.Email != null) {
//Create a website from the email domain
String domain = con.Email.split('@').get(1);
String website = 'www.' + domain;
System.debug('Matching' + con.FirstName + ' to website: ' + website);
List<Account> matchingAccounts = [SELECT Id
FROM Account
WHERE Website = :website];
//If only one match, move the contact
if(matchingAccounts.size() == 1){
con.AccountId = matchingAccounts.get(0).Id;
}
}
}
}
//Test class
@isTest
private class AccountMatcherHwTest {
@isTest static void noAccountMatch() {
Contact myCon = new Contact();
myCon.FirstName = 'Matt';
myCon.LastName = 'Tran';
myCon.Email = 'mtran@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 = 'www.'+ domain;
insert acc;
Contact myCon = new Contact();
myCon.FirstName = 'Matt';
myCon.LastName = 'Tran';
myCon.Email = 'mtran@waterfordhotels.com';
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