0% found this document useful (0 votes)
32 views42 pages

Apex Triggers

Apex triggers questions

Uploaded by

Md Muffasser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views42 pages

Apex Triggers

Apex triggers questions

Uploaded by

Md Muffasser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Completed

Sagar S: TASK 1 : Roll-up Contact level information to its respective Account

Configuration:
● In Contact Object - Create the two Record Type as enlisted below
○ Direct
○ Indirect
● In Account Object - Create the two Number Type fields as enlisted below
○ Direct Contacts
○ Indirect Contacts

Create a trigger to ensure the following functionality:


1. The Direct Contacts field in the Account Object should be always showing the Number
of Contacts under this Account that are of Record Type as Direct.
2. The Indirect Contacts field in the Account Object should be always showing the
Number of Contacts under this Account that are of Record Type as Indirect.

** Think of all the possible scenarios that we may need to handle.

Write a Unit test in Apex to ensure the above trigger covers all the scenarios
==============================HANDLER========================
/*
@MethodName : displayContactOnAccount
@param : List<Contact> lstContactNew.
@Description: displayContactOnAccount method will display No.of direct and indirect
contacts on Related Acoount.
*/
Private void displayContactOnAccount(List<Contact> lstContactNew){

//Iterate contact and store Account ids related to contacts.


Set<Id> setAccountIds = new Set<Id>();

for(Contact objContact : lstContactNew){


setAccountIds.add(objContact.AccountId);
}

integer directContact =0, indirectContact = 0;


//Fetch and iterate contacts related to setAccountIds.
for(Contact objContact : [SELECT Id, RecordType.Name from Contact WHERE AccountId
=: setAccountIds]){

//check record type and count.


if(objContact.RecordType.Name == 'Direct'){
directContact++;
}

else if(objContact.RecordType.Name == 'Indirect'){


indirectContact++;
}
}

//fetch account related to lstContactNew and Update the Indirect_Contacts__c and


Direct_Contacts__c on account.
List<Account> lstAccountToUpdate = new List<Account>();

for(Account objAccount : [SELECT Id FROM Account WHERE id =: setAccountIds]){

//Instance of Account.
Account objAccountUpdate = new Account(Id = objAccount.Id,
Indirect_Contacts__c = indirectContact,
Direct_Contacts__c = DirectContact);

lstAccountToUpdate.add(objAccountUpdate);
}
update lstAccountToUpdate;
}
===============TEST CLASS=======================================
/*
@MethodName : createContact
@param :-
@Description: createContact method will create the contact record.
*/
@isTest
static void createContact(){
//create Account record.
Account objAccount = new Account(Name = 'Muffu');
insert objAccount;

//Fetching Record types of contact object And adding to mapContacrtRecordTypes.


Map<String,Id> mapContacrtRecordTypes = new Map<String,Id>();
for(RecordType objRecordType : [SELECT Id,Name
FROM RecordType
WHERE sObjectType = 'Contact']){

mapContacrtRecordTypes.put(objRecordType.Name, objRecordType.Id);
}

//create Contact records related to objAccount.


List<Contact> lstContact = new List<Contact>();
for(Integer i = 0 ; i < 5; i++){

Contact objContact = new Contact(AccountId = objAccount.id,


LastName = 'muffasser',
RecordTypeId = mapContacrtRecordTypes.get('Direct'));
lstContact.add(objContact);

Contact objContact1 = new Contact(AccountId = objAccount.id,


LastName = 'Md muffasser',
RecordTypeId = mapContacrtRecordTypes.get('Indirect'));
lstContact.add(objContact1);
}
insert lstContact;

//Fetching Account related to lstContact records And doing system.assertEquals().


Account objAccountToCheck = [SELECT Id, Direct_Contacts__c, Indirect_Contacts__c
FROM Account WHERE id = :objAccount.Id];

System.assertEquals(5, objAccountToCheck.Direct_Contacts__c);
System.assertEquals(5, objAccountToCheck.Indirect_Contacts__c);

completed
Rushikesh: TASK 2 : Roll-up Contact level information to its respective Account

Configuration:
● In Account Object
○ Create a Text Area(Long) type field named “All Mailing States”

Create a trigger to ensure the following functionality:


● The Mailing States field in the Account Object should be always showing all the unique
Mailing State values within all the contacts under it in a comma separated manner.
Example : AL, NE, AK, NV, AZ

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios
============================handler==================================
//Iterate contact and store Account ids related to contacts and Store mailing States in
set.
Set<Id> setAccountIds = new Set<Id>();
Set<String> setAccountStr = new Set<String>();

for(Contact objContact : lstContactNew){

if(objContact.AccountId != Null)
setAccountIds.add(objContact.AccountId);

if((objContact.MailingState != Null) && (strTriggerEvent == 'Insert' ||


strTriggerEvent == 'Update' &&
mapContactOld.get(objContact.Id).MailingState == objContact.MailingState))

setAccountStr.add(objContact.MailingState);
}

//Fetch and iterate contacts related to setAccountIds.


for(Contact objContact : [SELECT Id, MailingState from Contact WHERE AccountId
=: setAccountIds]){

if(objContact.MailingState != Null)
setAccountStr.add(objContact.MailingState);
}

//fetch account related to lstContactNew and Update the All_Mailing_States__c on


account.
List<Account> lstAccountToUpdate = new List<Account>();

for(Account objAccount : [SELECT Id, All_Mailing_States__c FROM Account


WHERE id =: setAccountIds]){

//Instance of Account.
Account objAccountUpdate = new Account(Id = objAccount.Id,
All_Mailing_States__c =String.join(new
List<String>(setAccountStr), ', '));

lstAccountToUpdate.add(objAccountUpdate);
}
update lstAccountToUpdate;
}
================================test=====================================
static void createUser(){
//create Contact records related to objAccount.
List<Contact> lstContact = new List<Contact>();
Contact objContact = new Contact(LastName = 'muffasser12',
Create_User__c = true,
MailingState = 'ab',
Email ='[email protected]');

lstContact.add(objContact);
Contact objContact1 = new Contact(LastName = 'muffasser34',
Create_User__c = true,
MailingState = 'bc',
Email ='[email protected]');
lstContact.add(objContact1);

Contact objContact2 = new Contact(LastName = 'muffasser56',


MailingState = 'cd',
Email ='[email protected]');
lstContact.add(objContact2);
insert lstContact;

//storeing contact ids.


set<id> setid = new set<id>{objContact1.id};

test.startTest();
Sl_FutureMethodToCreateUser.futureMethodToInsertUser(setid);
test.stopTest();

//Fetching Account related to lstContact records And doing system.assertEquals().


User objContactToCheckUser = [SELECT Id, LastName FROM User WHERE
Contact_ID__c =: objContact1.Id Limit 1];
System.assertEquals(objContact1.LastName, objContactToCheckUser.LastName);

Completed
Ratan: TASK 3 : Sending email and creation of Task on opportunity status change.

Create a trigger to ensure the following functionality:


● Whenever the stage field on opportunity is set as “Closed won”, a task needs to be
created related to opportunity.
● Task object field mapping
○ Subject - 'Opportunity is closed and won'
○ Type - Email
○ Status - Completed
● Send an email message to the owner of the Opportunity. .

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios
================================HANDLER======================

insert lstTask;

List<Messaging.SingleEmailMessage> lstMails = new


List<Messaging.SingleEmailMessage>();

//fetch Owners email id of Opportunity and sending email to them.


for(Opportunity objOpportunityOwner : [SELECT Owner.Email, Owner.Name FROM
Opportunity WHERE Id in: setOpportunityIds]){

if(lstTask.size() > 0){

String[] strEmailId = new String[]{objOpportunityOwner.Owner.Email};


Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setSaveAsActivity(False);
email.setSenderDisplayName('Muffasser');
email.setSubject('Opportunity Status is Changed ');
email.setHtmlBody('Hi....'+objOpportunityOwner.Owner.Name+' Task is created
for Opportunity');
email.setToaddresses(strEmailId);
lstMails.add(email);
}
}

if(lstMails.size() > 0){

//Sending email to Owner.


Messaging.sendEmail(lstMails);
}
}
================================tEST======================
/*
@MethodName : createOpportunity
@param :-
@Description: createOpportunity method will create the Opportunity record.
*/
@isTest
static void createOpportunity(){
list<Opportunity> lstOpportunity = new list<Opportunity>();
//create opportunity records.
for(Integer i=1; i<= 10; i++){
Opportunity obj = new Opportunity(Name = 'Muffu'+i,
StageName = 'Closed Won',
CloseDate = Date.newInstance(2022, 12, 31));
lstOpportunity.add(obj);
}

insert lstOpportunity;

//check task is created or not.


Opportunity objOpportunityToCheck = [SELECT Id, (SELECT Id From Tasks) From
Opportunity WHERE ID =: lstOpportunity.get(5).Id];
System.assertEquals(1, objOpportunityToCheck.Tasks.Size());

//Limits.getEmailInvocations() will given number of mails send.


//system.assertEquals(1, Limits.getEmailInvocations());
}

/*
@MethodName : UpdateOpportunity
@param :-
@Description: UpdateOpportunity method will update the Opportunity record.
*/
@isTest
static void UpdateOpportunity(){
list<Opportunity> lstOpportunity = new list<Opportunity>();

//create opportunity records.


Opportunity objOpportunity = new Opportunity(Name = 'Muffu',
StageName = 'Qualification',
CloseDate = Date.newInstance(2022, 12, 31));

lstOpportunity.add(objOpportunity);

Opportunity objOpportunity1 = new Opportunity(Name = 'Muffu',


StageName = 'Prospecting',
CloseDate = Date.newInstance(2022, 12, 31));
lstOpportunity.add(objOpportunity1);

Opportunity objOpportunity2 = new Opportunity(Name = 'Muffu',


StageName = 'Needs Analysis',
CloseDate = Date.newInstance(2022, 12, 31));

lstOpportunity.add(objOpportunity2);

insert lstOpportunity;

//update status
objOpportunity.StageName = 'Closed Won';
update objOpportunity;

//check task is created or not.


Opportunity objOpportunityToCheck = [SELECT Id, (SELECT Id From Tasks) From
Opportunity WHERE ID =: objOpportunity.Id];
System.assertEquals(1, objOpportunityToCheck.Tasks.Size());

//Limits.getEmailInvocations() will given number of mails send.


//system.assertEquals(1, Limits.getEmailInvocations());
}

References:

Opportunity Stages
- https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/
object_reference/sforce_api_objects_opportunitystage.htm
- https://garysmithpartnership.com/opportunity-stages/#:~:text=Opportunity%20stages
%20describe%20the%20high,visibility%20through%20reports%20and%20dashboards.
Task Data Model and SOAP API
- https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/
sforce_api_erd_activities.htm
- https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/
sforce_api_objects_task.htm
Sending Email Messages:
- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/
apex_forcecom_email_outbound.htm
- https://www.sfdc99.com/2014/03/01/sending-emails-using-apex/

Completed
Vineet: TASK 4 : As a India Team I need to receive any automated notifications as and
when the Opportunity Probability% and Stages are moving upwards/downwards as soon
as the updates are reflected in Salesforce, so that I can keep tabs on the pipeline
forecast.

DESIGN CONSIDERATIONS
● Create a Custom Field of type Picklist(single select) in Opportunity object called "Group"
Values in this picklist would be as follows:
1. Professional Services
2. Managed Services

● Create a Trigger in the Opportunity object to notify via email to the relevant emails as
mentioned below in the conditions, that reflects the changes of Probability and Stage
fields from its previous values.

ACCEPTANCE CRITERIA

NOTIFICATION 1:

Condition:
● Group = Professional Services AND
● (Opportunity Probability has changed OR Opportunity Stage has changed)

Action:
● Send an Email to the [email protected] email group
● Notifying the changes of Probability and Stage fields capturing Earlier Values Vs
New Values.

NOTIFICATION 2:

Condition:
● Opportunity Group = Managed Services AND
● (Opportunity Probability has changed OR Opportunity Stage has changed)

Action:
● Send Email to the [email protected] email group
● Notifying the changes of Probability and Stage fields capturing Earlier Values Vs
New Values.

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios
================================HANDLER======================
/*
@MethodName : notifyViaEmail
@param : List<Opportunity> lstOpportunityNew, Map<Id,Opportunity>
mapOpportunityOld.
@Description: notifyViaEmail method will notify Owner when probability is
changed or StageName is Close Won in Opportunity object.
*/
Private void notifyViaEmail(List<Opportunity> lstOpportunityNew,
Map<Id,Opportunity> mapOpportunityOld){

Set<Id> setOpportunityIds = new Set<Id>();


List<Messaging.SingleEmailMessage> lstMails = new
List<Messaging.SingleEmailMessage>();

//Iterate Opportunity .
for(Opportunity objOpportunityNew : lstOpportunityNew){

Opportunity objOpportunityOld = mapOpportunityOld.get(objOpportunityNew.Id);


String[] strEmailId = Null;

//check probability is changed or StageName is Close Won then store email id in


String[].
if(objOpportunityNew.Group__c == 'Professional Services' &&
(objOpportunityNew.StageName != objOpportunityOld.StageName ||
objOpportunityNew.Probability != objOpportunityOld.Probability)){

strEmailId = new String[]{'[email protected]'};


}

else if(objOpportunityNew.Group__c == 'Managed Services' &&


(objOpportunityNew.StageName != objOpportunityOld.StageName ||
objOpportunityNew.Probability != objOpportunityOld.Probability)){

strEmailId = new String[]{'[email protected]'};


}

//Sending email to owner.


Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setSaveAsActivity(False);
email.setSenderDisplayName('Muffasser');
email.setSubject('Opportunity Status is Changed ');
email.setHtmlBody('Hi..Muffu Task is created for Opportunity');
email.setToaddresses(strEmailId);
lstMails.add(email);
}

if(lstMails.size() > 0){

//Sending email to Owner.


Messaging.sendEmail(lstMails);
}
}
}
================================tEST======================
/*
@MethodName : notifyViaEmail
@param :-
@Description: notifyViaEmail method will update the Opportunity record.
*/
@isTest
static void notifyViaEmail(){
list<Opportunity> lstOpportunity = new list<Opportunity>();
//create opportunity records.
Opportunity objOpportunity = new Opportunity(Name = 'Muffu',
StageName = 'Qualification',
Group__c = 'Managed Services',
Probability = 48.8,
CloseDate = Date.newInstance(2022, 12, 31));
lstOpportunity.add(objOpportunity);

Opportunity objOpportunity1 = new Opportunity(Name = 'Muffu',


StageName = 'Prospecting',
Group__c = 'Managed Services',
Probability = 48.8,
CloseDate = Date.newInstance(2022, 12, 31));
lstOpportunity.add(objOpportunity1);

Opportunity objOpportunity2 = new Opportunity(Name = 'Muffu',


StageName = 'Needs Analysis',
Group__c = 'Professional Services',
CloseDate = Date.newInstance(2022, 12, 31));
lstOpportunity.add(objOpportunity2);

insert lstOpportunity;
//Fetching and update stageName & probability on Opportunity.
Opportunity objOpportunityToUpdate = [SELECT Id,StageName,Probability FROM
Opportunity WHERE id =: objOpportunity.Id];
objOpportunityToUpdate.StageName = 'Closed Won';
objOpportunityToUpdate.Probability =86.8;
update objOpportunityToUpdate;

//Limits.getEmailInvocations() will given number of mails send.


system.assertEquals(1, Limits.getEmailInvocations());
}

Completed
Govardhini: TASK 5 : Write a trigger to implement a logic so that at any given time there
should be only one Contact under an Account which is marked as Primary.

DESIGN CONSIDERATIONS:
● On Account we have one Text field called Primary Contact
● On Contact we have one checkbox field called Primary
● Using trigger implement a logic so that at any given time there should be only one
Contact under an Account which is marked as Primary,
● Example(Scenario):
○ Account Name --> Test Account
○ Related Contacts --> A, B, C, D
○ If Contact B is marked as Primary then all other Contact's Primary checkbox
should be set to false.
○ Now if I go update Contact C as Primary then Contact C will become primary and
all other Contact's Primary Contact should be set to false.
○ The trigger should also update Account's Primary Contact field with selected
Primary Contact Name.

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios
============================handler==============================
/*
@MethodName : updatePrimaryContactOnAccount
@param : List<Contact> lstContactNew, Map<Id,Contact> mapContactOld,
String strTriggerEvent.
@Description: updatePrimaryContactOnAccount method will Update Acoount
primary contact.
*/
Private void updatePrimaryContactOnAccount(List<Contact> lstContactNew,
Map<Id,Contact> mapContactOld, String strTriggerEvent){
//Fetching the AccountId
Set<Id> setAccountId = new Set<Id>();

//Declaring a List to Update


List<Account> lstAccountToUpdate = new List<Account>();

for(Contact objContact : lstContactNew){

Contact objOldContact = new Contact();


if(StrTriggerEvent == 'Update'){

//Getting prior Contact Values and Store.


if(mapContactOld.ContainsKey(objContact.Id))
objOldContact = mapContactOld.get(objContact.Id);
}

//Creating an Instance of Account And update the Account


if(objContact != Null){
if(objContact.AccountId != Null && objContact.Primary__c ){
setAccountId.add(objContact.AccountId);

if(strTriggerEvent == 'Insert' || (objOldContact.Primary__c !=


objContact.Primary__c && strTriggerEvent == 'Update')){
Account objAccount = new Account(Id = objContact.AccountId,
Primary_Contact_s__c = objContact.LastName);
lstAccountToUpdate.add(objAccount);
}
}
}
}
update lstAccountToUpdate;

//Remaining Contacts makeing primary Checkbox as false.


List<Contact> lstContactToUpdate = new List<Contact>();

for(Contact objContact : [Select Id,Primary__c,LastName From Contact Where


AccountId IN :setAccountId And ID NOT IN : lstContactNew ]){

if(objContact.Primary__c)
objContact.Primary__c = False;

lstContactToUpdate.add(objContact);
}
update lstContactToUpdate;
}
====================================test=========================
/*
@MethodName : primaryContact
@param :-
@Description: primaryContact method will create and Update the contact record.
*/
@isTest
static void primaryContact(){

//create Account record.


Account objAccount = new Account(Name = 'Muffu');
insert objAccount;

//create Contact records related to objAccount.


List<Contact> lstContact = new List<Contact>();
Contact objContact = new Contact(AccountId = objAccount.id,
LastName = 'muffasser',
Primary__c = true);
lstContact.add(objContact);

Contact objContact2 = new Contact(AccountId = objAccount.id,


LastName = 'muffasser',
Primary__c = false);
lstContact.add(objContact2);

Contact objContact1 = new Contact(AccountId = objAccount.id,


LastName = 'Md muffasser',
Primary__c = false);
lstContact.add(objContact1);
System.debug('objContact1========>'+objContact1);
insert lstContact;

//Fetching Account related to lstContact records And doing system.assertEquals().


Account objAccountToCheck = [SELECT Id, Primary_Contact_s__c FROM Account
WHERE id = :objAccount.Id];
System.assertEquals(objContact.LastName,
objAccountToCheck.Primary_Contact_s__c);

//update contact to primary


objContact1.Primary__c = true;
update objContact1;
System.debug('objContact1====rupdate====>'+objContact1);

//Fetching Account related to lstContact records And doing system.assertEquals().


Account objAccountAfterUpdate = [SELECT Id, Primary_Contact_s__c FROM
Account WHERE id = :objAccount.Id];
System.assertEquals(objContact1.LastName,
objAccountAfterUpdate.Primary_Contact_s__c);

Test class pending


Rajasekar: TASK 6 : Write a trigger to convert a Lead to an Account, Contact &
Opportunity.

DESIGN CONSIDERATIONS:
● Create a custom field of type Checkbox in Lead Object named “Convert Lead”
● Whenever the Convert Lead field is set to true
○ Convert this lead in context to
■ Account
■ Contact
■ Opportunity

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios
================================HANDLER======================
/*
@MethodName : convertLead
@param : List<Lead> lstLeadNew, Map<Id,Lead> mapLeadOld.
@Description: convertLead method called on is Before update of Lead Object.
*/
Private void convertLead(List<Lead> lstLeadNew, Map<Id,Lead> mapLeadOld, String
strTriggerEvent){

//Fetch lead status and converting the lead.


LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE
IsConverted=true LIMIT 1];

//Iterate lstLeadNew the store prior values in objLeadOld.


for(Lead objLeadNew : lstLeadNew){

Lead objLeadOld = new Lead();


if(strTriggerEvent == 'Update'){

objLeadOld = mapLeadOld.get(objLeadNew.Id);
}

//check trigger event and compare old and new values.


if(strTriggerEvent == 'Insert' || objLeadOld.Convert_Lead__c !=
objLeadNew.Convert_Lead__c){

//check status is 'Closed - Converted' then convert the lead.


if(objLeadNew.Convert_Lead__c){
if(objLeadNew.isConverted == false){
//Instance Database.LeadConvert.
Database.LeadConvert objLeadConvert = new Database.LeadConvert();
objLeadConvert.setLeadId(objLeadNew.Id);
objLeadConvert.setConvertedStatus(convertStatus.MasterLabel);

//Instance Database.LeadConvertResult.
Database.LeadConvertResult objLeadConvertResult =
Database.convertLead(objLeadConvert);
}
}
}
}
}
================================tEST======================
/*
@MethodName : convertLead
@param :-
@Description: convertLead method will create the Lead record.
*/
@ISTest
static void convertLead(){

List<Lead> lstlead = new List<Lead>();


for(Integer i=1 ; i <= 20 ; i++){

Lead objLead = new Lead(LastName = 'muffu'+i,


Company = 'Slv',
Convert_Lead__c = true);
lstlead.add(objLead);

Lead objLead1 = new Lead(LastName = 'muffu',


Company = 'Delux');

lstlead.add(objLead1);
}

insert lstlead;

//Fetching Account with name is company name of lead.


list<Account> lstCheckAccount = [SELECT Id, Name FROM Account WHERE Name
='Slv'];
System.assertEquals(20, lstCheckAccount.Size());

List<Lead> lstleadToUpdate = new List<Lead>();


for(Lead objLead : [SELECT Id, Name FROM Lead WHERE Company = 'Delux']){
Lead objLeadToUpdate = new Lead(Id = objLead.Id,
Company ='IBM',
Convert_Lead__c = true);

lstleadToUpdate.add(objLeadToUpdate);
}
update lstleadToUpdate;

//Fetching Account with name is company name of lead.


list<Opportunity> lstCheckOpprtunity1 = [SELECT Id, Name FROM Opportunity
WHERE Name ='muffu'];
System.debug('lstCheckAccount1====>'+lstCheckOpprtunity1);
//System.assertEquals(20, lstCheckOpprtunity1.Size());
}

References :

● https://trailhead.salesforce.com/en/content/learn/modules/
leads_opportunities_lightning_experience/create-and-convert-leads-lightning

● https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/
langCon_apex_dml_examples_convertlead.htm
Test class pending
Sagar P: TASK 7 : Write a trigger to create a Task whenever a Lead is getting converted.

DESIGN CONSIDERATIONS:
● Whenever the Lead is getting Converted
○ Create a Task
■ Subject - 'Please reach out to the Contact to understand next steps'
■ Type - Phone
■ Task Owner - Converted Account’s Owner
■ WhatID - Converted Account’s Id
■ WhoID - Converted Contact’s Id

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios
================================HANDLER======================
/*
@MethodName : createTask
@param : List<Lead> lstLeadNew, Map<Id,Lead> mapLeadOld.
@Description: createTask method called on is Before update of Lead Object.
*/
Private void createTask(List<Lead> lstLeadNew, Map<Id,Lead> mapLeadOld){

//to sotre converted account ids.


Set<Id> setAccountIds = new Set<Id>();

//to sotre LeadConvertResult in database.


list<Database.LeadConvertResult> lstleadsConvertResult = new
list<Database.LeadConvertResult>();

//Fetch lead status and converting the lead.


LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE
IsConverted=true LIMIT 1];
for(Lead objLeadNew : lstLeadNew){

if(objLeadNew.Status == 'Closed - Converted'){

if(objLeadNew.isConverted == false){

//Instance Database.LeadConvert.
Database.LeadConvert objLeadConvert = new Database.LeadConvert();
objLeadConvert.setLeadId(objLeadNew.Id);
objLeadConvert.setConvertedStatus(convertStatus.MasterLabel);

//Instance Database.LeadConvertResult.
Database.LeadConvertResult objLeadConvertResult =
Database.convertLead(objLeadConvert);

if(objLeadConvertResult.accountid != Null)
setAccountIds.add(objLeadConvertResult.accountid);

lstleadsConvertResult.add(objLeadConvertResult);
}
}
}

//Fetch Account owner with respective converted AcoountId and store in


mapAccount.
map<Id,Account> mapAccountStoreOwnerId = new map<Id,Account>();
if(setAccountIds.size() > 0){

for(Account objAccount : [SELECT Id, OwnerId FROM Account WHERE Id =:


setAccountIds]){
mapAccountStoreOwnerId.put(objAccount.Id, objAccount);
}
}

List<Task> lstTask = new List<Task>();

//Iterate Database.LeadConvertResult and create task.


for(Database.LeadConvertResult objLeadConvertResult : lstleadsConvertResult){

//Creating a Task Record


Task objTask=New Task(Subject='Please reach out to the Contact to understand
next steps',
Type ='Phone',
OwnerId =
mapAccountStoreOwnerId.get(objLeadConvertResult.accountid).OwnerId,
WhatId = objLeadConvertResult.accountid,
WhoId=objLeadConvertResult.contactid);

//Adding Task Record to List.


lstTask.add(objTask);
}
//Firing DML Operation
Insert lstTask;
}
================================tEST===========================
/*
@MethodName : checkTask
@param :-
@Description: checkTask method will create the lead record.
*/
@ISTest
static void checkTask(){

List<Lead> lstlead = new List<Lead>();


for(Integer i=1 ; i <= 20 ; i++){

Lead objLead = new Lead(LastName = 'muffu'+i,


Company = 'Slv',
Status = 'Closed - Converted');

lstlead.add(objLead);

Lead objLead1 = new Lead(LastName = 'muffuq'+i,


Company = 'Delux');

lstlead.add(objLead1);
}

insert lstlead;

//Fetching Account with name is company name of lead.


list<Account> lstCheckAccount = [SELECT Id, Name FROM Account WHERE Name
='Slv'];
System.assertEquals(20, lstCheckAccount.Size());

List<Lead> lstleadToUpdate = new List<Lead>();


for(Lead objLead : [SELECT Id, Name FROM Lead WHERE Company = 'Delux']){

if(!objLead.IsConverted){

Lead objLeadToUpdate = new Lead(Id = objLead.Id,


Status='Closed - Converted');

lstleadToUpdate.add(objLeadToUpdate);
}
}
update lstleadToUpdate;

//Fetching Account with name is company name of lead.

Completed
Syeda: TASK 8 : Write a trigger to create a Task whenever a Case is populated with a
Contact.

DESIGN CONSIDERATIONS:
● Whenever the Case is populated with a Contact
○ Create a Task with the below details
■ Subject - 'Please reach out to the Contact to understand next steps'
■ Type - Phone
■ Task Owner - Case’s Account’s Owner
■ WhatID - Case Id
■ WhoID - Case’s Contact Id

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios
================================HANDLER======================
/*
@MethodName : createTask
@param : List<Case> lstCaseNew, Map<Id,Case> mapCaseOld.
@Description: createTask method called on is Before update of Lead Object.
*/
Private void createTask(List<Case> lstCaseNew, Map<Id,Case> mapCaseOld, String
strTriggerEvent){
List<Case> lstCaseToUpdate = new List<Case>();
Set<Id> setAccountIds = new Set<Id>();
//Iterate and store case and account Ids.
for(Case objCaseNew : lstCaseNew){

//check contactId and no prior task for case.


if(objCaseNew.ContactId != Null && objCaseNew.Tasks.size() == 0){

Case objCaseOld = new Case();


//check trigger event.
if(strTriggerEvent == 'Update'){

//store prior case values.


objCaseOld = mapCaseOld.get(objCaseNew.Id);
}

//check trigger event and compare old and new value of case.
if(strTriggerEvent == 'Insert' || objCaseNew.ContactId != objCaseOld.ContactId){

if(objCaseNew.AccountId != Null){

setAccountIds.add(objCaseNew.AccountId);
}
lstCaseToUpdate.add(objCaseNew);
}
}
}

//Fetch and store Account in Map.


map<Id,Account> mapAccount = new map<Id,Account>();
if(setAccountIds.size() > 0){

for(Account objAccount : [SELECT Id,OwnerId FROM Account WHERE Id =:


setAccountIds]){

mapAccount.put(objAccount.Id, objAccount);
}
}

//create task.
List<Task> lstTask = new List<Task>();
for(Case objCase : lstCaseToUpdate){

Task objTask = new Task(Subject = 'Please reach out to the Contact to understand
next steps',
Type = 'Phone',
WhatId = objCase.Id,
WhoId = objCase.ContactId);

if(setAccountIds.size() > 0){


objTask.OwnerId = mapAccount.get(objCase.accountid).OwnerId;
}
lstTask.add(objTask);
}
insert lstTask;
}
}
================================tEST======================
@isTest
public class SL_CaseHandler_Test {
@isTest
static void insertCase(){
//create Account record.
Account objAccount =new Account(Name = 'Muffu');
insert objAccount;

//create Contact record.


Contact objContact = new Contact(AccountId = objAccount.Id,
LastName = objAccount.Name);
insert objContact;

//create Case record.


List<Case> lstCase = new List<Case>();
Case objCase = new Case(AccountId = objAccount.Id,
ContactId = objContact.id,
Origin = 'Phone');
lstCase.add(objCase);

Case objCase1 = new Case(AccountId = objAccount.Id,


ContactId = objContact.id,
Origin = 'Phone');
lstCase.add(objCase1);

Case objCase2 = new Case(AccountId = objAccount.Id,


ContactId = objContact.id,
Origin = 'Phone');

lstCase.add(objCase2);
insert lstCase;

//Fetching Task related to Case records And doing system.assertEquals().


Task objTask = [SELECT ID,WhoId FROM Task WHERE WhatId =: lstCase.get(0).Id];
System.assertEquals(objContact.Id, objTask.WhoId);
}
@isTest
static void updateCase(){

//create Account record.


Account objAccount =new Account(Name = 'Muffu');
insert objAccount;
//create Contact record.
List<Contact> lstContact = new List<Contact>();

Contact objContact = new Contact(AccountId = objAccount.Id,


LastName = objAccount.Name);

lstContact.add(objContact);

Contact objContact1 = new Contact(AccountId = objAccount.Id,


LastName = objAccount.Name);

lstContact.add(objContact1);
insert lstContact;

//create Case record.


List<Case> lstCase = new List<Case>();
Case objCase = new Case(AccountId = objAccount.Id,
ContactId = objContact.id,
Origin = 'Phone');

lstCase.add(objCase);

Case objCase1 = new Case(AccountId = objAccount.Id,


ContactId = objContact.id,
Origin = 'Phone');
lstCase.add(objCase1);

Case objCase2 = new Case(AccountId = objAccount.Id,


ContactId = objContact.id,
Origin = 'Phone');
lstCase.add(objCase2);
insert lstCase;

//change contact in objCase.


objCase.ContactId = objContact1.Id;
update objCase;

//Fetching Task related to Case records And doing system.assertEquals().


Task objTask = [SELECT ID,WhoId FROM Task WHERE WhatId =: objCase.Id Order
by CreatedDate DESC limit 1];
System.assertEquals(objContact1.Id, objTask.WhoId);
}
}

Completed
Shubham: TASK 9 : Write a trigger to create a Task whenever the PULSE in an Account is
marked as “RED”.

DESIGN CONSIDERATIONS:
● Create a custom field of type Picklist in Account Object named “PULSE” with values as
listed below
○ RED
○ YELLOW
○ GREEN
● Whenever the Pulse is changed to RED
○ Create a Task with the below details
■ Subject - 'You will need to setup a call with the team to understand what
are the next steps to be taken care to make it Green or Yellow’
■ Type - Phone
■ Task Owner - Account’s Owner
■ WhatID - Account Id

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios
================================HANDLER======================
/*
@MethodName : createTask
@param : List<Account> lstAccountNew, Map<Id,Account> mapAccountOld,
String strTriggerEvent.
@Description: createTask method will create Task record when pulse is red on
Account object.
*/
Private void createTask(List<Account> lstAccountNew, Map<Id,Account>
mapAccountOld, String strTriggerEvent){

List<Task> lstTask = new List<Task>();


//Iterate Account.
for(Account objAccount : lstAccountNew){

Account objAccountOld = new Account();


if(strTriggerEvent == 'Update'){

//Storeing Account prior values.


objAccountOld = mapAccountOld.get(objAccount.Id);
}
//check trigger event is insert or account name is change
if(strTriggerEvent == 'Insert' || objAccount.Name != objAccountOld.Name){

if(objAccount.Pulse__c == 'RED'){

//create task.
Task objTask = new Task(Subject = 'You will need to setup a call with the
team to understand what are the next steps to be taken care to make it Green or Yellow',
Type = 'Phone',
OwnerId = objAccount.OwnerId,
WhatId = objAccount.Id);
lstTask.add(objTask);
}
}
}
insert lstTask;
}
================================tEST======================
/*
@MethodName : checkTaskCreated
@param :-
@Description: checkTaskCreated method will create the Account record.
*/
@isTest
private static void checkTaskCreated(){
//create profile for the user.
Profile objProfile = [SELECT Id FROM Profile WHERE Name='System Administrator'
limit 1];
//create user.
user objUser = new User(LastName = 'User1',
Email = '[email protected]',
Alias = 'Test1',
Username = '[email protected]',
CommunityNickname = 'test12',
LocaleSidKey = 'en_US',
TimeZoneSidKey = 'GMT',
profileId = objProfile.Id,
LanguageLocaleKey = 'en_US',
EmailEncodingKey = 'UTF-8');
insert objUser;

List<Account> lstAccount = new List<Account>();


//create Account records.
Account objAccount = new Account(Name = 'Muffu',
Pulse__c = 'Red',
OwnerId = objUser.id);
lstAccount.add(objAccount);

Account objAccount1 = new Account(Name = 'Muffu',


Pulse__c = 'Red',
OwnerId = objUser.id);
lstAccount.add(objAccount1);

Account objAccount2 = new Account(Name = 'Muffu',


Pulse__c = 'Red');
lstAccount.add(objAccount2);

insert lstAccount;

//Fetch Task related to objAccount1.


Task objTask = [SELECT ID,OwnerId FROM Task WHERE WhatId =: objAccount1.Id];
System.assertEquals(objAccount1.OwnerId, objTask.OwnerId);
}

Completed
Kiran: TASK 10 : Write a trigger, if the owner of an account is changed then the previous
owner should be notified of this change.

DESIGN CONSIDERATIONS:
● Whenever the owner of an Account is changed
○ Send an email notification to the previous owner stating that the Account’s
ownership got changed from him/her to the new owner in context

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios
================================HANDLER======================
/*
@MethodName : sendEmailToOwner
@param : List<Account> lstAccountNew, Map<Id,Account> mapAccountOld.
@Description: sendEmailToOwner method called on is Before update of Account
Object.
*/
Private void sendEmailToOwner(List<Account> lstAccountNew, Map<Id,Account>
mapAccountOld){

Set<Id> setAccountOldId = new Set<Id>();


Set<Id> setAccountIds = new Set<Id>();

//Iterate Account.
for(Account objAccount : lstAccountNew){

if(mapAccountOld.containskey(objAccount.id)){

//Store Account prior values in objAccountOld.


Account objAccountOld = mapAccountOld.get(objAccount.id);

if(objAccount.OwnerId != objAccountOld.OwnerId){
//Store Account prior values in setAccountOldId.
setAccountOldId.add(objAccountOld.Id);
setAccountIds.add(objAccount.Id);
}
}
}

//fetching new Account owner.


Account objAccountNewOwner = [SELECT Id, Name, Owner.Name FROM Account
WHERE Id In: setAccountIds];

//create list for Messaging.SingleEmailMessage.


List<Messaging.SingleEmailMessage> lstMails = new
List<Messaging.SingleEmailMessage>();

//Fetch User by using setAccountOldId.


for(Account objAccountOwnerOldEmail : [SELECT Id, Owner.Email, Owner.Name
FROM Account WHERE Id in: setAccountOldId]){

if(setAccountOldId.size() > 0){


String[] strEmailId = new String[]{objAccountOwnerOldEmail.Owner.Email};
//create instance of Messaging.SingleEmailMessage.
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setSaveAsActivity(False);
email.setSenderDisplayName('Muffasser');
email.setSubject('Account owner is Changed ');
email.setHtmlBody('the Account’s ownership got changed from you To
'+objAccountNewOwner.Owner.Name);
email.setToaddresses(strEmailId);

lstMails.add(email);
}
}

if(lstMails.size() > 0){


//sending Email to Old Account owners.
Messaging.sendEmail(lstMails);
}
}
================================tEST======================

/*
@MethodName : changeAccountOwner
@param :-
@Description: changeAccountOwner method will change the Account owner.
*/
@isTest
static void changeAccountOwner(){

List<User> lstUser = new List<User>();

//create profile for the user.


Profile objProfile = [SELECT Id FROM Profile WHERE Name='System Administrator'
limit 1];

//create user.
user objUser1 = new User(LastName = 'User1',
Email = '[email protected]',
Alias = 'Test1',
Username = '[email protected]',
CommunityNickname = 'test123',
LocaleSidKey = 'en_US',
TimeZoneSidKey = 'GMT',
profileId = objProfile.Id,
LanguageLocaleKey = 'en_US',
EmailEncodingKey = 'UTF-8');

lstUser.add(objUser1);

//create user.
user objUser2 = new User(LastName = 'User2',
Email = '[email protected]',
Alias = 'Test2',
Username = '[email protected]',
CommunityNickname = 'test456',
LocaleSidKey = 'en_US',
TimeZoneSidKey = 'GMT',
profileId = objProfile.Id,
LanguageLocaleKey = 'en_US',
EmailEncodingKey = 'UTF-8');

lstUser.add(objUser2);
insert lstUser;

List<Account> lstAccount = new List<Account>();


//create Account records.
Account objAccount = new Account(Name = 'Muffu',
Pulse__c = 'Red',
OwnerId = objUser1.id);
lstAccount.add(objAccount);
insert lstAccount;

//change Account owner


objAccount.OwnerId = objUser2.id;
Update objAccount;

//Fetch Account related to objAccount and checking owner is changed.


Account ObjAccountToCheck = [SELECT Id,OwnerId FROM Account WHERE id =:
objAccount.Id];
System.assertEquals(objUser2.id, ObjAccountToCheck.OwnerId);
}

completed
Shveta: TASK 11 : Write a trigger, to split the Total Amount budgeted from the Account
into its Contact records equally.

DESIGN CONSIDERATIONS:
● Create a custom field of type Currency in Account Object named “Total Budgeted
Amount”. This is a mandatory field.
● Create a custom field of type Currency in Contact Object named “Budget Amount”. This
is a mandatory field.
● Whenever the Total Budgeted Amount is populated or changed in the Account then
○ Distribute the Total Budgeted amount from the Account equally among it’s
related Contacts.

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios
=========================HANDLER=============================
/*
@MethodName : displayContactBudget
@param : List<Account> lstAccountNew, Map<Id,Account> mapAccountOld,
String strTriggerEvent.
@Description: displayContactBudget method Distribute the Total Budgeted
amount from the Account equally among it’s related Contacts .
*/
Private void displayContactBudget(List<Account> lstAccountNew, Map<Id,Account>
mapAccountOld, String strTriggerEvent){

LIST<Contact> lstContactToUpdate = new LIST<Contact>();


map<Id, Account> mapAccountToStore = new map<Id, Account>();

for(Account objAccount : lstAccountNew){

if(objAccount.Total_Budgeted_Amount__c == Null){
objAccount.addError('Enter Total Budgeted Amount filed');
}

else{
mapAccountToStore.put(objAccount.Id, objAccount);
}
}

//Fetching contacts related to Account.


list<Contact> lstContact = [SELECT ID, AccountId, Budgeted_Amount__c FROM
Contact WHERE AccountId =: mapAccountToStore.keySet()];

//distrubute Total_Budgeted_Amount__c equally to All related contacts.


if(lstContact.size() != 0){

for(Contact objContact : lstContact){

objContact.Budgeted_Amount__c =
(mapAccountToStore.get(objContact.AccountId).Total_Budgeted_Amount__c/
lstContact.size());
lstContactToUpdate.add(objContact);
}

update lstContactToUpdate;
}
}
=============================TEST======================================
/*
@MethodName : displayBugdetOnAccount
@param :-
@Description: displayBugdetOnAccount method will create the Account record.
*/
@isTest
static void displayBugdetOnAccount(){

//Cretate Account record.


Account objAccount = new Account(Name = 'Muffu',
Total_Budgeted_Amount__c = 100000);
insert objAccount;

//create contacts related to objAccount.


List<Contact> lstContact = new List<Contact>();
for(Integer i = 1 ; i <=5; i++){

Contact objContact = new Contact(AccountId = objAccount.id,


LastName = 'muffasser');

lstContact.add(objContact);
}

insert lstContact;

//update account budget.


objAccount.Total_Budgeted_Amount__c =100;
update objAccount;

//check bugdet on contact.


Contact objContactToCheck = [SELECT Id, Budgeted_Amount__c From Contact
WHERE ID =:lstContact.get(4).Id];
System.assertEquals(20, objContactToCheck.Budgeted_Amount__c);
}
inProcess
Sumanth AS: TASK 12 : Write a trigger, to validate the summation of the Budget
Allocation field of all the Contact(s) under an Account is always 100%.

DESIGN CONSIDERATIONS:
● Create a custom field of type Percentage in Contact Object named “Budget Allocation”.
This is a mandatory field. However, this field can accept a value as 0.
● Whenever Contact is created/updated/deleted
○ Validate the summation of the Budget Allocation field of all the Contact(s) under
an Account is always 100%.

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios
============================Handler=============================
/*

@MethodName : budgetAllocation
@param
: List<Contact> lstContactNew, Map<Id,Contact> mapContactOld, String strTriggerEvent.

@Description: budgetAllocation method will create user for Contact.


*/
Private void budgetAllocation(List<Contact> lstContactNew, Map<Id,Contact>
mapContactOld, String strTriggerEvent){

Set<Id> setAccountIds = new Set<Id>();


for(Contact objContact : lstContactNew){

if(objContact.AccountId != Null){

if(objContact.Budget_Allocation__c == Null){
objContact.addError('Please enter the Budget_Allocation__c field');
}

else if(objContact.AccountId != Null)


setAccountIds.add(objContact.AccountId);
}
}

double totalPercent = 0;
for(Contact objContact : [SELECT Id, Budget_Allocation__c FROM Contact WHERE
AccountId =: setAccountIds]){
totalPercent += objContact.Budget_Allocation__c;
}

for(Contact objContactToUpdate : lstContactNew){


Contact objOldContact = new Contact();
if(StrTriggerEvent == 'Update'){

//Getting prior Contact Values and Store.


if(mapContactOld.ContainsKey(objContactToUpdate.Id))
objOldContact = mapContactOld.get(objContactToUpdate.Id);
}
if(strTriggerEvent == 'Insert' || (objOldContact.Budget_Allocation__c !=
objContactToUpdate.Budget_Allocation__c && strTriggerEvent == 'Update'))
totalPercent+= objContactToUpdate.Budget_Allocation__c;

If(strTriggerEvent == 'delete')
totalPercent-= objContactToUpdate.Budget_Allocation__c;

if(totalPercent > 100){


objContactToUpdate.addError('your crossing Budget Allocation with respective
to Account');

}
}
}
===============================Test======================================
/*
@MethodName : budgetAllocation
@param :-
@Description: budgetAllocation method will create the contact record.
*/
@isTest
static void budgetAllocation(){

//create Account record.


Account objAccount = new Account(Name = 'Muffu',
Total_Budgeted_Amount__c =10000);
insert objAccount;

//create Contact records related to objAccount.


List<Contact> lstContact = new List<Contact>();
Contact objContact = new Contact(AccountId = objAccount.id,
LastName = 'muffasser',
MailingState = 'aa',
Budget_Allocation__c =10);
lstContact.add(objContact);

Contact objContact2 = new Contact(AccountId = objAccount.id,


LastName = 'muffasser',
MailingState = 'aa',
Budget_Allocation__c =68);
lstContact.add(objContact2);

Contact objContact1 = new Contact(AccountId = objAccount.id,


LastName = 'Md muffasser',
MailingState = 'bb',
Budget_Allocation__c =11);
lstContact.add(objContact1);
insert lstContact;

delete objContact1;

//update contact to Budget_Allocation__c


objContact2.Budget_Allocation__c =111;
update objContact2;

//Fetching contacts related to objAccount records And doing system.assertEquals().


//Contact objContactToCheck = [SELECT Id,Budget_Allocation__c,
Budgeted_Amount__c FROM Contact WHERE Id = : objContact1.Id];
//System.assertEquals(78, objContactToCheck.Budget_Allocation__c);

}
completed
Noel: TASK 13 : Write a trigger, to create a User whenever the Create User field in
Contact is checked the first time.

DESIGN CONSIDERATIONS:
● Create a custom field of type checkbox in Contact Object named “Create User”. Not a
required field.
● Create a custom field of type text in User Object named “Contact ID”.
● Whenever Contact is created/updated with the Create User checkbox as Checked for
the first time AND there is no User already created for this Contact Then
○ Create a User record with details from Contact.
○ Also ensure to assign Contact Id field on User record with Contact’s Id.

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios
===============================Handler=========================
/*
@MethodName : createUser
@param : List<Contact> lstContactNew, Map<Id,Contact> mapContactOld,
String strTriggerEvent.
@Description: createUser method will create user for Contact.
*/
Private void createUser(List<Contact> lstContactNew, Map<Id,Contact>
mapContactOld, String strTriggerEvent){

//Iterate lstContactNew and Store contact ids.


Set<Id> setContactIds = new Set<Id>();
for(Contact objContact : lstContactNew){

if(objContact.Create_User__c && objContact.id != null){


setContactIds.add(objContact.Id);
}
}

//calling futureMethodToInsertUser;
Sl_FutureMethodToCreateUser.futureMethodToInsertUser(setContactIds);
}
=============FUTURE METHOD
public class Sl_FutureMethodToCreateUser{
/*
@MethodName : futureMethodToInsertUser
@param : List<Contact> lstContactNew, Map<Id,Contact> mapContactOld,
String strTriggerEvent.
@Description: futureMethodToInsertUser method called on is After update of
Contact Object.
*/
@future
public static void futureMethodToInsertUser(Set<Id> contactIds){

//Fetching user profile and portal role.


Profile objProfile = [SELECT Id FROM Profile WHERE Name='Standard User' Limit
1];
UserRole portalRole = [SELECT Id FROM UserRole WHERE Name='CEO' Limit 1];
List<User> lstUser = new List<User>();
for(Contact objContact : [SELECT ID, Name, LastName, Email, RecordType.Name,
Create_User__c FROM Contact WHERE id =: contactIds]){

if(objContact.Create_User__c){
//Taking instance of User
User objUserToInsert = new User(LastName=objContact.LastName,
Email=objContact.LastName+'a'+System.now().millisecond()
+ '[email protected]',
Alias='a'+System.now().millisecond(),
Username = System.now().millisecond() + '[email protected]',
UserRoleId=portalRole.Id,
ProfileId=objProfile.Id,
IsActive=false,
TimeZoneSidKey='GMT',
LanguageLocaleKey='en_US',
EmailEncodingKey= 'UTF-8',
LocaleSidKey= 'en_US',
Contact_ID__c=objContact.Id);
// objUserToInsert.ContactId=objContact.Id;
if(objUserToInsert!=NULL)
lstUser.Add(objUserToInsert);
}
}
System.debug('=======>'+lstUser);
insert lstUser;
}
}
=============================TEST======================================
/*
@MethodName : createUser
@param :-
@Description: createUser method will create the contact record.
*/
@isTest
static void createUser(){
//create Contact records related to objAccount.
List<Contact> lstContact = new List<Contact>();
Contact objContact = new Contact(LastName = 'muffasser12',
Create_User__c = true,
MailingState = 'ab',
Email ='[email protected]');
lstContact.add(objContact);
Contact objContact1 = new Contact(LastName = 'muffasser34',
Create_User__c = true,
MailingState = 'bc',
Email ='[email protected]');
lstContact.add(objContact1);

Contact objContact2 = new Contact(LastName = 'muffasser56',


MailingState = 'cd',
Email ='[email protected]');
lstContact.add(objContact2);
insert lstContact;

//storeing contact ids.


set<id> setid = new set<id>{objContact1.id};

test.startTest();
Sl_FutureMethodToCreateUser.futureMethodToInsertUser(setid);
test.stopTest();

//Fetching Account related to lstContact records And doing system.assertEquals().


User objContactToCheckUser = [SELECT Id, LastName FROM User WHERE
Contact_ID__c =: objContact1.Id Limit 1];
System.assertEquals(objContact1.LastName, objContactToCheckUser.LastName);

completed
Sumanth P: TASK 14 : Write a trigger, to assign the user to the relevant group based on
profile.

DESIGN CONSIDERATIONS:
● Create a public group named “Users”
● Create a public group named “Admins”
● Whenever User is created/updated/deactivated
○ Check for the Profile of the User and add/remove the User to the respective
groups as shown below in the mapping

Group User Profile

Users All Users with Standard User as a Profile


Admins All Users with System Administrator as a Profile

** Think of all the possible scenarios that we may need to handle.


Write a Unit test in Apex to ensure the above trigger covers all the scenarios

=============================Handler============================
/*
* @ClassName : SL_UserHandler
* @JIRATicket : -
* @CreatedOn : 30/Aug/2022
* @ModifiedBy : SL_R_MD_MUFFASSER
* @Description : This is the handler class for User trigger runs when insert And update
operation are doing.
*/
public class SL_UserHandler{

/*
@MethodName : isAfterInsert
@param : List<User> lstUserNew.
@Description: isAfterInsert method called on is After Insert of User object.
*/
public void isAfterInsert(List<User> lstUserNew){

assignUsersToGroup(lstUserNew, null, 'Insert');


}

/*
@MethodName : isAfterUpdate
@param : List<User> lstUserNew, Map<Id,User> mapUserOld.
@Description: isAfterUpdate method called on is After update of User Object.
*/
public void isAfterUpdate(List<User> lstUserNew, Map<Id,User> mapUserOld){

assignUsersToGroup(lstUserNew, mapUserOld, 'Update');


}

/*
@MethodName : assignUsersToGroup
@param : List<User> lstUserNew, Map<Id,User> mapUserOld.
@Description: assignUsersToGroup method will add/remove the User to the
respective groups .
*/
private void assignUsersToGroup(List<User> lstUserNew, Map<Id,User> mapUserOld,
String strTriggerEvent){
//Fetching profile Id's
Profile objUserProfile = [SELECT Id FROM Profile WHERE Name='Standard User' Limit
1];
Profile objAdminProfile = [SELECT Id FROM Profile WHERE Name='System
Administrator' Limit 1];

map<String, Group> mapUserToFetch = new map<String, Group>();

//Fetching group and Iterating.


for(Group objGroup : [Select Id,Name From Group]){

//Group storeing in map.


mapUserToFetch.put(objGroup.Name, objGroup);
}

//Itreating User
list<GroupMember> lstGroupMember = new list<GroupMember>();
for(User objUserNew : lstUserNew){

//Check user profile id with Standard User and adding to public group.
if(objUserNew.ProfileId == objUserProfile.Id){
GroupMember objGroupMember = new GroupMember(GroupId
=mapUserToFetch.get('Users').Id,
UserOrGroupId = objUserNew.Id);

lstGroupMember.add(objGroupMember);
}

//Check user profile id with System Administrator and adding to public group.
else if(objUserNew.ProfileId == objAdminProfile.Id){
GroupMember objGroupMember = new GroupMember(GroupId
=mapUserToFetch.get('Admins').Id,
UserOrGroupId = objUserNew.Id);

lstGroupMember.add(objGroupMember);
}
}

//check list is empty or not and add to group


if(!lstGroupMember.isEmpty()) {
System.debug('groupMembe'+ lstGroupMember);
insert lstGroupMember;
}
}
}
================================Test========================================
/*
* @ClassName : SL_UserHandler_Test
* @CreatedOn : 26/Sept/2022
* @ModifiedBy : SL_R_MD_MUFFASSER
* @Description : This is the Test class for SL_UserHandler Class.
*/
@isTest
public class SL_UserHandler_Test {
/*
@MethodName : createContact
@param :-
@Description: createUser method will create the User.
*/
@isTest
static void createUser(){

//create profile for the user.


Profile objAdminProfile = [SELECT Id FROM Profile WHERE Name='System
Administrator' limit 1];
Profile objUserProfile = [SELECT Id FROM Profile WHERE Name='Standard User' Limit
1];

//create user.
list<User> lstUser = new list<User>();

user objUser = new User(LastName = 'User1',


Email = '[email protected]',
Alias = 'Test1',
Username = '[email protected]'+Math.random()*100 ,
CommunityNickname = 'test12'+Math.random()*100 ,
LocaleSidKey = 'en_US',
TimeZoneSidKey = 'GMT',
profileId = objAdminProfile.Id,
LanguageLocaleKey = 'en_US',
EmailEncodingKey = 'UTF-8');
lstUser.add(objUser);

user objUser2 = new User(LastName = 'User1',


Email = '[email protected]',
Alias = 'Test1',
Username = '[email protected]'+Math.random()*100 ,
CommunityNickname = 'test12'+Math.random()*100 ,
LocaleSidKey = 'en_US',
TimeZoneSidKey = 'GMT',
profileId = objUserProfile.Id,
LanguageLocaleKey = 'en_US',
EmailEncodingKey = 'UTF-8');
lstUser.add(objUser2);

user objUser3 = new User(LastName = 'User1',


Email = '[email protected]',
Alias = 'Test1',
Username = '[email protected]',
CommunityNickname = 'test12',
LocaleSidKey = 'en_US',
TimeZoneSidKey = 'GMT',
profileId = objUserProfile.Id,
LanguageLocaleKey = 'en_US',
EmailEncodingKey = 'UTF-8');
lstUser.add(objUser3);

insert lstUser;

//Fetching Users group and group members


Group objGroup = [Select Id,Name From Group Where Name = 'Users' Limit 1];
GroupMember obj = [SELECT Id,UserOrGroupId, SystemModstamp From GroupMember
Where GroupId =: objGroup.Id Order By SystemModstamp Desc Limit 1];

//check user is add to group are not


System.assertEquals(lstUser.get(2).Id, obj.UserOrGroupId);
}
}

You might also like