+ 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