Untitled

 avatar
unknown
plain_text
2 months ago
18 kB
3
Indexable
SRIKANTH INACTIVE OWNER DELIVERY CODE



global class InactiveDelivertOwnerAlertBatch implements Database.Batchable<SObject>, Schedulable {
    public string query = '';
    public Set<Id> ids = new Set<Id>();
    global InactiveDelivertOwnerAlertBatch(){
        
    }
    global InactiveDelivertOwnerAlertBatch(String querys,Set<Id> id){
        this.query = querys;
        this.ids = id;
    }
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([SELECT Id, Business__c, 
                                         Delivery_Owner__c, Delivery_Owner__r.Name, Delivery_Owner__r.email,
                                         Group_SBU__c, Name,Opportunity_ID__c,
                                         OwnerId, Owner.Name
                                         FROM Opportunity 
                                         WHERE Delivery_Owner__c != null AND stagename != 'Lost' AND CloseDate > TODAY
                                         ORDER BY Group_SBU__c
                                        ]);
    }
    
    global void execute(Database.BatchableContext BC, List<Opportunity> scope) {
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        Map<String, Group_SBU__c> students = Group_SBU__c.getAll();
        Map<String,String> nameVsEmail = new Map<String,String>();
        Set<String> activeUserEmail = new Set<String>();
        Set<String> activeEmplEmail = new Set<String>();
        Set<String> userName = new Set<String>();
        Set<String> emailsSet = new Set<String>();
        Map<String,List<Opportunity>> gbVsOpps = new Map<String,List<Opportunity>>();
        for(Opportunity opp : scope) {
            emailsSet.add(opp.Delivery_Owner__r.email);
        }
        if(emailsSet.size() > 0){
            List<User> userList = [select id,email from user where isactive = true AND email IN :emailsSet];
            List<Employee_Number__c> employeeList = [select id,Email_Address__c from Employee_Number__c where Status__c = 'ACTIVE' AND Email_Address__c IN :emailsSet ];
            for(User userRec : userList){
                activeUserEmail.add(userRec.email);
            }
            for(Employee_Number__c empl : employeeList){
                activeEmplEmail.add(empl.Email_Address__c);
            }
        }
        for(Group_SBU__c csetting : students.values()){
            if(String.isNotBlank(csetting.Users__c))  userName.addAll(csetting.Users__c.split(','));
        }
        if(userName.size() > 0){
            List<User> userList = [SELECT Id,Email,Name FROM User WHERE Name In :userName];
            for(User userRecord : userList){
                nameVsEmail.put(userRecord.Name,userRecord.Email);
            }
        }
        
        for(Opportunity opp : scope) {
            if(!activeUserEmail.contains(opp.Delivery_Owner__r.email) || !activeEmplEmail.contains(opp.Delivery_Owner__r.email)){
                if(gbVsOpps.containsKey(opp.Group_SBU__c)){
                    gbVsOpps.get(opp.Group_SBU__c).add(opp);
                }else{
                    gbVsOpps.put(opp.Group_SBU__c,new List<Opportunity>{opp});
                }
            }
        }
        for(String key : gbVsOpps.keySet()) {
            Integer count = 1;
            
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            List<String> toAddresses = getToAddress(key,nameVsEmail,students);
            email.setToAddresses(toAddresses);
            email.setCCAddresses(new List<String>{'asrikanthreddy@virtusa.com'});
            //email.setToAddresses(new List<String>{'asrikanthreddy@virtusa.com'});
            email.setSubject('Delivery owner status notification');
            String emailBody = 'Hi Team, Please find the below opt record where delivery owner is inactive. Kindly take action';
            emailBody += '<table border="1"><tr><th>Sr. No.</th><th>Opportunity</th><th>Opportunity_ID__c</th><th>Owner</th><th>Delivery Owner</th><th>Employee Status</th><th>User Status</th></tr>';
            for(Opportunity opp : gbVsOpps.get(key)){
                String isActiveEmployee = activeEmplEmail.contains(opp.Delivery_Owner__r.email) ? 'Active' : 'Inactive';
                String isActiveUser = activeUserEmail.contains(opp.Delivery_Owner__r.email) ? 'Active' : 'Inactive';
                emailBody += '<tr><td>' + count + '</td><td>' + opp.Name + '</td><td>' + opp.Opportunity_ID__c + '</td><td>' + opp.Owner.Name + '</td><td>' + opp.Delivery_Owner__r.Name + '</td><td>' 
                    + isActiveUser + '</td><td>' 
                    + isActiveEmployee + '</td> </tr>';
                count++;
            }
            emailBody += '</table>';
            email.setHtmlBody(emailBody);
            emails.add(email);
            
        }
        if(emails.size () > 0){
            Messaging.sendEmail(emails);
        }
    }
    
    global void finish(Database.BatchableContext BC) {
    }
    private static List<String> getToAddress(String groupSBU,Map<String,String> nameVsEmail,Map<String, Group_SBU__c> students){
        Group_SBU__c cSetting = students.get(groupSBU);
        List<String> users = cSetting != null ? cSetting.Users__c.split(',') : new List<string>();
        List<String> emailAddresses = new List<String>();
        for(String userName : users){
            if(nameVsEmail.get(userName) != null) emailAddresses.add(nameVsEmail.get(userName));
        }
        return emailAddresses;
    }
    global void execute(SchedulableContext sc) {
        Database.executeBatch(new InactiveDelivertOwnerAlertBatch(),2000);
    }
}




-----------------------------------








public class OpportunityTriggerUtility {
    public static void validateDeliveryOwner(List<Opportunity> newOppList) {
        validateDeliveryOwner(newOppList, null);
    }
		
    public static void validateDeliveryOwner(List<Opportunity> newOppList, Map<Id, Opportunity> oldOppMap) {
        Set<String> userIds = new Set<String>();
        Set<String> employeeIds = new Set<String>();
        Set<String> contactEmails = new Set<String>();
        Map<String, String> employeeIdVsUserId = new Map<String, String>();
            
        for(Opportunity opp : newOppList) {
            if (opp.Delivery_Owner__c != null) {
                contactEmails.add(opp.Delivery_Owner__r.email);
            }  
        }
        
        // Storing inactive employees
        List<Employee_Number__c> employeeList = [SELECT Id, Email_Address__c FROM Employee_Number__c WHERE Email_Address__c IN :contactEmails AND Status__c = 'INACTIVE'];
        for (Employee_Number__c emp : employeeList) {
            employeeIds.add(emp.Email_Address__c);
            employeeIdVsUserId.put(emp.Id, emp.Email_Address__c);
        }
        
        // Storing inactive users
        List<User> userList = [SELECT Id, email FROM User WHERE email IN :contactEmails AND IsActive = false];
        for (User emp : userList) {
            userIds.add(emp.email); 
        }

        // Iterate through the new Opportunity records to check conditions and send emails
        for (Opportunity opp : newOppList) {
            // Check if the email address of the delivery owner is in the set of inactive users
            if (employeeIds.contains(opp.Delivery_Owner__r.email) || userIds.contains(opp.Delivery_Owner__r.email)) {
                // The delivery owner is inactive
                // Check conditions related to business unit and SBU on the Opportunity record
                List<String> userNames = new List<String>();
                if (opp.Business__c == 'GROWTH MARKETS') {
                    if (opp.Group_SBU__c == 'GM APAC') {
                        userNames.add('Hari Naga Sai Pavan Kumar Tavva');
                        sendingEmail(userNames, opp);
                        userNames.clear();
                    }
                }
                // Need to check this with else if condition
                else if (opp.Business__c == 'PLATINUM ACCOUNTS') {
                    if (opp.Group_SBU__c == 'PLATINUM AC-CITI') {
                        // Handle this case
                    }
                    else if (opp.Group_SBU__c == 'PLATINUM AC-JPMC') {
                        // Handle this case
                    }
                }
                else if(opp.Business__c == 'GROWTH MARKETS') {
                    if (opp.Group_SBU__c == 'GM APAC') {
                        userNames.add('Hari Naga Sai Pavan Kumar Tavva');
                        sendingEmail(userNames, opp);
                        userNames.clear();
                    }
                }
                // Handle other business units similarly
            }
        }
    }

    // Method to send an email
    private static void sendingEmail(List<String> userNames, Opportunity opp) {
        for (String userName : userNames) {
            User specificUser = [SELECT Id, Email, IsActive FROM User WHERE Name = :userName LIMIT 1];
            if (specificUser != null) {
                // Email body with field values
                String emailBody = 'Opportunity Name: ' + opp.Name + '\n' +
                                   'Opportunity ID: ' + opp.Opportunity_ID__c + '\n' +
                                   'Delivery Owner: ' + opp.Delivery_Owner__r.name + '\n' +
                                   'Employee Status: ' + 'INACTIVE';

                // Create an instance of SingleEmailMessage
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

                // Set recipient email address
                mail.setToAddresses(new String[]{specificUser.Email});

                // Set email subject
                mail.setSubject('Delivery owner whose status is inactive');

                // Set the email body
                mail.setPlainTextBody(emailBody);

                // Send the email
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }
        }
    }
}
























// new task code




trigger MyApprovalTrigger on ProcessInstanceChangeEvent (after insert) {
    // Iterate through the new ProcessInstanceChangeEvent records
    for (ProcessInstanceChangeEvent event : Trigger.new) {
        // Check if the event represents a change in an approval record
        if (event.TargetObjectId.getSObjectType() == sbaa__Approval__c.SObjectType) {
            // Query the related Approval record
            sbaa__Approval__c relatedApproval = [SELECT Id, sbaa__AssignedTo__c FROM sbaa__Approval__c WHERE Id = :event.TargetObjectId];

            // Find the user assigned to the approval
            Id assignedUserId = relatedApproval.sbaa__AssignedTo__c;

            // Query the user's profile ID
            User assignedUser = [SELECT ProfileId FROM User WHERE Id = :assignedUserId];
            Id assignedUserProfileId = assignedUser.ProfileId;

            // Query users by profile
            List<User> usersInProfile = [SELECT Id, Email FROM User WHERE ProfileId = :assignedUserProfileId];

            // Send emails to users in the profile
            for (User user : usersInProfile) {
                // Construct and send email notification
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setToAddresses(new String[]{user.Email});
                mail.setSubject('Approval Assignment Notification');
                mail.setPlainTextBody('An approval record has been assigned to a user in your profile.');
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }
        }
    }
}
 

 




/*
trigger MyApprovalTrigger on ProcessInstanceChangeEvent (after insert) {
    // Get the list of approval records
    List<sbaa__Approval__c> approvalsToUpdate = new List<sbaa__Approval__c>();

    for (ProcessInstanceChangeEvent event : Trigger.new) {
        if (event.TargetObjectId.getSObjectType() == SBQQ__Quote__c.SObjectType) {
            // Query the related Quote record
            SBQQ__Quote__c relatedQuote = [SELECT Id, OwnerId FROM SBQQ__Quote__c WHERE Id = :event.TargetObjectId];

            // Find the user profile of the assigned user
            Id assignedUserId = relatedQuote.OwnerId;
            User assignedUser = [SELECT Id, ProfileId FROM User WHERE Id = :assignedUserId];
            Id assignedUserProfileId = assignedUser.ProfileId;

            // Query users by profile
            List<User> usersInProfile = [SELECT Id, Email FROM User WHERE ProfileId = :assignedUserProfileId];

            // Send emails to users in the profile
            for (User user : usersInProfile) {
                // Construct and send email notification
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setToAddresses(new String[]{user.Email});
                mail.setSubject('Quote Approval Notification');
                mail.setPlainTextBody('A quote has been assigned for approval.');
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }
        }
    }
}

*/





















---------------------------------------------







// only on after insert 

trigger MyApprovalTrigger on ProcessInstanceChangeEvent (after insert) {
    // Iterate through the new ProcessInstanceChangeEvent records
    for (ProcessInstanceChangeEvent event : Trigger.new) {
        // Check if the event represents a change in an approval record
        if (event.TargetObjectId.getSObjectType() == sbaa__Approval__c.SObjectType) {
            // Query the related Approval record
            sbaa__Approval__c relatedApproval = [SELECT Id, sbaa__AssignedTo__c FROM sbaa__Approval__c WHERE Id = :event.TargetObjectId];

            // Find the user assigned to the approval
            Id assignedUserId = relatedApproval.sbaa__AssignedTo__c;

             // Query the assigned user's details
            User assignedUser = [SELECT Id, Name, Email, ProfileId FROM User WHERE Id = :assignedUserId];

            // Query users by profile
            List<User> usersInProfile = [SELECT Id, Email FROM User WHERE ProfileId = :assignedUser.ProfileId];

            // Send emails to users in the profile
            for (User user : usersInProfile) {
                // Construct and send email notification
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setToAddresses(new String[]{user.Email});
                mail.setSubject('Approval Assignment Notification');
                mail.setPlainTextBody('An approval record has been assigned to ' + assignedUser.Name + '.');
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }
        }
    }
}
 


















/*
// works on after insert and after update(not supports for after update)
trigger MyApprovalTrigger on ProcessInstanceChangeEvent (after insert, after update) {
    // Create a set to store the IDs of related approval records
    Set<Id> approvalIds = new Set<Id>();

    // Iterate through the new ProcessInstanceChangeEvent records
    for (ProcessInstanceChangeEvent event : Trigger.new) {
        // Check if the event represents a change in an approval record
        if (event.TargetObjectId.getSObjectType() == sbaa__Approval__c.SObjectType) {
            approvalIds.add(event.TargetObjectId);
        }
    }

    // Query the related Approval records
    List<sbaa__Approval__c> relatedApprovals = [SELECT Id, sbaa__AssignedTo__c FROM sbaa__Approval__c WHERE Id IN :approvalIds];

    // Iterate through the related Approval records
    for (sbaa__Approval__c relatedApproval : relatedApprovals) {
        // Find the user assigned to the approval
        Id assignedUserId = relatedApproval.sbaa__AssignedTo__c;

        // Query the assigned user's details
        User assignedUser = [SELECT Id, Name, Email, ProfileId FROM User WHERE Id = :assignedUserId];

        // Query users by profile
        List<User> usersInProfile = [SELECT Id, Email FROM User WHERE ProfileId = :assignedUser.ProfileId];

        // Send emails to users in the profile
        for (User user : usersInProfile) {
            // Construct and send email notification
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setToAddresses(new String[]{user.Email});
            mail.setSubject('Approval Assignment Notification');
            mail.setPlainTextBody('An approval record has been assigned to ' + assignedUser.Name + '.');
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }
}

*/





/*
trigger MyApprovalTrigger on ProcessInstanceChangeEvent (after insert) {
    // Get the list of approval records
    List<sbaa__Approval__c> approvalsToUpdate = new List<sbaa__Approval__c>();

    for (ProcessInstanceChangeEvent event : Trigger.new) {
        if (event.TargetObjectId.getSObjectType() == SBQQ__Quote__c.SObjectType) {
            // Query the related Quote record
            SBQQ__Quote__c relatedQuote = [SELECT Id, OwnerId FROM SBQQ__Quote__c WHERE Id = :event.TargetObjectId];

            // Find the user profile of the assigned user
            Id assignedUserId = relatedQuote.OwnerId;
            User assignedUser = [SELECT Id, ProfileId FROM User WHERE Id = :assignedUserId];
            Id assignedUserProfileId = assignedUser.ProfileId;

            // Query users by profile
            List<User> usersInProfile = [SELECT Id, Email FROM User WHERE ProfileId = :assignedUserProfileId];

            // Send emails to users in the profile
            for (User user : usersInProfile) {
                // Construct and send email notification
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setToAddresses(new String[]{user.Email});
                mail.setSubject('Quote Approval Notification');
                mail.setPlainTextBody('A quote has been assigned for approval.');
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }
        }
    }
}

*/




--------------------------------------



Editor is loading...
Leave a Comment