/** * @description This service exposes methods that contain logic to make cloning an opportunity * much easier and more functional. * @author Cloud Performer Inc. * @version 1.0 * @group Opportunity Cloning * @history 2021-04-02 - CJG - Created */ public with sharing class OpportunityCloneService { /** * @description exception class that is thrown when something happens in the opportunity * clonde process. */ public class CloneException extends System.Exception {} public static Map opportunityChildrenMap; static { List childRelationshipList = Schema.Opportunity.getSObjectType().getDescribe().getChildRelationships(); opportunityChildrenMap = new Map(); for(Schema.ChildRelationship childRel:childRelationshipList) { Schema.DescribeSObjectResult childObjRes = childRel.getChildSObject().getDescribe(); opportunityChildrenMap.put(childObjRes.getName(),childObjRes); } } @AuraEnabled(cacheable=true) public static List ObtainOpporunityChildRelationships(){ return new List(opportunityChildrenMap.keySet()); } public static String ObtainQueryStringForOppAndChildren(Id oppRecordId, List relationships) { String queryString = 'SELECT '; queryString += String.join(ObtainFieldsForObject('Opportunity'),','); List subqueryList = new List(); for(String relationship:relationships){ Schema.DescribeSObjectResult childObject = opportunityChildrenMap.get(relationship); String childQueryString = '(SELECT ' + String.join(ObtainFieldsForObject(childObject.getName()),',') + ' FROM '; childQueryString += relationship + ')'; subqueryList.add(childQueryString); } queryString += ', ' + String.join(subqueryList,',') + 'FROM Opportunity WHERE Id =\'' + oppRecordId + '\''; return queryString; } /** * @description this method is responsible for getting the list of fields for a particular object */ private static List ObtainFieldsForObject(String objectName) { List fieldNameList; List objectListToDescribe = new List{objectName}; List describeItem = System.Schema.describeSObjects(objectListToDescribe); if(describeItem.isEmpty()) { throw new OpportunityCloneService.CloneException('Could not find info for ' + objectName + '.'); } Map fieldSObjectMapping = describeItem[0].fields.getMap(); fieldNameList = new List(); for(Schema.SObjectField fieldToken:fieldSObjectMapping.values()) { Schema.DescribeFieldResult fieldTokenDescribe = fieldToken.getDescribe(); if(fieldTokenDescribe.isCreateable() && fieldTokenDescribe.isUpdateable()) { fieldNameList.add(fieldTokenDescribe.getName()); } } return fieldNameList; } }