• Maria22
  • NEWBIE
  • 10 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 17
    Questions
  • 30
    Replies
Hi Experts,
I have a VF page for creation of an address from account.I mean we have Address as a related list on Account and in that related list we have a Crete New button which when clicked will opens up a VF page where user can fill details and Save records.
Every thing is working fine till now except one condition where I stuck badly.
Requirement
We have 2 checkboxes on VF page called as "Primary" and "Mailing". An account can have more than 1 addresses but at one time only 1 address can have Primary checkbox as checked and only one address has Mailing as checked.Suppose an account has 4 addresses in which Address 1 has Primary checkbox checked,Address 2 and 3 doesn't have either of the two checkbox checked,Addreress 4 has Mailing checkbox selected.
Now I have a requirement when already an address exits with both Flags "Current Residence(API Name-Primary__c) and Mailing(API Name-Mailing__c)" checked and then user is trying to create another address and if select "Current Residence" checkbox then "Mailing" checkbox will be selected automatically.I achieved this through the logic written behind Save button.When user tries to create another address and select Current Residence checkbox and clicks on Save button then "Mailing" checkbox is getting saved automatically upon saving of record. But business doesn't need thi solution after hitting Save button.What they need is to check the "Mailing" checkbox automatically once user is trying to create another address and check the "Current Residence" and that account already has one address where both flags were checked automatically


Below is the part of the code from Controlller which I did intially behind Save button
global Address__c addr{get; set;} 
List<Address__c> addrList = [select id, Mailing__c, Primary__c, (select Type__c, Primary__c from Address_Types__r) from Address__c 
                                     where Account__c=:acc.Id and Primary__c = true
                                     order by LastModifiedDate desc limit 1];

if (!addrList.isEmpty()) {
            primaryAddress = addrList[0];
}
 public PageReference Save()
    {   

if(primaryAddress != null && addr.Primary__c==true && primaryAddress.Mailing__c==true){
             
            addr.Mailing__c=true;
        }
}

But due to business requiremet they dont need behind Save button rather they need onclick of the checkbox itself.

Below is the part from my VF page
 
<apex:page id="thePage" standardController="Account" extensions="VFC_NewAddress" standardStylesheets="true" >
<style>
        body .bPageBlock .pbBody .grey .pbSubheader{
            background-color:#FFDADA;
        }
        body .label{
            padding-left: 2px;
            font-size: 91%;
            font-weight: bold;
        } 
        body .btn{
        }  
    </style>

<apex:pageBlockButtons id="btnid">  
                <apex:commandButton action="{!save}" value="Save" id="doSave" styleClass="btn" onclick="return validate();"/>
                <apex:commandButton action="{!cancel}" value="Cancel" onclick="return handleConsole();"/>
</apex:pageBlockButtons>
 <apex:outputPanel styleClass="grey" layout="block" id="panelId">
              
 <apex:pageBlockSection title="Information" columns="1" id="pageBlockSecId">
<apex:pageBlockSectionItem id="item20" >
                        <apex:outputText value="Current Residence" ></apex:outputText>
                        <apex:inputField value="{!addr.Primary__c}" id="primary"/>
                    </apex:pageBlockSectionItem>
                    
                    <apex:pageBlockSectionItem id="item100">
                        <apex:outputText value="Mailing" ></apex:outputText>
                        <apex:inputField value="{!addr.Mailing__c}" id="mailing"/>
                    </apex:pageBlockSectionItem>
                    
                </apex:pageBlockSection> 
</apex:outputPanel>
            
        </apex:pageBlock>
        
    </apex:form>
</apex:page>

Below is the sample screenshot
User-added imageOnce user selects Current Residence checkbox then Primary checkbox will be automatically selected without hitting Save button.Also this needs to be happen only when the account has such an address where both flag are on same address.Obviously because at any time only one address can have Current Residenec as checked or Primary as checked or may have both checked.

So as a business user the requirement should look like below
GIVEN user in Salesforce updated existing address to be the new Current Residence
WHEN user selects the Current Resident flag on existing address
AND account has an address where both Current Residenece and Mailing are checked
THEN the system automatically ticks the Mailing flag when Current Residence flag is selected on new address
    AND system does NOT allow Mailing to be unchecked
    AND if user tries they see message displayed on screen: 
'One active address must always be marked as Mailing.  Kindly select a different address to be Mailing or if customer has withdrawn consent please update their consent page.’

I didnt paste complete VF page and controller only those seems to be relevant as per my question.So I posted only relevant part from my code.

I hope I have provided detailed infor regarding my issue and somebody will definitely help me

Kindly help me

Many thanks in advance

Thanks & Regards,
Maria
HI All,

I got stuck at one place where I am not able to cover a particular catch block consisting application exception. Currently my test class is getting pass succefully with 72% coverage but not able to cover one catch block.

Below is my class:
@RestResource(urlMapping='/v1/someurl/*')
global with sharing class VerifiableAPI {
    
   private static BasicRestResponse response;
    
    @HttpPost
    global static void doPost(Request request) {
        Exception ex = null;
        Savepoint sp = Database.setSavepoint();
        CareService svr = null;
        
        try {
            svr =CareService(request, CareService.APIType.VERIFIABLE);
            svr.doPost();
            
            response = new RestResponseSuccess();
        } catch (ApplicationException e) {
            if (response == null) { response = new RestResponseError(); }
            response.setError('INVALID_REQUEST', e.getMessage());
            ex = e;
            Database.rollback(sp);
        } catch (Exception e) {
            if (response == null) { response = new RestResponseError(); }
            response.setError('INTERNAL_ERROR', e.getMessage());
            ex = e;
            Database.rollback(sp);
        }
        
        if (ex != null) {
            ApplicationLog.LogMessage('Error', 'CareVerifiableAPI', 'doPost', null, null, 
                                  JSON.serialize(response), JSON.serialize(RestContext.request), ex);
        }
        
      
        
        response.publish();
    }
    
    /**
     * Request of the API Call
     */
     global class Request {
        
         global String consent;
         
        
     }
}

Below is my test class:
@isTest
private class VerifiableAPITest {

    static testMethod void myUnitTest() {
      ;
       
           VerifiableAPI.Request reqst=new VerifiableAPI.Request();
        	reqst.consent='consent';
      
       
            String JsonMsg=JSON.serialize(reqst);
            Test.startTest();  
  		

           RestRequest req = new RestRequest(); 
           RestResponse res = new RestResponse();
        
            req.requestURI = '/services/apexrest/v1/demo';  //Request URL
            req.httpMethod = 'POST';//HTTP Request Type
            req.requestBody = Blob.valueof(JsonMsg);
            RestContext.request = req;
            RestContext.response= res;
        
           BasicRestResponse resp= new BasicRestResponse();
            resp.setError('title', 'detail');
            resp.setData(null);
            resp.getData();
            resp.publish();
            
        VerifiableAPI.doPost(reqst);
            Test.stopTest();
        
    }

}

Below is the catch block which I am not able to cover:
response = new RestResponseSuccess();
        } catch (ApplicationException e) {
            if (response == null) { response = new RestResponseError(); }
            response.setError('INVALID_REQUEST', e.getMessage());
            ex = e;
            Database.rollback(sp);
}

Any help will be gra​​​​​​eatly appreciated.

Many thanks in advance
HI All,

I got stuck at one place where I am not able to cover a particular catch block consisting application exception. Currently my test class is getting pass succefully with 72% coverage but not able to cover one catch block.

Below is my class:
 
@RestResource(urlMapping='/v1/someurl/*')
global with sharing class VerifiableAPI {
    
   private static BasicRestResponse response;
    
    @HttpPost
    global static void doPost(Request request) {
        Exception ex = null;
        Savepoint sp = Database.setSavepoint();
        CareService svr = null;
        
        try {
            svr =CareService(request, CareService.APIType.VERIFIABLE);
            svr.doPost();
            
            response = new RestResponseSuccess();
        } catch (ApplicationException e) {
            if (response == null) { response = new RestResponseError(); }
            response.setError('INVALID_REQUEST', e.getMessage());
            ex = e;
            Database.rollback(sp);
        } catch (Exception e) {
            if (response == null) { response = new RestResponseError(); }
            response.setError('INTERNAL_ERROR', e.getMessage());
            ex = e;
            Database.rollback(sp);
        }
        
        if (ex != null) {
            ApplicationLog.LogMessage('Error', 'CareVerifiableAPI', 'doPost', null, null, 
                                  JSON.serialize(response), JSON.serialize(RestContext.request), ex);
        }
        
      
        
        response.publish();
    }
    
    /**
     * Request of the API Call
     */
     global class Request {
        
         global String consent;
         
        
     }
}

Below is my test class:
 
@isTest
private class VerifiableAPITest {

    static testMethod void myUnitTest() {
      ;
       
           VerifiableAPI.Request reqst=new VerifiableAPI.Request();
        	reqst.consent='consent';
      
       
            String JsonMsg=JSON.serialize(reqst);
            Test.startTest();  
  		

           RestRequest req = new RestRequest(); 
           RestResponse res = new RestResponse();
        
            req.requestURI = '/services/apexrest/v1/demo';  //Request URL
            req.httpMethod = 'POST';//HTTP Request Type
            req.requestBody = Blob.valueof(JsonMsg);
            RestContext.request = req;
            RestContext.response= res;
        
           BasicRestResponse resp= new BasicRestResponse();
            resp.setError('title', 'detail');
            resp.setData(null);
            resp.getData();
            resp.publish();
            
        VerifiableAPI.doPost(reqst);
            Test.stopTest();
        
    }

}

Below is the catch block which I am not able to cover:
 
response = new RestResponseSuccess();
        } catch (ApplicationException e) {
            if (response == null) { response = new RestResponseError(); }
            response.setError('INVALID_REQUEST', e.getMessage());
            ex = e;
            Database.rollback(sp);
}

Any help will be gra​​​​​​eatly appreciated.

Many thanks in advance
Hi Everyone,

I stuck at one place and could not able to resolve the issue.I know what is the issue and where its happening still I am clueless.Actually I am getting System.NullPointerException: Argument cannot be null in Test Class.

Below is my class:
 
01global with sharing class Audit {
02     
03    global String created_by;
04    global String reason;
05    global String requested_by_customer;
06    global String requested_by_type;
07    // Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
08    global Long requested_datetime;
09    global String requested_method;
10    global String others;
11    global String source_system;
12     
13     
14    global Consent_History__c getConsentHistory() {
15        Consent_History__c consentHistory = newConsent_History__c();
16         
17        consentHistory.Consent_Change_Created_By__c= this.created_by;
18        consentHistory.Change_Reason__c =this.reason;
19        consentHistory.Consent_Change_Requested_By_Customer__c= this.requested_by_customer;
20        consentHistory.Change_Received_From_Type__c= this.requested_by_type;
21        consentHistory.Change_Received_DateTime__c= DateTime.newInstance(this.requested_datetime);
22        consentHistory.Change_Received_Method__c= this.requested_method;
23        consentHistory.Consent_Change_Others__c =this.others;
24        consentHistory.Source_System__c =this.source_system;
25         
26        return consentHistory;
27    }
28}
Below is my test class:
01@isTest
02private class AuditTest {
03 
04    static testMethod void getConsentHistory() {
05       
06        Datetime myDate=System.now();
07         
08        Consent_History__c consentHistory = newConsent_History__c();
09       
10        consentHistory.Consent_Change_Created_By__c= 'User1@cochlear.com';
11        consentHistory.Change_Reason__c ='Test';
12        consentHistory.Consent_Change_Requested_By_Customer__c= 'Customer1';
13        consentHistory.Change_Received_From_Type__c='Professional';
14        consentHistory.Change_Received_DateTime__c= myDate;
15        consentHistory.Change_Received_Method__c= 'Consent Card';
16        consentHistory.Consent_Change_Others__c ='Consent Test';
17        consentHistory.Source_System__c=Constants.SYSTEM_MCP;
18       insert consentHistory;
19         
20       Test.startTest();
21       
22       Audit audit=new Audit();
23       audit.getConsentHistory();
24       Test.stopTest();
25         
26    }
27   
28}
I am receiving error at below line in class:
1consentHistory.Change_Received_DateTime__c =DateTime.newInstance(this.requested_datetime);
and below line in test class:
1audit.getConsentHistory();
I understand that there is something which I am not able to catch for date time in above class which results in returning null value.

Kindly help me to pass this error in my test class.

Any help will be greatly appreciated.

Many thanks in advance

Thanks & Regards,
Maria
Hi Everyone,

I stuck at one place and could not able to resolve the issue.I know what is the issue and where its happening still I am clueless.Actually I am getting System.NullPointerException: Argument cannot be null in Test Class.

Below is my class:
 
global with sharing class Audit {
    
    global String created_by;
    global String reason;
    global String requested_by_customer;
    global String requested_by_type;
    // Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
    global Long requested_datetime;
    global String requested_method;
    global String others;
    global String source_system;
    
    
    global Consent_History__c getConsentHistory() {
        Consent_History__c consentHistory = new Consent_History__c();
        
        consentHistory.Consent_Change_Created_By__c = this.created_by;
        consentHistory.Change_Reason__c = this.reason;
        consentHistory.Consent_Change_Requested_By_Customer__c = this.requested_by_customer;
        consentHistory.Change_Received_From_Type__c = this.requested_by_type;
        consentHistory.Change_Received_DateTime__c = DateTime.newInstance(this.requested_datetime);
        consentHistory.Change_Received_Method__c = this.requested_method;
        consentHistory.Consent_Change_Others__c = this.others;
        consentHistory.Source_System__c = this.source_system;
        
        return consentHistory;
    }
}

Below is my test class:
@isTest
private class AuditTest {

    static testMethod void getConsentHistory() {
      
        Datetime myDate=System.now();
        
        Consent_History__c consentHistory = new Consent_History__c();
      
        consentHistory.Consent_Change_Created_By__c = 'User1@cochlear.com';
        consentHistory.Change_Reason__c ='Test';
        consentHistory.Consent_Change_Requested_By_Customer__c = 'Customer1';
        consentHistory.Change_Received_From_Type__c ='Professional';
        consentHistory.Change_Received_DateTime__c = myDate;
        consentHistory.Change_Received_Method__c = 'Consent Card';
        consentHistory.Consent_Change_Others__c = 'Consent Test';
        consentHistory.Source_System__c =Constants.SYSTEM_MCP;
       insert consentHistory;
        
       Test.startTest();
      
       Audit audit=new Audit();
       audit.getConsentHistory();
       Test.stopTest();
        
    }
  
}

I am receiving error at below line in class:
consentHistory.Change_Received_DateTime__c = DateTime.newInstance(this.requested_datetime);

and below line in test class:
audit.getConsentHistory();

I understand that there is something which I am not able to catch for date time in above class which results in returning null value.

Kindly help me to pass this error in my test class.

Any help will be greatly appreciated.

Many thanks in advance

Thanks & Regards,
Maria

​​​​​​​
I got stuck at one place on one of my requirement on which I am working on.

My use case is as follows:
 
SCENARIO 1: Close Opportunity when Upgrade Order is cancelled 
GIVEN a a person account record in Salesforce AND the has an open upgrade opportunity record in Salesforce AND the opportunity record type equals "Upgrade Opportunity" AND the opportunity stage is not "Closed - Won" WHEN  places an upgrade order AND the status of the upgrade order has been changed to Cancelled THEN the open upgrade opportunity Stage field is set to "Closed - Lost" AND all other related opportunities that also meet this scenario criteria (Upgrade Opportunity, not Closed-Won) are set to "Closed - Lost"

I have done the scenario and code is also getting saved but getting System.NullPointerException:Attempt to de-reference a null Object when try to change the status of an upgrade order from a value say"Order-Placed" to "Cancelled"

Below is my Apex Class which runs in before update from Apex Trigger:
 
public with sharing class OrderTriggerService extends TriggerService {
public void updateOpportunityStage(){
        Set<Id> setIds = new Set<Id>();
        Map<Id,Order> orderOldMap =(Map<Id,Order>)oldMap;
        Map<Id,Order> orderNewMap=(Map<Id,Order>)newMap;
        Set<Opportunity>  updateOppties=new Set<Opportunity>();
        DateTime statusChange= System.now()-90;
        
        for (Order childObj : (List<Order>) newList) {
            if(childObj.Account_Record_Type_Name__c == 'Recipient' && childObj.Record_Type_Dev_Name__c == 'Upgrade_Order'){ 
            setIds.add(childObj.AccountId);
               
            }
        }
        if (setIds.isEmpty()) { return; }
        
        Map<ID, Account> parentAccts = new Map<Id, Account>(
                                          [select id, Upgrade_Order_Booked_Date__c, Upgrade_Order_Status__c, Order_Cancellation_Reason__c,Upgrade_Order_Number__c,Order_Cancellation_Date__c,
                                          (select id, Name, Booked_Date__c, Status ,Order_Cancellation_Reason__c,Oracle_Order_Number__c,Order_Cancellation_Date__c
                                            from Orders ) 
                                           from Account where id in :setIds]);
        System.debug('updateOrderUpgrade parentAccts: ' + parentAccts);
        
        Map<Account, Order> accountToLatestOrder = new Map<Account, Order>();
        for (Account acc : parentAccts.values()) {
            if (acc.orders.isEmpty() == false) {
                accountToLatestOrder.put(acc, acc.orders[0]);
            }
        }
         
    
      for(Account acc : [select id, Upgrade_Order_Booked_Date__c, Upgrade_Order_Status__c, Order_Cancellation_Reason__c,Upgrade_Order_Number__c,Order_Cancellation_Date__c,
                         			(select Id,Name,closedate,amount,StageName,Oracle_Order_Number__c,Status_Last_Changed_On__c
                                     from opportunities where Record_Type_Dev_Name__c='Upgrade_Opportunity') 
                         			from Account where id in : setIds]){
                             
                             for(Order orders : accountToLatestOrder.values()){            
                             		for(Opportunity opps : acc.opportunities){
                                 
                                 		if(opps.StageName<>'Upgrade-Closed Won' && orders.Status!=orderOldMap.get(orders.Id).Status && orders.Status=='Cancelled'){
                                 		
                                                 opps.StageName='Upgrade - Closed Lost'; 
                                                 
                                                 
                                 		}
                               
                            	
                                 System.debug('updateOpportunityStage Opportunity: ' + opps);  
                    			updateOppties.add(opps);
                             }
                             }
                         }
        
         				List<Opportunity> updateopps=new List<Opportunity>(updateOppties);
        				update updateopps;
        			}
}

Also,attached is the screenshots

Errors snapshot taken from UI

Kindly help me.

Any help will be greatly appreciated.

Many thanks​
I got stuck at one place on one of my requirement on which I am working on.

My use case is as follows:
 
SCENARIO 1: Close Opportunity when Upgrade Order is cancelled 
GIVEN a a person account record in Salesforce AND the has an open upgrade opportunity record in Salesforce AND the opportunity record type equals "Upgrade Opportunity" AND the opportunity stage is not "Closed - Won" WHEN the recipient places an upgrade order AND the status of the upgrade order has been changed to Cancelled THEN the open upgrade opportunity Stage field is set to "Closed - Lost" AND all other related opportunities that also meet this scenario criteria (Upgrade Opportunity, not Closed-Won) are set to "Closed - Lost"
 
CENARIO 2: Close Opportunity when Upgrade Order is shipped (ie Closed in Salesforce)
GIVEN a person account record in Salesforce
    AND thehas an opportunity record in Salesforce 
    AND the opportunity record type equals "Upgrade Opportunity"
    AND the stage of the opportunity record is not Closed-Won
    AND the stage of the opportunity record is not Closed-Lost (unless the stage was automatically set to Closed-Lost within the past 90 days due to an order cancellation)
WHEN the places an upgrade order
    AND the upgrade order has a status of Closed
THEN the open upgrade opportunity Stage field is set to "Closed - Won"
    AND all other related opportunities that also meet this scenario criteria (Upgrade Opportunity, not Closed-Won, not Closed-Lost unless automatically changed to Closed-Lost within 90 days) are set to "Closed - Won"

I have done 1st scenario and works well.For 2nd scenario also I have done almost everything except one scenario where I need to track "the stage of the opportunity record is not Closed-Lost (unless the stage was automatically set to Closed-Lost within the past 90 days due to an order cancellation)

Below is my Apex Class which runs in before update from Apex Trigger:
 
public with sharing class OrderTriggerService extends TriggerService {


public void updateOpportunityStage(){
    Set<Id> setIds = new Set<Id>();
    Map<Id,Order> orderOldMap =(Map<Id,Order>)oldMap;
    Set<Opportunity>  updateOppties=new Set<Opportunity>();

    for (Order childObj : (List<Order>) newList) {

        if(childObj.Account_Record_Type_Name__c == 'INDIA' && childObj.Record_Type_Dev_Name__c == 'Upgrade_Order'){ 
        setIds.add(childObj.AccountId);

        }
    }
    if (setIds.isEmpty()) { return; }

 //Set<Opportunity>  updateOppties=new Set<Opportunity>();
  for(Account acc : [select id,Name
                        (selectId,Name,closedate,amount,StageName
                             from opportunities where 
                            Record_Type_Dev_Name__c='Upgrade_Opportunity') 
                                from Account where id in:setIds]){

                         for(Order orders : (List<Order>) newList){            
                                for(Opportunity opps : acc.opportunities){

                                    if(opps.StageName<>'Closed Won' && orders.Status!=orderOldMap.get(orders.Id).Status && orders.Status=='Cancelled'){
                                             opps.StageName='Closed Lost'; 


                                    }

                            else if((opps.StageName<>'Closed Won'||opps.StageName<>'Closed Lost')&& orders.Status!=orderOldMap.get(orders.Id).Status && orders.Status=='Closed'){         
                                        opps.StageName='Closed Won';

                             }

                            updateOppties.add(opps);
                         }
                         }
                     }

                    List<Opportunity> updateopps=new List<Opportunity(updateOppties);
                    update updateopps;

}
  }
I am not able to find a way to track opp.stagename<>'Closed Lost'(unless the stage was automatically set to Closed-Lost within the past 90 days due to an order cancellation) in my class.
Kindly help.

Any help will be greatly appreciated.

Many thanks in advance
 
Hi Experts,

I am working on one requirement and I got stuck at one place. I hope someone will help me to resolve my problem and guide me in proper directions.

My use case is as follows:
SCENARIO 1: Close Opportunity when Upgrade Order is cancelled 
GIVEN a  a person account record in Salesforce 
AND the has an open upgrade opportunity record in Salesforce 
AND the opportunity record type equals "Upgrade Opportunity" 
AND the opportunity stage is not "Closed - Won" 
WHEN the recipient places an upgrade order AND the status of the upgrade order has been changed to Cancelled THEN the open upgrade opportunity Stage field is set to "Closed - Lost" 
AND all other related opportunities that also meet this scenario criteria (Upgrade Opportunity, not Closed-Won) are set to "Closed - Lost"
 
SCENARIO 2: Close Opportunity when Upgrade Order is shipped (ie Closed in Salesforce)
    GIVEN a person account record in Salesforce
        AND thehas an opportunity record in Salesforce 
        AND the opportunity record type equals "Upgrade Opportunity"
        AND the stage of the opportunity record is not Closed-Won
        AND the stage of the opportunity record is not Closed-Lost (unless the stage was automatically set to Closed-Lost within the past 90 days due to an order cancellation)
    WHEN the places an upgrade order
        AND the upgrade order has a status of Closed
    THEN the open upgrade opportunity Stage field is set to "Closed - Won"
        AND all other related opportunities that also meet this scenario criteria (Upgrade Opportunity, not Closed-Won, not Closed-Lost unless automatically changed to Closed-Lost within 90 days) are set to "Closed - Won"

I have done 1st scenario and works well.For 2nd scenario also I have done almost everything except one scenario where I need to track "the stage of the opportunity record is not Closed-Lost (unless the stage was automatically set to Closed-Lost within the past 90 days due to an order cancellation)"

Below is my Apex Class which runs in before update from Apex Trigger:
 
public with sharing class OrderTriggerService extends TriggerService {
    
   
    public void updateOpportunityStage(){
        Set<Id> setIds = new Set<Id>();
        Map<Id,Order> orderOldMap =(Map<Id,Order>)oldMap;
        Set<Opportunity>  updateOppties=new Set<Opportunity>();
        
        for (Order childObj : (List<Order>) newList) {
            
            if(childObj.Account_Record_Type_Name__c == 'INDIA' && childObj.Record_Type_Dev_Name__c == 'Upgrade_Order'){ 
            setIds.add(childObj.AccountId);
               
            }
        }
        if (setIds.isEmpty()) { return; }
         
     //Set<Opportunity>  updateOppties=new Set<Opportunity>();
      for(Account acc : [select id,Name
                         	(selectId,Name,closedate,amount,StageName
                                 from opportunities where 
                                Record_Type_Dev_Name__c='Upgrade_Opportunity') 
                         			from Account where id in:setIds]){
                             
                             for(Order orders : (List<Order>) newList){            
                             		for(Opportunity opps : acc.opportunities){
                                 
                                 		if(opps.StageName<>'Closed Won' && orders.Status!=orderOldMap.get(orders.Id).Status && orders.Status=='Cancelled'){
                                                 opps.StageName='Closed Lost'; 
                                                 
                                                 
                                 		}
                               
                            	else if((opps.StageName<>'Closed Won'||opps.StageName<>'Closed Lost')&& orders.Status!=orderOldMap.get(orders.Id).Status && orders.Status=='Closed'){         
                               				opps.StageName='Closed Won';
                                    	 	
                                 }
                                
                    			updateOppties.add(opps);
                             }
                             }
                         }
        
         				List<Opportunity> updateopps=new List<Opportunity(updateOppties);
        				update updateopps;
        			
    }
      }

I am not able to find a way to track opp.stagename<>'Closed Lost'(unless the stage was automatically set to Closed-Lost within the past 90 days due to an order cancellation) in my class.

Kindly help.

Any help will be greatly appreciated.

Many thanks in advance
Hi All,

I have written a trigger on Order object which will take the status of Order Start Date field from Order and copy the same on "Upgrade Order Date" field in accounts.

I am receiving System.NullPointerException and I am not able to find out where I am making mistakes or what I have done wrong.

Below is my trigger:
trigger OrderTrigger on Order (after insert) {
                
    OrderTriggerHandler orderhandler= new OrderTriggerHandler(trigger.new);
    
     if(trigger.isAfter && trigger.isInsert) {  
         orderhandler.HandleAfterInsert();
     }
    
}

Below is my trigger Handler:
 
public class OrderTriggerHandler {
   List<Order>newOrders;
 
    public OrderTriggerHandler(List<Order>newOrders){
        this.newOrders=newOrders;
        
    }
    
    public void HandleAfterInsert(){ 
       updateOrderUpgradeStatus();
    }
    
    
    public void updateOrderUpgradeStatus(){
        
         Map<ID, Account> parentAccts = new Map<ID, Account>(); //Making it a map instead of list for easier lookup
          //List<Id> listIds = new List<Id>();
            Set<Id> setIds=new Set<Id>();
        
            for (Order childObj : newOrders) {
            setIds.add(childObj.Name);
          }
        
            system.debug('The value is: ' + parentAccts);
            //parentAccts = new Map<Id, Account>([Select id,Name,Upgrade_Order_Date__c,(Select id,EffectiveDate,Name,Header_Id__c from Orders where RecordType.name = 'Upgrade Order' ORDER BY Header_Id__c DESC) from Account WHERE  ID IN :setIds AND RecordType.name = 'Recipient']);
          parentAccts = new Map<Id, Account>([Select id,Name,Upgrade_Order_Date__c,(Select id,Name,EffectiveDate,Header_Id__c,Status from Orders where RecordType.name = 'Upgrade Order' ORDER BY Header_Id__c DESC NULLS LAST) from Account WHERE  ID IN :setIds AND RecordType.name = 'Recipient' ]);
          for (Order order: newOrders){
              
            // if(Order.Type=='Upgrade Order'){
              
             Account myParentAcct = parentAccts.get(order.Name);
               system.debug('The value is: ' + myParentAcct);    
             myParentAcct.Upgrade_Order_Date__c= order.EffectiveDate;
              //order.EffectiveDate=myParentAcct.Upgrade_Order_Date__c;
             
              //}
          }
        system.debug('The value is: ' + parentAccts);
   		 update parentAccts.values();
         
            }
     
        
    }

I ran the query in workbench and getting few records as well but in debug logs "parentAccts" doesn'r returning any row and line
system.debug('The value is: ' + myParentAcct);

retuen null and  myParentAcct.Upgrade_Order_Date__c= order.EffectiveDate shows the attempt to de-reference a null object.

Kindly help/guide/suggests.
Any help will be greatly apprecaited

Many thanks in advance

Thanks & Regards,
Harjeet
  • September 05, 2018
  • Like
  • 0
Hi All,

I hope everyone is doing good. I turned up here for a valuable advise from all of you experts.

My usecase is as below:

We have 2 objects "Accounts" and "Orders". I need to update one field on account object called as "Upgrade Order Status"(API Name- Upgrade_Order_Status__c) which is a text field with the value of "Order Status" field of only that Order where new Order is being created as Order Type = 'Upgarde Order' or an already existing order with Order type='Upgarde Order' and status is getting changed.

Order type is a picklist field on Order object having multiple values in which "Upgrade Order" is one of among them. Account can have multiple Orders with different Order Type.But my use case is to populate account's "Upgrade Order Status" field with the Order status field value of recently created order having order type= "Upgarde Order' OR there is a change in Order Status field of an already existing Orders of type "Upgrade Order".

Illustartion:
Account Name: Account Demo
has 5 Orders with different Order Type
1. Order1 with Order Type= "ABC" with Order Status= "New"
2. Order2-with Order Type= "Upgrade Order" with Order Status="Open"
3. Order3 with Order Type= "XYZ" with Order Status="Open"
4. Order4 with Order Type="Upgrade Order" with Order Status= "New"
5. Order 5 with Order Type="ABCQRS"with Order Status= "Closed"
So we need to populated "Upgrade Order Status" with the status value of recently created/changed Orders's Status where Order Type= "Upgrade Order".So if suppose among 5 above mentioned orders if Order 4 is recently created  orders with Order Type="Upgrade Order" then "Upgrade Order Status" on account should be populated with value "New" because Order 4 is having Order Status= "New".
In case if we modify Order 2 and changed the status from "Open" to "Closed" then "Upgrade Order Status" on account should be populated with value "Closed" because Order 2 is recently modified order with order type=Upgarde Order.

My issues is
Trigger is working for when I am creating new Order and status is getting copied to account's field OR when I am changing the status of Order then also status is getting copied to account's field. But its is working only for the recently cretaed Orders.It is not working when I tried to change the status of an older Orders with Order type= Upgarde Order then status is not getting copied to Account's field. 

Below is my Trigger Code:
 
trigger OrderTrigger on Order (after insert, after update) {

 Map<ID, Account> parentAccts = new Map<ID, Account>(); //Making it a map instead of list for easier lookup

Set<Id> setIds=new Set<Id>();

  for (Order childObj : Trigger.new) {
    setIds.add(childObj.Bill_to_Customer__c);
  }

 system.debug('The value is: ' + parentAccts);
  parentAccts = new Map<Id, Account>([Select id,Type,Upgrade_Order_Status__c,(Select id,Type,OrderNumber,Bill_to_Customer__c,Status from Orders where Type ='Upgrade Order') from Account WHERE ID IN :setIds]);


  for (Order order: Trigger.new){
      
      if(Order.Type=='Upgrade Order'){
      
     Account myParentAcct = parentAccts.get(order.Bill_to_Customer__c);
       system.debug('The value is: ' + myParentAcct.Upgrade_Order_Status__c );    
     myParentAcct.Upgrade_Order_Status__c = order.Status;
     
      }
  }
system.debug('The value is: ' + parentAccts);
  update parentAccts.values();
}

Account is Parent Object
Order is related object.

Kindly help/suggests on above.

Any help will be greatly appreciated

Many thanks in advance

Thanks & Regards,
Harjeet​
Hi All,

I hope everyone is doing good. I turned up here for a valuable advise from all of you experts.

My usecase is as below:

We have 2 objects "Accounts" and "Orders". I need to update one field on account object called as "Upgrade Order Status"(API Name- Upgrade_Order_Status__c) which is a text field with the value of "Order Status" field of only that Order where new Order is being created as Order Type = 'Upgarde Order' or an already existing order with Order type='Upgarde Order' and status is getting changed.

Order type is a picklist field on Order object having multiple values in which "Upgrade Order" is one of among them. Account can have multiple Orders with different Order Type.But my use case is to populate account's "Upgrade Order Status" field with the Order status field value of recently created order having order type= "Upgarde Order' OR there is a change in Order Status field of an already existing Orders of type "Upgrade Order".

Illustartion:
Account Name: Account Demo
has 5 Orders with different Order Type
1. Order1 with Order Type= "ABC" with Order Status= "New"
2. Order2-with Order Type= "Upgrade Order" with Order Status="Open"
3. Order3 with Order Type= "XYZ" with Order Status="Open"
4. Order4 with Order Type="Upgrade Order" with Order Status= "New"
5. Order 5 with Order Type="ABCQRS"with Order Status= "Closed"
So we need to populated "Upgrade Order Status" with the status value of recently created/changed Orders's Status where Order Type= "Upgrade Order".So if suppose among 5 above mentioned orders if Order 4 is recently created  orders with Order Type="Upgrade Order" then "Upgrade Order Status" on account should be populated with value "New" because Order 4 is having Order Status= "New".
In case if we modify Order 2 and changed the status from "Open" to "Closed" then "Upgrade Order Status" on account should be populated with value "Closed" because Order 2 is recently modified order with order type=Upgarde Order.

Solution which I tried:
I created one Process Builder on Order Object with everytime ceated or edited with Criteria like mentioned below:

((ISNEW() && ISPICKVAL([Order].Type, 'UPGRADE ORDER') && [Order].Account_RecordType__c  = '012E0000000dZ7h' ) || 
(ISCHANGED([Order].Status )  && ISPICKVAL([Order].Type, 'UPGRADE ORDER') && [Order].Account_RecordType__c  = '012E0000000dZ7h') )

My Current Issue:

But it is working only for recently created Order with Order type= Upgarde Order and status of that Order is getting copied to Account's field OR When the status of same Order I mean recently created Order with Order Type= Upgrade order then new status value is getting copied to Account's field. This is just the half of my requiremnt done. Infact I also want the status of any other existing Order with Order Type= Upgrade Order is getting changed then the new value shhould be copied to Account's field. Currently only for the Order with Order Type=Upgarde Order which is craeted latest or when the same latest Order's status is modified then Account's field is updating

Is there a way I will be able to succefully update "Upgarde Order Status" with the status value of Order with Order Type= Upgrade Order when that Order with Order Type=Upgarde Order is either recetly created OR whenever any other existing Order's staus  with Order Type=Upgarde Order is getting changed(not just the latest created one) then the same status value should get copied to Account's "Upgrade Order Status" field.

Any valuable suggestions/inputs are greatly appraciated

Many thanks in advance
 
Hi All,

I hope everyone is doing good. I turned up here for a valuable advise from all of you experts.

My usecase is as below:

We have 2 objects "Accounts" and "Orders". I need to update one field on account object called as "Upgrade Order Status"(API Name- Upgrade_Order_Status__c) which is a text field with the value of "Order Status" field of only that Order where new Order is being created as Order Type = 'Upgarde Order' or an already existing order with Order type='Upgarde Order' and status is getting changed.

Order type is a picklist field on Order object having multiple values in which "Upgrade Order" is one of among them. Account can have multiple Orders with different Order Type.But my use case is to populate account's "Upgrade Order Status" field with the Order status field value of recently created order having order type= "Upgarde Order' OR there is a change in Order Status field of an already existing Orders of type "Upgrade Order".

Illustartion:
Account Name: Account Demo
has 5 Orders with different Order Type
1. Order1 with Order Type= "ABC" with Order Status= "New"
2. Order2-with Order Type= "Upgrade Order" with Order Status="Open"
3. Order3 with Order Type= "XYZ" with Order Status="Open"
4. Order4 with Order Type="Upgrade Order" with Order Status= "New"
5. Order 5 with Order Type="ABCQRS"with Order Status= "Closed"
So we need to populated "Upgrade Order Status" with the status value of recently created/changed Orders's Status where Order Type= "Upgrade Order".So if suppose among 5 above mentioned orders if Order 4 is recently created  orders with Order Type="Upgrade Order" then "Upgrade Order Status" on account should be populated with value "New" because Order 4 is having Order Status= "New".
In case if we modify Order 2 and changed the status from "Open" to "Closed" then "Upgrade Order Status" on account should be populated with value "Closed" because Order 2 is recently modified order with order type=Upgarde Order.

Kindly let me know if any further inputs/clarifications needed on my question.

Any advise/suggestions/help will be greatly appreciated

Many thanks in advance

Thanks & Regards,
Harjeet
Hi Everyone,

I need yours all experet advises which help me to achieve more than 75% coverage for my batch class. Right now my code coverage for my class stands at 73%(46 lines covered out of 63). I have tried so much and gave try to almost all permutations and combinations still not able to achieve more than 75%.

Below is the batch class for which I wrote test class
 
global with sharing class OpportunityWithSurgeryBatch extends BasicJob  {
    
   
    global OpportunityWithSurgeryBatch() {
        super(200);
    }
    
    global OpportunityWithSurgeryBatch(Integer batchSize) {
        super(batchSize, null);
    }
   
   /*
    Fetch all potential accounts to close the opportunities.
   */
    
    global List<Application_Log__c> logRec2insert = new List<Application_Log__c>();
    
    global override Database.QueryLocator start(Database.BatchableContext BC){
     
      return Database.getQueryLocator([
                    SELECT 
                    (
                        SELECT Surgery_Date__c 
                        FROM Install_Base__r 
                        WHERE Surgery_Date__c <> NULL 
                        ORDER BY Surgery_Date__c DESC
                    ), 
                    Candidate_Creation_Date__c, 
                    Lead_Status__pc, 
                    ID,
                    (
                        SELECT ID, stageName, Surgery_Date__c,CreatedDate,Probability
                        FROM Opportunities 
                        WHERE RecordType.name  = 'Surgery' 
                    , 
                        AND stageName NOT IN('Surgery Complete',' Closed Won','Closed Lost')
                        ORDER BY CreatedDate DESC
                    ) 
                    FROM Account 
                    WHERE RecordType.name = 'Recipient'

                    AND First_Surgery_Date__c <> NULL
                ]);
    }
    
    /*
        Process all the records
    */
    global override void execute(Database.BatchableContext BC, List<sObject> scope){
        
        String myLogMessage;
        Integer processedRecordsNumber;
        Map<Id,String> accIdLogMessageMap=new Map<Id,String>();
        //create list of opportunities to update
        List<Opportunity> opportunities2update = new List<Opportunity>();         
        List<Account> accounts2update = new List<Account>();         
        //check update conditions
        processedRecordsNumber = 0;
        try{            
            for(Account acc : (List<Account>)scope) {
                
                if (acc.Install_Base__r.size() > 0) {                   
                    Install_Base__c equipment = acc.Install_Base__r[0];
                    
            
                      
                        //set opportunity to update
                        list<Opportunity> opp = acc.Opportunities;
                    
                      //Create a boolean variable to check if the processed oppty is the latest one
                        Boolean FirstRecord = true;
                    
                    //Run through the oppty
                        for (Opportunity op :opp) {
                            
                            
                          
                            if(Op.CreatedDate < equipment.Surgery_Date__c && FirstRecord){
                                FirstRecord = false;
                                myLogMessage = ''; 
                                op.stageName = 'Closed Won';
                                op.Surgery_Date__c = equipment.Surgery_Date__c;
                                op.Probability = 100;
                                opportunities2update.add(op);
                                myLogMessage = myLogMessage  + 'opportunity ID =(' + op.ID + '), ';
                                
                            }
                            //closed lost
                           if(Op.CreatedDate < equipment.Surgery_Date__c && (Op.StageName<>'Surgery Complete' || Op.StageName<>'ClosedWon'||Op.StageName<>'Closed Lost')) {
                               myLogMessage = ''; 
                                op.stageName = 'Closed Lost';
                                op.Surgery_Date__c = equipment.Surgery_Date__c;
                                //op.Probability = 100;
                                opportunities2update.add(op);
                                myLogMessage = myLogMessage  + 'opportunity ID =(' + op.ID + '), '; 
                            }
                       
                        if (myLogMessage <> ''){
                            ++processedRecordsNumber;
                            myLogMessage   = 'Record number in the batch (' + processedRecordsNumber + '), ' 
                                + myLogMessage; 
                            accIdLogMessageMap.put(acc.ID,myLogMessage );                            
                        }
                        else{
                            accIdLogMessageMap.put(acc.ID,'' );
                        }
                    }
                }
            }
            
            
        update opportunities2update;
            
           
        
        for(Id accId:accIdLogMessageMap.keySet()){    
          
            // set account for update  
            Account acc=new Account(id=accId);
            acc.Lead_Status__pc = 'Surgery Complete';
            accounts2update.add(acc);
            if(accIdLogMessageMap.get(accId)!=''){
                //set log to insert
                Application_Log__c myLog       = new Application_Log__c();
                myLog.Source__c = 'OpportunityWithSurgery';
                myLog.Source_Function__c = 'close';
                myLog.Reference_Id__c = acc.ID;
                myLog.Reference_Info__c = 'MasterAccountId';
                myLog.Status__c  = 'Completed';
                myLog.Message__c   = accIdLogMessageMap.get(accId);
                logRec2insert.add(myLog);
            }
        
        }
        
        update accounts2update;       
              
            
        }catch (Exception ex){
            ApplicationLog.logMessage('Opportunity update Fail', 'OpportunityWithSurgery', 'close', 'EXCEPTION', null, 
                                   null, null, ex);
        }
        finally {   
            ApplicationLog.logMessage('Completed', 'OpportunityWithSurgery', 'close', 'EXCEPTION', null, 
                                      ' Total SQL: ' +  Limits.getLimitQueries() + ' Used SQL:' + Limits.getQueries(), null, null);
                                     
        }    
      
    }

   global override void finish(Database.BatchableContext BC){
    insert logRec2insert;
   }
}

Below is the test class which stands at 73%
 
@isTest
public class OpportunityWithSurgeryBatchTest{
    
    @testSetup static void setup() {
        
        Id recipientId = RecordTypeUtility.getRecordTypeId(Account.sobjecttype, Constants.ACCOUNT_RECORDTYPE_RECIPIENT);
        Id surgeryId = RecordTypeUtility.getRecordTypeId(Opportunity.sobjecttype, Constants.OPP_RECORDTYPE_SURGERY);
     
        Date My_Base_Test_Date = System.today(); //set some test date
        List<Account>   accountList = new  List<Account>();
        List<Install_Base__c>   ibList = new  List<Install_Base__c>();
        List<Opportunity>   OppList = new  List<Opportunity>();
        
        for(Integer i =0;i<10;i++){
            Account acct = new Account();
            acct.LastName = 'TestOpportunityWithSurgery'; 
            acct.RecordTypeId = recipientId;        
            acct.First_Surgery_Date__c = My_Base_Test_Date.addDays(+i);
            
            accountList.add(acct);
        }

        INSERT accountList;
        
        for(Integer i =0;i<10;i++){
            Install_Base__c ib = new Install_Base__c();
            ib.Owner__c = accountList[i].Id;            
            ib.Surgery_Date__c = My_Base_Test_Date;
            ibList.add(ib);
            
            Opportunity opp = new Opportunity();
            opp.AccountId = accountList[i].Id;
            opp.Name = 'OppName';
            opp.RecordTypeID  = surgeryId;
            opp.StageName = 'New';
            opp.CreatedDate = My_Base_Test_Date.addDays(-i);
            opp.CloseDate = System.today(); 
            OppList.add(opp);
        }
            
        INSERT ibList;   
            
        INSERT OppList;     
    }
    
    static testMethod void test(){
      
        Id recipientId = RecordTypeUtility.getRecordTypeId(Account.sobjecttype, Constants.ACCOUNT_RECORDTYPE_RECIPIENT);
        Id surgeryId = RecordTypeUtility.getRecordTypeId(Opportunity.sobjecttype, Constants.OPP_RECORDTYPE_SURGERY);
      
        Date My_Base_Test_Date = System.today(); //set some test date
            
        Account acct = new Account();
        acct.LastName = 'TestOpportunityWithSurgery'; 
        acct.RecordTypeId = recipientId;
        //make registration date before surgery
        acct.First_Surgery_Date__c = My_Base_Test_Date.addDays(+1);
        //acct.Candidate_Creation_Date__c = My_Base_Test_Date.addDays(-1);
        acct.Lead_Status__pc = 'Surgery Complete';
        INSERT acct;
        
        Install_Base__c ib = new Install_Base__c();
        ib.Owner__c = acct.Id;
      
        ib.Surgery_Date__c = My_Base_Test_Date;
        INSERT ib;
        
        Opportunity opp = new Opportunity();
        opp.AccountId = acct.Id;
        opp.Name = 'OppName';
        opp.RecordTypeID  = surgeryId;
        //opp.StageName = 'New';
        opp.StageName ='Closed Won';
        opp.CloseDate = System.today(); 
        opp.CreatedDate =  My_Base_Test_Date.addDays(-1);
        opp.Surgery_Date__c =  My_Base_Test_Date;
        INSERT opp;  
               
        Integer beforeCount = getApplicationLogCount();
        
        Test.startTest();
        OpportunityWithSurgeryBatch obj = new OpportunityWithSurgeryBatch();
        DataBase.executeBatch(obj);        
        Test.stopTest();
            
        Integer afterCount = getApplicationLogCount();
        
        acct = getAccount(acct.Id);
        System.assert(acct.Lead_Status__pc == 'Surgery Complete');
        
        opp = getOpportunity(acct.Id);
      
         System.assert(opp.StageName == 'Closed Won');
       
        System.assert(opp.Surgery_Date__c == ib.Surgery_Date__c);
             
        System.assertEquals(beforeCount + 2 ,afterCount);
    }
    
    private static Account getAccount(Id acctId) {
        return [SELECT Lead_Status__pc FROM Account WHERE Id = :acctId];
    }
    
    private static Opportunity getOpportunity(Id acctId) {
        return [SELECT stageName, Surgery_Date__c, Probability FROM Opportunity WHERE AccountId = :acctId];
    }
    
    private static Integer getApplicationLogCount() {
        return [SELECT count() FROM Application_Log__c WHERE 
                Source__c = 'OpportunityWithSurgery' AND Source_Function__c = 'close'];
    }   
    
    
    static testMethod void testforMultipleRecords(){
        
               
        Integer beforeCount = getApplicationLogCount();
        
        Test.startTest();
        OpportunityWithSurgeryBatch obj = new OpportunityWithSurgeryBatch();
        DataBase.executeBatch(obj,200);        
        Test.stopTest();
            
        Integer afterCount = getApplicationLogCount();           
        System.assertEquals(beforeCount + 2, afterCount);
    }   
    
}

Below are the lines of codes which is not getting covered
 
for(Id accId:accIdLogMessageMap.keySet()){          
            // set account for update  
            Account acc=new Account(id=accId);
            acc.Lead_Status__pc = 'Surgery Complete';
            accounts2update.add(acc);
            if(accIdLogMessageMap.get(accId)!=''){
                //set log to insert
                Application_Log__c myLog       = new Application_Log__c();
                myLog.Source__c = 'OpportunityWithSurgery';
                myLog.Source_Function__c = 'close';
                myLog.Reference_Id__c = acc.ID;
                myLog.Reference_Info__c = 'MasterAccountId';
                myLog.Status__c  = 'Completed';
                myLog.Message__c   = accIdLogMessageMap.get(accId);
                logRec2insert.add(myLog);
            }
        }

Any help will be greatly appreciated.

Mnay thanks in advance

Thanks & Regards,
Harjeet​
I am working on a requirement which goes like something bleow:
We have Accounts and Opportunities. Opportunities has a record type as Surgery.
1. If the account has more then one suregery opportunity, Surgery Opportunity with most recent (newest) Opportunity Created Date should remain Closed Won
2. If the account has more then one suregery opportunity, Surgery Opportunity/ies with older Opportunity Created Date should be changed to Closed Lost
3. If the Opportunity is in Closed Lost dont do anything
4.f there is an existing Opportunity in "Surgery Complete" that it not change to closed lost.

I have written below code but it seems not working as expectation.Currently all of the surgery opportunity is changing to Closed/Won
 
global with sharing class OpportunityWithSurgeryBatch extends BasicJob  {


    global OpportunityWithSurgeryBatch() {
        super(200);
    }

    global OpportunityWithSurgeryBatch(Integer batchSize) {
        super(batchSize, null);
    }

   /*
    Fetch all potential accounts to close the opportunities.
   */

    global List<Application_Log__c> logRec2insert = new List<Application_Log__c>();

    global override Database.QueryLocator start(Database.BatchableContext BC){

      return Database.getQueryLocator([
                    SELECT 
                    (
                        SELECT Surgery_Date__c 
                        FROM Install_Base__r 
                        WHERE Surgery_Date__c <> NULL 
                        ORDER BY Surgery_Date__c DESC
                    ), 
                    Candidate_Creation_Date__c, 
                    Lead_Status__pc, 
                    ID,
                    (
                        SELECT ID, stageName, Surgery_Date__c,CreatedDate,Probability
                        FROM Opportunities 
                        WHERE RecordType.name  = 'Surgery' 
                        AND stageName <> 'Surgery Complete'
                         ORDER BY CreatedDate DESC
                    ) 
                    FROM Account 
                    WHERE RecordType.name = 'Recipient'
                    
                    AND First_Surgery_Date__c <> NULL
                ]);
    }

    /*
        Process all the records
    */
    global override void execute(Database.BatchableContext BC, List<sObject> scope){

        String myLogMessage;
        Integer processedRecordsNumber;
        Map<Id,String> accIdLogMessageMap=new Map<Id,String>();
        //create list of opportunities to update
        List<Opportunity> opportunities2update = new List<Opportunity>();         
        List<Account> accounts2update = new List<Account>();         
        //check update conditions
        processedRecordsNumber = 0;
        try{            
            for(Account acc : (List<Account>)scope) {

                if (acc.Install_Base__r.size() > 0) {                   
                    Install_Base__c equipment = acc.Install_Base__r[0];


                        //set opportunity to update
                        list<Opportunity> opp = acc.Opportunities;

                        for (Opportunity op :opp) {
                            //Below conditions compare Oppty Creation Date less than Surgery Date 
                            if(Op.CreatedDate < equipment.Surgery_Date__c) {
                                myLogMessage = ''; 
                                op.stageName = 'Closed Won';
                                op.Surgery_Date__c = equipment.Surgery_Date__c;
                                op.Probability = 100;
                                opportunities2update.add(op);
                                myLogMessage = myLogMessage  + 'opportunity ID =(' + op.ID + '), ';
                        }

                        if (myLogMessage <> ''){
                            ++processedRecordsNumber;
                            myLogMessage   = 'Record number in the batch (' + processedRecordsNumber + '), ' 
                                + myLogMessage; 
                            accIdLogMessageMap.put(acc.ID,myLogMessage );                            
                        }
                        else{
                            accIdLogMessageMap.put(acc.ID,'' );
                        }
                    }
                }
            }


        update opportunities2update;

        for(Id accId:accIdLogMessageMap.keySet()){          
            // set account for update  
            Account acc=new Account(id=accId);
            acc.Lead_Status__pc = 'Surgery Complete';
            accounts2update.add(acc);
            if(accIdLogMessageMap.get(accId)!=''){
                //set log to insert
                Application_Log__c myLog       = new Application_Log__c();
                myLog.Source__c = 'OpportunityWithSurgery';
                myLog.Source_Function__c = 'close';
                myLog.Reference_Id__c = acc.ID;
                myLog.Reference_Info__c = 'MasterAccountId';
                myLog.Status__c  = 'Completed';
                myLog.Message__c   = accIdLogMessageMap.get(accId);
                logRec2insert.add(myLog);
            }
        }

        update accounts2update;       


        }catch (Exception ex){
            ApplicationLog.logMessage('Opportunity update Fail', 'OpportunityWithSurgery', 'close', 'EXCEPTION', null, 
                                   null, null, ex);
        }
        finally {   
            ApplicationLog.logMessage('Completed', 'OpportunityWithSurgery', 'close', 'EXCEPTION', null, 
                                      ' Total SQL: ' +  Limits.getLimitQueries() + ' Used SQL:' + Limits.getQueries(), null, null);

        }    

    }

   global override void finish(Database.BatchableContext BC){
    insert logRec2insert;
   }
}

Kindly note we are using Surgery Complete as Closed/Won for our Surgery Oppty.

Kindly advise what I am doing wrong here and what I am missing on same
Many thanks in advance
I am working on a requirement which goes like something bleow:
We have Accounts and Opportunities. Opportunities has a record type as Surgery.
1. If the account has more then one suregery opportunity, Surgery Opportunity with most recent (newest) Opportunity Created Date should remain Closed Won
2. If the account has more then one suregery opportunity, Surgery Opportunity/ies with older Opportunity Created Date should be changed to Closed Lost
3. If the Opportunity is in Closed Lost dont do anything
4.f there is an existing Opportunity in "Surgery Complete" that it not change to closed lost.

I have written below code but it seems not working as expectation.Currently all of the surgery opportunity is changing to Closed/Won
 
global with sharing class OpportunityWithSurgeryBatch extends BasicJob  {


    global OpportunityWithSurgeryBatch() {
        super(200);
    }

    global OpportunityWithSurgeryBatch(Integer batchSize) {
        super(batchSize, null);
    }

   /*
    Fetch all potential accounts to close the opportunities.
   */

    global List<Application_Log__c> logRec2insert = new List<Application_Log__c>();

    global override Database.QueryLocator start(Database.BatchableContext BC){

      return Database.getQueryLocator([
                    SELECT 
                    (
                        SELECT Surgery_Date__c 
                        FROM Install_Base__r 
                        WHERE Surgery_Date__c <> NULL 
                        ORDER BY Surgery_Date__c DESC
                    ), 
                    Candidate_Creation_Date__c, 
                    Lead_Status__pc, 
                    ID,
                    (
                        SELECT ID, stageName, Surgery_Date__c,CreatedDate,Probability
                        FROM Opportunities 
                        WHERE RecordType.name  = 'Surgery' 
                        AND stageName <> 'Surgery Complete'
                         ORDER BY CreatedDate DESC LIMIT 1
                    ) 
                    FROM Account 
                    WHERE RecordType.name = 'Recipient'
                    
                    AND First_Surgery_Date__c <> NULL
                ]);
    }

    /*
        Process all the records
    */
    global override void execute(Database.BatchableContext BC, List<sObject> scope){

        String myLogMessage;
        Integer processedRecordsNumber;
        Map<Id,String> accIdLogMessageMap=new Map<Id,String>();
        //create list of opportunities to update
        List<Opportunity> opportunities2update = new List<Opportunity>();         
        List<Account> accounts2update = new List<Account>();         
        //check update conditions
        processedRecordsNumber = 0;
        try{            
            for(Account acc : (List<Account>)scope) {

                if (acc.Install_Base__r.size() > 0) {                   
                    Install_Base__c equipment = acc.Install_Base__r[0];


                        //set opportunity to update
                        list<Opportunity> opp = acc.Opportunities;

                        for (Opportunity op :opp) {
                            //Below conditions compare Oppty Creation Date less than Surgery Date 
                            if(Op.CreatedDate < equipment.Surgery_Date__c) {
                                myLogMessage = ''; 
                                op.stageName = 'Surgery Complete';
                                op.Surgery_Date__c = equipment.Surgery_Date__c;
                                op.Probability = 100;
                                opportunities2update.add(op);
                                myLogMessage = myLogMessage  + 'opportunity ID =(' + op.ID + '), ';
                        }

                        if (myLogMessage <> ''){
                            ++processedRecordsNumber;
                            myLogMessage   = 'Record number in the batch (' + processedRecordsNumber + '), ' 
                                + myLogMessage; 
                            accIdLogMessageMap.put(acc.ID,myLogMessage );                            
                        }
                        else{
                            accIdLogMessageMap.put(acc.ID,'' );
                        }
                    }
                }
            }


        update opportunities2update;

        for(Id accId:accIdLogMessageMap.keySet()){          
            // set account for update  
            Account acc=new Account(id=accId);
            acc.Lead_Status__pc = 'Surgery Complete';
            accounts2update.add(acc);
            if(accIdLogMessageMap.get(accId)!=''){
                //set log to insert
                Application_Log__c myLog       = new Application_Log__c();
                myLog.Source__c = 'OpportunityWithSurgery';
                myLog.Source_Function__c = 'close';
                myLog.Reference_Id__c = acc.ID;
                myLog.Reference_Info__c = 'MasterAccountId';
                myLog.Status__c  = 'Completed';
                myLog.Message__c   = accIdLogMessageMap.get(accId);
                logRec2insert.add(myLog);
            }
        }

        update accounts2update;       


        }catch (Exception ex){
            ApplicationLog.logMessage('Opportunity update Fail', 'OpportunityWithSurgery', 'close', 'EXCEPTION', null, 
                                   null, null, ex);
        }
        finally {   
            ApplicationLog.logMessage('Completed', 'OpportunityWithSurgery', 'close', 'EXCEPTION', null, 
                                      ' Total SQL: ' +  Limits.getLimitQueries() + ' Used SQL:' + Limits.getQueries(), null, null);

        }    

    }

   global override void finish(Database.BatchableContext BC){
    insert logRec2insert;
   }
}

Kindly note we are using Surgery Complete as Closed/Won for our Surgery Oppty.

Kindly advise what I am doing wrong here and what I am missing on same
Many thanks in advance
I am working on a requirement which goes like something bleow:
We have Accounts and Opportunities. Opportunities has a record type as Surgery. 1. If the account has more then one suregery opportunity, Surgery Opportunity with most recent (newest) Opportunity Created Date should remain Closed Won
2. If the account has more then one suregery opportunity, Surgery Opportunity/ies with older Opportunity Created Date should be changed to Closed Lost
3. If the Opportunity is in Closed Lost dont do anything

I have written below code but it seems not working as expectation.Currently all of the surgery opportunity is changing to Closed/Won
 
global with sharing class OpportunityWithSurgeryBatch extends BasicJob  {


    global OpportunityWithSurgeryBatch() {
        super(200);
    }

    global OpportunityWithSurgeryBatch(Integer batchSize) {
        super(batchSize, null);
    }

   /*
    Fetch all potential accounts to close the opportunities.
   */

    global List<Application_Log__c> logRec2insert = new List<Application_Log__c>();

    global override Database.QueryLocator start(Database.BatchableContext BC){

      return Database.getQueryLocator([
                    SELECT 
                    (
                        SELECT Surgery_Date__c 
                        FROM Install_Base__r 
                        WHERE Surgery_Date__c <> NULL 
                        ORDER BY Surgery_Date__c DESC
                    ), 
                    Candidate_Creation_Date__c, 
                    Lead_Status__pc, 
                    ID,
                    (
                        SELECT ID, stageName, Surgery_Date__c,CreatedDate,Probability
                        FROM Opportunities 
                        WHERE RecordType.name  = 'Surgery' 
                        AND stageName <> 'Surgery Complete'
                         ORDER BY CreatedDate DESC LIMIT 1
                    ) 
                    FROM Account 
                    WHERE RecordType.name = 'Recipient'
                    
                    AND First_Surgery_Date__c <> NULL
                ]);
    }

    /*
        Process all the records
    */
    global override void execute(Database.BatchableContext BC, List<sObject> scope){

        String myLogMessage;
        Integer processedRecordsNumber;
        Map<Id,String> accIdLogMessageMap=new Map<Id,String>();
        //create list of opportunities to update
        List<Opportunity> opportunities2update = new List<Opportunity>();         
        List<Account> accounts2update = new List<Account>();         
        //check update conditions
        processedRecordsNumber = 0;
        try{            
            for(Account acc : (List<Account>)scope) {

                if (acc.Install_Base__r.size() > 0) {                   
                    Install_Base__c equipment = acc.Install_Base__r[0];


                        //set opportunity to update
                        list<Opportunity> opp = acc.Opportunities;

                        for (Opportunity op :opp) {
                            //Below conditions compare Oppty Creation Date less than Surgery Date 
                            if(Op.CreatedDate < equipment.Surgery_Date__c) {
                                myLogMessage = ''; 
                                op.stageName = 'Surgery Complete';
                                op.Surgery_Date__c = equipment.Surgery_Date__c;
                                op.Probability = 100;
                                opportunities2update.add(op);
                                myLogMessage = myLogMessage  + 'opportunity ID =(' + op.ID + '), ';
                        }

                        if (myLogMessage <> ''){
                            ++processedRecordsNumber;
                            myLogMessage   = 'Record number in the batch (' + processedRecordsNumber + '), ' 
                                + myLogMessage; 
                            accIdLogMessageMap.put(acc.ID,myLogMessage );                            
                        }
                        else{
                            accIdLogMessageMap.put(acc.ID,'' );
                        }
                    }
                }
            }


        update opportunities2update;

        for(Id accId:accIdLogMessageMap.keySet()){          
            // set account for update  
            Account acc=new Account(id=accId);
            acc.Lead_Status__pc = 'Surgery Complete';
            accounts2update.add(acc);
            if(accIdLogMessageMap.get(accId)!=''){
                //set log to insert
                Application_Log__c myLog       = new Application_Log__c();
                myLog.Source__c = 'OpportunityWithSurgery';
                myLog.Source_Function__c = 'close';
                myLog.Reference_Id__c = acc.ID;
                myLog.Reference_Info__c = 'MasterAccountId';
                myLog.Status__c  = 'Completed';
                myLog.Message__c   = accIdLogMessageMap.get(accId);
                logRec2insert.add(myLog);
            }
        }

        update accounts2update;       


        }catch (Exception ex){
            ApplicationLog.logMessage('Opportunity update Fail', 'OpportunityWithSurgery', 'close', 'EXCEPTION', null, 
                                   null, null, ex);
        }
        finally {   
            ApplicationLog.logMessage('Completed', 'OpportunityWithSurgery', 'close', 'EXCEPTION', null, 
                                      ' Total SQL: ' +  Limits.getLimitQueries() + ' Used SQL:' + Limits.getQueries(), null, null);

        }    

    }

   global override void finish(Database.BatchableContext BC){
    insert logRec2insert;
   }
}

Kindly note we are using Surgery Complete as Closed/Won for our Surgery Oppty.

Kindly advise what I am doing wrong here and what I am missing on same
Many thanks in advance
I am working on a requirement which goes like something bleow: We have Accounts and Opportunities. Opportunities has a record type as Surgery. 1. If the account has more then one suregery opportunity, Surgery Opportunity with most recent (newest) Opportunity Created Date should remain Closed Won
2. If the account has more then one suregery opportunity, Surgery Opportunity/ies with older Opportunity Created Date should be changed to Closed Lost
3. If the Opportunity is in Closed Lost DONT DO ANYTHING.

I have written below code but it seems not working as expectation.Currently all of the surgery opportunity is changing to Closed/Won
global with sharing class OpportunityWithSurgeryBatch extends BasicJob  {


    global OpportunityWithSurgeryBatch() {
        super(200);
    }

    global OpportunityWithSurgeryBatch(Integer batchSize) {
        super(batchSize, null);
    }

   /*
    Fetch all potential accounts to close the opportunities.
   */

    global List<Application_Log__c> logRec2insert = new List<Application_Log__c>();

    global override Database.QueryLocator start(Database.BatchableContext BC){

      return Database.getQueryLocator([
                    SELECT 
                    (
                        SELECT Surgery_Date__c 
                        FROM Install_Base__r 
                        WHERE Surgery_Date__c <> NULL 
                        ORDER BY Surgery_Date__c DESC
                    ), 
                    Candidate_Creation_Date__c, 
                    Lead_Status__pc, 
                    ID,
                    (
                        SELECT ID, stageName, Surgery_Date__c,CreatedDate,Probability
                        FROM Opportunities 
                        WHERE RecordType.name  = 'Surgery' 
                        AND stageName <> 'Surgery Complete'
                         ORDER BY CreatedDate DESC LIMIT 1
                    ) 
                    FROM Account 
                    WHERE RecordType.name = 'Recipient'
                    
                    AND First_Surgery_Date__c <> NULL
                ]);
    }

    /*
        Process all the records
    */
    global override void execute(Database.BatchableContext BC, List<sObject> scope){

        String myLogMessage;
        Integer processedRecordsNumber;
        Map<Id,String> accIdLogMessageMap=new Map<Id,String>();
        //create list of opportunities to update
        List<Opportunity> opportunities2update = new List<Opportunity>();         
        List<Account> accounts2update = new List<Account>();         
        //check update conditions
        processedRecordsNumber = 0;
        try{            
            for(Account acc : (List<Account>)scope) {

                if (acc.Install_Base__r.size() > 0) {                   
                    Install_Base__c equipment = acc.Install_Base__r[0];


                        //set opportunity to update
                        list<Opportunity> opp = acc.Opportunities;

                        for (Opportunity op :opp) {
                            //Below conditions compare Oppty Creation Date less than Surgery Date 
                            if(Op.CreatedDate < equipment.Surgery_Date__c) {
                                myLogMessage = ''; 
                                op.stageName = 'Surgery Complete';
                                op.Surgery_Date__c = equipment.Surgery_Date__c;
                                op.Probability = 100;
                                opportunities2update.add(op);
                                myLogMessage = myLogMessage  + 'opportunity ID =(' + op.ID + '), ';
                        }

                        if (myLogMessage <> ''){
                            ++processedRecordsNumber;
                            myLogMessage   = 'Record number in the batch (' + processedRecordsNumber + '), ' 
                                + myLogMessage; 
                            accIdLogMessageMap.put(acc.ID,myLogMessage );                            
                        }
                        else{
                            accIdLogMessageMap.put(acc.ID,'' );
                        }
                    }
                }
            }


        update opportunities2update;

        for(Id accId:accIdLogMessageMap.keySet()){          
            // set account for update  
            Account acc=new Account(id=accId);
            acc.Lead_Status__pc = 'Surgery Complete';
            accounts2update.add(acc);
            if(accIdLogMessageMap.get(accId)!=''){
                //set log to insert
                Application_Log__c myLog       = new Application_Log__c();
                myLog.Source__c = 'OpportunityWithSurgery';
                myLog.Source_Function__c = 'close';
                myLog.Reference_Id__c = acc.ID;
                myLog.Reference_Info__c = 'MasterAccountId';
                myLog.Status__c  = 'Completed';
                myLog.Message__c   = accIdLogMessageMap.get(accId);
                logRec2insert.add(myLog);
            }
        }

        update accounts2update;       


        }catch (Exception ex){
            ApplicationLog.logMessage('Opportunity update Fail', 'OpportunityWithSurgery', 'close', 'EXCEPTION', null, 
                                   null, null, ex);
        }
        finally {   
            ApplicationLog.logMessage('Completed', 'OpportunityWithSurgery', 'close', 'EXCEPTION', null, 
                                      ' Total SQL: ' +  Limits.getLimitQueries() + ' Used SQL:' + Limits.getQueries(), null, null);

        }    

    }

   global override void finish(Database.BatchableContext BC){
    insert logRec2insert;
   }
}

Kindly note we are using Surgery Complete as Closed/Won for our Surgery Oppty.
Kindly advise/suggests what I am doing wrong here and what I am missing on same
Many thanks in advance
HI All,

I got stuck at one place where I am not able to cover a particular catch block consisting application exception. Currently my test class is getting pass succefully with 72% coverage but not able to cover one catch block.

Below is my class:
@RestResource(urlMapping='/v1/someurl/*')
global with sharing class VerifiableAPI {
    
   private static BasicRestResponse response;
    
    @HttpPost
    global static void doPost(Request request) {
        Exception ex = null;
        Savepoint sp = Database.setSavepoint();
        CareService svr = null;
        
        try {
            svr =CareService(request, CareService.APIType.VERIFIABLE);
            svr.doPost();
            
            response = new RestResponseSuccess();
        } catch (ApplicationException e) {
            if (response == null) { response = new RestResponseError(); }
            response.setError('INVALID_REQUEST', e.getMessage());
            ex = e;
            Database.rollback(sp);
        } catch (Exception e) {
            if (response == null) { response = new RestResponseError(); }
            response.setError('INTERNAL_ERROR', e.getMessage());
            ex = e;
            Database.rollback(sp);
        }
        
        if (ex != null) {
            ApplicationLog.LogMessage('Error', 'CareVerifiableAPI', 'doPost', null, null, 
                                  JSON.serialize(response), JSON.serialize(RestContext.request), ex);
        }
        
      
        
        response.publish();
    }
    
    /**
     * Request of the API Call
     */
     global class Request {
        
         global String consent;
         
        
     }
}

Below is my test class:
@isTest
private class VerifiableAPITest {

    static testMethod void myUnitTest() {
      ;
       
           VerifiableAPI.Request reqst=new VerifiableAPI.Request();
        	reqst.consent='consent';
      
       
            String JsonMsg=JSON.serialize(reqst);
            Test.startTest();  
  		

           RestRequest req = new RestRequest(); 
           RestResponse res = new RestResponse();
        
            req.requestURI = '/services/apexrest/v1/demo';  //Request URL
            req.httpMethod = 'POST';//HTTP Request Type
            req.requestBody = Blob.valueof(JsonMsg);
            RestContext.request = req;
            RestContext.response= res;
        
           BasicRestResponse resp= new BasicRestResponse();
            resp.setError('title', 'detail');
            resp.setData(null);
            resp.getData();
            resp.publish();
            
        VerifiableAPI.doPost(reqst);
            Test.stopTest();
        
    }

}

Below is the catch block which I am not able to cover:
response = new RestResponseSuccess();
        } catch (ApplicationException e) {
            if (response == null) { response = new RestResponseError(); }
            response.setError('INVALID_REQUEST', e.getMessage());
            ex = e;
            Database.rollback(sp);
}

Any help will be gra​​​​​​eatly appreciated.

Many thanks in advance
HI All,

I got stuck at one place where I am not able to cover a particular catch block consisting application exception. Currently my test class is getting pass succefully with 72% coverage but not able to cover one catch block.

Below is my class:
 
@RestResource(urlMapping='/v1/someurl/*')
global with sharing class VerifiableAPI {
    
   private static BasicRestResponse response;
    
    @HttpPost
    global static void doPost(Request request) {
        Exception ex = null;
        Savepoint sp = Database.setSavepoint();
        CareService svr = null;
        
        try {
            svr =CareService(request, CareService.APIType.VERIFIABLE);
            svr.doPost();
            
            response = new RestResponseSuccess();
        } catch (ApplicationException e) {
            if (response == null) { response = new RestResponseError(); }
            response.setError('INVALID_REQUEST', e.getMessage());
            ex = e;
            Database.rollback(sp);
        } catch (Exception e) {
            if (response == null) { response = new RestResponseError(); }
            response.setError('INTERNAL_ERROR', e.getMessage());
            ex = e;
            Database.rollback(sp);
        }
        
        if (ex != null) {
            ApplicationLog.LogMessage('Error', 'CareVerifiableAPI', 'doPost', null, null, 
                                  JSON.serialize(response), JSON.serialize(RestContext.request), ex);
        }
        
      
        
        response.publish();
    }
    
    /**
     * Request of the API Call
     */
     global class Request {
        
         global String consent;
         
        
     }
}

Below is my test class:
 
@isTest
private class VerifiableAPITest {

    static testMethod void myUnitTest() {
      ;
       
           VerifiableAPI.Request reqst=new VerifiableAPI.Request();
        	reqst.consent='consent';
      
       
            String JsonMsg=JSON.serialize(reqst);
            Test.startTest();  
  		

           RestRequest req = new RestRequest(); 
           RestResponse res = new RestResponse();
        
            req.requestURI = '/services/apexrest/v1/demo';  //Request URL
            req.httpMethod = 'POST';//HTTP Request Type
            req.requestBody = Blob.valueof(JsonMsg);
            RestContext.request = req;
            RestContext.response= res;
        
           BasicRestResponse resp= new BasicRestResponse();
            resp.setError('title', 'detail');
            resp.setData(null);
            resp.getData();
            resp.publish();
            
        VerifiableAPI.doPost(reqst);
            Test.stopTest();
        
    }

}

Below is the catch block which I am not able to cover:
 
response = new RestResponseSuccess();
        } catch (ApplicationException e) {
            if (response == null) { response = new RestResponseError(); }
            response.setError('INVALID_REQUEST', e.getMessage());
            ex = e;
            Database.rollback(sp);
}

Any help will be gra​​​​​​eatly appreciated.

Many thanks in advance
Hi Everyone,

I stuck at one place and could not able to resolve the issue.I know what is the issue and where its happening still I am clueless.Actually I am getting System.NullPointerException: Argument cannot be null in Test Class.

Below is my class:
 
01global with sharing class Audit {
02     
03    global String created_by;
04    global String reason;
05    global String requested_by_customer;
06    global String requested_by_type;
07    // Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
08    global Long requested_datetime;
09    global String requested_method;
10    global String others;
11    global String source_system;
12     
13     
14    global Consent_History__c getConsentHistory() {
15        Consent_History__c consentHistory = newConsent_History__c();
16         
17        consentHistory.Consent_Change_Created_By__c= this.created_by;
18        consentHistory.Change_Reason__c =this.reason;
19        consentHistory.Consent_Change_Requested_By_Customer__c= this.requested_by_customer;
20        consentHistory.Change_Received_From_Type__c= this.requested_by_type;
21        consentHistory.Change_Received_DateTime__c= DateTime.newInstance(this.requested_datetime);
22        consentHistory.Change_Received_Method__c= this.requested_method;
23        consentHistory.Consent_Change_Others__c =this.others;
24        consentHistory.Source_System__c =this.source_system;
25         
26        return consentHistory;
27    }
28}
Below is my test class:
01@isTest
02private class AuditTest {
03 
04    static testMethod void getConsentHistory() {
05       
06        Datetime myDate=System.now();
07         
08        Consent_History__c consentHistory = newConsent_History__c();
09       
10        consentHistory.Consent_Change_Created_By__c= 'User1@cochlear.com';
11        consentHistory.Change_Reason__c ='Test';
12        consentHistory.Consent_Change_Requested_By_Customer__c= 'Customer1';
13        consentHistory.Change_Received_From_Type__c='Professional';
14        consentHistory.Change_Received_DateTime__c= myDate;
15        consentHistory.Change_Received_Method__c= 'Consent Card';
16        consentHistory.Consent_Change_Others__c ='Consent Test';
17        consentHistory.Source_System__c=Constants.SYSTEM_MCP;
18       insert consentHistory;
19         
20       Test.startTest();
21       
22       Audit audit=new Audit();
23       audit.getConsentHistory();
24       Test.stopTest();
25         
26    }
27   
28}
I am receiving error at below line in class:
1consentHistory.Change_Received_DateTime__c =DateTime.newInstance(this.requested_datetime);
and below line in test class:
1audit.getConsentHistory();
I understand that there is something which I am not able to catch for date time in above class which results in returning null value.

Kindly help me to pass this error in my test class.

Any help will be greatly appreciated.

Many thanks in advance

Thanks & Regards,
Maria
Hi Everyone,

I stuck at one place and could not able to resolve the issue.I know what is the issue and where its happening still I am clueless.Actually I am getting System.NullPointerException: Argument cannot be null in Test Class.

Below is my class:
 
global with sharing class Audit {
    
    global String created_by;
    global String reason;
    global String requested_by_customer;
    global String requested_by_type;
    // Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
    global Long requested_datetime;
    global String requested_method;
    global String others;
    global String source_system;
    
    
    global Consent_History__c getConsentHistory() {
        Consent_History__c consentHistory = new Consent_History__c();
        
        consentHistory.Consent_Change_Created_By__c = this.created_by;
        consentHistory.Change_Reason__c = this.reason;
        consentHistory.Consent_Change_Requested_By_Customer__c = this.requested_by_customer;
        consentHistory.Change_Received_From_Type__c = this.requested_by_type;
        consentHistory.Change_Received_DateTime__c = DateTime.newInstance(this.requested_datetime);
        consentHistory.Change_Received_Method__c = this.requested_method;
        consentHistory.Consent_Change_Others__c = this.others;
        consentHistory.Source_System__c = this.source_system;
        
        return consentHistory;
    }
}

Below is my test class:
@isTest
private class AuditTest {

    static testMethod void getConsentHistory() {
      
        Datetime myDate=System.now();
        
        Consent_History__c consentHistory = new Consent_History__c();
      
        consentHistory.Consent_Change_Created_By__c = 'User1@cochlear.com';
        consentHistory.Change_Reason__c ='Test';
        consentHistory.Consent_Change_Requested_By_Customer__c = 'Customer1';
        consentHistory.Change_Received_From_Type__c ='Professional';
        consentHistory.Change_Received_DateTime__c = myDate;
        consentHistory.Change_Received_Method__c = 'Consent Card';
        consentHistory.Consent_Change_Others__c = 'Consent Test';
        consentHistory.Source_System__c =Constants.SYSTEM_MCP;
       insert consentHistory;
        
       Test.startTest();
      
       Audit audit=new Audit();
       audit.getConsentHistory();
       Test.stopTest();
        
    }
  
}

I am receiving error at below line in class:
consentHistory.Change_Received_DateTime__c = DateTime.newInstance(this.requested_datetime);

and below line in test class:
audit.getConsentHistory();

I understand that there is something which I am not able to catch for date time in above class which results in returning null value.

Kindly help me to pass this error in my test class.

Any help will be greatly appreciated.

Many thanks in advance

Thanks & Regards,
Maria

​​​​​​​
I got stuck at one place on one of my requirement on which I am working on.

My use case is as follows:
 
SCENARIO 1: Close Opportunity when Upgrade Order is cancelled 
GIVEN a a person account record in Salesforce AND the has an open upgrade opportunity record in Salesforce AND the opportunity record type equals "Upgrade Opportunity" AND the opportunity stage is not "Closed - Won" WHEN  places an upgrade order AND the status of the upgrade order has been changed to Cancelled THEN the open upgrade opportunity Stage field is set to "Closed - Lost" AND all other related opportunities that also meet this scenario criteria (Upgrade Opportunity, not Closed-Won) are set to "Closed - Lost"

I have done the scenario and code is also getting saved but getting System.NullPointerException:Attempt to de-reference a null Object when try to change the status of an upgrade order from a value say"Order-Placed" to "Cancelled"

Below is my Apex Class which runs in before update from Apex Trigger:
 
public with sharing class OrderTriggerService extends TriggerService {
public void updateOpportunityStage(){
        Set<Id> setIds = new Set<Id>();
        Map<Id,Order> orderOldMap =(Map<Id,Order>)oldMap;
        Map<Id,Order> orderNewMap=(Map<Id,Order>)newMap;
        Set<Opportunity>  updateOppties=new Set<Opportunity>();
        DateTime statusChange= System.now()-90;
        
        for (Order childObj : (List<Order>) newList) {
            if(childObj.Account_Record_Type_Name__c == 'Recipient' && childObj.Record_Type_Dev_Name__c == 'Upgrade_Order'){ 
            setIds.add(childObj.AccountId);
               
            }
        }
        if (setIds.isEmpty()) { return; }
        
        Map<ID, Account> parentAccts = new Map<Id, Account>(
                                          [select id, Upgrade_Order_Booked_Date__c, Upgrade_Order_Status__c, Order_Cancellation_Reason__c,Upgrade_Order_Number__c,Order_Cancellation_Date__c,
                                          (select id, Name, Booked_Date__c, Status ,Order_Cancellation_Reason__c,Oracle_Order_Number__c,Order_Cancellation_Date__c
                                            from Orders ) 
                                           from Account where id in :setIds]);
        System.debug('updateOrderUpgrade parentAccts: ' + parentAccts);
        
        Map<Account, Order> accountToLatestOrder = new Map<Account, Order>();
        for (Account acc : parentAccts.values()) {
            if (acc.orders.isEmpty() == false) {
                accountToLatestOrder.put(acc, acc.orders[0]);
            }
        }
         
    
      for(Account acc : [select id, Upgrade_Order_Booked_Date__c, Upgrade_Order_Status__c, Order_Cancellation_Reason__c,Upgrade_Order_Number__c,Order_Cancellation_Date__c,
                         			(select Id,Name,closedate,amount,StageName,Oracle_Order_Number__c,Status_Last_Changed_On__c
                                     from opportunities where Record_Type_Dev_Name__c='Upgrade_Opportunity') 
                         			from Account where id in : setIds]){
                             
                             for(Order orders : accountToLatestOrder.values()){            
                             		for(Opportunity opps : acc.opportunities){
                                 
                                 		if(opps.StageName<>'Upgrade-Closed Won' && orders.Status!=orderOldMap.get(orders.Id).Status && orders.Status=='Cancelled'){
                                 		
                                                 opps.StageName='Upgrade - Closed Lost'; 
                                                 
                                                 
                                 		}
                               
                            	
                                 System.debug('updateOpportunityStage Opportunity: ' + opps);  
                    			updateOppties.add(opps);
                             }
                             }
                         }
        
         				List<Opportunity> updateopps=new List<Opportunity>(updateOppties);
        				update updateopps;
        			}
}

Also,attached is the screenshots

Errors snapshot taken from UI

Kindly help me.

Any help will be greatly appreciated.

Many thanks​
I got stuck at one place on one of my requirement on which I am working on.

My use case is as follows:
 
SCENARIO 1: Close Opportunity when Upgrade Order is cancelled 
GIVEN a a person account record in Salesforce AND the has an open upgrade opportunity record in Salesforce AND the opportunity record type equals "Upgrade Opportunity" AND the opportunity stage is not "Closed - Won" WHEN the recipient places an upgrade order AND the status of the upgrade order has been changed to Cancelled THEN the open upgrade opportunity Stage field is set to "Closed - Lost" AND all other related opportunities that also meet this scenario criteria (Upgrade Opportunity, not Closed-Won) are set to "Closed - Lost"
 
CENARIO 2: Close Opportunity when Upgrade Order is shipped (ie Closed in Salesforce)
GIVEN a person account record in Salesforce
    AND thehas an opportunity record in Salesforce 
    AND the opportunity record type equals "Upgrade Opportunity"
    AND the stage of the opportunity record is not Closed-Won
    AND the stage of the opportunity record is not Closed-Lost (unless the stage was automatically set to Closed-Lost within the past 90 days due to an order cancellation)
WHEN the places an upgrade order
    AND the upgrade order has a status of Closed
THEN the open upgrade opportunity Stage field is set to "Closed - Won"
    AND all other related opportunities that also meet this scenario criteria (Upgrade Opportunity, not Closed-Won, not Closed-Lost unless automatically changed to Closed-Lost within 90 days) are set to "Closed - Won"

I have done 1st scenario and works well.For 2nd scenario also I have done almost everything except one scenario where I need to track "the stage of the opportunity record is not Closed-Lost (unless the stage was automatically set to Closed-Lost within the past 90 days due to an order cancellation)

Below is my Apex Class which runs in before update from Apex Trigger:
 
public with sharing class OrderTriggerService extends TriggerService {


public void updateOpportunityStage(){
    Set<Id> setIds = new Set<Id>();
    Map<Id,Order> orderOldMap =(Map<Id,Order>)oldMap;
    Set<Opportunity>  updateOppties=new Set<Opportunity>();

    for (Order childObj : (List<Order>) newList) {

        if(childObj.Account_Record_Type_Name__c == 'INDIA' && childObj.Record_Type_Dev_Name__c == 'Upgrade_Order'){ 
        setIds.add(childObj.AccountId);

        }
    }
    if (setIds.isEmpty()) { return; }

 //Set<Opportunity>  updateOppties=new Set<Opportunity>();
  for(Account acc : [select id,Name
                        (selectId,Name,closedate,amount,StageName
                             from opportunities where 
                            Record_Type_Dev_Name__c='Upgrade_Opportunity') 
                                from Account where id in:setIds]){

                         for(Order orders : (List<Order>) newList){            
                                for(Opportunity opps : acc.opportunities){

                                    if(opps.StageName<>'Closed Won' && orders.Status!=orderOldMap.get(orders.Id).Status && orders.Status=='Cancelled'){
                                             opps.StageName='Closed Lost'; 


                                    }

                            else if((opps.StageName<>'Closed Won'||opps.StageName<>'Closed Lost')&& orders.Status!=orderOldMap.get(orders.Id).Status && orders.Status=='Closed'){         
                                        opps.StageName='Closed Won';

                             }

                            updateOppties.add(opps);
                         }
                         }
                     }

                    List<Opportunity> updateopps=new List<Opportunity(updateOppties);
                    update updateopps;

}
  }
I am not able to find a way to track opp.stagename<>'Closed Lost'(unless the stage was automatically set to Closed-Lost within the past 90 days due to an order cancellation) in my class.
Kindly help.

Any help will be greatly appreciated.

Many thanks in advance
 
hi all,

I urgently need to edit/delete a post made by me on this discussion forum...But its not allowing me to do so and pops up
saying that 'you cant delete this question as others are interested in it'.
There are no likes and no comments on it still i am unable  to delete it
Any help would be highly appreciated

Its very urgent,
Thanks,