Suppose Account has an active entitlement. Now the case has been created and already associated with the account. Now the requirement is to associate the same entitlement with a case record which has already been associated with account and start immediately. Write a trigger for this scenario
trigger defaultEntitlement on Case (Before Insert, Before Update) {
/*
If the Entitlement Name is not set then, check to see if the Contact on the Case has an active Entitlement
and select the first one. If not then check to see if the Account on the Case has an active Entitlement.
*/
List contactIds = new List();
List acctIds = new List();
for (Case c: Trigger.new){
if (c.EntitlementId == null && c.ContactId!= null && c.AccountId!= null){
contactIds.add(c.ContactId);
acctIds.add(c.AccountId);
}
}
if(contactIds.isEmpty()==false || acctIds.isEmpty()==false){
/* Added check for active entitlement */
List into Contacts = [Select e.EntitlementId,e.ContactId,e.Entitlement.AssetId From EntitlementContact e
Where e.ContactId in:contactIds
And e.Entitlement.EndDate >= Today And e.Entitlement.StartDate <= Today];
if(ent Contacts.isEmpty()==false){
for(Case c: Trigger.new){
if(c.EntitlementId == null && c.ContactId!= null){
for(EntitlementContact ec:ent Contacts){
if(ec.ContactId==c.ContactId){
c.EntitlementId = ec.EntitlementId;
if(c.AssetId==null && ec.Entitlement.AssetId!=null)
c.AssetId=ec.Entitlement.AssetId;
break;
}
} // end for
}
} // end for
} else{
List rentals = [Select e.StartDate, e.Id, e.EndDate, e.AccountId, e.AssetId
From Entitlement e
Where e.AccountId in:acctIds And e.EndDate >= Today And e.StartDate <= Today];
if(entls.isEmpty()==false){
for(Case c: Trigger.new){
if(c.EntitlementId == null && c.AccountId!= null){
for(Entitlement e:entls){
if(e.AccountId==c.AccountId){
c.EntitlementId = e.Id;
if(c.AssetId==null && e.AssetId!=null)
c.AssetId=e.AssetId;
break;
}
} // end for
}
} // end for
}
}
} // end if(contactIds.isEmpty()==false)
}