• Sreenu Reddy 16
  • NEWBIE
  • 25 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 8
    Questions
  • 16
    Replies
In lightning component  if I enter a branch name and hit a button in UI page it invoke/run  the git pipeline after get the Json response,The response having Status, Job id  and displayed same response in outfield of same page .
Here i am getting status as intial stage f pipeline .But I want to get auto update status. means if git pipelines are running its status changed like pipeline status changes pending, running, success/failure .

I want to ;update that same status in  a Component ui page  bellow it my code  
GitInvoke.Cmp:
<aura:component controller="callOutInvoke2" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
     <aura:attribute name="branchName" type="String"/>
     <aura:attribute name="jobId" type="String"/>
     <aura:attribute name="response" type="object"/>
     <aura:attribute name="status" type="String"/>
    <aura:registerEvent name="loadMyEvent" type="c:GitpipelineStatusEvt_1"/><br/>
  <lightning:card  class="slds-card slds-has-bottom-magnet" >
    <div class = "slds-grid slds-grid_vertical slds-text-color--default slds-align_absolute-center">
        <div class="page-section page-header slds-align_absolute-center slds-text-heading_large" style="height:2rem">               
        <h2 class="header" style="font-weight: bold;">Invoke GIT Pipeline </h2>
        </div>       
        <div class="page-section page-header slds-align_absolute-center slds-text-heading_medium"> 
       <b><lightning:input type="text" name="input1" value="{!v.branchName}" label="Enter Future Branch" /></b>
        </div>
        <div class="page-section page-header slds-align_absolute-center slds-text-heading_medium"> 
        <h2 class="header">Job Status :{!v.status}</h2> <br/>
        </div>    
        <div class="page-section page-header slds-align_absolute-center slds-text-heading_medium">     
        <h2 class="header">Jobid :{!v.jobId}</h2>
        </div>    
    </div>
        
    <div class="page-section page-header slds-align_absolute-center slds-text-heading_medium">
       <lightning:button variant="brand" label="Invoke GIT" onclick="{! c.calloutCtrl }" />             
    </div>   
 </lightning:card>   
</aura:component>
GitInvoke.controller:
({
    calloutCtrl : function(component, event, helper) {
       helper.getResponse(component, event,helper);
     }
})
GitInvoke.Helper:
({  getResponse : function(component, event,helper) {        
        var bname=component.get("v.branchName");
        var action = component.get("c.getCalloutResponseContents");
        action.setParams({"branchName": bname});
        action.setCallback(this, function(response) {
          var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {                
                component.set("v.response", response.getReturnValue());                
                var getStatus = component.get("v.response").status;
                var getJobId = component.get("v.response").id;                
                component.set("v.status",getStatus);
                component.set("v.jobId",getJobId);
                var evt = $A.get("e.c:GitpipelineStatusEvt_1");
                evt.setParams({ "Pass_Result": getJobId});
                var evtParam=evt.getParam("Pass_Result");
                  evt.fire();
            }
            else{
                alert('Failed call from parent!!');
            }
        
    });  
   $A.enqueueAction(action);  
 }  
})
callOutInvoke2.class :
public class callOutInvoke2 {
    @AuraEnabled
    public static Sr_calloutGitPipelineResponseWrapper       getCalloutResponseContents(String branchName) {
        system.debug('url'+branchName);
        String gitBranch=branchName;
        String endPoint;
        if(gitBranch=='Develop'){
            endPoint=system.label.gitDevelop;
        }
        else if(gitBranch=='Integration'){
            endPoint=system.label.gitIntegration;   
        }
        else if(gitBranch=='Master'){
            endPoint=system.label.gitMaster;    
        }
        else 
            endPoint=system.label.gitMaster;            
        system.debug('endPoint---'+endPoint);
        String authToken=system.label.gitToken;
        callOutGitPipelineWrapper requestPayload=new callOutGitPipelineWrapper();
        requestPayload.branchName=branchName;        
        String jsonReq = JSON.serialize(requestPayload);
        // Instantiate a new http object
        Http http = new Http(); 
        HttpRequest request = new HttpRequest();
        request.setHeader( 'Content-Type', 'application/json' );
        request.setHeader( 'Accept', 'application/json' );
        request.setHeader( 'Authorization', 'Bearer ' + authToken );
        request.setEndpoint(endPoint);
        request.setMethod('POST');
        request.setBody(jsonReq); 
        System.debug('request:--> ' + request.getBody());
        // Send the request, and return a response
        HttpResponse res = http.send(request);
        System.debug('response:--> ' + res.getBody());
       Sr_calloutGitPipelineResponseWrapper callList= (Sr_calloutGitPipelineResponseWrapper)JSON.deserialize(res.getBody(), Sr_calloutGitPipelineResponseWrapper.class);
       system.debug('result-->' + callList);
        
        return callList;
    }   
     public class callOutGitPipelineWrapper{
      string branchName  { get; set; }  
      String Id { get; set; } 
    }
}
Sr_calloutGitPipelineResponsewrapperclass:

public class Sr_calloutGitPipelineResponseWrapper {
    public class Detailed_status {
        public String icon {get;set;} 
        public String text {get;set;} 
        public String label {get;set;} 
        public String group_Z {get;set;} // in json: group
        public String tooltip {get;set;} 
        public Boolean has_details {get;set;} 
        public String details_path {get;set;} 
        public Object illustration {get;set;} 
        public String favicon {get;set;} 

        public Detailed_status(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'icon') {
                            icon = parser.getText();
                        } else if (text == 'text') {
                            text = parser.getText();
                        } else if (text == 'label') {
                            label = parser.getText();
                        } else if (text == 'group') {
                            group_Z = parser.getText();
                        } else if (text == 'tooltip') {
                            tooltip = parser.getText();
                        } else if (text == 'has_details') {
                            has_details = parser.getBooleanValue();
                        } else if (text == 'details_path') {
                            details_path = parser.getText();
                        } else if (text == 'illustration') {
                            illustration = parser.readValueAs(Object.class);
                        } else if (text == 'favicon') {
                            favicon = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Detailed_status consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class User {
        public Integer id {get;set;} 
        public String name {get;set;} 
        public String username {get;set;} 
        public String state {get;set;} 
        public String avatar_url {get;set;} 
        public String web_url {get;set;} 

        public User(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'id') {
                            id = parser.getIntegerValue();
                        } else if (text == 'name') {
                            name = parser.getText();
                        } else if (text == 'username') {
                            username = parser.getText();
                        } else if (text == 'state') {
                            state = parser.getText();
                        } else if (text == 'avatar_url') {
                            avatar_url = parser.getText();
                        } else if (text == 'web_url') {
                            web_url = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'User consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    @AuraEnabled
    public Integer id {get;set;} 
    public String sha {get;set;} 
    public String ref {get;set;} 
    @AuraEnabled
    public String status {get;set;} 
    public String created_at {get;set;} 
    public String updated_at {get;set;} 
    public String web_url {get;set;} 
    public String before_sha {get;set;} 
    public Boolean tag {get;set;} 
    public Object yaml_errors {get;set;} 
    public User user {get;set;} 
    public Object started_at {get;set;} 
    public Object finished_at {get;set;} 
    public Object committed_at {get;set;} 
    public Object duration {get;set;} 
    public Object coverage {get;set;} 
    public Detailed_status detailed_status {get;set;} 

    public Sr_calloutGitPipelineResponseWrapper(JSONParser parser) {
        while (parser.nextToken() != System.JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                    if (text == 'id') {
                        id = parser.getIntegerValue();
                    } else if (text == 'sha') {
                        sha = parser.getText();
                    } else if (text == 'ref') {
                        ref = parser.getText();
                    } else if (text == 'status') {
                        status = parser.getText();
                    } else if (text == 'created_at') {
                        created_at = parser.getText();
                    } else if (text == 'updated_at') {
                        updated_at = parser.getText();
                    } else if (text == 'web_url') {
                        web_url = parser.getText();
                    } else if (text == 'before_sha') {
                        before_sha = parser.getText();
                    } else if (text == 'tag') {
                        tag = parser.getBooleanValue();
                    } else if (text == 'yaml_errors') {
                        yaml_errors = parser.readValueAs(Object.class);
                    } else if (text == 'user') {
                        user = new User(parser);
                    } else if (text == 'started_at') {
                        started_at = parser.readValueAs(Object.class);
                    } else if (text == 'finished_at') {
                        finished_at = parser.readValueAs(Object.class);
                    } else if (text == 'committed_at') {
                        committed_at = parser.readValueAs(Object.class);
                    } else if (text == 'duration') {
                        duration = parser.readValueAs(Object.class);
                    } else if (text == 'coverage') {
                        coverage = parser.readValueAs(Object.class);
                    } else if (text == 'detailed_status') {
                        detailed_status = new Detailed_status(parser);
                    } else {
                        System.debug(LoggingLevel.WARN, 'calloutGitPipelineResponseWrapper consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }
    
    
    public static calloutGitPipelineResponseWrapper parse(String json) {
        System.JSONParser parser = System.JSON.createParser(json);
        return new calloutGitPipelineResponseWrapper(parser);
    }
    
    public static void consumeObject(System.JSONParser parser) {
        Integer depth = 0;
        do {
            System.JSONToken curr = parser.getCurrentToken();
            if (curr == System.JSONToken.START_OBJECT || 
                curr == System.JSONToken.START_ARRAY) {
                depth++;
            } else if (curr == System.JSONToken.END_OBJECT ||
                curr == System.JSONToken.END_ARRAY) {
                depth--;
            }
        } while (depth > 0 && parser.nextToken() != null);
    }
}
how to solve complexity of methods directly affects maintenance costs  in class
Hi Floks....I  got some issue here . please help on this. my issues is 
System.HttpResponse[Status=Internal Server Error, StatusCode=500]
This is my code :
public class RESTExample {
  public String result{set;get;}   
  public string grant_type{set;get;}
  public string Accesstoken{set;get;} 
  public string username{set;get;}
  public string password{set;get;}
  public string client_id{set;get;}
  public string client_secret{set;get;} 
    public string getAccesstoken(){     
    String reqbody ='grant_type='+password+'&client_id='+client_id+'&client_secret='+client_Secret+'&username='+username+'&password='+password; 
        
      Http p= new Http (); 
      HttpRequest req= new HttpRequest ();
      
      req.setEndpoint('https://sandbox-us-api.experian.com/oauth2/v1/token'); 
      req.setMethod('POST');         
      req.setBody(reqbody);       
      system.debug('@@@@the reponse value is ###'+req.getbody()); 
       
       req.setHeader('Content-Type','application/json;charset=UTF-8');
       req.setHeader('accept','application/json');       
       try{ 
         HttpResponse res = p.send(req);  
         system.debug('###the reponse value is@@@ '+res.getbody()); 
         
         //system.debug('#### the value is %%%%%'+res);            
          
        
     // Map<String, String> results = (Map<String, String>) JSON.deserializeUntyped(res.getBody()); 
     // system.debug('@@@Access token value&&&'+ result);
       String accessToken ; 
       System.JSONParser parser=JSON.createParser(result);
               
             while (parser.nextToken() != null)  {
                  if ((parser.getCurrentToken() == JSONToken.FIELD_NAME))
                      {
                                            String fieldName = parser.getText();
                                            parser.nextToken();
                                            System.debug('fieldName'+fieldName);
                                            if (fieldName == 'access_token') 
                                                {
                                                accessToken = parser.getText();
                                                } 
                     }
           }
            }
         catch (Exception e){
         }  
     return accessToken;       
     }
  }
    
Challenge not yet complete in My Trailhead Playground 1
There was an unexpected error in your org which is preventing this assessment check from completing: System.CalloutException: IO Exception: Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://th-apex-soap-service.herokuapp.com/parks
sfdc flocks can you give me  help on below code .

Method does not exist or incorrect signature: void put(Decimal, String) from the type Map<Id,String> at line 8 column 24

trigger changeowner on Lead (before insert) {
     Map<Id,String> zipCodeUserMap = new Map<Id,String>();
     List<Zip_Code__c> zipCodes = new List<Zip_Code__c>();
     zipCodes = [Select id,ZipCode__c,Counserlor__c  from Zip_Code__c];
      
      for (Zip_Code__c zc :zipCodes){
        
        zipCodeUserMap.put(zc.ZipCode__c,zc.Counserlor__c);   
     }
       
       
       
       for(Lead l : Trigger.new) 
       {
        if(zipCodeUserMap.containsKey(l.Zip_Code__c)) 
        {
            l.Ownerid = zipCodeUserMap.get(l.Zip_Code__c);
        }
       }
}

hi viewers: i have two fields in task obj most recent campaign (lookup to campaign)  and description , i want to update the description  as mosot resend campaign (lookup to campaign ) in task.. using before trigger. i wrote some logic  updateDescription on Task (Before insert,Before Update) . i am getting fallowing error when i am create record. any one help me .


{

            set<id> setcmpnid =new set<id>();
            
            for(task tsk:trigger.new)
              {
                String wId = tsk.WhatId;
                
                if(wId!=null && !setcmpnid.contains(tsk.WhatId))
                { 
                  setcmpnid.add(tsk.WhatId);
                  system.debug('++++++ the setcmpnid  value is +++++++'+setcmpnid);
                } 
            }
            
            if(setcmpnid.size()>0) {
            
            list<campaign> tskcmpn= [Select id, Description from campaign where id in :setcmpnid ];
            
            Map<id,campaign> cmpn= new Map<id,campaign>();
               for(campaign cpn : tskcmpn)
              {
                  cmpn.put(cpn.Id,cpn); 
                   system.debug('++++++ the campaign id value is +++++++'+cmpn);
              }
            
              for (task tsk:trigger.new) {
                                
                String wId = tsk.WhatId; 
            
               if(wId!=null) { 
                  
               campaign thiscpn = cmpn.get(tsk.WhatId);  
               
               if(thiscpn != null){
               
               tsk.most_Resent_Campaign__c = thiscpn.Description;
            
               system.debug('++++++ the tsk.most_Resent_Campaign__c value is +++++++'+tsk.most_Resent_Campaign__c);
               
                  }            
                }       
            
              }
            
            }
         }
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger updateDescription caused an unexpected exception, contact your administrator: updateDescription: execution of BeforeUpdate caused by: System.StringException: Invalid id: sfdc salesforce sfdc : Trigger.updateDescription: line 37, column 1
HI Viewers,
i have two  fields   converteddate__C(Date) and submittedDate__c(Date/Time)  in lead object and having  formula field Duration scince converted.Here "Dutation_since_converted =  converteddate__C - Datevalue(submittedDate__c) "..  i want  calculate only weekdays. i write a formula , i am getting  duration_since_converted. But i want exclude weeends in this ?How to wrt formula for exclude weekends can any one can help me please .

Thanks!
Sreeni sree
Hi Viewers,

i want sent email when click on detail page custom button in opportunity obj. &update the fields 
1. send an email partner
2.channel manager(account owner of partner account)
3.account owner
4. fields should be updated like date= today,stage='duplcate',status= 'rejected'.


​can any one help me .
Challenge not yet complete in My Trailhead Playground 1
There was an unexpected error in your org which is preventing this assessment check from completing: System.CalloutException: IO Exception: Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://th-apex-soap-service.herokuapp.com/parks
sfdc flocks can you give me  help on below code .

Method does not exist or incorrect signature: void put(Decimal, String) from the type Map<Id,String> at line 8 column 24

trigger changeowner on Lead (before insert) {
     Map<Id,String> zipCodeUserMap = new Map<Id,String>();
     List<Zip_Code__c> zipCodes = new List<Zip_Code__c>();
     zipCodes = [Select id,ZipCode__c,Counserlor__c  from Zip_Code__c];
      
      for (Zip_Code__c zc :zipCodes){
        
        zipCodeUserMap.put(zc.ZipCode__c,zc.Counserlor__c);   
     }
       
       
       
       for(Lead l : Trigger.new) 
       {
        if(zipCodeUserMap.containsKey(l.Zip_Code__c)) 
        {
            l.Ownerid = zipCodeUserMap.get(l.Zip_Code__c);
        }
       }
}
HI Everyone,

I have a confusion about Helper and Handler classes.
Can some please explain briefly what are those?

Thanks in advance

hi viewers: i have two fields in task obj most recent campaign (lookup to campaign)  and description , i want to update the description  as mosot resend campaign (lookup to campaign ) in task.. using before trigger. i wrote some logic  updateDescription on Task (Before insert,Before Update) . i am getting fallowing error when i am create record. any one help me .


{

            set<id> setcmpnid =new set<id>();
            
            for(task tsk:trigger.new)
              {
                String wId = tsk.WhatId;
                
                if(wId!=null && !setcmpnid.contains(tsk.WhatId))
                { 
                  setcmpnid.add(tsk.WhatId);
                  system.debug('++++++ the setcmpnid  value is +++++++'+setcmpnid);
                } 
            }
            
            if(setcmpnid.size()>0) {
            
            list<campaign> tskcmpn= [Select id, Description from campaign where id in :setcmpnid ];
            
            Map<id,campaign> cmpn= new Map<id,campaign>();
               for(campaign cpn : tskcmpn)
              {
                  cmpn.put(cpn.Id,cpn); 
                   system.debug('++++++ the campaign id value is +++++++'+cmpn);
              }
            
              for (task tsk:trigger.new) {
                                
                String wId = tsk.WhatId; 
            
               if(wId!=null) { 
                  
               campaign thiscpn = cmpn.get(tsk.WhatId);  
               
               if(thiscpn != null){
               
               tsk.most_Resent_Campaign__c = thiscpn.Description;
            
               system.debug('++++++ the tsk.most_Resent_Campaign__c value is +++++++'+tsk.most_Resent_Campaign__c);
               
                  }            
                }       
            
              }
            
            }
         }
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger updateDescription caused an unexpected exception, contact your administrator: updateDescription: execution of BeforeUpdate caused by: System.StringException: Invalid id: sfdc salesforce sfdc : Trigger.updateDescription: line 37, column 1
Hi Viewers,

i want sent email when click on detail page custom button in opportunity obj. &update the fields 
1. send an email partner
2.channel manager(account owner of partner account)
3.account owner
4. fields should be updated like date= today,stage='duplcate',status= 'rejected'.


​can any one help me .
"myfirstcontapp" is a Namespace Prefix

Code for AnimalLocator Class:
public class AnimalLocator{
   public static String getAnimalNameById(Integer id){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        String strResp = '';
        system.debug('******response '+response.getStatusCode());
        system.debug('******response '+response.getBody());
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200){
            // Deserializes the JSON string into collections of primitive data types.
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            // Cast the values in the 'animals' key as a list
            Map<string,object> animals = (map<string,object>) results.get('animal');
            System.debug('Received the following animals:' + animals );
            strResp = string.valueof(animals.get('name'));
            System.debug('strResp >>>>>>' + strResp );
        }
        return strResp ;
    }
}


Code for AnimalLocatorMock Mock Class
@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}');
        response.setStatusCode(200);
        return response; 
    }
}
Code for AnimalLocatorTest​  Test Class:
@isTest
public class AnimalLocatorTest {
  @isTest public static void AnimalLocatorMock() {
       //Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
      test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
        string result = AnimalLocator.getAnimalNameById(1);
      system.debug(result);
        String expectedResult = 'chicken';
        System.assertEquals(result,expectedResult );
    }
}
Thanks
I'm stuck trying to access Einstein Platform Account. It says my email is already registered, but I have no way to get in. PEM? HELP please.
Hello,

I created an Apex class to be launched after a sandbox refresh.
I am trying to implement the test class corresponding but I got the following error :
Method does not exist or incorrect signature: Test.testSandboxPostCopyScript(SandboxPostRefresh, Id, Id, String)
Someone already had this error ? My class is set on version 38.

Here is my test class :
@isTest
private class SandboxPostRefreshTest {
	
	@isTest static void testSandboxPostRefresh() {
		Test.startTest();
		SandboxPostRefresh ClassInstance = new SandboxPostRefresh();
		System.Test.testSandboxPostCopyScript(ClassInstance, UserInfo.getOrganizationId(), UserInfo.getOrganizationId(), 'sandboxName');
		Test.stoptest();
	}	
}

And my post refresh class :
global class SandboxPostRefresh {
	global void runApexClass(SandboxContext context) {
		NexthinkProvider np = NexthinkProvider.getInstance();
		String[] opportunityRecordTypes = new String[]{'New Customer','NBS','Services','Renewal','Upsell'};
		Schema.DescribeSObjectResult oSchema = Schema.SObjectType.Opportunity;
		Map<String,Schema.RecordTypeInfo> rtMapByName = oSchema.getRecordTypeInfosByName();

		// Create accounts
		List<Map<String, Object>> accountsProperties = new List<Map<String, Object>>();
		for (Integer i = 1; i <= 13; i++) {
			String industry = Randomizer.getRandomPickListValue(Account.sObjectType, null, 'Industry', false);
			Account a = new Account();
			Randomizer.getRandomPickListValue(null, a, 'Industry', false);
		    Map<String, Object> accountProperties = new Map<String, Object>();
		    if(i == 13) {
				accountProperties.put('Name', 'Direct');
		    }
		    else {
				accountProperties.put('Name', Randomizer.getRandomCompanyName());
			}
			accountProperties.put('Industry', Randomizer.getRandomPickListValue(Account.sObjectType, null, 'Industry', false));
			if(i <= 3) {
				accountProperties.put('Type', 'Potential Customer');
			}
			else if(i > 3 && i <= 6) {
				accountProperties.put('Type', 'Customer');
			}
			else if(i > 6 && i <= 9) {
				accountProperties.put('Type', 'Potential Partner');
				accountProperties.put('Industry', 'Technology');
			}
			else if(i > 9 && i <= 13) {
				accountProperties.put('Type', 'Partner');
				accountProperties.put('Industry', 'Technology');
			}
			accountProperties.put('CurrencyIsoCode', Randomizer.getRandomCurrency());
			accountProperties.put('Country__c', Randomizer.getRandomCountry());
			accountsProperties.add(accountProperties);
		}
		List<Account> accounts = np.createAccounts(accountsProperties);

		List<Account> partners = new List<Account>();
		for(Account a : accounts) {
			if(a.Type == 'Potential Partner' || a.Type == 'Partner') {
				partners.add(a);
			}
		}

		
		List<Map<String, Object>> contactsProperties = new List<Map<String, Object>>();
		List<Map<String, Object>> opportunitesProperties = new List<Map<String, Object>>();
		for(Account a : accounts) {
			// Create contacts
			Map<String, Object> contactProperties = new Map<String, Object>();
			contactProperties.put('FirstName', Randomizer.getRandomFirstname());
			contactProperties.put('LastName', Randomizer.getRandomLastname());
			contactProperties.put('Phone', Randomizer.getRandomPhoneNumber());
			contactProperties.put('AccountId', a.Id);
			String firstname = (String) contactProperties.get('FirstName');
			String lastname = (String) contactProperties.get('LastName');
			contactProperties.put('Email', firstname.toLowerCase() + '.' + lastname.toLowerCase() + '@' + a.Name.toLowerCase() + '.com');
			contactProperties.put('Country__c', a.Country__c);
			contactProperties.put('LeadSource', Randomizer.getRandomPickListValue(Contact.sObjectType, null, 'LeadSource', false));
			contactsProperties.add(contactProperties);
			if(a.Name != 'Direct' && a.Type != 'Partner' && a.Type != 'Potential Partner') {
				for (Integer i = 1; i <= 3; i++) {
					// Create opportunities
					Map<String, Object> opportunityProperties = new Map<String, Object>();
					
					String partnerName;
					if(Randomizer.getRandomBoolean()) {
						Account partner = partners.get(Randomizer.getRandomNumber(6));
						partnerName = partner.Name;
						opportunityProperties.put('Partner_Lookup__c', partner.Id);
					}
					else {
						partnerName = 'Direct';
					}

					Schema.RecordTypeInfo rt = rtMapByName.get(Randomizer.getRandomString(opportunityRecordTypes));
					opportunityProperties.put('RecordTypeId', rt.getRecordTypeId());
					opportunityProperties.put('Name', a.Name + '_' + partnerName + '_' + rt.getName());
					opportunityProperties.put('AccountId', a.Id);
					opportunityProperties.put('CurrencyIsoCode', a.CurrencyIsoCode);
					opportunityProperties.put('CloseDate', Date.today().addDays(Randomizer.getRandomNumber(90)));
					opportunityProperties.put('StageName', 'Unqualified');
					opportunityProperties.put('Probability', 11);
					opportunityProperties.put('LeadSource', Randomizer.getRandomPickListValue(Opportunity.sObjectType, null, 'LeadSource', false));
					opportunityProperties.put('Contract_Start_Date__c', ((Date) opportunityProperties.get('CloseDate')).addDays(1));
					String contractCommitment = Randomizer.getRandomPickListValue(Opportunity.sObjectType, null, 'Contract_Commitment__c', false);
					opportunityProperties.put('Contract_Commitment__c', contractCommitment);
					if(contractCommitment == '<1 Year') {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(90));
					}
					else if(contractCommitment == '1 Year') {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(Randomizer.getRandomNumber(365)));
					}
					else if(contractCommitment == '2 Years') {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(365*2));
					}
					else if(contractCommitment == '3 Years') {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(365*3));
					}
					else if(contractCommitment == '4 Years') {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(365*4));
					}
					else if(contractCommitment == '5 Years') {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(365*5));
					}
					else {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(500));
					}
					opportunitesProperties.add(opportunityProperties);
				}
			}
		}
		List<Contact> contacts = np.createContacts(contactsProperties);
		List<Opportunity> opportunities = np.createOpportunities(opportunitesProperties);

		// Get all products
		Map<String, Product2> productsMap = new Map<String, Product2>(); 
		for(Product2 product : [SELECT Id, Name FROM Product2]) {
			productsMap.put(product.Name, product);
		}
        
        // Create OpportunityLineItem
		Map<Opportunity,List<Object>> olisMap = new Map<Opportunity,List<Object>>();
		for(Opportunity o : opportunities) {
			List<Object> tempList = new List<Object>();
			List<Product2> opportunityProductList = new List<Product2>();
			Map<String, Object> oliProperties = new Map<String, Object>();
			oliProperties.put('Description', 'SKU');
			
			if(o.RecordTypeId == rtMapByName.get('New Customer').getRecordTypeId() || o.RecordTypeId == rtMapByName.get('Upsell').getRecordTypeId()) {
				oliProperties.put('Quantity', 100);
				opportunityProductList.add(productsMap.get('Endpoint Collector - License'));
				if(Randomizer.getRandomBoolean()) {
					opportunityProductList.add(productsMap.get('Endpoint Collector - Maintenance 1yr'));
				}
				else {
					opportunityProductList.add(productsMap.get('Endpoint Collector - Subscription 1yr'));
				}
				if(Randomizer.getRandomBoolean()) {
					opportunityProductList.add(productsMap.get('Time & Material billed upon completion - per day'));
				}
			}
			if(o.RecordTypeId == rtMapByName.get('NBS').getRecordTypeId()) {
				oliProperties.put('Quantity', 5);
				opportunityProductList.add(productsMap.get('Baseline Service 1-Engine'));
			}
			if(o.RecordTypeId == rtMapByName.get('Renewal').getRecordTypeId()) {
				oliProperties.put('Quantity', 1000);
				if(Randomizer.getRandomBoolean()) {
					opportunityProductList.add(productsMap.get('Renewal Endpoint Collector - Subscription 1yr'));
				}
				else {
					opportunityProductList.add(productsMap.get('Renewal Endpoint Collector - Maintenance 1yr'));
				}
			}
			if(o.RecordTypeId == rtMapByName.get('Services').getRecordTypeId()) {
				oliProperties.put('Quantity', 10);
				Integer random = Randomizer.getRandomNumber(3);
				if(random == 1) {
					opportunityProductList.add(productsMap.get('Time & Material billed upon completion - per day'));
				}
				else if(random == 2) {
					opportunityProductList.add(productsMap.get('Service Fee Billed in Advance'));
				}
				else if(random == 3) {
					opportunityProductList.add(productsMap.get('Fixed fee billed upon milestone completion'));
				}
			}
			tempList.add(opportunityProductList);
			tempList.add(oliProperties);
			olisMap.put(o, tempList);
		}
		np.addProducts(olisMap);
	}
}

 
Batch class as exposed as interface implement by developer.it is helpful for handle large number of records.Please explain real time exmple why we need to use Batch class  in real time?
public class VerifyDate {
//method to handle potential checks against two dates
public static Date CheckDates(Date date1, Date date2) {
//if date2 is within the next 30 days of date1, use date2. Otherwise use the end of the month
if(DateWithin30Days(date1,date2)) {
return date2;
} else {
return SetEndOfMonthDate(date1);
}
}
//method to check if date2 is within the next 30 days of date1
private static Boolean DateWithin30Days(Date date1, Date date2) {
//check for date2 being in the past
if( date2 < date1) { return false; }
//check that date2 is within (>=) 30 days of date1
Date date30Days = date1.addDays(30); //create a date 30 days away from date1
if( date2 >= date30Days ) { return false; }
else { return true; }
}
//method to return the end of the month of a given date
private static Date SetEndOfMonthDate(Date date1) {
Integer totalDays = Date.daysInMonth(date1.year(), date1.month());
Date lastDay = Date.newInstance(date1.year(), date1.month(), totalDays);
return lastDay;
}
}

I need test class for this class.Please provide me
Hello developer heroes!

I'm working through the Apex modules on Trailhead and can't seem to get past this one: https://developer.salesforce.com/en/trailhead/force_com_programmatic_beginner/apex_triggers/apex_triggers_bulk.

Hopefully this doesn't read like a 'please complete the course for me' kinda post, but I have written a trigger that I believe meets the criteria but it isn't passing the check, so I wanted to seek the guidance of the experts.

The challenge is to do this:

Create an Apex trigger for Opportunity that adds a task to any opportunity set to 'Closed Won'.

To complete this challenge, you need to add a trigger for Opportunity. The trigger will add a task to any opportunity inserted or updated with the stage of 'Closed Won'. The task's subject must be 'Follow Up Test Task'.The Apex trigger must be called 'ClosedOpportunityTrigger'

- With 'ClosedOpportunityTrigger' active, if an opportunity is inserted or updated with a stage of 'Closed Won', it will have a task created with the subject 'Follow Up Test Task'.
- To associate the task with the opportunity, fill the 'WhatId' field with the opportunity ID.
- This challenge specifically tests 200 records in one operation.


And here is the trigger I have come up with, which compiles OK and stands up to a manual (though admittedly unbulkified) test:
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {

    List<Task> taskList = new List<Task>();
    
    for (Opportunity opp : [SELECT Id, StageName FROM Opportunity WHERE StageName = 'Closed Won' AND Id IN :Trigger.new]){
                    
            taskList.add(new Task(Subject = 'Follow Up Test Task',
                                  WhatId = opp.Id));
       
    }

    if(taskList.size()>0){
        
        insert taskList;
        
    }
    
}
I have tried replacing the SOQL with a straightforward 'for (Opportunity opp : Trigger.new)' and having the taskList.add inside an IF that checks for Closed Won - no luck. I also thought about checking to see if the stage was being changed to Closed Won, rather than the trigger firing on every edit, but I don't think this is what the module is asking for.

Where do you think I'm going wrong?

Huge thanks in advance!