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
bobnunny1bobnunny1 

Superbadge APEX Error

Performing the first Challenge of this Superbadge for APEX, I am receiving the below error. But it is not true because the Maintenance Request does indeed have all of the attributes cited when I try via the GUI and via a Test Class. Can someone please tell me what is wrong?

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.

(Also, the challenge didn't specifically mention that the Case and Product2 objects should be relabeled)
Best Answer chosen by bobnunny1
Yogesh DYogesh D
No problem. Even I faced the same problem earlier. Check my this post https://developer.salesforce.com/forums/ForumsMain?id=906F0000000kEvmIAE (http://No problem. Even I faced the same problem earlier. Check my this post https://developer.salesforce.com/forums/ForumsMain?id=906F0000000kEvmIAE)

All Answers

bobnunny1bobnunny1
To be clear, when the Case is Closed with the applicable Type and Status, it creates a new case with a due date of the date of the work part product maintenance cycle, and the related work part.  The test class and GUI confirm this.  What else is it looking for?
Yogesh DYogesh D

Error here states that the new case that you are creating should have the same value in the field Vehicle__c as the old case that you have closed. And the type of the new case that you areting should be set to 'Routine Maintenance'.

I guess you are missing this statement somewhere... (newCase.Vehicle__c = oldCase.Vehicle__c; before inserting the newCase)

bobnunny1bobnunny1
It does.  I've double-checked and my test class confirms it.

                        caseInsLIST.add(new Case(
                            Subject = caseItem.ID + ' Scheduled Checkup', 
                            Description = caseItem.ID + ' Scheduled Checkup for related Work Part', 
                            Vehicle__c = caseItem.Vehicle__c, 
                            Type = 'Routine Maintenance', 
                            Date_Reported__c = system.Today(), 
                            Date_Due__c = system.Today() + (wpItem.Equipment__r.Maintenance_Cycle__c == null ? 0 : (integer) wpItem.Equipment__r.Maintenance_Cycle__c)));
 
Yogesh DYogesh D
Can you please specify what exactly is caseItem here in your code? you can try posting your full code here.... will debug it for you...
Abhishek Malik 9Abhishek Malik 9
Hi yogesh
can you please help me to earn super badge actually am trying to learn apex and now finally am just started the super badges am beginer in salesforce but for "Automate record creation" part am not getting the requirement please explain me and also send me code please if you can.
Jeff DouglasJeff Douglas
Please post the code for you trigger's helper class and I'll take a look.

Jeff Douglas
Trailhead Developer Advocate
bobnunny1bobnunny1
Thanx Jeff, below is what I have so far and my test class works for 300 as well as the GUI.  I assert the new cases, new work parts, and Vehicle got carried over.  The TestFlag is so that I can cover the Catch block and errors during Insert. Thanx.
 
public class MaintenanceRequestHelper {
    /*
    Created By: Robert Nunemaker
    Created On: 06/29/2016
    Purpose: APEX SuperBadge Case Maintenance functionality
    --------------------------------------------------------------------------
    Modified By:    
    Modified On:  
    Modification: 
    */
    
    public static string strTestFlag = '';
    
    public static void updateWorkOrders(MAP<ID, Case> triggerOldMAP, MAP<ID, Case> triggerNewMAP){

        try {            
            if (strTestFlag == 'Try') integer nThrowTestError = 1 / 0;
            
            // Get ID's in scope
            LIST<Case> caseLIST = new LIST<Case>();
            system.debug('triggerOldMAP: ' + triggerOldMAP);
            system.debug('triggerNewMAP: ' + triggerNewMAP);
            for (ID caseID : triggerNewMAP.keySet()) {
                if ((triggerOldMAP.get(caseID).Type <> triggerNewMAP.get(caseID).Type
                    || triggerOldMAP.get(caseID).Status <> triggerNewMAP.get(caseID).Status)
                    && triggerNewMAP.get(caseID).Status == 'Closed'
                    && (triggerNewMAP.get(caseID).Type == 'Routine Maintenance' || triggerNewMAP.get(caseID).Type == 'Repair')) {
                    
                    caseLIST.add(triggerNewMAP.get(caseID));
                    system.debug('caseLIST: ' + caseLIST);
                } // END if (triggerOldMAP.get(caseID).Type <> triggerNewMAP.get(caseID).Type...
            } // END for (Case caseItem : triggerNewLIST)
            
            // Get full records needed in scope
            LIST<Case> caseScopeLIST = new LIST<Case>();
            if (caseLIST.size() > 0) {
                caseScopeLIST = 
                    [select ID, Vehicle__c, Type, Status,
                            (select ID, Name, Equipment__c, Quantity__c, Maintenance_Request__c, Equipment__r.Maintenance_Cycle__c from Work_Parts__r)
                        from Case
                        where ID in :caseLIST];
                system.debug('caseScopeLIST: ' + caseScopeLIST);
            } // END if (caseLIST.size() > 0)
            
            // Create new Cases and Work Parts for records in scope
            if (caseScopeLIST.size() > 0) {
                MAP<integer, string> errToReqMAP = new MAP<integer, string>();
                LIST<Case> caseInsLIST = new LIST<Case>();
                LIST<Work_Part__c> wpInsLIST = new LIST<Work_Part__c>();
                MAP<integer, Work_Part__c> newCaseWPMAP = new MAP<integer, Work_Part__c>();
    
				integer nRcdNbr = 0;
                for (Case caseItem : caseScopeLIST) {    
                    for (Work_Part__c wpItem : caseItem.Work_Parts__r) {
                        caseInsLIST.add(new Case(
                            Subject = caseItem.ID + ' Scheduled Checkup', 
                            Description = caseItem.ID + ' Scheduled Checkup for related Work Part', 
                            Vehicle__c = caseItem.Vehicle__c, 
                            Type = (strTestFlag <> 'Case' ? 'Routine Maintenance' : 'Routine Maintenance Routine Maintenance Routine Maintenance Routine Maintenance Routine Maintenance'), 
                            Date_Reported__c = system.Today(), 
                            Date_Due__c = system.Today() + (wpItem.Equipment__r.Maintenance_Cycle__c == null ? 0 : (integer) wpItem.Equipment__r.Maintenance_Cycle__c)));
                        newCaseWPMAP.put(nRcdNbr, new Work_Part__c(Equipment__c = wpItem.Equipment__c, Quantity__c = wpItem.Quantity__c, Maintenance_Request__c = wpItem.Maintenance_Request__c)); // Maintenance_Request__c will be replaced if successful
                        nRcdNbr ++;
                    } // END for (Work_Part__c wpItem : caseItem.Work_Parts__r)
                } // END for (Case caseItem : caseScopeLIST)
                system.debug('caseInsLIST: ' + caseInsLIST);
                system.debug('newCaseWPMAP: ' + newCaseWPMAP);
                
                if (caseInsLIST.size() > 0) {
                    nRcdNbr = 0;
                    Work_Part__c wpItem = new Work_Part__c();
                    MAP<integer, integer> wpToNewCaseMAP = new MAP<integer, integer>();
                    
                    for (database.SaveResult srItem : database.insert(caseInsLIST, false)) {
                        system.debug('srItem: ' + srItem);
                        if (!srItem.IsSuccess()) {
                            system.debug('Error Detected on Case Insert for Record ' + string.valueOf(nRcdNbr) + ': ' + srItem);
                            triggerNewMAP.get(caseInsLIST[nRcdNbr].Subject.left(18)).addError('Error creating Scheduled Case for Case ID: ' + caseInsLIST[nRcdNbr].Subject.left(18) + ', Error: ' + srItem.getErrors()[0].getMessage());
                        } else {
                            wpItem = new Work_Part__c();
                            wpItem = newCaseWPMAP.get(nRcdNbr);
                            wpItem.Maintenance_Request__c = srItem.getID();
                            wpInsLIST.add(wpItem);
                            wpToNewCaseMAP.put(wpInsLIST.size() - 1, nRcdNbr);
                        } // END if (!srItem.IsSuccess())
                        nRcdNbr ++;
                    } // END for (database.SaveResult srItem : database.insert(caseInsLIST, false))
                    system.debug('wpToNewCaseMAP: ' + wpToNewCaseMAP);
                    
                    if (wpInsLIST.size() > 0) {
                        nRcdNbr = 0;
                        for (database.SaveResult srItem : database.insert(wpInsLIST, false)) {
                            system.debug('srItem: ' + srItem);
                            if (!srItem.IsSuccess() || strTestFlag == 'WorkPart') {
                                system.debug('Error Detected on Work Part Insert for Record ' + string.valueOf(nRcdNbr) + ': ' + srItem);
                                string strError = (strTestFlag == 'WorkPart' ? 'Testing Error from Test Class' : srItem.getErrors()[0].getMessage());
                                triggerNewMAP.get(caseInsLIST[wpToNewCaseMAP.get(nRcdNbr)].Subject.left(18)).addError('Error creating Scheduled Work Part for Case ID: ' + caseInsLIST[wpToNewCaseMAP.get(nRcdNbr)].Subject.left(18) + ', Error: ' + strError);
                            } // END if (!srItem.IsSuccess())
                            nRcdNbr ++;
                        } // END for (database.SaveResult srItem : database.insert(wpInsLIST, false))
                    } // END if (wpInsLIST.size() > 0)
                    
                } // END if (caseInsLIST.size() > 0)
                
            } // END if (caseScopeLIST.size() > 0)
        } catch (exception e) {
            for (string caseID : triggerNewMAP.keySet()) {
                triggerNewMAP.get(caseID).addError('Unexpected Error creating Scheduled Case for Case ID: ' + e.getMessage());
            } // END for (string caseID : triggerNewMAP.keySet())
        } // END try
        
    } // END updateWorkOrders
    
} // END MaintenanceRequestHelper

 
Jeff DouglasJeff Douglas
bobnunny1, If you want to email me (jdouglas@salesforce.com) your DE org login credentials, I'll take a look.

Jeff Douglas
Trailhead Developer Advocate
Yogesh DYogesh D
Hello ,

On eproblem that I see in your code is this code...
for (Work_Part__c wpItem : caseItem.Work_Parts__r) {
055
	                        caseInsLIST.add(new Case(
056
	                            Subject = caseItem.ID + ' Scheduled Checkup',
057
	                            Description = caseItem.ID + ' Scheduled Checkup for related Work Part',
058
	                            Vehicle__c = caseItem.Vehicle__c,
059
	                            Type = (strTestFlag <> 'Case' ? 'Routine Maintenance' : 'Routine Maintenance Routine Maintenance Routine Maintenance Routine Maintenance Routine Maintenance'),
060
	                            Date_Reported__c = system.Today(),
061
	                            Date_Due__c = system.Today() + (wpItem.Equipment__r.Maintenance_Cycle__c == null ? 0 : (integer) wpItem.Equipment__r.Maintenance_Cycle__c)));
062
	                        newCaseWPMAP.put(nRcdNbr, new Work_Part__c(Equipment__c = wpItem.Equipment__c, Quantity__c = wpItem.Quantity__c, Maintenance_Request__c = wpItem.Maintenance_Request__c)); // Maintenance_Request__c will be replaced if successful
063
	                        nRcdNbr ++;
064
	                    } // END for (Work_Part__c wpItem : caseItem.Work_Parts__r)

you are creating new case for each associated work part which is wrong. you just need to create one case and then change the association on all the work part records from old case to new case.... check my last reply here on this link https://developer.salesforce.com/forums/ForumsMain?id=906F0000000kEG5IAM
bobnunny1bobnunny1
Thanx, I'll take a look.  I thought of that, but every work part wouldn't necessarily have the same due date.  So it didn't seem logical to me.  Also, would the due date be the greatest or earliest of the work parts?
Yogesh DYogesh D
For due date I am not using work parts ...
If you look closely there is a field Equipment__c on Case object which is a lookup to Product

User-added image

I am using this relation and creating one ormula field on csae object itself. Something ;like this,
User-added image

Once done this .... I am populating due date by doing this...
newCase.Date_Due__c = Date.today().addDays(Integer.valueOf(eachCase.Maintenance_Cycle_Days_Case__c));
Even I did the code earlier the hard way and tried to complete the challenge but I guess here they are expecting much simpler and straight forward customization. Don't overthink or overwork  it just keep it simple that's what I will suggest.
 
Yogesh DYogesh D
In y first version of the solution I tried doing the same way that you are thinking and then I had chosen the due date to be the earliest of the work parts....
version 1 of my code... (I am not using this anymore and completed challenge by commenting it out)
if(insertCaseList != null)
            {
                List<Case> casesTobeUpdatedWithDueDate = [Select Id, Date_Due__c, Date_Reported__c, (Select Id, Maintenance_Cycle_Days__c From Work_Parts__r) 
                                                          From Case Where Id IN :insertCaseList];
                List<Case> updateCases = new List<Case>();

                for(Case eachCase : casesTobeUpdatedWithDueDate)
                {
                    List<Decimal> maintenance_days_list = new List<Decimal>();
                    for(Work_Part__c eachWorkPart : eachcase.Work_Parts__r)
                    {
                        maintenance_days_list.add(eachWorkPart.Maintenance_Cycle_Days__c);
                    }
                    maintenance_days_list.sort(); // sort the list so that you can use the minimum maintenance days number.

                    if(maintenance_days_list != null && maintenance_days_list.size() != 0)
                        eachCase.Date_Due__c = eachCase.Date_Reported__c.addDays(Integer.valueOf(maintenance_days_list.get(0)) );
                    else
                        eachCase.Date_Due__c = eachcase.Date_Reported__c;
                    
                    updateCases.add(eachCase);
                }
                update updateCases;    
            }

 
bobnunny1bobnunny1
Thanx Jeff and Yogesh.  The problem wasn't clear in the requirements (at least to me).  The Equipment field wasn't on screen, so I didn't know there was one recorded there and I was using the date from each Work Part since each could have a different due date.  Once I used that, it passed.  Recommend the requirements be made a little more clear on that...
Yogesh DYogesh D
No problem. Even I faced the same problem earlier. Check my this post https://developer.salesforce.com/forums/ForumsMain?id=906F0000000kEvmIAE (http://No problem. Even I faced the same problem earlier. Check my this post https://developer.salesforce.com/forums/ForumsMain?id=906F0000000kEvmIAE)
This was selected as the best answer
bobnunny1bobnunny1
Yeah, now I'm having issues with the test.  When I run it, I get 100% coverage, and it covers bulk (300) positive/negative with asserts for everything the requirements say.  But still says it fails.  Not sure of where to go from here...

Challenge Not yet complete... here's what's wrong: 
The 'MaintenanceRequest' trigger does not appear to be handling bulk operations correctly. For the positive use case of inserting and updating more than 200 records, it did not produce the expected outcome.
bobnunny1bobnunny1
It would be really helpful if there was something that would tell us what outcome they are testing for...
Yogesh DYogesh D
You can check what exactly they are testing and what anonymous execution they are performing to test the challenge by enabling debug logs.... so when you run the challenge it gets recorded in your debug log records.
bobnunny1bobnunny1
Tried that, but it comes back with 2 debugs and both are showing my debugs from the Helper class with no errors...
bobnunny1bobnunny1
Found it.  The test is looking for Cases that have a subject that contains the original subject.  I didn't have that as the requirements simply said Not NULL.  Fix it and it passes.  Thanx!
Yogesh DYogesh D
Glad that helped you. You can like my comment if it really proved to be helpful to solve your problem, so that if someone else faces the same issues he should be able to find the useful comments quickly. Thanks.
Jean Luc RaesJean Luc Raes
Yep, indeed copying subject made it pass. So nobody could have the First Ascent flag with the current specs.
Thx.
Sudhir Kumar 19Sudhir Kumar 19
It did not work for me. Any help appreciated!
MUSTAPHA ELMADIMUSTAPHA ELMADI

Hello, here is my code for the test but i have this error:Challenge Not yet complete... here's what's wrong: 
The 'MaintenanceRequest' trigger does not appear to be handling bulk operations correctly. For the positive use case of inserting and updating more than 200 records, it did not produce the expected outcome.
I will put all my codes bellow thanks for the help.

trigger MaintenanceRequest on Case (before update, after update) {
    
   List<case> testRequests = [SELECT Id, subject, Vehicle__c, equipment__c, type FROM Case WHERE status = 'Closed' AND (type='Repair' OR type='Routine Maintenance')];
    //system.debug('Le select de trigger ' + ClosedCaseList.size());
   // for (case c : trigger.new)
    //{
        MaintenanceRequestHelper.updateWorkOrders(testRequests);
    //}
         
    
}
 
public class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(List<Case> ListCase){
        // update workorders
        //List<case> closedCaseList = ;
        //System.debug('ID METODE'+ closedCaseList[0].id );
        //system.debug('le nombre de closedcaseList --- ' +ClosedCaseList.size() );
        list<case> insertCaseList = new list<case>();
        for(Case c : ListCase)
            {
                Case newCase = new Case();
                newCase.Type = 'Routine Maintenance';
                newCase.Status = 'New';
                newCase.Vehicle__c = c.Vehicle__c;
                newCase.Subject =  c.Subject;
                newCase.Date_Reported__c = Date.today();
                newCase.Date_Due__c = Date.today();
                newCase.Equipment__c = c.Equipment__c;
                insertCaseList.add(newCase);
            }
        
        insert insertCaseList;
    }
        
}
 
@IsTest
public class MaintenanceRequestTest 
{
	@IsTest
	static void TestPositiveSingle()
    {
        List<Case> testRequests = TestDataFactory.createMaintenanceRequest('Repair', 1);
        testRequests[0].Status = 'Closed';
        update testRequests;
        List<Case> nouveauxCases = [SELECT ID,Status,Type FROM Case];
        
        Test.startTest();
        System.assertEquals(2, nouveauxCases.size());
        Test.stopTest();

    }
    @IsTest
	static void TestNegativeSingle()
    {
        List<Case> testRequests = TestDataFactory.createMaintenanceRequest('RepairIncorrecte', 1);
        testRequests[0].Status = 'Closed';
        update testRequests[0];
        List<Case> nouveauxCases = [SELECT ID,Status,Type FROM Case];
        
        Test.startTest();
        System.assertEquals(1, nouveauxCases.size());
        Test.stopTest();
    }
    
    @IsTest
	static void TestBulkNegative()
    {
        List<Case> testRequests = TestDataFactory.createMaintenanceRequest('RepairIncorrecte', 300);
        for(Case c : testRequests)
        {
            c.Status = 'Closed';
        	
        }      
        update testRequests ;
        List<Case> nouveauxCases = [SELECT ID,Status,Type FROM Case];
        Test.startTest();
        System.assertEquals(300, nouveauxCases.size());
        Test.stopTest();
    }
    
   @IsTest
	static void TestBulkPositive()
    {
        List<Case> testRequests = TestDataFactory.createMaintenanceRequest('Repair', 300);
        for(Case c : testRequests)
        {
            c.Status = 'Closed'; 
        }
       
        update testRequests;
        
     Test.startTest();
        List<Case> nouveauxCases = [SELECT ID,Status,Type FROM Case];
        System.assertEquals(1000, nouveauxCases.size());
        Test.stopTest();
    }


}
Mukesh pal 7Mukesh pal 7
its a Question??????


I am try complete Apex superbadge Synchronize Salesforce data with an external system. my code show this error "Challenge Not yet complete... here's what's wrong:
The runWarehouseEquipmentSync method does not appear to have run successfully. Could not find a successfully completed @future job for this method. Make sure that you run this method at least one before attempting this challenge. Since this method is annotated with the @future method, you may want to wait for a few seconds to ensure that it has processed successfully.



my code is
global with sharing class WarehouseCalloutService {

    private static final String WAREHOUSE_URL = 'https://th-superbadge-apex.herokuapp.com/equipment';
    
    // complete this method to make the callout (using @future) to the
    // REST endpoint and update equipment on hand.
    @future(callout=true)
    public static void runWarehouseEquipmentSync()
    {    
        System.debug('entered method of warehouse callout services');
        Http http=new http();
        HttpRequest call=new HttpRequest();
        call.setEndpoint('https://th-superbadge-apex.herokuapp.com/equipment');
        call.setMethod('GET');
        HttpResponse res=http.send(call);
          List<Product2> p2 = new List<Product2>();
        if (res.getStatusCode() == 200)
        {
  List<Object> equipments = (List<Object>) JSON.deserializeUntyped(res.getBody());
           // List<Product2> p2 = new List<Product2>();
            for(Object obj :  equipments){
           map<String, Object> mapProduct = (Map<String, Object>)obj;
            Product2 product = new Product2();
            
          product.Name = (string)mapProduct.get('name');
                System.debug('product name='+product.Name);

          product.Cost__c = (integer)mapProduct.get('cost');

         product.Current_Inventory__c = (integer)mapProduct.get('quantity');

         product.Maintenance_Cycle__c = (Decimal)mapProduct.get('maintenanceperiod');

                product.Replacement_Part__c = true;

                product.Lifespan_Months__c = (integer)mapProduct.get('lifespan');

                product.Warehouse_SKU__c = (string)mapProduct.get('sku');

                product.ProductCode = (string)mapProduct.get('_id');

                p2.add(product);
                }
           

                System.debug(p2);
                system.debug('function');
         
try
{      
    upsert p2 Warehouse_SKU__c;
     System.debug('upsert');
}
Catch(DmlException e)
 {
                 System.debug(e.getMessage());   
        }
    }    
    }
}
Jeff DouglasJeff Douglas
Did you run the method using Exec Anonymous before attempting the challenge?
WarehouseCalloutService.runWarehouseEquipmentSync();
Jeff Douglas
Trailhead Developer Advocate


 
Mukesh pal 7Mukesh pal 7
Thanks jeff , yes  after some attempted  I was try this method and  get a sucessfully check challenge
Arpit Jain92Arpit Jain92
Hello All,

I am working on first challenge of apex superbadge and according to the requirement I created new case with Routine Maintenance status and also attached an old vehicle but I don't know why I am getting this error.

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.

Below is my code:
Trigger: MaintenanceRequest 
trigger MaintenanceRequest on Case (after update) 
{
        MaintenanceRequestHelper.updateWorkOrders(Trigger.new);
}

MaintenanceRequestHelper  Class:
public with sharing class MaintenanceRequestHelper 
{
    public static void updateWorkOrders(List<case> newcaes)
    {

        list<case> newcases = new list<case>(); 
            for(case newc:newcaes)
            {
                integer datevalue = getdate(newc.id);
                if(newc.Status == 'Closed' && newc.Type == 'Repair' || newc.Type == 'ROUTINE_MAINTENANCE')
                {
                    case creatingcase = new case();
                    creatingcase.Subject = 'New case created by Trigger';
                    creatingcase.Vehicle__c = newc.Vehicle__c;
                    creatingcase.Equipment__c = newc.Equipment__c;
                    creatingcase.Type = 'Routine Maintenance';
                    creatingcase.Date_Reported__c = date.today();
                    creatingcase.Date_Due__c = Date.today().addDays(datevalue);
                    creatingcase.status= 'new';
                    newcases.add(creatingcase);
                }
            }
            insert newcases;
        }
        public static Integer getdate(id caseids)
        {
            List<Work_Part__c> work = new List<Work_Part__c>();
            list<Integer> duedates = new list<Integer>();
            work =[select id, Equipment__r.Maintenance_Cycle__c, Maintenance_Request__c from Work_Part__c where Maintenance_Request__r.id =: caseids];
            system.debug('size of work list....'+work.size());
            integer duedate = 0;
                for(Work_Part__c w:work)
                {
                        duedates.add(Integer.valueOf(w.Equipment__r.Maintenance_Cycle__c));
                        duedates.sort();
                        duedate = duedates[0];
                }
                return duedate;
        }
 
vikas patidarvikas patidar
trigger MaintenanceRequest on Case (before update, after update) {
    
    if(Trigger.isUpdate && Trigger.isBefore)
        
    	MaintenanceRequestHelper.updateWorkOrders(Trigger.New);
}



-----------------------------------******************************-----------------------------------------------------

public with sharing class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(List<Case> caseList) {
        // TODO: Complete the method to update workorders
        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;
    }        
    
}
Hey! The below code is working for me and I successfully passed my First challenge. check it out and let me know whether it's working for you or not. 
 
Srishti Gupta 8Srishti Gupta 8
Hi ,
Anyone still having any problem in completing step 1 of apex specialist superbadge, refer this link..

https://salesforceranger.blogspot.com/2020/07/apex-specialist-challenge-1.html
 
venkata bejagamvenkata bejagam
Hello guys, Please help me where i got mistake i am rigorously working , The error  i got 
Closing a Maintenance Request of type 'Routine Maintenance' or 'Repair' did not create of a new Maintenance Request with the correct due date. The challenge is expecting the due date to be calculated using the maintenance cycle defined on the related equipment records. If multiple equipments are used in the maintenance request, choose the shortest maintenance cycle to define the service date.
My trigger code.
trigger MaintenanceRequest on Case (after update) {

    // This is an after update trigger, but you can use the same structure for other trigger events.
    // Remember: One trigger per object. 
    
    //Create a Map to store the Maintenance Requests to evaluate:
    Map<Id, Case> casesToEvaluate = new Map<Id, Case>();
    
    if(Trigger.isAfter && Trigger.isUpdate){
        for(Case maintenance : Trigger.new){
            // Check if this Maintenance Type and Status follow the requirements:
            if((maintenance.Type.contains('Repair') || maintenance.Type.contains('Routine Maintenance')) && maintenance.Status == 'Closed'){
                casesToEvaluate.put(maintenance.Id,maintenance);
            }
        }       
    }
    // Simple! With the collection of Cases in a Map, we can invoke the method from the handler class:

Helper Class
public class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(Map<Id, Case> applicableCases){
        System.debug('****Inside MaintenanceRequestHelper Class****');
        Map<Id, Integer> mapProduct = new Map<Id, Integer>(); 
           List<Case> newCaseList = new List<Case>();
        
        List<Product2> listProduct = [select Id, Maintenance_Cycle__c from Product2];                                   
        for (Product2 p : listProduct) {
            if (p != null) {
                if(p.Maintenance_Cycle__c != null){
                    mapProduct.put(p.Id, Integer.valueOf(p.Maintenance_Cycle__c));
                }               
            }
        }

        for(Case a: applicableCases.values()){
            Case newCase = new Case();
            newCase.Vehicle__c = a.Vehicle__c;
            
            newCase.Type = 'Routine Maintenance';
            newCase.Subject = String.isBlank(a.Subject) ? 'Routine Maintenance Request' : a.Subject;
            newCase.Date_Reported__c = Date.today();
            newCase.Status = 'New';
            newCase.Product__c = a.Product__c;
            newCase.AccountId = a.AccountId;
            newCase.ContactId = a.ContactId;
            newCase.AssetId = a.AssetId;
            newCase.Origin = a.Origin;
            newCase.Reason = a.Reason;
            newCase.Date_Due__c =  (mapProduct.get(a.Id) != null) ? (Date.today().addDays(Integer.valueOf(mapProduct.get(a.Id)))) : (Date.today());
            newCaseList.add(newCase);
        }
        if(newCaseList.size() > 0){
            insert newCaseList;
        }
                
        
    }           
    
}




    MaintenanceRequestHelper.updateWorkOrders(casesToEvaluate);
}
Nagaraja AvulaNagaraja Avula

Hi team,
I facing issues in the first challenge in APEX Specialist superBadge.
what I have done in this challenge is 
step-1>>  I created New trailhead
Step-2>> Install the unmanaged package(How We Roll Maintenance)
step-3>> Renamed the Objects  "Case" TO "Maintenance Request"
                                             "Products"  TO "Equipment"
Note;  I also changed "Products" TO "Vehicle" 
 
Step-4 >>Here My Code :
MY TRIGGER:
trigger MaintenanceRequest on Case (before update, after update) {
    if ( Trigger.isAfter && Trigger.isUpdate ) {
        MaintenanceRequestHelper.updateWorkOrders ( Trigger.New, Trigger.OldMap );
    }
}
MY APEX CLASS:
public class MaintenanceRequestHelper {
    
    // Retrieve the Cases from the database, in order to retrieve the related Equipments.
    public static List<Case> updatedMaintenanceList( List<Case> maintenanceRequests ) {
        return [ SELECT ID, Equipment__r.Maintenance_Cycle__c, Type, Status, Vehicle__c, Subject, Equipment__c FROM CASE WHERE ID =: maintenanceRequests ];
    }
    
    // Create a new Routine and Update Work Orders
    public static void updateWorkOrders( List<Case> maintenanceRequests, Map<Id, Case> mapOldRecords ) {
    
        List<Case> maintenanceRequestsThatMetTheCriteria = new List<Case>();
    
        // New maintenances.
        List<Case> newMaintenanceListForRoutineCheckup = new List<Case>();
        
        // Iterating to check for those that meet the criteria
        for ( Case maintenanceRequest : updatedMaintenanceList( maintenanceRequests ) ) {
            Case oldMaintenance = mapOldRecords.get( maintenanceRequest.Id );
            
            if ( meetCriteria( maintenanceRequest, oldMaintenance ) && maintenanceRequest.Type == 'Repair' || maintenanceRequest.Type == 'Routine Maintenance' ) {
                maintenanceRequestsThatMetTheCriteria.add( maintenanceRequest );
            }
        }
        
        // Retrieve the mimimun number of cycle days required to close the newest case.
        Map<Id, Decimal> mapMaintenanceIdWithCycleDays = retrieveMinimunCycleDays( maintenanceRequestsThatMetTheCriteria );
        
        for ( Case newMaintenaceRequest : maintenanceRequestsThatMetTheCriteria ) {
            // Create a new routine once the first one is closed, with same vehicle and equipment
            Case routineCheckupMaintenance = new Case();
            routineCheckupMaintenance.Vehicle__c = newMaintenaceRequest.Vehicle__c;
            routineCheckupMaintenance.Equipment__c = newMaintenaceRequest.Equipment__c;
            routineCheckupMaintenance.Type = 'Routine Maintenance';
            routineCheckupMaintenance.Subject = String.isBlank( newMaintenaceRequest.Subject ) ? 'New Routine ' : newMaintenaceRequest.Subject;
            routineCheckupMaintenance.Status = 'New';
            routineCheckupMaintenance.Date_Reported__c = System.today();
            if ( mapMaintenanceIdWithCycleDays.containsKey( newMaintenaceRequest.Id ) ) {
                routineCheckupMaintenance.Date_Due__c = System.today().addDays( ( Integer ) mapMaintenanceIdWithCycleDays.get( newMaintenaceRequest.Id ) );
            } //else {
              //  routineCheckupMaintenance.Date_Due__c = System.today().addDays( ( Integer ) newMaintenaceRequest.Equipment__r.Maintenance_Cycle__c );
            //}
            routineCheckupMaintenance.Old_Case__c  = newMaintenaceRequest.Id;
            newMaintenanceListForRoutineCheckup.add( routineCheckupMaintenance );  
        }
        
        insert newMaintenanceListForRoutineCheckup;
        updateRelatedWorkParts( newMaintenanceListForRoutineCheckup );
    }
    
    // Once the new maintenance records are created, update the work parts
    public static void updateRelatedWorkParts( List<Case> createdMaintenances) {
        
        Map<Id, Id> mapNewMaintenancesWithClosedMaintenances = new Map<Id, Id>();
        for ( Case newMaintenances : createdMaintenances ) {
            mapNewMaintenancesWithClosedMaintenances.put( newMaintenances.Old_Case__c , newMaintenances.Id );
        }
        
        List<Work_Part__c> workParkList = new List<Work_Part__c>();
        
        // Query work parts to be updated
        for ( Work_Part__c workPart : [ SELECT Id, Maintenance_Request__c, Equipment__c, Quantity__c  FROM Work_Part__c
                                            WHERE Maintenance_Request__c =: mapNewMaintenancesWithClosedMaintenances.keySet() ] ) {
            workParkList.add(new Work_Part__c(Maintenance_Request__c = mapNewMaintenancesWithClosedMaintenances.get( workPart.Maintenance_Request__c ), 
                                              Equipment__c = workPart.Equipment__c, Quantity__c = workPart.Quantity__c));
        }
        
        insert workParkList;
    }
    
    // Method to check if the cases being updated meet the criteria (They must be closed)
    public static boolean meetCriteria( Case newcase, Case oldMaintenance ) {
        Boolean falg = false;
        if ( newCase.Status == 'Closed' && oldMaintenance.Status != newCase.Status ) {
            falg = true;
        }
        return falg;
    }
    
    // Use an aggregate function to return the minimum number of cycle days related to the Case
    public static Map<Id, Decimal> retrieveMinimunCycleDays( List<Case> maintenanceRequests ) {
        
      AggregateResult[] listWorkParts = [ SELECT Maintenance_Request__c, MIN( Equipment__r.Maintenance_Cycle__c )
                             FROM Work_Part__c WHERE Maintenance_Request__c =: maintenanceRequests 
                            Group By Maintenance_Request__c ];
    
    Map<Id, Decimal> mapWorkPartaAndMaintenanceRecords = new Map<Id, Decimal>();        
        for ( AggregateResult ar : listWorkParts ) {
            mapWorkPartaAndMaintenanceRecords.put( ( Id ) ar.get( 'Maintenance_Request__c' ), ( Decimal ) ar.get( 'expr0' ) );
        }
        
        return mapWorkPartaAndMaintenanceRecords;
    }
    
}

MY APEX TEST
@isTest
public class MaintenanceRequestTest {

    @testSetup
    static void setup(){
        Product2 prod = new Product2();
        prod.Cost__c = 50;
        prod.Name = 'Ball Valve 10 cm';
        prod.Lifespan_Months__c = 12;
        prod.Maintenance_Cycle__c = 365;
        prod.Current_Inventory__c = 50;
        prod.Replacement_Part__c = true;
        prod.Warehouse_SKU__c = '100009';
        insert prod;
        
        Product2 prod2 = new Product2();
        prod2.Cost__c = 50;
        prod2.Name = 'Ball Valve 10 cm';
        prod2.Lifespan_Months__c = 12;
        prod2.Maintenance_Cycle__c = 240;
        prod2.Current_Inventory__c = 50;
        prod2.Replacement_Part__c = true;
        prod2.Warehouse_SKU__c = '100009';
        insert prod2;
        
        List<Case> caseList = new List<Case>();
        for(Integer i=0; i<300; i++) {
            Case caseNew = new Case();
            caseNew.Subject = 'Maintenance ' + i;
            caseNew.Type = 'Other';
            caseNew.Status = 'New';
            caseNew.Equipment__c = prod.Id;
            caseNew.SuppliedName = 'Test';
            caseList.add(caseNew);   
            
            if(i==10){
                caseNew.Subject = 'Maintenance test 10';
            }
        }
        
        insert case list;
        
        List<Work_Part__c> workPartList = new List<Work_Part__c>();
        for(Case caseHere : [select Id, Subject from Case where SuppliedName = 'Test']) {
            Work_Part__c workPart = new Work_Part__c();
            workPart.Maintenance_Request__c = caseHere.Id;
            workPart.Equipment__c = prod.Id;
            workPartList.add(workPart);   
            
            if(caseHere.Subject == 'Maintenance test 10'){
                Work_Part__c workPart2 = new Work_Part__c();
                workPart2.Maintenance_Request__c = caseHere.Id;
                workPart2.Equipment__c = prod2.Id;
                workPartList.add(workPart2);
            }
        }
        
        insert workPartList;
    }
    
    @isTest
    static void testMaintenanceRequest(){
        List<Case> caseList = new List<Case>();
        for(Case caseHere : [select Id from Case where SuppliedName = 'Test']) {
            caseHere.Type = 'Repair';
            caseHere.Status = 'Closed';
            caseList.add(caseHere);
        }
        
        Test.startTest();
        update caseList;
        System.assertEquals(300, [SELECT count() FROM Case WHERE Type = 'Routine Maintenance' and Date_Reported__c = :Date.today()]);
        Test.stopTest();
        
    }
}
 
MY ERROR:

Challenge Not yet complete... here's what's wrong:
Closing a Maintenance Request of type 'Routine Maintenance' or 'Repair' did not create of a new Maintenance Request with the correct due date. The challenge is expecting the due date to be calculated using the maintenance cycle defined on the related equipment records. If multiple equipments are used in the maintenance request, choose the shortest maintenance cycle to define the service date.
Close errors
 
Thanks in advance
Further Information:
My Email Id:anagarajasfdc@gmail.com
Krishna ShahiKrishna Shahi
Hi Nagaraja Avula,
Please check below code. If you find it helpful then Mark the answer as best so that it will help other trailblazers as well.
public with sharing class MaintenanceRequestHelper {
    
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() 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 void updateWorkOrders(List<Case> caseList) {
        
        Map<String,Integer> result=getDueDate(caseList);
        List<Id> clonedCaseIds = new List<Id>();
        List<Equipment_Maintenance_Item__c> newItems = new List<Equipment_Maintenance_Item__c>();
		
        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.cloned_case_id__c = c.Id;
                    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);
                    clonedCaseIds.add(c.Id);
                }
        }        
        insert newCases;   
        
        List<Equipment_Maintenance_Item__c> items=
            [select id,name,Maintenance_Request__c from Equipment_Maintenance_Item__c where Maintenance_Request__c in:clonedCaseIds];
        
        for(Case caseO : newCases){
            
            for(Equipment_Maintenance_Item__c item : items){
                if(caseO.cloned_case_id__c==item.Maintenance_Request__c){
                    Equipment_Maintenance_Item__c newItem = new Equipment_Maintenance_Item__c();
                    newItem.Maintenance_Request__c=caseO.Id;
                    newItems.add(newItem);
                }
            }
        }
        insert newItems;
    }       
}
CHEERS!
 
Mamta DeviiMamta Devii
Hi, 

If anyone is still stuck, below solution worked for me.
  • Create Cloned_Case_Id__c TEXT field on Case object as a pre-requistive.
  • Modify MaintenanceRequest class as shown
trigger MaintenanceRequest on Case (before update, after update) {

    if(Trigger.isAfter)
       MaintenanceRequestHelper.updateWorkOrders(Trigger.New);
}
  • Modify MaintenanceRequestHelper class as shown
public with sharing class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(List<Case> caseList) {
        Map<String,Integer> IDToCycleMap = getMinMaintenanceCycleByCaseID(caseList);
        
        List<case> newCasesList = new List<Case>();        
        for(Case oldCase : caseList){
            if(oldCase.status=='closed' && (oldCase.type=='Repair' || oldCase.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 = oldCase.Vehicle__c;
                newCase.Date_Reported__c = Date.today();
                newcase.Cloned_Case_Id__c = oldCase.Id;
                newCase.Date_Due__c = IDToCycleMap.get(oldCase.Id) == null ? Date.today() : Date.today()+IDToCycleMap.get(oldCase.Id);           
                newCasesList.add(newCase);
            }
        }       
		insert newCasesList;     
        
        updateEquipments(newCasesList);
    }
    
    //update Equipments : Reparent them with new Case
    public static void updateEquipments(List<Case> newCasesList){
     List<Equipment_Maintenance_Item__c> equipmentsList = [select ID, Maintenance_Request__c from Equipment_Maintenance_Item__c];
     List<Equipment_Maintenance_Item__c> updatedEquipmentsList  = new List<Equipment_Maintenance_Item__c>();
        for(Case c : newCasesList){
            for(Equipment_Maintenance_Item__c e : equipmentsList ){
                if(e.Maintenance_Request__c == c.Cloned_Case_Id__c){
                    e.Maintenance_Request__c = c.Id;
                    updatedEquipmentsList.add(e);
                }
            }
        }
        update updatedEquipmentsList;
    }
    
    //Get min Maintenance Cycle by  Case IDs    
    public static Map<String,Integer> getMinMaintenanceCycleByCaseID(List<Case> caseList){
        Map<String,Integer> IDToCycleMap = new Map<String,Integer>();
        List<String> CaseIDList = new List<String>();   
        for(Case eachCase  : caseList){
            caseIDList.add(eachCase.ID);
        }
        
        List<AggregateResult> result =[SELECT Maintenance_Request__r.ID CaseID, MIN(Equipment__r.Maintenance_Cycle__c)  Cycle FROM Equipment_Maintenance_Item__c WHERE 
                                       Maintenance_Request__r.ID IN :caseIDList AND Equipment__r.Maintenance_Cycle__c != null group by Maintenance_Request__r.ID];
        
        
        for(AggregateResult a : result){
            IDToCycleMap.put((String)a.get('CaseID'),Integer.valueOf(a.get('Cycle')));
            
        }
        return IDToCycleMap;
    }
    
}

Please Like my answer if helped you solve the challenge.
RaulAtSfRaulAtSf
Mamta Devii - you need to change the field 

Equipment_Maintenance_Item__c.Maintenance_Request__c to allow reparenting. Basically enable the checkbox -

Reparentable Master Detail
Akram Zaki 7Akram Zaki 7
Hi,
I am facing issue while creating SOQL query. As i can see object "Equipment Maintenance Item" is child object of "case" but somehow my query is not returning expected result. Can someone explain why this is happening.
User-added image
Denys Lukeniuk 10Denys Lukeniuk 10
@Akram Zaki 7 '...(SELECT id FROM Equipment_Maintenance_Items__r)'. You are missing an 's'. 
Pooja Redekar 10Pooja Redekar 10
Thank you @Mamta Devii ..your code helped a lot with @RaulAtSf suggested modification.
Hanusha GanjiHanusha Ganji
Hi @Pooja Redekar, ,tried the code provided but
Challenge Not yet complete... here's what's wrong:
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Update failed. First exception on row 0 with id 5005g000009okFrAAI; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MaintenanceRequest: execution of AfterUpdate caused by: System.SObjectException: Field is not writeable: Equipment_Maintenance_Item__c.Maintenance_Request__c Class.MaintenanceRequestHelper.updateEquipments: line 33, column 1 Class.MaintenanceRequestHelper.updateWorkOrders: line 23, column 1 Trigger.MaintenanceRequest: line 4, column 1: []
Amol KastureAmol Kasture
@bobnunny1

For Apex Superbadge Challenge 4 Use following solution. As I have completed this challenge after number of R&D...

For this challenge need to create follwing things:

1. MaintenanceRequestHelper Class
2. MaintenanceRequest Trigger on Case object 
3. MaintenanceRequestHelperTest  for testing purpose as name given in challenge

Use following code for following things:

1. MaintenanceRequestHelper Class
-------------------------------------------------------------------------------------------------------------------------------------------------------
public class MaintenanceRequestHelper {
    
 
    public static void updateWorkOrders(Map<Id, Case> applicableCases){
        
        Map<Id, Integer> mapProduct = new Map<Id, Integer>(); 
        List<Case> newCases = new List<Case>();
        List<Product2> listProduct = [select Id, Maintenance_Cycle__c from Product2];                                   
        for (Product2 p : listProduct) {
            if (p != null) {
                if(p.Maintenance_Cycle__c != null){
                    mapProduct.put(p.Id, Integer.valueOf(p.Maintenance_Cycle__c));
                }               
            }
        }
        for(Case a: applicableCases.values()){
            Case newCase = new Case();
            newCase.Vehicle__c = a.Vehicle__c;
            newCase.Equipment__c = a.Equipment__c;
            newCase.Type = 'Routine Maintenance';
            newCase.Subject = String.isBlank(a.Subject) ? 'Routine Maintenance Request' : a.Subject;
            newCase.Date_Reported__c = Date.today();
            newCase.Status = 'New';
            newCase.Product__c = a.Product__c;
            newCase.AccountId = a.AccountId;
            newCase.ContactId = a.ContactId;
            newCase.AssetId = a.AssetId;
            newCase.Origin = a.Origin;
            newCase.Reason = a.Reason;
            newCase.Date_Due__c =  (mapProduct.get(a.Id) != null) ? (Date.today().addDays(Integer.valueOf(mapProduct.get(a.Id)))) : (Date.today());
                newCases.add(newCase);
        }
        if(newCases.size() > 0){
            insert newCases;
        }
    }           
}

========================================================================================================

2. MaintenanceRequest Trigger on Case object 

--------------------------------------------------------------------------------------------------------------------------------------
trigger MaintenanceRequest on Case (before update, after update) {
    // call MaintenanceRequestHelper.updateWorkOrders
    
    Map<Id,Case> applicableCases = new Map<Id,Case>();    
    if(Trigger.isUpdate){
        if(Trigger.isAfter){
            for(Case a: Trigger.new){
                if (a.IsClosed && (a.Type.equals('Repair') || a.Type.equals('Routine Maintenance'))){
                    applicableCases.put(a.Id, a);
                }
            }
            MaintenanceRequestHelper.updateWorkOrders(applicableCases);    
        }
    } 
      
}

=================================================================================================

3. MaintenanceRequestHelperTest

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

@isTest
public class MaintenanceRequestHelperTest {
    @isTest
    static void testMaintenanceRequest(){
        
        List<Case> caseList = new List<Case>();
        Product2 prod = new Product2();
        prod.Cost__c = 50;
        prod.Name = 'Ball Valve 10 cm';
        prod.Lifespan_Months__c = 12;
        prod.Maintenance_Cycle__c = 365;
        prod.Current_Inventory__c = 50;
        prod.Replacement_Part__c = true;
        prod.Warehouse_SKU__c = '100009';
        insert prod;
        System.assertEquals(1, [SELECT count() FROM Product2 WHERE Name = 'Ball Valve 10 cm']);
        
        for(Integer i=1;i<=300;i++) {
            Case caseNew = new Case();
            caseNew.Subject = 'Maintenance';
            caseNew.Type = 'Other';
            caseNew.Status = 'New';
            caseNew.Equipment__c = prod.Id;
            caseList.add(caseNew);   
        }
        
        Test.startTest();
        
        insert caseList;
        System.assertEquals(300, [SELECT count() FROM Case WHERE Type = 'Other']);
        
        for(Case a : caseList){
            a.Type = 'Repair';
            a.Status = 'Closed';
        }
        update caseList;
        System.assertEquals(300, [SELECT count() FROM Case WHERE Type = 'Repair']);
        Test.stopTest();
    }
}

======================================================================================================

If you like and used this code then please mark my solution as Best Answer
 
Geetharani DakojuGeetharani Dakoju
Best Answer . I used this code and passed the challenge 4
Mila MirovicMila Mirovic
This link (https://www.automationcodes.com/2021/07/apex-specialist-superbadge-solutions.html) helped me pass this challenge. Glad if it helps.
Lalit Kumar 145Lalit Kumar 145
Create a Lookup Relationship field On Maintenance Request(Case) , Related to  Equipment, Field Name - Equipment.
Abhilasha ManhasAbhilasha Manhas
Challenge Not yet complete... here's what's wrong:
Closing a Maintenance Request of type 'Routine Maintenance' did not create of a new Maintenance Request related to the same Vehicle.
Abhilasha ManhasAbhilasha Manhas
Please help me to solve this problem.
Sree KrishnanSree Krishnan
Iam also facing the same issue in Challenge 2 - Closing a Maintenance Request of type 'Routine Maintenance' did not create of a new Maintenance Request related to the same Vehicle. Any Solution???