• Will Boyce
  • NEWBIE
  • 0 Points
  • Member since 2015
  • Sales Operations
  • Rolls Boyce

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 3
    Replies
I have an apex class that I need to change to a batch class because there are too many records being processed.  Any help is greatly apprciated! 

Order_Item__c is the child object in a Master-Detail relationship with the Account object.

The scheduled apex reviews all open Order_Item__c records on Accounts and then if those accounts do not have an open outreach case record for those open order items it should create a case.

global class createAffiliateOutreachCases implements Schedulable {
    global void execute(SchedulableContext ctx) {
        
        // Define outbound string variables for queues
        String outboundAffiliate = [SELECT Id from Group where Name = 'Outreach eConnect Affiliate' and Type = 'Queue' Limit 1].Id;        
        
        Datetime affiliateTime = Datetime.now().addDays(-1);
        
        Set<Id> setAffiliate = new Set<Id>();
        
        Id outreachId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('eConnect Outreach').getRecordTypeId();
        
        // Get Open Affiliate and Member Order
        List<Order_Item__c> affiliateOrders = [SELECT id, CreatedDate, Item_Status__c, Account__r.Id FROM Order_Item__c WHERE (Account__r.Partner_Status__c = 'Affiliate' OR Account__r.Partner_Status__C = 'Member') AND (Item_Status__c = 'AWAITING_APPROVAL' OR Item_Status__c = 'FAILED_TO_COMMUNICATE_VET')];

        for (Order_Item__c o :affiliateOrders) {
            if (o.CreatedDate <= affiliateTime && !setAffiliate.contains(o.Account__r.Id)) {
                setAffiliate.add(o.Account__r.Id);
            }
        }        
        
        List<Account> accsAffil = [SELECT Id FROM Account WHERE Id IN :setAffiliate];
        
        List<Case> opencases = [SELECT Id, Account.Id FROM Case WHERE RecordTypeId = :outreachId AND Status != 'Completed'];
        
        List<Case> NewCases = new List<Case>();
        
        List<Account> hasrecord = new List<Account>();
        
        for (case c: opencases) {
            hasrecord.add(c.Account);
        }
        
        for (account a: accsAffil) {
            if (hasrecord.contains(a) == false){
                Case c = new Case();
                c.Accountid = a.Id;
                c.OwnerId = outboundAffiliate;
                c.Status = 'New';
                c.RecordTypeId = outreachId;
                c.Subject = 'Please Help Client Approve Orders';
                NewCases.add(c);
            }
        }
        if(!NewCases.isEmpty()){
            insert NewCases;
        }
    }
}
Hello community!  I have a REST Post callout that is fired from a trigger.  I am passing three parameters from that trigger into the callout method.  I am having trouble writing a text class for this callout.  Any help or suggestions are welcomed.  Thanks in advance for your time and knowledge!

HERE IS THE CLASS:

public class RESTCallout {
    @future (callout=true)
    public static void makePostCallout(string taskType, string orderNumber, string siteId) {
       
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        String authorizationHeader = 'BASIC' + 'somecredential';
        String endpoint = 'http://api.website.com/api2/rest/v1/order/'+orderNumber+'/communication/'+siteId;
        System.debug(endpoint);
        
        request.setEndpoint(endpoint);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setHeader('Authorization', authorizationHeader);
        
        JSONGenerator gen = JSON.createGenerator(true);    
        gen.writeStartObject();      
        gen.writeStringField('communicationType', taskType);
        gen.writeEndObject();    
        String jsonS = gen.getAsString();
        System.debug('jsonMaterials'+jsonS);
        
        request.setBody(jsonS);
        HttpResponse response = http.send(request);
       
        if (response.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
            response.getStatusCode() + ' ' + response.getStatus());
        } else {
            System.debug(response.getBody());
        }
    }
}

HERE IS THE TRIGGER:

trigger PostToFulfillment on Task (after update, after insert) {
    
        Set<Id> caseIdSet = new Set<Id>();

    for(Task t: Trigger.new) {
        If(t.whatId != null && t.whatId.getsObjectType() == Case.sObjectType ){
            caseIdSet.add(t.whatId);
        }       
    }

    if(!caseIdSet.isEmpty()) {
        Map<Id, Case> caseMap = new Map<Id, Case>([Select Id, RecordType.DeveloperName, RecordTypeId, Order_Number__c, Type, Site_ID__c, Status from Case where Id =: caseIdSet]);
        for(Task t: Trigger.new) {
            If(t.whatId.getsObjectType() == Case.sObjectType){
                Case c = caseMap.get(t.whatId);
                if(c != null && t.Status == 'Completed' && c.RecordType.DeveloperName == 'eConnect') {
                    eConnTaskRESTCallout.makePostCallout(t.Type, c.Order_Number__c, c.Site_ID__c);
                }
            }
        }
    }    
}
We have a mysql database on a linux box and we would like to sync changes to that data into our SFDC environment.  Data does not need to go both ways at this time, just from the linux box to SFDC.  I have seen a number of Apps for this but I was hoping someone could help me with coding this.  I am fairly new to coding but I am a quick study and unfortunately this problem has me stuck.  I have searched this Forum for answers to this question but they all lead to partial answers and I feel like I am missing something at the end of each tutorial I watch on SOAP/REST APIs.  

Can someone please, pretty please point me in the correct direction?  Thank you in advance for your time and guidance!
Hello community!  I have a REST Post callout that is fired from a trigger.  I am passing three parameters from that trigger into the callout method.  I am having trouble writing a text class for this callout.  Any help or suggestions are welcomed.  Thanks in advance for your time and knowledge!

HERE IS THE CLASS:

public class RESTCallout {
    @future (callout=true)
    public static void makePostCallout(string taskType, string orderNumber, string siteId) {
       
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        String authorizationHeader = 'BASIC' + 'somecredential';
        String endpoint = 'http://api.website.com/api2/rest/v1/order/'+orderNumber+'/communication/'+siteId;
        System.debug(endpoint);
        
        request.setEndpoint(endpoint);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setHeader('Authorization', authorizationHeader);
        
        JSONGenerator gen = JSON.createGenerator(true);    
        gen.writeStartObject();      
        gen.writeStringField('communicationType', taskType);
        gen.writeEndObject();    
        String jsonS = gen.getAsString();
        System.debug('jsonMaterials'+jsonS);
        
        request.setBody(jsonS);
        HttpResponse response = http.send(request);
       
        if (response.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
            response.getStatusCode() + ' ' + response.getStatus());
        } else {
            System.debug(response.getBody());
        }
    }
}

HERE IS THE TRIGGER:

trigger PostToFulfillment on Task (after update, after insert) {
    
        Set<Id> caseIdSet = new Set<Id>();

    for(Task t: Trigger.new) {
        If(t.whatId != null && t.whatId.getsObjectType() == Case.sObjectType ){
            caseIdSet.add(t.whatId);
        }       
    }

    if(!caseIdSet.isEmpty()) {
        Map<Id, Case> caseMap = new Map<Id, Case>([Select Id, RecordType.DeveloperName, RecordTypeId, Order_Number__c, Type, Site_ID__c, Status from Case where Id =: caseIdSet]);
        for(Task t: Trigger.new) {
            If(t.whatId.getsObjectType() == Case.sObjectType){
                Case c = caseMap.get(t.whatId);
                if(c != null && t.Status == 'Completed' && c.RecordType.DeveloperName == 'eConnect') {
                    eConnTaskRESTCallout.makePostCallout(t.Type, c.Order_Number__c, c.Site_ID__c);
                }
            }
        }
    }    
}
Hi Folks,

Any one used this Class before 'OpportunityTerritory2AssignmentFilter' ?
It implements an interface 'TerritoryMgmt.OpportunityTerritory2AssignmentFilter' ,Its a sample class provided by salesforce!
Im trying to write a Test Class for this , 
Anyone has  test class for this Sample class ??
If anyone has worked on this before any help, references or suggestions are highly appreciaed ! :)
TIA
You can find this class here or below...

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_interface_TerritoryMgmt_OpportunityTerritory2AssignmentFilter.htm


 
/*** Apex version of the default logic.
* If opportunity's assigned account is assigned to
*  Case 1: 0 territories in active model
*            then set territory2Id =   null
*  Case 2: 1 territory in active model
*            then set territory2Id =   account's territory2Id
*  Case 3: 2 or more territories in active model
*            then set territory2Id =   account's territory2Id that is of highest priority.
*            But if multiple   territories have same highest priority, then set territory2Id = null 
*/
global class OppTerrAssignDefaultLogicFilter implements
TerritoryMgmt.OpportunityTerritory2AssignmentFilter {
     /**
     * No-arg constructor.
     */ 
     global   OppTerrAssignDefaultLogicFilter() {}

     /**
      * Get mapping of   opportunity to territory2Id. The incoming list of opportunityIds contains only those with IsExcludedFromTerritory2Filter=false.
      * If territory2Id =   null in result map, clear the opportunity.territory2Id if set.
      * If opportunity is not present in result map, its territory2Id remains intact.
      */
    global Map<Id,Id> getOpportunityTerritory2Assignments(List<Id> opportunityIds) {
        Map<Id,   Id> OppIdTerritoryIdResult = new Map<Id, Id>();

        //Get the active territory model Id
        Id   activeModelId = getActiveModelId();

        if(activeModelId   != null){
            List<Opportunity>   opportunities =
              [Select Id, AccountId, Territory2Id from Opportunity where Id   IN
              :opportunityIds];
            Set<Id>   accountIds = new Set<Id>();
            //Create   set of parent accountIds
            for(Opportunity opp:opportunities){
                if(opp.AccountId   != null){
                    accountIds.add(opp.AccountId);
                    }
                }

                Map<Id,Territory2Priority> accountMaxPriorityTerritory = 
getAccountMaxPriorityTerritory(activeModelId, accountIds);

            //for each opportunity, assign the highest priority territory if there is 
no conflict, else assign null
            for(Opportunity opp: opportunities){
               Territory2Priority tp = accountMaxPriorityTerritory.get(opp.AccountId);
               //assign highest priority
              territory if there is only 1
              if((tp   != null) && (tp.moreTerritoriesAtPriority == false) && 
(tp.territory2Id != opp.Territory2Id)){
                   OppIdTerritoryIdResult.put(opp.Id, tp.territory2Id);
               }else{
                   OppIdTerritoryIdResult.put(opp.Id,   null);
               }
            }
        }
        return   OppIdTerritoryIdResult;
    }
    
    /**
      * Query assigned territoryIds in active model for given accountIds
      * Create a map of accountId to max priority territory 
      */
     private Map<Id,Territory2Priority> getAccountMaxPriorityTerritory(Id
activeModelId, Set<Id> accountIds){
        Map<Id,Territory2Priority> accountMaxPriorityTerritory = new 
Map<Id,Territory2Priority>();
        for(ObjectTerritory2Association ota:[Select ObjectId, Territory2Id, 
Territory2.Territory2Type.Priority from ObjectTerritory2Association where objectId IN 
:accountIds and Territory2.Territory2ModelId = :activeModelId]){
            Territory2Priority tp = accountMaxPriorityTerritory.get(ota.ObjectId);

            if((tp   == null) || (ota.Territory2.Territory2Type.Priority > 
tp.priority)){
                //If this is the first territory examined for account or it has 
greater priority than current highest priority territory, then set this as new highest 
priority territory.
                tp = new 
Territory2Priority(ota.Territory2Id,ota.Territory2.Territory2Type.priority,false);
            }else if(ota.Territory2.Territory2Type.priority == tp.priority){
                //The priority of current highest territory is same as this, so set   
moreTerritoriesAtPriority to indicate multiple highest priority territories seen so far.
                tp.moreTerritoriesAtPriority = true;
            }
            
            accountMaxPriorityTerritory.put(ota.ObjectId,   tp);
        }
        return accountMaxPriorityTerritory;
    }

             
    /**
     * Get the Id of the Active Territory Model. 
     * If none exists, return   null;
     */
   private Id getActiveModelId() {
       List<Territory2Model>   models = [Select Id from Territory2Model where State = 'Active'];
       Id activeModelId = null;
       if(models.size()   == 1){
           activeModelId = models.get(0).Id;
       }
       
       return activeModelId;
   }
   
   /**
    * Helper class to help   capture territory2Id, its priority, and whether there are more territories with same priority assigned to the
 account
    */
   private class Territory2Priority {
       public Id territory2Id { get; set; }
       public Integer priority { get; set; }
       public   Boolean moreTerritoriesAtPriority { get; set; }
       
              Territory2Priority(Id territory2Id, Integer priority, Boolean moreTerritoriesAtPriority){
           this.territory2Id = territory2Id;
           this.priority = priority;
           this.moreTerritoriesAtPriority = moreTerritoriesAtPriority;
       }
   }
}}