Sunday 23 April 2017

Opportunity Owner should get email notification when task is completed on opportunity

trigger NotifyOpportunityowner on Task ( after update) {
List<Task> taskList = new List<Task>();
Set<ID> taskIDSet = new Set<ID>();

if (trigger.old != null)
{
for (Task t: trigger.old)
{
taskIDSet.add(t.ID);
}Set<String> strwhatIDs = new Set<String>();
set<Id> setClosedTaskId = new set<Id>();
Map<id,string> maprecortypes=new Map<id,string>();
Map<id,string> mapEmailAdress=new Map<id,string>();
Map<id,string> mapcurrentOwnerid=new Map<id,string>();
string[] toaddress = New String[] {};
for (Task t : (List<Task>)Trigger.new) {
Task oldTask = (Task)trigger.oldMap.get(t.Id);
Task newTask = (Task)trigger.newMap.get(t.Id);
if(((oldTask.status != newTask.status) && t.status == 'Completed' )){
strwhatIDs.add(t.whatID);
setClosedTaskId.add(t.id);

}  
}
list<Task> lstTask = [select id,OwnerId,what.recordtype.developername,what.recordtype.name from Task where Id IN : setClosedTaskId ];

EmailTemplate objEt =  [select id,developername from EmailTemplate where developername ='Testing_vf_template'];
list<Opportunity> lstopt = [select id,owner.email from Opportunity where id IN: strwhatIDs];

if(!lstopt.isEmpty()){
for(Opportunity Opt : lstopt){

mapEmailAdress.put(Opt.id,Opt.owner.email);

}
}
 
if(!mapEmailAdress.values().isEmpty()){
for(string str :mapEmailAdress.values()){
toaddress = New String[] {str};
}
}
List<Messaging.SingleEmailMessage> lstEmailId=new List<Messaging.SingleEmailMessage>();
Contact cont = [select id,name from contact limit 1];

if(!lstTask.isEmpty()){
for(Task tk : lstTask){
system.debug('toaddress exception'+toaddress);

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(toaddress);
mail.setTemplateId(objEt.id);
mail.setWhatId(tk.id);
mail.setTargetObjectId(cont.id);
mail.setTreatTargetObjectAsRecipient(false);
mail.setSaveAsActivity(false);
lstEmailId.add(mail);                

}
}
if(lstEmailId.size()>0){
try{              
Messaging.sendEmail(lstEmailId);
}Catch(Exception ee){
system.debug('Print exception'+ee);
}
}
}
 

}

No comments:

Post a Comment

customize omni channel logic to distribute cases based on Case Creation Date

Omni Channel queues distributes cases, based on Date/Time the case is assigned to the queue. we can customize this logic to look for some ...