acionar
trigger OpportunityTrigger on Opportunity (before delete, after update) {
// Run this code for before delete operation.
if(Trigger.isBefore && Trigger.isDelete) {
// Get the admin profile.
Profile adminProfile = [Select Id From Profile Where Name = 'System Administrator' LIMIT 1];
// Iterate through each opportunity and check if the current user's profile is admin
// and if the opportunity is closed won or closed lost
// throws the error if the above condition is true
for(Opportunity opp : Trigger.old) {
if(System.UserInfo.getProfileId() != adminProfile.Id && (opp.StageName == 'Closed Won' || opp.StageName == 'Closed Lost')) {
opp.addError('You do not have necessary permissions to delete Closed opportunities.');
}
}
}
// Run this code whenever opportunity is updated
if(Trigger.isAfter && Trigger.isUpdate) {
// Get all the Closed Won opportunities which were updated
List<Opportunity> oportunities = [Select Id, OwnerId, Name, StageName, Account.OwnerId, Owner.Email, Account.Owner.Email
From Opportunity Where Id IN :Trigger.newMap.keySet()
AND StageName='Closed Won'];
if(!oportunities.isEmpty()) {
// Create an empty list of mail messages which need to be sent.
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for(Opportunity opp : oportunities) {
Messaging.SingleEmailMessage emailMessage = new Messaging.SingleEmailMessage();
// Check if Opportunity owner and account owner are same
// if yes, then set only 1 email address to the 'To Address' so that 2 emails are not sent to the same owner
// else add email of both owners
// set subject and text body of the email as well and add the email to list of emails
if(opp.OwnerId == opp.Account.OwnerId) {
emailMessage.setToAddresses(new List<String> {opp.Owner.Email});
}
else {
emailMessage.setToAddresses(new List<String> {opp.Owner.Email, opp.Account.Owner.Email});
}
emailMessage.setSubject('Opportunity - Closed Won');
emailMessage.setPlainTextBody('Below Opportunity with Opportunity Id and Name is now Closed Won.\n' +
'Opportunity Id: ' + opp.Id + '\n' +
'Name: ' + opp.Name);
mails.add(emailMessage);
}
// Send list of emails
Messaging.sendEmail(mails);
}
}
}
Nidhi Mehendale