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
Frederick H LaneFrederick H Lane 

Automate Record Creation - Apex Specialist

I'm getting the following error;
"Challenge Not yet complete... here's what's wrong: 
Inserting a new Maintenance Request of type 'Routine Maintenance' and then closing it did not create of a new Maintenance Request based upon the original record correctly. The challenge is expecting to find the closed Maintenance Request plus an 'New' Maintenance Request of type 'Routine Maintenance' with the same Vehicle as the closed one."
I have had a look at the forum links you provided in a previous post but it's not resolving.

I have added 'Routine Maintenance' and 'Repair' in Case field Type. (Why should this be needed and this type is inconsistent with the other picklist types e.g Electrical, Structural etc)
I also include a filed 'Old Case' to store the Case ID once closed. The challenge is to automate through writing the trigger and the helkper class right? No test class is required at this stage?
Here is my code;
___________________________________________________________
trigger MaintenanceRequest on Case (before update, after update) {  
    List<case>ClosedCaseList = [SELECT Id, subject,Reason, Vehicle__c, vehicle__r.Name, equipment__c,type 
                                FROM Case WHERE Id IN :Trigger.New 
                                AND (status = 'closed' AND (type = 'Repair' OR type = 'Routine Maintenance'))];   
    Map<Id, Case>CasesToConsider = new Map<Id, Case>();
    for(Case c: ClosedCaseList){
        Boolean alreadyClosed = Trigger.oldMap.get(c.Id).Status.equals('Closed') ;
        if(!alreadyClosed)
        {
            CasesToConsider.put(c.id, c);
        }
    }
    
    List<Work_Part__c> allWorkParts = [SELECT ID, Equipment__c, Maintenance_Request__c, 
                Quantity__c, Equipment__r.Maintenance_Cycle__c FROM Work_Part__c 
                WHERE Maintenance_Request__c in: CasesToConsider.keySet()];
    
    MaintenanceRequestHelper.updateWorkOrders(CasesToConsider, allWorkParts);       
}

___________________________________________________________
public class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(List<Case> maintenanceRequests){

        Set<Case> targetRequests = new Set<Case>();
        for (Case mr : maintenanceRequests)
            if (('Repair' == mr.Type || 'Routine Maintenance' == mr.Type) && 'Closed' == mr.Status)
                targetRequests.add(mr);

        List<AggregateResult> results = [
            SELECT Maintenance_Request__c, MIN(Equipment__r.Maintenance_Cycle__c)
            FROM Work_Part__c
            WHERE Maintenance_Request__c IN :targetRequests
            GROUP BY Maintenance_Request__c
        ];

        Map<Id, Integer> requestToMinCycle = new Map<Id, Integer>();
        for (AggregateResult ar : results)
            requestToMinCycle.put(
                (Id)ar.get('Maintenance_Request__c'),
                ((Double)ar.get('expr0')).intValue()
            );

        List<Case> workOrders = new List<Case>();
        for (Case t : targetRequests)
            if (('Repair' == t.Type || 'Routine Maintenance' == t.Type) && 'Closed' == t.Status)
                workOrders.add(new Case(
                    Vehicle__c=t.Vehicle__c,
                    Type='Routine Maintenance',
                    Subject=t.Subject,
                    Status='New',
                    Date_Reported__c=Date.today(),
                    Date_Due__c=Date.today().addDays(requestToMinCycle.get(t.Id))
                ));
        
        if (!workOrders.isEmpty())
            insert workOrders;
    } 
}
Best Answer chosen by Frederick H Lane
Frederick H LaneFrederick H Lane
Still no help

All Answers

NagendraNagendra (Salesforce Developers) 
Hi Frederick,

May I suggest you please check with below link from the forums community with a similar discussion which might help. Please let us know if this helps.

Thanks,
Nagendra
Frederick H LaneFrederick H Lane
No it hasn't helped. Please can you read my text as I did specify that the forums weren't helping? Kind Regards
Frederick H LaneFrederick H Lane
Still no help
This was selected as the best answer
Nidhi gupta 150Nidhi gupta 150
Change the labels for Case and Product To Maintenance Request and Vehicle respectively.
Go to Setup -> Customize -> Tab Names and Labels -> Rename Tabs and Labels.

Codes that worked for me

trigger MaintenanceRequest on Case (before update, after update) {
    // ToDo: Call MaintenanceRequestHelper.updateWorkOrders
    if(Trigger.isAfter)
                 MaintenanceRequestHelper.updateWorkOrders(Trigger.New);
                
            
    }

Update the Helper class

public with sharing class MaintenanceRequestHelper {
    public static void updateWorkOrders(List<Case> caseList) {
        List<case> newCases = new List<Case>();
        Map<String,Integer> result=getDueDate(caseList);
        for(Case c : caseList){
            if(c.status=='closed')
                if(c.type=='Repair' || c.type=='Routine Maintenance'){
                    Case newCase = new Case();
                    newCase.Status='New';
                    newCase.Origin='web';
                    newCase.Type='Routine Maintenance';
                    newCase.Subject='Routine Maintenance of Vehicle';
                    newCase.Vehicle__c=c.Vehicle__c;
                    newCase.Equipment__c=c.Equipment__c;
                    newCase.Date_Reported__c=Date.today();
                    if(result.get(c.Id)!=null)
                     newCase.Date_Due__c=Date.today()+result.get(c.Id);
                    else
                        newCase.Date_Due__c=Date.today();
                    newCases.add(newCase);
                }
        }        
        insert newCases;   
    }
    //
    public static  Map<String,Integer> getDueDate(List<case> CaseIDs){       
       Map<String,Integer> result = new Map<String,Integer>();
        Map<Id, case> caseKeys = new Map<Id, case> (CaseIDs);        
       List<AggregateResult> wpc=[select Maintenance_Request__r.ID cID,min(Equipment__r.Maintenance_Cycle__c)cycle
                      from Work_Part__c where  Maintenance_Request__r.ID in :caseKeys.keySet() group by             Maintenance_Request__r.ID ];
        for(AggregateResult res :wpc){
            Integer addDays=0;
            if(res.get('cycle')!=null)
                addDays+=Integer.valueOf(res.get('cycle'));
            result.put((String)res.get('cID'),addDays);
        }
        return result;
}

}
 
gangineni manoj 10gangineni manoj 10
Use this class and create the new field in Equipment in case object  and allow the reparenting
Equipment Maintenance Item for the Master detail object. 

If it's resolved, Please mark this as Best Answer. 

public class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(List<Case> updatedWOs, Map<Id,Case> oldCaseMap){
        Set<Id> validWOIds = new Set<Id>(); //set of valid work order IDs 
        
        //going thru updatedWOs and checking if there is closed one AND of type repair/routine maintenance -> throw it into our Set then
        for (Case c: updatedWOs) {
            if (oldCaseMap.get(c.Id).Status != 'Closed' && c.Status == 'Closed') {
                if (c.Type == 'Repair' || c.Type == 'Routine Maintenance') {
                    validWOIds.add(c.Id);
                }
            }
        } 
        
        //If our Set is NOT empty,we calculate times  
        if (!validWOIds.isEmpty()) {
            List<Case> newCases = new List<Case>();
         
            Map<Id, Case>closedCaseMap = new Map<Id, Case>(updatedWOs);
        
            Map<Id, Decimal> maintCycleMap = new Map<Id, Decimal>();
            AggregateResult[] results = [SELECT Maintenance_Request__c, MIN(Equipment__r.Maintenance_Cycle__c)cycle
                                         FROM Equipment_Maintenance_Item__c 
                                         WHERE Maintenance_Request__c IN :validWOIds 
                                         GROUP BY Maintenance_Request__c];
            
            List<Equipment_Maintenance_Item__c> itemList = [SELECT Id, Maintenance_Request__c
                                         FROM Equipment_Maintenance_Item__c 
                                         WHERE Maintenance_Request__c IN :validWOIds];
            
            //put every result into map with Id as key and Decimal as its value
            for (AggregateResult ar : results) {
                maintCycleMap.put((Id) ar.get('Maintenance_Request__c'), (Decimal) ar.get('cycle') );
            }
            
            //Creating new cases here
            for (Id caseId: validWOIds){
                Case cc = closedCaseMap.get(caseId);
                Case nc = new Case (ParentId = cc.Id,
                                    Status = 'New',
                                    Subject = 'Routine Maintenance',
                                    Type = 'Routine Maintenance',
                                    Vehicle__c = cc.Vehicle__c,
                                    Equipment__c = cc.Equipment__c,
                                    Origin = 'Web',  
                                    Date_Reported__c = Date.today());
                
                //calculating the maintenance request due dates
                nc.Date_Due__c = Date.today().addDays((Integer) maintCycleMap.get(cc.Id));
                newCases.add(nc);
            }
            
            insert newCases;
            

            List<Equipment_Maintenance_Item__c> copiedWorkParts = new List<Equipment_Maintenance_Item__c>();
            //cloning work parts here
            for (Case nc: newCases) {
                //going thru closedCaseMap and giving workparts right case ID
                for (Equipment_Maintenance_Item__c workparts: itemList) {
                    if (workparts.Maintenance_Request__c == nc.ParentId){
                       workparts.Maintenance_Request__c = nc.Id;
                    copiedWorkParts.add(workparts); 
                    }
                }
            }
            update copiedWorkParts;
        }     
    }
}
 
Aman Raj SaxenaAman Raj Saxena
I am listing down the step-by-step solution. Please complete the prerequisites mentioned on the Apex specialist challenge page.

Please do like the answer if it works out for you.

Create below fields in case the object
Cloned Case Id text(255)
Equipment Lookup(equipment)

Code for MainttenceRequestHelper class
public with sharing class MaintenanceRequestHelper {
    public static void updateWorkOrders(List<Case> caseList) {
        List<case> newCases = new List<Case>();
        Map<String,Integer> result=getDueDate(caseList);
        list<Equipment_Maintenance_Item__c> itemsListToinsert= new list<Equipment_Maintenance_Item__c>();
      Map<String,list<Equipment_Maintenance_Item__c>> resultItmes=getMaintainanceItems(caseList);
        for(Case c : caseList){
            if(c.status=='closed')
                if(c.type=='Repair' || c.type=='Routine Maintenance'){
                    Case newCase = new Case();
                    newCase.Status='New';
                    newCase.Origin='web';
                    newCase.Type='Routine Maintenance';
                    newCase.Subject='Routine Maintenance of Vehicle';
                    newCase.Vehicle__c=c.Vehicle__c;
                    newCase.Equipment__c=c.Equipment__c;
                    newCase.Date_Reported__c=Date.today();
                    newcase.Cloned_Case_Id__c=c.Id;
                    if(result.get(c.Id)!=null)
                     newCase.Date_Due__c=Date.today()+result.get(c.Id);
                    else
                        newCase.Date_Due__c=Date.today();
                    newCases.add(newCase);
                }
        }        
       if(newCases.size()>0)
       {  	
           insert newCases; 
           
           for(Case c : newCases){
             List<Equipment_Maintenance_Item__c> temp =  resultItmes.get(c.Cloned_Case_Id__c);
               if(temp !=null){
                    for(Equipment_Maintenance_Item__c row:temp){
                    Equipment_Maintenance_Item__c newitem = new Equipment_Maintenance_Item__c();
                        newitem.Equipment__c=row.Equipment__c;
                        newitem.Maintenance_Request__c= c.Id;
                        newitem.Quantity__c= row.Quantity__c;  
                        itemsListToinsert.add(newitem);
                        
                    }
               }
               
           }
           
           
       }
        
       if(itemsListToinsert.size()>0)
           insert itemsListToinsert;
    }
    //
    public static  Map<String,Integer> getDueDate(List<case> CaseIDs){       
       Map<String,Integer> result = new Map<String,Integer>();
        Map<Id, case> caseKeys = new Map<Id, case> (CaseIDs);        
       List<AggregateResult> wpc=[select Maintenance_Request__r.ID cID,min(Equipment__r.Maintenance_Cycle__c)cycle
                      from Equipment_Maintenance_Item__c where  Maintenance_Request__r.ID in :caseKeys.keySet() and Equipment__r.Maintenance_Cycle__c != null group by             Maintenance_Request__r.ID ];
        for(AggregateResult res :wpc){
            Integer addDays=0;
            if(res.get('cycle')!=null)
                addDays+=Integer.valueOf(res.get('cycle'));
            result.put((String)res.get('cID'),addDays);
        }
        return result;
}
    
    
     public static Map<String,list<Equipment_Maintenance_Item__c>> getMaintainanceItems(List<case> CaseIDs){       
     
       Map<String,list<Equipment_Maintenance_Item__c>> mapofMaintainanceItems = new Map<String,list<Equipment_Maintenance_Item__c>>();
        Map<Id, case> caseKeys = new Map<Id, case> (CaseIDs);        
       list<Equipment_Maintenance_Item__c> lstrec = new  list<Equipment_Maintenance_Item__c>([select id ,Maintenance_Request__c,Equipment__c,Quantity__c  
                      from Equipment_Maintenance_Item__c where  Maintenance_Request__r.ID in :caseKeys.keySet() ]);
        
         for(Equipment_Maintenance_Item__c row:lstrec){
              
                if (mapofMaintainanceItems.containsKey(row.Maintenance_Request__c)) {
                    List<Equipment_Maintenance_Item__c> temp = mapofMaintainanceItems.get(row.Maintenance_Request__c);
						temp.add(row);
					mapofMaintainanceItems.put(row.Maintenance_Request__c, temp);
                }
				else{
                    mapofMaintainanceItems.put(row.Maintenance_Request__c, new List<Equipment_Maintenance_Item__c> { row });
                }    
               		
         }
         
        return mapofMaintainanceItems;
}
    
    
}

code for Maintainence Request Trigger
trigger MaintenanceRequest on Case (before update, after update) {
    // ToDo: Call MaintenanceRequestHelper.updateWorkOrders
    if(Trigger.isAfter)
                 MaintenanceRequestHelper.updateWorkOrders(Trigger.New);
}

 
Vibhav JoshiVibhav Joshi
@Aman Raj Saxena Thank you for the code it worked!
 
Hanusha GanjiHanusha Ganji
hi 
@Vibhav Joshi , Is the code still working, it seems the challenge got updated
Variable does not exist: Equipment__c........> getting this error
nelson dandenelson dande
@hanusha Ganji

Create below fields in case the object
Cloned Case Id text(255)
Equipment Lookup(equipment)
Veera Lakshmi VaidadiVeera Lakshmi Vaidadi
@Aman Raj Saxena.......you are awsome bro i was stuck here from 1 week u r the only one who gives right direction ....thanks a lot brother