function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Babar Hussain 4Babar Hussain 4 

Apex logic

Requirement;
***This logic apply to only T&E Record Type.****
As per current logic, creating tasks and assign to Buy Desk when the amount is under 250K.
As per new logic, Create below list of Tasks and route approval to GSM LCM irrespective of Project Type and remove 250k price condition.
Data Privacy Review
Insurance Review
Supplier Diversity Review
Buy Desk Review
Technical Solution:
Update logic in below Apex class
CaseTriggerProcurementHandler
CaseTriggerProcurementHandlerTest

Can anyone please modify my apex code as per the requirement this is immediate deliver change, and the help won't be forgettable.
*****************************************************************************
********************************************************************************

@isTest
public class CaseTriggerProcurementHandlerTest {
    
    //Create test data, available for every test
    @testSetup 
    public static void testClassData() 
    {    
        
    }
    
    
    @isTest
    public static void testBuyDeskTask()
    {
        Id rtId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('Procurement_Professional_Services').getRecordTypeId();
        //Create Case
        case cse = New Case(
            RecordTypeId = rtId,
            Total_Expected_Cost_for_Duration__c = 20000,
            Region__c = 'APAC',
            Procurement_System__c = 'Non-Ariba'
        );
        insert cse;
        
        List<Task> tsklist = [Select Id FROM Task  WHERE WhatId = :cse.id];
        system.assertNotEquals(tsklist.size() , 0);
    }
    
        @isTest
    public static void testITBuyDeskTask()
    {
        Id rtId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('Procurement_Professional_Services').getRecordTypeId();
        //Create Case
        case cse = New Case(
            RecordTypeId = rtId,
            Total_Expected_Cost_for_Duration__c = 20000,
            Region__c = 'APAC',
            BRM_Listing__c ='scott.strong@sbdinc.com',
            BRM_Email_Address__c='scott.strong@sbdinc.com'
        );
        insert cse;
        
        List<Task> tsklist = [Select Id FROM Task  WHERE WhatId = :cse.id];
        system.assertNotEquals(tsklist.size() , 0);
    }
    
    @isTest
    public static void testLCMTask()
    {
        Id rtId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('Procurement_Professional_Services').getRecordTypeId();
        //Create Case
        case cse = New Case(
            RecordTypeId = rtId,
            Total_Expected_Cost_for_Duration__c = 260000,
            Region__c = 'APAC'
        );
        insert cse;
        
        List<Task> tsklist = [Select Id FROM Task  WHERE WhatId = :cse.id];
        system.assertNotEquals(tsklist.size() , 0);
    }
    
    @isTest
    public static void testITLCMTask()
    {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        Blob b = Crypto.GenerateAESKey(128);
        String h = EncodingUtil.ConvertTohex(b);
        String uid = h.SubString(0,8);
        User u = new User(Alias = uid, Email= uid + '@myorg.com', 
                          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
                          LocaleSidKey='en_US', ProfileId = p.Id, 
                          TimeZoneSidKey='America/New_York', UserName= uid +'mvkrish@myorg.com');
        insert u;
        Id rtId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('Procurement_Professional_Services').getRecordTypeId();
        //Create Case
        case cse = New Case(
            RecordTypeId = rtId,
            Total_Expected_Cost_for_Duration__c = 260000,
            Region__c = 'APAC',
            BRM_Listing__c ='scott.strong@sbdinc.com',
            Requestor_Email__c = 'testproc2@proc2.com',
            BRM_Email_Address__c='scott.strong@sbdinc.com'
        );
        insert cse;
        //KSAINI: June 14 2022
        List<Task> tsklist = [Select Id FROM Task  WHERE WhatId = :cse.id];
        system.assertNotEquals(tsklist.size() , 0);
        List<Task> updatelist = new List<Task>();
        for(Task t : tsklist)
        {
            t.Status = 'Completed';
            updatelist.add(t);
        }
        
        update updatelist;
        List<Case> listOfCases = [Select Id, Status from Case Where Id =:cse.Id];
        listOfCases[0].OwnerId = u.Id;
        //listOfCases[0].BRM_Email_Address__c ='test@test.com';
        update listOfCases;
        List<Case> listOfupdatedCase = [Select Id, Status from Case Where Id =:cse.Id];
        listOfupdatedCase[0].Status = 'Closed';
        update listOfupdatedCase;
        
    }
    
    @isTest
    public static void testTradeComplianceTask() //Covers Trade Compliance, risk and diversity
    {
        Id rtId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('Procurement_Professional_Services').getRecordTypeId();
        //Create Case
        case cse = New Case(
            RecordTypeId = rtId,
            Total_Expected_Cost_for_Duration__c = 260000,
            Region__c = 'APAC',
            Project_Type__c = 'New Contract'
        );
        insert cse;
        
        List<Task> tsklist = [Select Id FROM Task  WHERE WhatId = :cse.id];
        system.assertNotEquals(tsklist.size() , 0);
    }
    
    @isTest
    public static void testSourcingCouncilTask() //Covers Trade Compliance, risk and diversity
    {
        Id rtId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('Procurement_Professional_Services').getRecordTypeId();
        //Create Case
        case cse = New Case(
            RecordTypeId = rtId,
            Total_Expected_Cost_for_Duration__c = 600000
        );
        insert cse;
        
        List<Task> tsklist = [Select Id FROM Task  WHERE WhatId = :cse.id];
        system.assertNotEquals(tsklist.size() , 0);
    }
}
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Babar,

I see you have only shared the test class. There is not apex class handler . Can you also spefify what have you tried so far and where excatly you are struck.

In the requirement there is a word called route approval to GSM LCM. Is there any approval process and does the requiremenet meant to send the records for approval?

Thanks,
 
Babar Hussain 4Babar Hussain 4
public without sharing class CaseTriggerProcurementHandler {
    
    public static void handleprocurementCaseAfterInsert(List<SObject> newSobjs)
    {
        //Turn SObject list to case list
        List<Case> newCases = (List<Case>) newSobjs;
        
        //Get RT name, to match to the cmdt
        Map<ID,Schema.RecordTypeInfo> rt_Map = Case.sObjectType.getDescribe().getRecordTypeInfosById();

        //Create empty list of tasks to be inserted
        Task[] tskList = new List<Task>();
        
        //Create empty var to store the mapping of tasks that match the case record type
        List<Procurement_Case_Task_Settings__mdt> recordTypeSpecificMap = new List<Procurement_Case_Task_Settings__mdt>();
        
        //Will contain the list of tasks to be created if case details match the conditional logic
        List<Procurement_Case_Task_Settings__mdt> conditionalMap = new List<Procurement_Case_Task_Settings__mdt>();
        
        //Get case record type/task mappings
        Procurement_Case_Task_Settings__mdt[] fullTaskMapping = [Select Id, Task_Owner__c,Task_Record_Type__c, Task_Subject__c, Task_Status__c, Case_Record_Type__c, Task_Type__c, Label, Task_SLA_Days__c, Conditional_Creation__c 
                                                                 FROM Procurement_Case_Task_Settings__mdt];
        
        Id itRecTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('Procurement_IT').getRecordTypeId();
        
        Boolean buyDeskTaskCreated = false;
        Boolean projectTypePOSCT = false;
        
        //Loop through all cases in trigger
        for(case u : newCases){
            
            //Loop through the full task mapping
            for(Procurement_Case_Task_Settings__mdt fs : fullTaskMapping){
                
                //For the case record type, find all matching task mappings and add to a list
                If (fs.Case_Record_Type__c == rt_map.get(u.recordTypeID).getDeveloperName()){
                    recordTypeSpecificMap.add(fs);
                }
            }
            
            //Loop through specific mapping
            for(Procurement_Case_Task_Settings__mdt sm : recordTypeSpecificMap){
                
                //Create tasks with unconditional creation logic (Specified in the cmdt mapping)
                If (!sm.Conditional_Creation__c && u.Project_Type__c != 'PO/SCT Approval Only'){
                    Task tsk = New Task(
                        RecordTypeId = sm.Task_Record_Type__c,
                        Subject = sm.Task_Subject__c,
                        status = sm.Task_Status__c,
                        Type = sm.Task_Type__c,
                        OwnerId = sm.Task_Owner__c,
                        WhatId = u.id,
                        ActivityDate = date.today() + integer.valueof(sm.Task_SLA_Days__c));
                    tskList.add(tsk);
                } else {
                    
                    /**************************************
                    CONDITIONAL CREATION LOGIC
                    For all tasks where the CMDT mappng's Conditional_Creation__c is TRUE, check whether the case details match creation requirements
                    ***************************************/
                    //Create Buy Desk Review for non-IT case?
                    /*If (u.RecordTypeId != itRecTypeId &&
                        sm.Task_Type__c == 'Buy Desk Review' && 
                        u.Total_Expected_Cost_for_Duration__c < 250000 &&
                        u.Procurement_System__c == 'Ariba' &&
                        (u.Region__c == 'North America' || u.Region__c == 'EANZ')){
                        conditionalMap.add(sm);
                        buyDeskTaskCreated = true;
                    }*/
                    
                    //Create GSM LCM Review for non-IT case?
                    /*If (u.RecordTypeId != itRecTypeId && 
                        sm.Task_Type__c == 'GSM LCM Review' && 
                        !(u.Total_Expected_Cost_for_Duration__c < 250000 &&
                        u.Procurement_System__c == 'Ariba' &&
                        (u.Region__c == 'North America' || u.Region__c == 'EANZ'))){
                        conditionalMap.add(sm);
                    } */    
                    
                    //Create Buy Desk Review for IT case?
                    If (//u.RecordTypeId == itRecTypeId &&
                        sm.Task_Type__c == 'Buy Desk Review' && 
                        u.Total_Expected_Cost_for_Duration__c < 250000){
                        conditionalMap.add(sm); 
                           
                       buyDeskTaskCreated = true;
                    } 
Babar Hussain 4Babar Hussain 4
This is Apex code, And yes there is a approval process 

//Babar Hussain
      //*****************************************************************************************
       If (//u.RecordTypeId == itRecTypeId &&
                        sm.Task_Type__c == 'T & E' && 
                        u.Total_Expected_Cost_for_Duration__c < 250000){
                        conditionalMap.add(sm); 
                           
                       T&E = true;
                    } 
      //*****************************************************************************************
                    
                    //Create GSM LCM Review for IT case?
                    If (//u.RecordTypeId == itRecTypeId && 
                        sm.Task_Type__c == 'GSM LCM Review' && 
                        !(u.Total_Expected_Cost_for_Duration__c < 250000)){
                        conditionalMap.add(sm);
                    }
                    
                    
                    
                    //Create Trade Compliance Review? removed PO/SCT Approval Only
                    list <String> tcProjTypes = new List <String> {'Proof of Concept', 'New Contract', 'Sourcing Event (RFQ, RFP, RFI)'};
                        If (sm.Task_Type__c == 'Trade Compliance Review' && tcProjTypes.Contains(u.Project_Type__c)){
                            conditionalMap.add(sm);
                        }
                    
                    //Create Supplier Risk Review? 06/02:removed 'Amendment/SOW'
                    list <String> srProjTypes = new List <String> {'Contract Renewal/Renegotiation', 'Proof of Concept', 'New Contract', 'Sourcing Event (RFQ, RFP, RFI)'};
                        system.debug(srProjTypes);
                    If (sm.Task_Type__c == 'Supplier Risk Review' && srProjTypes.Contains(u.Project_Type__c)){
                        conditionalMap.add(sm);
                    }
                    
                    //Create Supplier Divesity Review?
                    list <String> sdProjTypes = new List <String> {'Amendment/SOW', 'Proof of Concept', 'New Contract', 'Sourcing Event (RFQ, RFP, RFI)'};
                        If (sm.Task_Type__c == 'Supplier Diversity Review' && sdProjTypes.Contains(u.Project_Type__c)){
                            conditionalMap.add(sm);
                        }
                    
                    //Create Sourcing Council Review? 
                    If (sm.Task_Type__c == 'Sourcing Council Review' && (u.Total_Expected_Cost_for_Duration__c >= 500000)){
                        conditionalMap.add(sm);
                    }
                }
            }
            
            //Create tasks with conditional creation logic 
            for(Procurement_Case_Task_Settings__mdt cMap : conditionalMap){
                Task tsk = New Task(
                    RecordTypeId = cMap.Task_Record_Type__c,
                    Subject = cMap.Task_Subject__c,
                    status = cMap.Task_Status__c,
                    Type = cMap.Task_Type__c,
                    OwnerId = cMap.Task_Owner__c,
                    WhatId = u.id,
                    ActivityDate = date.today() + integer.valueof(cMap.Task_SLA_Days__c));
                tskList.add(tsk);
            }
        }
        
        //Scott 05/06/22 If Buy Desk Review Task is created, then Data Privacy Review and Insurance Review should also be routed to Buy Desk Team, not to LCM GSM Team
        if(buyDeskTaskCreated == true){
            for(task tsk : tskList){
                if(tsk.Type == 'Data Privacy Review' || tsk.Type == 'Insurance Review' ){
                    tsk.OwnerId = '00G4x000000S8Wj'; //buydesk queue
                }
            }
        }
        
        //Insert List of all tasks
        Insert tskList;
    }
    
    public static void handleprocurementCaseBeforeUpdate(List<SObject> newSobjs, List<SObject> oldSobjs)
    {
        //Turn SObject list to case list
        List<Case> newCases = (List<Case>) newSobjs;
        List<Case> OldCases = (List<Case>) oldSobjs;
        Map<Id, Case> mapOfExistingRecords = new Map<Id, Case>();
        Set<Id> setOfCaseId = new Set<Id>();
        Set<Id> setOfCases = new Set<Id>();
        Set<Id> setOfOnHoldCases = new Set<Id>();
        List<Task> listOfTasks = new List<Task>();
        List<Task> listOfColsedTasks = new List<Task>();
        List<Task> listOfUpdateTasks = new List<Task>();
        List<Task> listOfUpdateTask = new List<Task>();
        
        Boolean isApprovalRejected = false;
        
         List<ProcessInstance > listOfProcessInstance  = new List<ProcessInstance>();
        List<ProcessInstance > listOfClosedProcessInstance  = new List<ProcessInstance>();
        
        ID userId = UserInfo.getUserId();
        List<Group> pGroupList = [SELECT Id, Name FROM Group WHERE Type = 'Regular' And name ='GSM Spend Control Tower'];
        Set<ID> setGroupId = new Set<Id>();
        List<GroupMember> ListGM  = new List<GroupMember>();
        for(Group g : pGroupList)
        {
            setGroupId.add(g.Id);
        }
        system.debug('setGroupId--?'+setGroupId);        
        if(!setGroupId.isEmpty())
        {
            ListGM  = [Select Id from GroupMember where UserOrGroupID =:userId and GroupId  in :setGroupId];
        }
        for(Case c : OldCases)
        {
            mapOfExistingRecords.put(c.Id, c);
        }
        
        for(Case cse : newCases)
        {
            Case oldcase = (Case)mapOfExistingRecords.get(cse.Id);
            
            if(cse.Status == 'Closed' && oldcase.Status != 'Closed')
            {
                setOfCaseId.add(cse.Id);
            }
        }
        
        If(!setOfCaseId.isEmpty())
        {
            listOfTasks = [Select id,Status from Task where WhatId IN:setOfCaseId];
            listOfProcessInstance = [SELECT TargetObjectId, Status, Id FROM ProcessInstance where TargetObjectId IN:setOfCaseId 
                                         ORDER BY CreatedDate DESC 
                                         Limit 1];
            system.debug('listOfProcessInstance-->'+listOfProcessInstance);
            if(!listOfTasks.isEmpty())
            {
                for(Task t : listOfTasks)
                {
                    system.debug('t.Status-->'+t.Status);
                    if(t.Status == 'Completed'  || t.Status == 'No Longer Required')
                    {
                        listOfColsedTasks.add(t);
                    }
                }
            }
            
            /*if(!listOfProcessInstance.isEmpty())
            {
                for(ProcessInstance p : listOfProcessInstance)
                {
                    if(p.Status == 'Approved')
                    {
                        listOfClosedProcessInstance.add(p);
                    }
                }
            }*/
            
        }
        
        for(Case cse : newCases)
        {
            Case oldcase = (Case)mapOfExistingRecords.get(cse.Id);
            if(cse.Status == 'Closed' && oldcase.Status != 'Closed')
            {
                if(!ListGM.isEmpty())
                {
                    cse.OwnerId = userId;
                                   
                }
                
                if(!listOfProcessInstance.isEmpty())
                {
                    for(ProcessInstance p : listOfProcessInstance)
                    {
                        system.debug('p.Status-->'+p.Status);
                        
                        if(p.Status == 'Pending')
                        {
                            cse.addError('Please complete all the approval before you close the case');
                        }
                        
                         if(p.Status == 'Rejected')
                         {
                             isApprovalRejected = true;
                         }
                    }
                }
                
                if(!listOfTasks.isEmpty())
                {
                    if(listOfTasks.Size()!=listOfColsedTasks.size())
                    {
                        if(isApprovalRejected == false)
                        {
                            cse.addError('Please close all the taks before you close the case');
                        }
                        
                        
                    }
                }
                
                
                }
                    
            
        }
        
        for(Case cse : newCases)
        {
            Case oldcase = (Case)mapOfExistingRecords.get(cse.Id);
            
            if(cse.Status == 'Hold' && oldcase.Status != 'Hold')
            {
                system.debug('cse.Status-->'+cse.Status);
                if(ListGM.isEmpty())
                {
                    cse.addError('You can not change the Status');
                }
                else{
                    setOfCases.add(cse.Id);
                }
            }
        }
        
        if(!setOfCases.isEmpty())
        {
            listOfTasks = [Select id,Status,ActivityDate  from Task where WhatId IN:setOfCases];
            system.debug('cse.listOfTasks-->'+listOfTasks);
            for(Task t : listOfTasks)
            {
                if(t.Status == 'In-Progress')
                {
                    t.Status = 'On Hold';
                    listOfUpdateTasks.add(t);
                }
            }
            
            if(!listOfUpdateTasks.isEmpty())
            {
                system.debug('listOfUpdateTasks-->'+listOfUpdateTasks);
                update listOfUpdateTasks;
                system.debug('listOfUpdateTasks-->'+listOfUpdateTasks);
            }
        }
        
        
        
        for(Case cse : newCases)
        {
            Case oldcase = (Case)mapOfExistingRecords.get(cse.Id);
            
            if(cse.Status != 'Hold' && oldcase.Status == 'Hold')
            {
                if(ListGM.isEmpty())
                {
                    cse.addError('You can not change the Status');
                }
                else{
                    setOfOnHoldCases.add(cse.Id);
                }
            }
        }
        
        if(!setOfOnHoldCases.isEmpty())
        {
            listOfTasks = [Select id,Status,ActivityDate  from Task where WhatId IN:setOfOnHoldCases];
            
            system.debug('listOfTasks-->'+listOfTasks);
            for(Task t : listOfTasks)
            {
                if(t.Status == 'On Hold')
                {
                    t.Status = 'In-Progress';
                    listOfUpdateTask.add(t);
                }
            }
            
            if(!listOfUpdateTask.isEmpty())
            {
                system.debug('listOfUpdateTask-->'+listOfUpdateTask);
                update listOfUpdateTask;
            }
        }

    }
   /* public static void handleprocurementCaseAfterUpdate(List<SObject> newSobjs, Map<Id,SObject> newSobjsMap , Map<Id,SObject> oldSobjsMap)
    {
        system.debug('InssireUpdate-->');
       Set<Id> setOfCaseId = new Set<Id>(); 
        ID userId = UserInfo.getUserId();
        List<Task> listOfTasks = new List<Task>();
        List<Task> listOfColsedTasks = new List<Task>();
        List<ProcessInstance > listOfProcessInstance  = new List<ProcessInstance>();
        List<ProcessInstance > listOfClosedProcessInstance  = new List<ProcessInstance>();
        
        for(Case caseInstance:(List<Case>)newSobjs)
        {
            Case oldcases = (Case)oldSobjsMap.get(caseInstance.Id);
             system.debug('InssireUpdate2-->');
            if(caseInstance.Status == 'Closed' && oldcases.Status != 'Closed')
            {
                 system.debug('InssireUpdate3-->');
                setOfCaseId.add(caseInstance.Id);
            }
        }
        system.debug('setOfCaseId-->'+setOfCaseId);
        If(!setOfCaseId.isEmpty())
        {
            listOfTasks = [Select id,Status from Task where WhatId IN:setOfCaseId];
            
            system.debug('listOfTasks-->'+listOfTasks);
            listOfProcessInstance = [SELECT TargetObjectId, Status, Id FROM ProcessInstance where TargetObjectId IN:setOfCaseId 
                                         ORDER BY CreatedDate DESC 
                                         Limit 1];
            system.debug('listOfProcessInstance-->'+listOfProcessInstance);
            if(!listOfTasks.isEmpty())
            {
                for(Task t : listOfTasks)
                {
                    if(t.Status != 'Completed')
                    {
                        t.OwnerId = userId;
                        t.Status = 'Completed';
                        listOfColsedTasks.add(t);
                    }
                }
            }
            if(!listOfColsedTasks.isEmpty())
            {
                //update listOfColsedTasks;
            }
            
            if(!listOfProcessInstance.isEmpty())
            {
                for(ProcessInstance p : listOfProcessInstance)
                {
                    if(p.Status == 'Pending')
                    {
                        //p.Status = 'Rejected';
                        listOfClosedProcessInstance.add(p);
                    }
                }
            }
            if(!listOfClosedProcessInstance.isEmpty())
            {
                //update listOfClosedProcessInstance;
            }
            
        }
        
        
        
    }*/
}
Babar Hussain 4Babar Hussain 4


User-added imageUser-added image
Babar Hussain 4Babar Hussain 4
This is the approval Process and splitted my apex code coz it not allowing to share entire code 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Babar,

By checking the code in Glance I understand that as of now we have condition of Total_Expected_Cost_for_Duration__c>250k for creation of tasks. As per the requirement we have to remove that condition. 

Where excatly you are facing the issue in removing the condition? 

Thanks,
 
Babar Hussain 4Babar Hussain 4
Thanks for the reply very quickly , But mu doubt is 
As per new logic, Create below list of Tasks and route approval to GSM LCM irrespective of Project Type and remove 250k price condition.
Data Privacy Review
Insurance Review
Supplier Diversity Review
Buy Desk Review


How I need to assign these tasks to GSM LCM group and how to remove for this process to BUy Desk Team 
So Where I need to go & Chnage the code. & Process.


As per current logic, creating tasks and assign to Buy Desk when the amount is under 250K.

Data Privacy Review
Insurance Review
Supplier Diversity Review
Buy Desk Review
As per new logic, Create below list of Tasks and assign to GSM LCM irrespective of Project Type
Data Privacy Review
Insurance Review
Supplier Diversity Review
Buy Desk Review