Apex Specialist Superbadge Walkthrough

Hello, and welcome to Another Salesforce Blog! Here I will be posting solutions to problems that I couldn’t find an answer to in hopes of helping those who find themselves stuck when using the Salesforce platform.

This blog post is going to be a walkthrough with helpful hints for the first three steps of the Apex Specialist Superbadge.

Disclaimer: this is only one way to solve the challenge, and is not meant to be a full solution.

There is no shortage of full answers for the challenge on the internet, but this post is meant for folks who are learning Salesforce (like me!) and would like to work through the solution with a few hints for the tricky parts.

Again, copying and pasting what is in this blog post will NOT complete the challenge.

Step One – Automate Record Creation

First, we must create the MaintenanceRequest.apxt trigger and MaintenanceRequestHelper.apxc helper. Per the business requirements:

When an existing maintenance request of type Repair or Routine Maintenance is Closed, you create a new maintenance request for a future routine checkup. This new request is tied to the same vehicle and piece of equipment to be serviced as the original closed service request. This new request’s Type should be set as Routine Maintenance. The Subject should not be null and the Report Date field reflects the day the request was created. Another aspect about parts is they all have different lifespans. Therefore, you need to calculate and set the next due date using the maintenance cycle defined on the related work part records. If multiple work parts are used in the maintenance request, choose the shortest maintenance cycle to define the service date.

https://trailhead.salesforce.com/content/learn/superbadges/superbadge_apex

We know that this trigger will fire after an existing cases is updated to “Closed” status. It will use the same vehicle and service the same piece of equipment, and it will be scheduled a certain number of days after the closed request based on the lifespan of the equipment.

The hardest part of this challenge for me was deciding how I was going to build my trigger. Initially, I passed this challenge using a brute force solution, but I have since revised it to be more elegant.

Step 1 Resources:

Rethink Trigger Logic with Apex Switch – I opted to use a Switch statement so that this code will be easily understood and easy to build on.

Step 1 Code Hints:

MaintenanceRequest.apxt

trigger MaintenanceRequest on Case (before update, after update) {
    MaintenanceRequestHelper.handleTrigger(Trigger.new, Trigger.old, Trigger.operationType);
}

MaintenanceRequestHelper.apxc

public class MaintenanceRequestHelper {
    public static void handleTrigger(List<Case> trigNew, List<Case> trigOld, System.TriggerOperation trigEvent){
        Map<Id,Case> recordsToUpdate = new Map<Id,Case>();
        switch on trigEvent{
            when AFTER_UPDATE {
                for(Case c: trigNew){
                    if(c.IsClosed && (c.Type.equals('Repair') || c.Type.equals('RoutineMaintenance'))){
                        recordsToUpdate.put(c.Id, c);
                    }
                }
                if(!recordsToUpdate.values().isEmpty()){
                    updateClosedOrders(recordsToUpdate);
                }
            }
            when else{}
        }
    }
    public static void updateClosedOrders(Map<Id, Case> ClosedMaintReq){...}
}

Step Two – Synchronize Inventory Management

Next, we must synchronize our inventory data with an external system:

Write a class that makes a REST callout to an external warehouse system to get a list of equipment that needs to be updated. The callout’s JSON response returns the equipment records that you upsert in Salesforce. Beyond inventory, you also ensure that other potential warehouse changes carry over to Salesforce. Your class maps the following fields: replacement part (always true), cost, current inventory, lifespan, maintenance cycle, and warehouse SKU. Use the warehouse SKU as the external ID to identify which equipment records to update within Salesforce.

https://trailhead.salesforce.com/content/learn/superbadges/superbadge_apex

Step 2 Resources:

Apex REST Callouts Trailhead – This Trailhead has the bulk of the code for the WarehouseCalloutService.apxc file.
JSON Class – This link in the Developer Guide explains how to map a JSON response.

Step 2 Code Hints:

public 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(){...}
    
    public static HttpResponse getResponse(){...}
    
    public static List<Product2> getProductList(HttpResponse response){
            
        List<Object> results = (List<Object>) JSON.deserializeUntyped(response.getBody());
            
        //cast the values in the 'equipment' key as a list
        List<Product2> productList = new List<Product2>();
        
        for(Object o : results) {
            Map<String, Object> objectMap = (Map<String, Object>)o;
            
            Product2 product = new Product2();
                    
            //map fields in JSON
            String name = (String)objectMap.get('name');
            Boolean replacement = (Boolean)objectMap.get('replacement');
            Integer cost = (Integer)objectMap.get('cost');
            Integer currentInventory = (Integer)objectMap.get('quantity');
            Integer lifespan = (Integer)objectMap.get('lifespan');
            Integer maintenanceCycle = (Integer)objectMap.get('maintenanceperiod');
            String warehouseSKU = (String)objectMap.get('sku');
        
            product.Name = name;
            product.Replacement_Part__c = replacement;
            product.Cost__c = cost;
            product.Current_Inventory__c = currentInventory;
            product.Lifespan_Months__c = lifespan;
            product.Maintenance_Cycle__c = maintenanceCycle;
            product.Warehouse_SKU__c = warehouseSKU;
        
            productList.add(product);
        }
        return productList;
    }

}

Step Three – Schedule Synchronization

Step 3 requires us to schedule our job during off hours:

Although HowWeRoll is an international company, the remote offices follow the lead of the HQ’s work schedule. Therefore, all maintenance requests are processed during HQ’s normal business hours. You need to update Salesforce data during off hours (at 1:00 AM PST). This logic runs daily so that the inventory is up to date every morning at HQ.

https://trailhead.salesforce.com/content/learn/superbadges/superbadge_apex

Step 3 Resources:

Schedule Jobs Using the Apex Scheduler Trailhead – This Trailhead shows how to schedule a job using the Schedulable interface, as well as how to test it.
Apex Scheduler – This documentation in the Developer Guide details the System.schedule method, as well as the format for the CRON_EXP String.

Step 3 Code Hints:

Follow the Apex Scheduler Trailhead! No hints here, this one is a gimme.

Steps Four through Six – Test Classes

Lastly, we must create test classes with 100% coverage to make sure that our code works and covers positive and negative test cases.

Test Class Resources:

Get Started with Apex Unit Tests Trailhead – How to write a test class in Apex.
Add a Test Class – Developer Guide documentation on how to test a trigger and handler class.
Test Class – Developer Guide documentation regarding test classes.

Summary

It took me longer than 12 hours, but I completed the Apex Specialist Superbadge. I hope that this post helps you complete it as well!

Thanks for reading, let me know if you have any comments or questions!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: