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
Salesforce Admin2Salesforce Admin2 

Batchsync Class Statuses are not updating when push from integrated system ('Lucity') to SalesForce

Batchsync Class Statuses are not updating when push from integrated system to SalesForce error message received 'You are receiving this email because you are a member of the Public Group 311 Lucity Failure Notifications.\n\r Unable to update the cases given below due to errors. Please Find the Error Details Below\n';   The only thing that I can think that may be going on in the code is that the batch id identifier  changes when push back to Salesforce, meaning no match is found in Salesforce to update the statues. Another developer wrote the below code, and I am still new to apex code.  So I am not able to interpret everything that is going on in the code. Does anyone have an idea of what could be stopping the update of statues between the integrated app (Lucity) and SalesForce.. Code is attached. Thanking you in advance for any assistance that you may be able to give me.  Frances
/* The batch class that is used to get the lucity records, verify for changes and update
 * salesforce records accordingly. Also triggers LucitySfCaseUpdate and LucitySfOwnerUpdate.
 * Implements BRULE 16 and BRULE 24
 */

global class BatchSync implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {

public String query = 'Select Id,CaseNumber,status,Lucity_Status_code__c ,Lucity_Returned_Date__c,Lucity_Status_Type__c ,Lucity_Category_Code__c,Lucity_Prob_Code__c,Lucity_Dept_Code__c ,Lucity_Cause_Code__c,Lucity_WR_ID__c,Lucity_public_works__c,Lucity_parks__c from case where Lucity_WR_ID__c != NULL and status!=\'Closed\'';
 global Map<String,String> M = new Map<String,String>();  
     global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
     }

    global class GetLucityRequests{
        public string StatusCode;
        public string StatusType;
        public string DepartmentCode;
        public string ProblemCode;
        public string CauseCode;
        public string CategoryCode;
       
    }   
 
     global void execute(Database.BatchableContext BC, List<Case> records) {         
              
            String endpoint = null; 
            String stat2 = null;          
            List<Case> temp = new List<Case>();
            List<Authorization__c> authzn = Authorization__c.getall().values();
            String uname,pwd,works,parks;
                    if(authzn != null && authzn.size() > 0) {
                        for(Authorization__c au : authzn) {
                            uname=au.username__c;
                            pwd=au.password__c;
                            works=au.Public_works__c;
                            parks=au.Parks__c;                            
                        } 
                    }
            String before = uname+':'+pwd;
            for ( integer i = 0; i< records.size(); i++ ) {
                     if(records[i].Lucity_public_works__c == TRUE)  
                         endpoint = works+'/Work/Request.svc/?format=json&Filter=WKREQ%20WHERE%20RQ_ID%3D'+records[i].Lucity_WR_ID__c;                        
                     else 
                         endpoint = parks+'/Work/Request.svc/?format=json&Filter=WKREQ%20WHERE%20RQ_ID%3D'+records[i].Lucity_WR_ID__c;
                         
             System.debug('End Point '+endpoint + 'Record size '+records.size());    
             if(Test.isRunningTest()) {
                      GetLucityRequests r = new GetLucityRequests();
                      endpoint = works+'/Work/Request.svc/?format=json&Filter=WKREQ%20WHERE%20RQ_ID%3D'+records[i].Lucity_WR_ID__c;
              }        
             try {                  
                  HttpRequest req = new HttpRequest();
                  HttpResponse res = new HttpResponse();
                  Http http = new Http();                  
                  Blob beforeblob = Blob.valueOf(before);
                  //encode
                  String paramvalue = EncodingUtil.base64Encode(beforeblob);
                  System.debug(before + ' is now encoded as: ' + paramvalue);
                  String auth = 'Basic '+ paramvalue ;
                  req.setHeader('Authorization',auth);                   
                  req.setHeader('Content-Type', 'application/json');                                  
                  String sJson = null;  
                  Integer statCode=null;
                  String stat=null;                      
                  // req.setCompressed(true);                  
                  if (!Test.isRunningTest()) { 
                    req.setEndpoint(endpoint); 
                    req.setMethod('GET');     
                    res = http.send(req);
                    statCode = res.getStatusCode();
                    if(statCode == 200 || statCode == 201) {
                        sJson = res.getBody();                   
                        System.debug('Str:' + res.getBody());
                        sJson = sJson.replace('[','');
                        sJson = sJson.replace(']','');
                        System.debug('String JSON: ' + sJson);
                        // Parse response.  
                        GetLucityRequests aResponse = (GetLucityRequests) Json.Deserialize(sJson, GetLucityRequests.class);                    
                        if((records[i].Lucity_Status_code__c != Integer.ValueOf(aResponse.StatusCode)) || (records[i].Lucity_Status_Type__c != aResponse.StatusType)) {
                            records[i].Lucity_Status_code__c = Integer.ValueOf(aResponse.StatusCode);
                            records[i].Lucity_Status_Type__c = aResponse.StatusType;
                            if((aResponse.StatusCode == '10') && (records[i].Lucity_Dept_Code__c != aResponse.DepartmentCode)) {
                                records[i].Lucity_Dept_Code__c = aResponse.DepartmentCode;
                            }
                            if((aResponse.StatusCode == '10') && (records[i].Lucity_Prob_Code__c!= aResponse.ProblemCode)) {
                                records[i].Lucity_Prob_Code__c= aResponse.ProblemCode;
                            }
                            if((records[i].Lucity_Parks__c == TRUE) && (aResponse.StatusCode == '10') && (records[i].Lucity_Cause_Code__c!= aResponse.CauseCode)) {
                                records[i].Lucity_Cause_Code__c= aResponse.CauseCode;
                            }
                            if((records[i].Lucity_Parks__c == TRUE) && (aResponse.StatusCode == '10') && (records[i].Lucity_Category_Code__c!= aResponse.CategoryCode)) {
                                records[i].Lucity_Category_Code__c= aResponse.CategoryCode;
                            }
                            if(aResponse.StatusCode == '952') {
                                records[i].Lucity_Returned_Date__c= System.NOW();
                            }
                             System.debug('Lucity Status code '+ records[i].Lucity_Status_code__c);
                            temp.add(records[i]);               
                            System.debug('TEMP '+temp);
                        }  
                       System.debug('Status code '+aResponse.StatusCode + 'Status Type ' +aResponse.StatusType + 'Department code ' + aResponse.DepartmentCode);              
                    }
                    else {
                        stat = 'Status Code: ' + statCode + '. \n Status: ' + res.getStatus() + '. \n Cause of Error might be: Invalid URL/Server Down/Case doesn\'t exist in Lucity Server.\n\r';
                        M.put(records[i].CaseNumber,stat);
                        system.debug('STAT ' + stat + ' MAP ' + M + ' CaseNumber ' +  records[i].CaseNumber);
                    }                               
                  }             
          }
          catch (Exception e) {         
            System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );             
                  
          }
       }
      if(temp.size() > 0) {  
          Database.SaveResult[] srList = null;
          try {         
            srList = Database.update(temp,false);
          }
          catch(Exception ex)    {             
                for (Database.SaveResult sr : srList) {
                    if (!sr.isSuccess()) {
                        // Operation failed, so get all errors                
                        for(Database.Error err : sr.getErrors()) {
                            System.debug('The following error has occurred.');                    
                            System.debug(err.getStatusCode() + ': ' + err.getMessage());
                            System.debug('Case fields that affected this error: ' + err.getFields());
                            stat2 = 'Error occurred during updation.Details are as follows \n Status code: ' + err.getStatusCode() + '\n Error Message ' + err.getMessage() + '\nCase fields that affected this error: ' + err.getFields();
                            String cNum = sr.getId();
                            List<Case> casNum = [Select CaseNumber from Case where Id=: cNum];
                            M.put(casNum[0].CaseNumber,stat2);
                        }
                        sendErrorEmail(M);
                    }
                }    
          }  
      } 
       System.debug('Updated and Future boolean is '+ CaseFieldUpdate.inLucityFutureContext );
    }   

    global void finish(Database.BatchableContext BC){
        CaseFieldUpdate.inLucityFutureContext = false;
        system.debug('MAP AT FINISH ' + M + ' SIZE' + M.size());
        if (!Test.isRunningTest())
            sendErrorEmail(M);          
    }
    
  public void sendErrorEmail(Map<String,String> M) {      
        String[] toAddresses = getMailAddresses();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();             
        mail.setToAddresses(toAddresses);
        mail.setUseSignature(false);
        mail.setBccSender(true);
        mail.setSaveAsActivity(false);   
        Authorization__c aut = Authorization__c.getValues('Lucity');
        String sub = aut.Email_Subject__c;
        System.debug(sub);               
        mail.setSubject('Batch Sync Job Error Summary '+ sub);
        String mailBody = '';
        system.debug('MAP ' + M + ' Size ' + M.size());
        if(M.size() > 0) {
            mailBody = 'You are receiving this email because you are a member of the Public Group 311 Lucity Failure Notifications.\n\r Unable to update the cases given below due to errors. Please Find the Error Details Below\n';
            for(String str : M.KeySet()) {
                mailBody += 'Case Number : ' + str + '\n ERROR \n ' + M.get(str);
            }
           system.debug('Mail Body ' + mailBody);
           mail.setPlainTextBody(mailBody);                  
           Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
         }
         
  }  
    
   public List<String> getMailAddresses()
     {
                  List<String> mailList = new List<String>();
                  List<String> mailAddresses = new List<String>(); 
                  
                  Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = '311 Lucity Failure Notifications'];
                  for (GroupMember gm : g.groupMembers) 
                  {
                   mailList.add(gm.userOrGroupId);
                  }
                  User[] usr = [SELECT email FROM user WHERE id IN :mailList];
                  for(User u : usr) 
                  {
                  mailAddresses.add(u.email);
                  } 
                  return mailAddresses;
      } 
}