• trailhead solutions 10
  • NEWBIE
  • 40 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 22
    Questions
  • 20
    Replies
What is Release Updates in Salesforce and what to update and what is the detailed step by step process to Complete it fully in Production?

Thanks
TH
Hello All

we have one Issue Facing in real time.

Previously---- We had a Chat Button already Implemented in our website. It is working fine and deployed to web page.

Current Requirement--- We need to Implement Automated Invitation on the same web page whenever Consumer stays on the page for 5 secs.

So when we are trying to add this code to already existed page, it is not allowing on that page since, there is already a Embedded Code in it.

So, we raised a Ticket to SF Support and suggested that, Two Embedded Chat Buttons , we cant add in a same web Page. Limitation from Salesforce.

Hence, I request you to Please suggest us , how to implement both Button and Automated Invitation on a same web Page? Is there any Suggestion to Implement this, Please share us.

Thanks in Advance!!
 
Need detailed information on reports and dashboard its limits and what is the minimum access needed for running
1) reports of self owned records ? and
2) subordinate record if his manager runs it.?

Please someone help with Info on Access and Limits required to Run reports in all aspects?
Hello All

I have to write a Apex rest service for http post, in order to Push the Salesforce Records.

Currently, To Query the records, they are using get method and connected App.But, now needs to change to Post method and that should be dynamically for any sObject.

Here I wrote for one Object. But, Some Please let me know what should I build the Code, for all sObjects dynamically.

@RestResource(urlMapping='/v1/sss-api/*')
global class Common_Api_Service {
    final static String baseUrl=URL.getSalesforceBaseUrl().toExternalForm();
    @Httppost
    global static String getObjectDetailsByQuery(String sobjectname, String sQuery){
        
        String con = 'Select AccountId, Id, Alternative_Email_2__c, Email, FirstName, LastName, HomePhone, MailingAddress, MailingCity, MailingCountry, MailingGeocodeAccuracy, MailingLatitude, MailingLongitude, MailingPostalCode, MailingState, MailingStreet, MiddleName, MobilePhone, Name, OtherAddress, OtherCity, OtherCountry, OtherGeocodeAccuracy, OtherLatitude, OtherLongitude, OtherPersonPhoneID__c, OtherPhone, OtherPostalCode, OtherState, OtherStreet, PersonID_Email__c, PersonID_Phone__c, Phone, Region__c, Secondary_Email__c, Previous_Emails__c FROM Contact' ;
         List <sObject> slist  = Database.query(con);
        return con;

    }
}

Thanks
GSN
Hello All

I have to write a Apex rest service for http post, in order to Push the Salesforce Records.

Currently, To Query the records, they are using get method and connected App.But, now needs to change to Post method and that should be dynamically for any sObject.

Here I wrote for one Object. But, Some Please let me know what should I build the Code, for all sObjects dynamically.

@RestResource(urlMapping='/v1/sss-api/*')
global class Common_Api_Service {
    final static String baseUrl=URL.getSalesforceBaseUrl().toExternalForm();
    
    
    @Httppost
    global static String getObjectDetailsByQuery(String sobjectname, String sQuery){
        
        String con = 'Select AccountId, Id, Alternative_Email_2__c, Email, FirstName, LastName, HomePhone, MailingAddress, MailingCity, MailingCountry, MailingGeocodeAccuracy, MailingLatitude, MailingLongitude, MailingPostalCode, MailingState, MailingStreet, MiddleName, MobilePhone, Name, OtherAddress, OtherCity, OtherCountry, OtherGeocodeAccuracy, OtherLatitude, OtherLongitude, OtherPersonPhoneID__c, OtherPhone, OtherPostalCode, OtherState, OtherStreet, PersonID_Email__c, PersonID_Phone__c, Phone, Region__c, Secondary_Email__c, Previous_Emails__c FROM Contact' ;
         List <sObject> slist  = Database.query(con);
        return con;

    }
}

Thanks
GSN
Hello

My Requirement is to, whenever there is Phone Number entered in case Object, then in that case, if User enters any Special Characters, then it should ignore the Special Characters and display only the Digits.

I wrote a Trigger on it. Seems to be Correct. But, not working while I am testing.Please someone test in your Org and let me know, where I did mistake.

trigger PhNumValidation on Case (before insert,before update) {
    list<case> clist=new list<case>();
    for(Case c:Trigger.new){
      if (c.Phone_Number__c != null ) {
           string phone =c.Phone_Number__c;
          string newph=phone.replaceAll('\\D','');
          system.debug('Ph: '+newph);
        }   
          
           
        }
        
    }


Thanks
GSN
Hello

Anyone worked on Automated Invitation to Pop up on the Website, Please let me know how to implement the Process. I havegone through Sites from Salesforce. But, just need someones help, how they did in real time.

Thanks
GSN
Hello

Can Some one help me to Build Live Chat Pop Up Interaction with Agent on Website from Automated Invitations.

If Some one work on this, Please let me clarify the Step by Step Implementation to achieve this. I have seen from Help Docs of Salesforce. But not Clear on Implementing.

Thanks in Advance
GSN
Hello

I have wrote a before delete trigger on EmailMessage Object in order to restrict non sys Admins to delete an email record. It is working fine actually. But, the test class passed and  covers only 83%.,Trigger 100%,  in which it is not covering the line of adderror method. It is taking only negative scenario. If I giving positive scenario, it is not covering.

In Handler Class, should I need to mention Case also?

Can someone please try in their Org and let me suggest, where I did wrong.

The Error is like: Assertion failed. Expected: false, Actual:True.

Here is my Handler Class, Trigger and Test Class. Please some one help to increase the code coverage as it should be 95% for my Company, in order to deploy to Production.

Handler Class
=============

public class HelperDeleteEmail {
public static void NoDeleteEmail (List<EmailMessage> emails){
         Id profileId=userinfo.getProfileId();
    
       String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
         
        for(EmailMessage t : emails){
            if(profileName != 'System Administrator') {
                
                t.addError('You Do not have the Permission to Delete the Email');
            }   
     }

}
}

Trigger
========

trigger PreventDeleteEmail on EmailMessage (before delete) {
     if(Trigger.isBefore){
        System.debug('Inside the Trigger');
        HelperDeleteEmail.NoDeleteEmail(Trigger.Old);
    }
}

Test Class:
=========
@isTest
public class TestHelperDeleteEmail {
     @isTest 
    public static void testdeleteemail(){
        
        Profile p = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
        User testUser = new User(Alias = 'newUser', Email='TestTest1234@User.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US', ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName = 'TestTest1234@User.com');
        insert testUser;
         
        Id userId = testuser.Id;
             
        list<EmailMessage>emails=new list<EmailMessage>();
        EmailMessage e = new EmailMessage();
        e.FromAddress='nalinig@gmail.com';
        e.subject='test';
        e.ToAddress='ttt@gmail.com';
        e.TextBody = '23456 ';
        
       // e.parentId=c.Id;
        insert e;
        emails.add(e);
        
        
        Test.startTest(); 
        system.runas(testuser){
            try
            {
                delete  e;       
            }
            catch(Exception ex)
            {
                Boolean expectedExceptionThrown =  ex.getMessage().contains('You Do not have the Permission to Delete the Email') ? true : false;
                System.AssertNotEquals(expectedExceptionThrown,true);
                //System.Assert(ex.getMessage().contains('You Do not have the Permission to Delete the Email'));
            }
            
           // HelperDeleteEmail.NoDeleteEmail(events);
        }
        Test.stopTest(); 
    
    }
}


Thanks
GSN
Hello

I have written a Batch Class to change published Knowledge Articles to Draft and Vice Versa as well.Class is working fine.  I have successfully changed the status from online to draft, updated 36k records for 1 field with data loader, and again change to online.

But the Test class is Passes with 44% code coverage. Start and Finish are fine. But, Not running the execute method. Not sure, where I did wrong. Can someone please help me in this, where to change in Apex and Test Class?.

Can someone please try in their Org and let me know. Need to deploy this to Production urgent.

Batch Class:
global class KarepublishBatch implements Database.Batchable<sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext BC){
    String query = 'SELECT Id,title, ArticleNumber,ps_CX_Functional_Owner__c, publishstatus,KnowledgeArticleId FROM Knowledge__kav WHERE PublishStatus = \'draft\' and ps_CX_Functional_Owner__c!=null';
        return Database.getQueryLocator(query);
    }


global void execute(Database.BatchableContext BC, list<Knowledge__kav> Draftlist){
    for(Knowledge__kav k :Draftlist){
    
    try{
KbManagement.PublishingService.publishArticle(k.knowledgearticleId, true);  
    }
    catch(exception e){
        system.debug('record failed:'+e.getmessage());
    }

}
global void finish(Database.BatchableContext BC) {

    }
}

Test Class:
=========
@isTest
public class TestKarepublishBatch {
static testmethod void publishArticle(){
    String articleTitle = 'Test Article';
    String articleBody = 'Test Body';
    String articleUrlName = 'test-Article';
    String language = 'en_US';
    string PublishStatus = 'online';

    Knowledge__kav article = new Knowledge__kav(
      Title = articleTitle,
      Summary = articleBody,
      UrlName = articleUrlName,
      Language = language
      //PublishStatus = PublishStatus  
    );

    insert article; 
    Knowledge__kav ka = [SELECT ArticleCreatedDate, Publishstatus,ArticleNumber FROM Knowledge__kav WHERE Id =: article.Id and title='test article'];
    
    String articleId = ka.Id;
 try{
KbManagement.PublishingService.publishArticle(articleId, true);  
    }
    catch(exception e){
        system.debug('record failed:'+e.getmessage());
    }
    Test.startTest();
    KarepublishBatch ka1= new KarepublishBatch();
        Id batchId = Database.executeBatch(ka1,1);
        Test.stopTest();
}
}



Thanks
GSN
Hello

I have written a Batch Class to change published Knowledge Articles to Draft and Vice Versa as well. But the Test class is Passes with 44% code coverage. Start and Finish are fine. But, Not running the execute method. Not sure, where I did wrong. Can someone please help me in this.

Batch Class:
global class KarepublishBatch implements Database.Batchable<sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext BC){
    String query = 'SELECT Id,title, ArticleNumber,ps_CX_Functional_Owner__c, publishstatus,KnowledgeArticleId FROM Knowledge__kav WHERE PublishStatus = \'draft\' and ps_CX_Functional_Owner__c!=null';
        return Database.getQueryLocator(query);
    }


global void execute(Database.BatchableContext BC, list<Knowledge__kav> Draftlist){
    for(Knowledge__kav k :Draftlist){
    
    try{
KbManagement.PublishingService.publishArticle(k.knowledgearticleId, true);  
    }
    catch(exception e){
        system.debug('record failed:'+e.getmessage());
    }

}
global void finish(Database.BatchableContext BC) {

    }
}

Test Class:
=========
@isTest
public class TestKarepublishBatch {
static testmethod void publishArticle(){
    String articleTitle = 'Test Article';
    String articleBody = 'Test Body';
    String articleUrlName = 'test-Article';
    String language = 'en_US';
    string PublishStatus = 'online';

    Knowledge__kav article = new Knowledge__kav(
      Title = articleTitle,
      Summary = articleBody,
      UrlName = articleUrlName,
      Language = language
      //PublishStatus = PublishStatus  
    );

    insert article; 
    Knowledge__kav ka = [SELECT ArticleCreatedDate, Publishstatus,ArticleNumber FROM Knowledge__kav WHERE Id =: article.Id and title='test article'];
    
    String articleId = ka.Id;
 try{
KbManagement.PublishingService.publishArticle(articleId, true);  
    }
    catch(exception e){
        system.debug('record failed:'+e.getmessage());
    }
    Test.startTest();
    KarepublishBatch ka1= new KarepublishBatch();
        Id batchId = Database.executeBatch(ka1,1);
        Test.stopTest();
}
}



Thanks
GSN
Hello All

I am trying to execute the below code from Anonymous window to change Published articles to Draft Articles.
While Executing, I came across with few errors. So to handle that errors skip and continue for the Iteration, I tried with try-catch block. After that, when number increased, it is showing error as --too many soql queries-101. So to handle this error, '@future' cant be written and used in local, it showing.So I cant manually click the execute button multiple times as there are 35k records to change to draft status.
So, request to please someone help to write this code in Batch apex, so that it divides and runs automatically for 35000 records.

for(integer i=0;i<=3;i++){
       
List<String> NewdraftList = new List<String>();
list<Knowledge__kav> publishlist=[SELECT Id,title, ArticleNumber, KnowledgeArticleId,IsVisibleInPkb FROM Knowledge__kav WHERE PublishStatus = 'Online'
limit 25];
for(Knowledge__kav k :publishlist){
try{ 
String newDraftArticleId = KBManagement.PublishingService.editOnlineArticle(k.KnowledgeArticleId,true);
NewdraftList.add(newDraftArticleId);       
}
 catch(exception e){
    system.debug('The records failed to process:'+e.getmessage());
 }   
}   
     
}


Thanks
GSN
 
Hello

I found a link for updation of Publish Article to Draft via API from Salesforce.
https://developer.salesforce.com/docs/atlas.en-us.knowledge_dev.meta/knowledge_dev/knowledge_REST_unpublish_master_version.htm


Can anyone Please let me know the procedure (The Process involved in it) above mentioned to do update from publish status to Draft via API? as I am new to API.

Thanks
TH Aspirant
Hi Everyone

If anyone worked on reports related to Einstein Chat Bots, Please refer how to do. My requirement is to get the Chat Ids with respective Agent Available or not and with Percentages.

I installed a package related to Chatbots, but chat Transcript Id with Agent not getting.

Please help how to build.
Hello All

Please find the below,   controller and a part of VF Page. Here the refresh not working when User clicks on Verify Asset button, the new one , which User has to enter is populating 3 Fields (Location, Warranty, Date) with the Previous entered Values. Please someone help in change of code or where have to change to get empty of those 3 fields on addition of new?

Thanks in Advance!
TrialHead Aspirant

VF Page:
========

 <apex:outputPanel rendered="{!renderAddAsset}">
                
                Model Number:<apex:inputText value="{!modelNumber}"/> 
                Serial Number:<apex:inputText value="{!serialNumber}"/>
                Install Date:<apex:input value="{!installDate}" 
                    html-placeholder="Install Date" 
                                              type="date"/>
                <apex:selectList label="Fields" value="{!selectedLocationId}" multiselect="false" size="1" >
                     <apex:selectOptions value="{!LocationSelections}" />
                </apex:selectList>
                In Warranty?<apex:selectList id="WarrantyStatusId" value="{!WarrantyStatus}" size="1">
                    <apex:selectOption itemValue="true" itemLabel="Yes"/>
                    <apex:selectOption itemValue="false" itemLabel="No"/>
                </apex:selectList> 
                 <apex:commandButton action="{!verifyAsset}" value="Verify Asset" reRender="apexform" status="spinnerStatus" styleclass="slds-button slds-button_brand"/>
                 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <apex:commandButton action="{!cancelAddAsset}" value="Cancel" reRender="apexform" status="spinnerStatus" styleclass="slds-button slds-button_brand"/>
            </apex:outputPanel>

Controller:
============
public PageReference verifyAsset(){
        resetError();
        Boolean hasErrors = false;
       
        
        if(modelNumber == '' || modelNumber == null){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Please enter model number.')); 
            hasErrors = true;
        }
        if(selectedLocationId == 'Select service location' ){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Please select a location.')); 
            hasErrors = true;
        }
        if(!string.isBlank(modelNumber)  && !modelNumber.isAlphanumeric() ){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Model Number can only contain alphanumeric characters.')); 
            hasErrors = true;
        }
        if(hasErrors){
            assetError = true;
            return null;
        }
        User-added image
Hello All
The test class for the below Apex Rest API with Http Patch Method is failing and at 0% Code Coverage. Can someone please help to complete this in order to deploy to Production.

Apex Class:
@RestResource(urlMapping='/opportunityiWiseUpdate/*')
global class opportunityiWiseUpdate {
    public class responseWrapper{
      public id SalesForceId;
      public Date EffectiveDate;
      public string stage;
      //public date closedate;
      public Decimal ContractValue;
      }

    @httppatch
      global Static string fetchopportunity(){
      RestRequest req = RestContext.request;
      RestResponse res = Restcontext.response;
          system.debug('req : ' + req);
      string jsonString=req.requestBody.tostring();
          system.debug(jsonString);
      responseWrapper wResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);
          system.debug('wResp : ' + wResp);
         
          for(opportunity op : [select id,recordtype.name,stagename,closedate,Amount,TCV__c from opportunity 
                                where id =:wResp.SalesForceId ]){
          system.debug('op : ' + op);
         // if(op.id !=null){
              if(op.recordtype.Name=='HOS'){
               op.Id = wResp.SalesForceId;
               op.Amount = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
               else if(op.recordtype.Name=='IBS'){
               op.Id = wResp.SalesForceId;
               op.TCV__C = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
          }
             
          return 'sucess';
      }
       
}

Test Class:
@isTest
global class opportunityiWiseUpdateTest {
   @testsetup
    static void datasetup(){ 
       
        String strRecordTypeId = [Select Id From RecordType Where SobjectType = 'Account' and Name = 'IBS'].Id;
    Account a = new Account();
            a.Name = 'EXPEDIA';
            a.Segment__c = 'Aviation';
            a.Sub_Segment__c = 'Startup';
            a.IBS_Region__c = 'IBSZ';
            a.IBS_Sub_Region__c = 'ANZ';
            a.Account_Domain_Name__c = 'test.com';
            a.Account_Code__c='MIII';
            a.Approved__c = True;
            a.RecordTypeId=strRecordTypeId;
            insert a;
    
    String strRecordTypeId1 = [Select Id From RecordType Where SobjectType = 'Opportunity' and Name = 'IBS'].Id;
           Opportunity o = new Opportunity();
                
            o.Name = 'Test Opportunity ibs';
            o.AccountId = a.Id;
           // o.Opportunity_Name__c = 'Test Record';
            o.Contract_Type__c = 'CDx Services';
            o.TCV__c = 5000;
            o.CloseDate = system.today();
            o.Type_of_Deal__c = 'CR';
            o.Opportunity_Source__c = 'Other';
                o.Type_of_Proposal__c='RFP';
            o.StageName = 'Closed Won';
           o.IBS_Lob__c = 'Adopt - ADOPT';
                o.Reason_for_Closed_Won__c='Pricing';
           o.Products__c = 'iFlight Crew Planning Classic';
            o.Incumbent__c = 'Sabre';
           o.Tenure__c = 6;
            o.Tenure_Unit_of_Measure__c = 'Years';
           o.One_Time_Fee__c = 5000;
            o.Reason_for_Winning_or_Losing__c ='Pricing';
            o.Annual_Recurring_Revenue__c = 100001;
            o.RecordTypeId=strRecordTypeId1;
            insert o;
            
     
                
    String strRecordTypeIda1 = [Select Id From RecordType Where SobjectType = 'Account' and Name = 'HOS'].Id;
    Account a1 = new Account();
            a1.Name = 'EXPEDIA1';
            a1.Type='Prospect';
            a1.Industry='Supply';
            a1.RecordTypeId=strRecordTypeIda1;
            insert a1;
    
    String strRecordTypeIdo1 = [Select Id From RecordType Where SobjectType = 'Opportunity' and Name = 'HOS'].Id;
           Opportunity o1 = new Opportunity();
                
            o1.Name = 'Test Opportunity';
            o1.AccountId = a1.Id;
           // o1.Opportunity_Name__c = 'Test Record';
            o1.StageName = 'Closed Won';
            o1.Category__c='CORE';
            o1.Type='Supply - Accom';
            o1.CloseDate = system.today();
            o1.Amount=8520;
            o1.Term__c=5;
            o1.Implementation_Fee__c=58;
            o1.Ramp_to_Live__c=5;
            o1.Ramp_to_Maturity__c=6;
            o1.Probability=10;
            o1.Finance_TCV_Stage__c='Initial - 10%';
            o1.Lead_Generation_Date__c=system.today();
            o1.RecordTypeId=strRecordTypeIdo1;
            insert o1;
    }
    
       @isTest
   static void updateBOClassMethod(){
   Test.startTest();
 Opportunity sHOppRec= [SELECT Id,Name,recordtype.DeveloperName,StageName,CloseDate,Amount From Opportunity Where Name ='Test Opportunity' Limit 1];
system.debug('sHOppRec : ' + sHOppRec);        
   SingleRequestMock fakeResponse1 = new SingleRequestMock(sHOppRec.Id,22500,
                                                
                                                 'Contracted',
                                                 system.today()+1
                                                   );
    String JsonMsg=JSON.serialize(fakeResponse1);
        system.debug('JsonMsg : ' + JsonMsg);
   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
    req.httpMethod = 'PATCH';//HTTP Request Type
    req.requestBody = Blob.valueof(JsonMsg);
    RestContext.request = req;
    RestContext.response= res; 
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
    
    
    
 @isTest
    static void updateBOClassMethod1(){
   Test.startTest();
 Opportunity sIOppRec= [SELECT Id,Name,recordtype.Name,StageName,CloseDate,TCV__c From Opportunity Where Name ='Test Opportunity ibs' Limit 1];
        system.debug('sIOppRec : ' + sIOppRec);
   SingleRequestMock fakeResponse1 = new SingleRequestMock(sIOppRec.Id,82503,
                                               
                                                 'Contracted',
                                                 system.today()+2
                                                   );
    String JsonMsg=JSON.serialize(fakeResponse1);
        system.debug('JsonMsg : ' + JsonMsg);
   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
    req.httpMethod = 'PUT';//HTTP Request Type
    req.requestBody = Blob.valueof(JsonMsg);
    RestContext.request = req;
    RestContext.response= res;
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
 public class SingleRequestMock {
        
      public id SalesForceId;
      public Date EffectiveDate;
      public string stage;
     // public date closedate;
      public Decimal ContractValue;
        
            public SingleRequestMock(id SalesForceId, Decimal ContractValue, string stage,Date EffectiveDate) {
            this.SalesForceId = SalesForceId;
            this.EffectiveDate = EffectiveDate;
            this.stage = stage;
            this.ContractValue = ContractValue;
        }
    }
  
}

Thanks in Advance!
Hello Everyone

Can someone help me on how to test PUT Method from Postman to Salesforce, instance URL generated from all details like Client Id, Secret, test URL, Username, Password. After getting instance URL, how to connect with SF Org endpoint URL? Confused on PUT Method. Someone Please Share.

Thanks in Advance
TH Aspirant

 
Hello

Please someone help me in writing test class for this class rest api for Http put.  My Test Class is failing at 20%.

Thanks in Advance
SF Aspirant

@RestResource(urlMapping='/opportunityiWiseUpdate/*')
Global class opportunityiWiseUpdate {
    global class responseWrapper{
       global id SalesForceId;
       global Date EffectiveDate;
       global string stage;
       global date closedate;
       global Decimal ContractValue;
      }

    @httpput
      global Static string fetchopportunity(){
      RestRequest req = RestContext.request;
      RestResponse res = Restcontext.response;
      string jsonString=req.requestBody.tostring();
          system.debug(jsonString);
      responseWrapper wResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);
          //system.debug(wResp);
          //string id = wResp.Id;
         // system.debug(id);
     
      opportunity op = [select id,recordtype.name,stagename,closedate,Amount,TCV__c from opportunity where id =:wResp.SalesForceId ];
          
          if(op.id !=null){
              if(op.recordtype.Name=='H'){
               op.Id = wResp.SalesForceId;
               op.Amount = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
               else if(op.recordtype.Name=='I'){
               op.Id = wResp.SalesForceId;
               op.TCV__C = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
          }
             
          return 'sucess';
      }
       
}



My Test Class:
@istest
public class TestUpdateBOfromiwise {
 @testsetup
    static void datasetup(){

        Profile p =[SELECT ID FROM Profile Where Name='System Administrator'];
        
        User u = new User();
        u.Alias = 'standt1';
        u.Email='sauser1@testorg.com';
        u.EmailEncodingKey='UTF-8'; 
        u.LastName='Testing1';
        u.LanguageLocaleKey='en_US';
        u.LocaleSidKey='en_US';
        u.ProfileId = p.Id;
        u.TimeZoneSidKey='America/Los_Angeles';
        u.UserName='sauser1@testorg.com';
        u.Head_Of_Region__c = 'IBSZ';
        insert u;
        
        Account a = new Account();
        a.Name = 'Test Account';
        a.Segment__c = 'Aviation';
        a.Sub_Segment__c = 'Startup';
        a.IBS_Region__c = 'IBSZ';
        a.IBS_Sub_Region__c = 'ANZ';
        a.Account_Domain_Name__c = 'test.com';
        a.Account_Code__c='Test';
        a.Approved__c = True;
        insert a;
        
        Opportunity o = new Opportunity();
        o.Name = 'Test Opportunity';
        o.AccountId = a.Id;
        o.Opportunity_Name__c = 'Test Record';
        o.Contract_Type__c = 'CDx Services';
        o.TCV__c = 5000;
        o.CloseDate = system.today();
        o.Type_of_Deal__c = 'New Deal';
        o.Opportunity_Source__c = 'Other';
        o.StageName = 'SQL';
        o.IBS_Lob__c = 'Aviation Passenger Solutions - APS';
        o.Products__c = 'iFly Res';
        o.Incumbent__c = 'Sabre';
        o.Tenure__c = 6;
        o.Tenure_Unit_of_Measure__c = 'Years';
        o.One_Time_Fee__c = 5000;
        o.Annual_Recurring_Revenue__c = 100001;
        insert o;
        
         string name='nalini';
    }
       @isTest
    static void updateBOClassMethod(){
         
        Test.startTest();

   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
    req.httpMethod = 'POST';//HTTP Request Type
  
    RestContext.request = req;
    RestContext.response= res;
 
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
}
 
Hello

The below trigger is working fine if not putting or differentiating with   record types. Please help whether this is in right format to get fire?

Thanks in Advance
SF Aspirant


trigger sendDatatoWiseApi on Opportunity (after update) {
 
    Trigger_Setting__mdt    triggr = [Select Trigger_Name__c,Active__c from Trigger_Setting__mdt where Trigger_Name__c ='iWise Trigger' ];

  if(triggr.Active__c == TRUE){
    set<id> oppIds = new set<id>();
    if(shouldIRun.canIRun())
   {
    for(Opportunity op : trigger.new){
        if(op.recordtype.Name=='H'){
        if(op.StageName=='Closed Won'  || 
           (trigger.oldMap.get(op.Id).Response_from_iWise_System__c==null && op.Response_from_iWise_System__c!=null && 
            op.Response_from_iWise_System__c.containsIgnoreCase('Error'))){
            oppIds.add(op.Id);
        }
    
    if(oppIds.size()>0)
        
        calliwisehos.sendBoToIwise(oppIds); 
    }
        if(op.recordtype.Name=='I'){
        if(op.StageName=='Closed Won'  || 
           (trigger.oldMap.get(op.Id).Response_from_iWise_System__c==null && op.Response_from_iWise_System__c!=null && 
            op.Response_from_iWise_System__c.containsIgnoreCase('Error'))){
            oppIds.add(op.Id);
        }
    
    if(oppIds.size()>0)
        callIwiseAPI.sendBoToIwise(oppIds); 
       //calliwisehos.sendBoToIwise(oppIds);
    }  
    }
   }
  }
}
 
Hello

Please someone help how to cover the test class and code coverage for the below rest api class?

Thanks in Advance
TH

public class callIwiseAPI {

    //To capture getOauthToken response
    public class tokenResponse{
        public string access_token;
    }
  
  public class OpptyInput{
    String SalesForceId;
        string OpportunityType;
    String Lob;
    String Product;
    String Region;
        String SubRegion;
    String BOTitle;
  //  String BType;
    String DealNature;
  //  String BOCurrency;
    Decimal ContractValue;
    Date EffectiveDate;
    Decimal ContractDuration;
    String ContractDurationUnitOfMesurement;
  //  String AccountCode;
    String Description;
    String SalesPerson1;
    String CreatedBy;
        string ProspectName;
        String ContactPerson;
        String ContactNumber;
        String Competitors;
        String ContactEmail;
        String JobTitle;
        String AccountName;

  }
/******************************************************************************************************************
Method      : getOauthToken
Parameters  : # 
ReturnType  : object
Description : Calling iWise API to get oAuth Token and pass the same token get the BO data
*******************************************************************************************************************/
    public  String getOauthToken(){
        String oAuthToken;
        tokenResponse atResponse = new tokenResponse();
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('callout:iWise_Credentials/token');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json; charset=utf-8');
        request.setHeader('username', '{!$Credential.Username}');
        request.setHeader('password', '{!$Credential.Password}');
        request.setHeader('grant_type', 'password');
    
        System.debug('Request to get oAuth Token:'+request);
        
    
        HttpResponse response = http.send(request);
        system.debug('Response from iWise for OAUTH Token:::'+response.toString());
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 201 || response.getStatusCode() == 200) {
            // Deserialize the JSON string into collections of primitive data types.
            //Map<String, object> results = (Map<String, object>) JSON.deserializeUntyped(response.getBody());
            system.debug(':::: Response::::'+response.getBody());
            atResponse = (tokenResponse)json.deserialize(response.getBody(),tokenResponse.class);
            // get the oAuth tken from the response
            
            oAuthToken = atResponse.access_token;//(String) results.get('access_token');
            System.debug('OAuth Acces Token from response:'+oAuthToken);
            return oAuthToken;
            
        }
        else{
            System.debug('The status code returned was not expected: ' +
            response.getStatusCode() + ' ' + response.getStatus());
            return oAuthToken;
        }
        
    }
    
/******************************************************************************************************************
Method      : sendBoToIwise
Parameters  : oAuthToken 
ReturnType  : object
Description : Calling iWise API to send the BO
*******************************************************************************************************************/
  @future(callout = true)
    public static void sendBoToIwise(set<id> oppIds){
//    system.debug('this');
    list<Opportunity> opty = new list<Opportunity>();
       String oAuthToken;
        
    
    opty = [select Id,Name,TCV__c,IBS_Lob__c,Contract_Type__c,Competitors_Names__c,Products__c,CloseDate,Type_of_Deal__c,Tenure_Unit_of_Measure__c,Tenure__c,Description,Owner.Name,Owner.Email,Account__r.Account_Code__c,Response_from_iWise_System__c,Account.Name,
                ( SELECT contact.firstName,contact.phone,contact.Email,contact.Title,contact.IBS_Region__c,contact.IBS_Sub_Region__c FROM OpportunityContactRoles ),
                (select Name,TeamMemberRole,User.Name,User.Email   from OpportunityTeamMembers where  TeamMemberRole = 'Sales Rep')
                                                from Opportunity where Id IN : oppIds];
            system.debug(opty);
       list<OpptyInput> inputRequest = new list<OpptyInput>();
        callIwiseAPI obj = new callIwiseAPI();
        oAuthToken = obj.getOauthToken();
    if(!opty.isEmpty()){
      for(Opportunity op : opty){
        OpptyInput reqInput  = new OpptyInput();
        reqInput.BOTitle=op.Name;
        reqInput.SalesForceId=op.Id;
                reqInput.OpportunityType=op.Type_of_Deal__c;
        reqInput.Lob = op.IBS_Lob__c;
        reqInput.Product=op.Products__c;
        reqInput.Region=op.OpportunityContactRoles[0].contact.IBS_Region__c;
        reqInput.SubRegion=op.OpportunityContactRoles[0].contact.IBS_Sub_Region__c;
      //  reqInput.BType = 'New BO';
        reqInput.DealNature = op.Contract_Type__c;
      //  reqInput.BOCurrency = 'USD';
        reqInput.ContractValue = op.TCV__c;
                reqInput.EffectiveDate = op.CloseDate;
        reqInput.ContractDuration = op.Tenure__c;
        reqInput.ContractDurationUnitOfMesurement = op.Tenure_Unit_of_Measure__c ;
      //  reqInput.AccountCode= op.Account__r.Account_Code__c;
      //  reqInput.Description= op.Description;
        reqInput.SalesPerson1 =op.OpportunityTeamMembers[0].User.Email;
        reqInput.CreatedBy=op.Owner.Email;
                reqInput.ProspectName= op.Account.Name;
                reqInput.ContactPerson=op.OpportunityContactRoles[0].contact.firstName;
                reqInput.ContactNumber=op.OpportunityContactRoles[0].contact.phone;
                reqInput.Competitors=op.Competitors_Names__c;
                reqInput.ContactEmail = op.OpportunityContactRoles[0].contact.Email;
                reqInput.JobTitle=op.OpportunityContactRoles[0].contact.Title;
                reqInput.AccountName=op.Account.Name;

      inputRequest.add(reqInput);
      
      } 
    }
    String OpportunityInput = Json.serialize(inputRequest);
    System.debug('Input request to send Opportunity to iWise::'+OpportunityInput); 
    Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('Actual Endpoint to service');// also add this endpoint in remote site settings
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json; charset=utf-8');
        request.setHeader('Authorization', oAuthToken);
    request.setBody(OpportunityInput);
    
    System.debug('Request to send Opportunity:'+request);
    System.debug('Request body send Opportunity:'+request.getBody());
    
    HttpResponse response = http.send(request);
        system.debug('Response from iWise for Get Opportunity request:::'+response.toString());
    system.debug('Response from iWise for Get Opportunity request:::'+response.getBody());
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200) {
      System.debug('Success Response from iWise::'+response.getStatus());
        opty[0].Response_from_iWise_System__c=response.getStatusCode()+' - '+response.getStatus()+' - '+ response.getBody();
    }
    else{
      System.debug('Error Response from iWise::'+response.getStatus());
      opty[0].Response_from_iWise_System__c=response.getStatusCode()+' - '+response.getStatus()+' - '+ response.getBody();
    }
    if(!opty.isEmpty())
      Update opty;  
  }
}
Hi @all
 I made a login flow and run it and its flow got fail due to this I am not able to log in again into my org ...
Hello

My Requirement is to, whenever there is Phone Number entered in case Object, then in that case, if User enters any Special Characters, then it should ignore the Special Characters and display only the Digits.

I wrote a Trigger on it. Seems to be Correct. But, not working while I am testing.Please someone test in your Org and let me know, where I did mistake.

trigger PhNumValidation on Case (before insert,before update) {
    list<case> clist=new list<case>();
    for(Case c:Trigger.new){
      if (c.Phone_Number__c != null ) {
           string phone =c.Phone_Number__c;
          string newph=phone.replaceAll('\\D','');
          system.debug('Ph: '+newph);
        }   
          
           
        }
        
    }


Thanks
GSN
Hello

Can Some one help me to Build Live Chat Pop Up Interaction with Agent on Website from Automated Invitations.

If Some one work on this, Please let me clarify the Step by Step Implementation to achieve this. I have seen from Help Docs of Salesforce. But not Clear on Implementing.

Thanks in Advance
GSN
Hello

I have wrote a before delete trigger on EmailMessage Object in order to restrict non sys Admins to delete an email record. It is working fine actually. But, the test class passed and  covers only 83%.,Trigger 100%,  in which it is not covering the line of adderror method. It is taking only negative scenario. If I giving positive scenario, it is not covering.

In Handler Class, should I need to mention Case also?

Can someone please try in their Org and let me suggest, where I did wrong.

The Error is like: Assertion failed. Expected: false, Actual:True.

Here is my Handler Class, Trigger and Test Class. Please some one help to increase the code coverage as it should be 95% for my Company, in order to deploy to Production.

Handler Class
=============

public class HelperDeleteEmail {
public static void NoDeleteEmail (List<EmailMessage> emails){
         Id profileId=userinfo.getProfileId();
    
       String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
         
        for(EmailMessage t : emails){
            if(profileName != 'System Administrator') {
                
                t.addError('You Do not have the Permission to Delete the Email');
            }   
     }

}
}

Trigger
========

trigger PreventDeleteEmail on EmailMessage (before delete) {
     if(Trigger.isBefore){
        System.debug('Inside the Trigger');
        HelperDeleteEmail.NoDeleteEmail(Trigger.Old);
    }
}

Test Class:
=========
@isTest
public class TestHelperDeleteEmail {
     @isTest 
    public static void testdeleteemail(){
        
        Profile p = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
        User testUser = new User(Alias = 'newUser', Email='TestTest1234@User.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US', ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName = 'TestTest1234@User.com');
        insert testUser;
         
        Id userId = testuser.Id;
             
        list<EmailMessage>emails=new list<EmailMessage>();
        EmailMessage e = new EmailMessage();
        e.FromAddress='nalinig@gmail.com';
        e.subject='test';
        e.ToAddress='ttt@gmail.com';
        e.TextBody = '23456 ';
        
       // e.parentId=c.Id;
        insert e;
        emails.add(e);
        
        
        Test.startTest(); 
        system.runas(testuser){
            try
            {
                delete  e;       
            }
            catch(Exception ex)
            {
                Boolean expectedExceptionThrown =  ex.getMessage().contains('You Do not have the Permission to Delete the Email') ? true : false;
                System.AssertNotEquals(expectedExceptionThrown,true);
                //System.Assert(ex.getMessage().contains('You Do not have the Permission to Delete the Email'));
            }
            
           // HelperDeleteEmail.NoDeleteEmail(events);
        }
        Test.stopTest(); 
    
    }
}


Thanks
GSN
Hello

I have written a Batch Class to change published Knowledge Articles to Draft and Vice Versa as well.Class is working fine.  I have successfully changed the status from online to draft, updated 36k records for 1 field with data loader, and again change to online.

But the Test class is Passes with 44% code coverage. Start and Finish are fine. But, Not running the execute method. Not sure, where I did wrong. Can someone please help me in this, where to change in Apex and Test Class?.

Can someone please try in their Org and let me know. Need to deploy this to Production urgent.

Batch Class:
global class KarepublishBatch implements Database.Batchable<sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext BC){
    String query = 'SELECT Id,title, ArticleNumber,ps_CX_Functional_Owner__c, publishstatus,KnowledgeArticleId FROM Knowledge__kav WHERE PublishStatus = \'draft\' and ps_CX_Functional_Owner__c!=null';
        return Database.getQueryLocator(query);
    }


global void execute(Database.BatchableContext BC, list<Knowledge__kav> Draftlist){
    for(Knowledge__kav k :Draftlist){
    
    try{
KbManagement.PublishingService.publishArticle(k.knowledgearticleId, true);  
    }
    catch(exception e){
        system.debug('record failed:'+e.getmessage());
    }

}
global void finish(Database.BatchableContext BC) {

    }
}

Test Class:
=========
@isTest
public class TestKarepublishBatch {
static testmethod void publishArticle(){
    String articleTitle = 'Test Article';
    String articleBody = 'Test Body';
    String articleUrlName = 'test-Article';
    String language = 'en_US';
    string PublishStatus = 'online';

    Knowledge__kav article = new Knowledge__kav(
      Title = articleTitle,
      Summary = articleBody,
      UrlName = articleUrlName,
      Language = language
      //PublishStatus = PublishStatus  
    );

    insert article; 
    Knowledge__kav ka = [SELECT ArticleCreatedDate, Publishstatus,ArticleNumber FROM Knowledge__kav WHERE Id =: article.Id and title='test article'];
    
    String articleId = ka.Id;
 try{
KbManagement.PublishingService.publishArticle(articleId, true);  
    }
    catch(exception e){
        system.debug('record failed:'+e.getmessage());
    }
    Test.startTest();
    KarepublishBatch ka1= new KarepublishBatch();
        Id batchId = Database.executeBatch(ka1,1);
        Test.stopTest();
}
}



Thanks
GSN
Hello

I have written a Batch Class to change published Knowledge Articles to Draft and Vice Versa as well. But the Test class is Passes with 44% code coverage. Start and Finish are fine. But, Not running the execute method. Not sure, where I did wrong. Can someone please help me in this.

Batch Class:
global class KarepublishBatch implements Database.Batchable<sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext BC){
    String query = 'SELECT Id,title, ArticleNumber,ps_CX_Functional_Owner__c, publishstatus,KnowledgeArticleId FROM Knowledge__kav WHERE PublishStatus = \'draft\' and ps_CX_Functional_Owner__c!=null';
        return Database.getQueryLocator(query);
    }


global void execute(Database.BatchableContext BC, list<Knowledge__kav> Draftlist){
    for(Knowledge__kav k :Draftlist){
    
    try{
KbManagement.PublishingService.publishArticle(k.knowledgearticleId, true);  
    }
    catch(exception e){
        system.debug('record failed:'+e.getmessage());
    }

}
global void finish(Database.BatchableContext BC) {

    }
}

Test Class:
=========
@isTest
public class TestKarepublishBatch {
static testmethod void publishArticle(){
    String articleTitle = 'Test Article';
    String articleBody = 'Test Body';
    String articleUrlName = 'test-Article';
    String language = 'en_US';
    string PublishStatus = 'online';

    Knowledge__kav article = new Knowledge__kav(
      Title = articleTitle,
      Summary = articleBody,
      UrlName = articleUrlName,
      Language = language
      //PublishStatus = PublishStatus  
    );

    insert article; 
    Knowledge__kav ka = [SELECT ArticleCreatedDate, Publishstatus,ArticleNumber FROM Knowledge__kav WHERE Id =: article.Id and title='test article'];
    
    String articleId = ka.Id;
 try{
KbManagement.PublishingService.publishArticle(articleId, true);  
    }
    catch(exception e){
        system.debug('record failed:'+e.getmessage());
    }
    Test.startTest();
    KarepublishBatch ka1= new KarepublishBatch();
        Id batchId = Database.executeBatch(ka1,1);
        Test.stopTest();
}
}



Thanks
GSN
Hello All

Please find the below,   controller and a part of VF Page. Here the refresh not working when User clicks on Verify Asset button, the new one , which User has to enter is populating 3 Fields (Location, Warranty, Date) with the Previous entered Values. Please someone help in change of code or where have to change to get empty of those 3 fields on addition of new?

Thanks in Advance!
TrialHead Aspirant

VF Page:
========

 <apex:outputPanel rendered="{!renderAddAsset}">
                
                Model Number:<apex:inputText value="{!modelNumber}"/> 
                Serial Number:<apex:inputText value="{!serialNumber}"/>
                Install Date:<apex:input value="{!installDate}" 
                    html-placeholder="Install Date" 
                                              type="date"/>
                <apex:selectList label="Fields" value="{!selectedLocationId}" multiselect="false" size="1" >
                     <apex:selectOptions value="{!LocationSelections}" />
                </apex:selectList>
                In Warranty?<apex:selectList id="WarrantyStatusId" value="{!WarrantyStatus}" size="1">
                    <apex:selectOption itemValue="true" itemLabel="Yes"/>
                    <apex:selectOption itemValue="false" itemLabel="No"/>
                </apex:selectList> 
                 <apex:commandButton action="{!verifyAsset}" value="Verify Asset" reRender="apexform" status="spinnerStatus" styleclass="slds-button slds-button_brand"/>
                 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <apex:commandButton action="{!cancelAddAsset}" value="Cancel" reRender="apexform" status="spinnerStatus" styleclass="slds-button slds-button_brand"/>
            </apex:outputPanel>

Controller:
============
public PageReference verifyAsset(){
        resetError();
        Boolean hasErrors = false;
       
        
        if(modelNumber == '' || modelNumber == null){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Please enter model number.')); 
            hasErrors = true;
        }
        if(selectedLocationId == 'Select service location' ){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Please select a location.')); 
            hasErrors = true;
        }
        if(!string.isBlank(modelNumber)  && !modelNumber.isAlphanumeric() ){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Model Number can only contain alphanumeric characters.')); 
            hasErrors = true;
        }
        if(hasErrors){
            assetError = true;
            return null;
        }
        User-added image
Hello Everyone

Can someone help me on how to test PUT Method from Postman to Salesforce, instance URL generated from all details like Client Id, Secret, test URL, Username, Password. After getting instance URL, how to connect with SF Org endpoint URL? Confused on PUT Method. Someone Please Share.

Thanks in Advance
TH Aspirant

 
Hello

Please someone help me in writing test class for this class rest api for Http put.  My Test Class is failing at 20%.

Thanks in Advance
SF Aspirant

@RestResource(urlMapping='/opportunityiWiseUpdate/*')
Global class opportunityiWiseUpdate {
    global class responseWrapper{
       global id SalesForceId;
       global Date EffectiveDate;
       global string stage;
       global date closedate;
       global Decimal ContractValue;
      }

    @httpput
      global Static string fetchopportunity(){
      RestRequest req = RestContext.request;
      RestResponse res = Restcontext.response;
      string jsonString=req.requestBody.tostring();
          system.debug(jsonString);
      responseWrapper wResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);
          //system.debug(wResp);
          //string id = wResp.Id;
         // system.debug(id);
     
      opportunity op = [select id,recordtype.name,stagename,closedate,Amount,TCV__c from opportunity where id =:wResp.SalesForceId ];
          
          if(op.id !=null){
              if(op.recordtype.Name=='H'){
               op.Id = wResp.SalesForceId;
               op.Amount = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
               else if(op.recordtype.Name=='I'){
               op.Id = wResp.SalesForceId;
               op.TCV__C = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
          }
             
          return 'sucess';
      }
       
}



My Test Class:
@istest
public class TestUpdateBOfromiwise {
 @testsetup
    static void datasetup(){

        Profile p =[SELECT ID FROM Profile Where Name='System Administrator'];
        
        User u = new User();
        u.Alias = 'standt1';
        u.Email='sauser1@testorg.com';
        u.EmailEncodingKey='UTF-8'; 
        u.LastName='Testing1';
        u.LanguageLocaleKey='en_US';
        u.LocaleSidKey='en_US';
        u.ProfileId = p.Id;
        u.TimeZoneSidKey='America/Los_Angeles';
        u.UserName='sauser1@testorg.com';
        u.Head_Of_Region__c = 'IBSZ';
        insert u;
        
        Account a = new Account();
        a.Name = 'Test Account';
        a.Segment__c = 'Aviation';
        a.Sub_Segment__c = 'Startup';
        a.IBS_Region__c = 'IBSZ';
        a.IBS_Sub_Region__c = 'ANZ';
        a.Account_Domain_Name__c = 'test.com';
        a.Account_Code__c='Test';
        a.Approved__c = True;
        insert a;
        
        Opportunity o = new Opportunity();
        o.Name = 'Test Opportunity';
        o.AccountId = a.Id;
        o.Opportunity_Name__c = 'Test Record';
        o.Contract_Type__c = 'CDx Services';
        o.TCV__c = 5000;
        o.CloseDate = system.today();
        o.Type_of_Deal__c = 'New Deal';
        o.Opportunity_Source__c = 'Other';
        o.StageName = 'SQL';
        o.IBS_Lob__c = 'Aviation Passenger Solutions - APS';
        o.Products__c = 'iFly Res';
        o.Incumbent__c = 'Sabre';
        o.Tenure__c = 6;
        o.Tenure_Unit_of_Measure__c = 'Years';
        o.One_Time_Fee__c = 5000;
        o.Annual_Recurring_Revenue__c = 100001;
        insert o;
        
         string name='nalini';
    }
       @isTest
    static void updateBOClassMethod(){
         
        Test.startTest();

   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
    req.httpMethod = 'POST';//HTTP Request Type
  
    RestContext.request = req;
    RestContext.response= res;
 
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
}
 
Hello

The below trigger is working fine if not putting or differentiating with   record types. Please help whether this is in right format to get fire?

Thanks in Advance
SF Aspirant


trigger sendDatatoWiseApi on Opportunity (after update) {
 
    Trigger_Setting__mdt    triggr = [Select Trigger_Name__c,Active__c from Trigger_Setting__mdt where Trigger_Name__c ='iWise Trigger' ];

  if(triggr.Active__c == TRUE){
    set<id> oppIds = new set<id>();
    if(shouldIRun.canIRun())
   {
    for(Opportunity op : trigger.new){
        if(op.recordtype.Name=='H'){
        if(op.StageName=='Closed Won'  || 
           (trigger.oldMap.get(op.Id).Response_from_iWise_System__c==null && op.Response_from_iWise_System__c!=null && 
            op.Response_from_iWise_System__c.containsIgnoreCase('Error'))){
            oppIds.add(op.Id);
        }
    
    if(oppIds.size()>0)
        
        calliwisehos.sendBoToIwise(oppIds); 
    }
        if(op.recordtype.Name=='I'){
        if(op.StageName=='Closed Won'  || 
           (trigger.oldMap.get(op.Id).Response_from_iWise_System__c==null && op.Response_from_iWise_System__c!=null && 
            op.Response_from_iWise_System__c.containsIgnoreCase('Error'))){
            oppIds.add(op.Id);
        }
    
    if(oppIds.size()>0)
        callIwiseAPI.sendBoToIwise(oppIds); 
       //calliwisehos.sendBoToIwise(oppIds);
    }  
    }
   }
  }
}
 
Hello

I have added apex class and VF Page to override standard convert button to Accept Button. The mentioned below code is working fine. But it is getting converted in Classic Version. But need the lead Conversion Page in Lightning Version. Anyone Please suggest.

public class AutoConvertLeads {
    
    private final Lead lead; //variable for the standard Lead object
    
    public AutoConvertLeads(ApexPages.StandardController standardPageController) {
        this.lead = (Lead)standardPageController.getRecord(); //initialize the standard controller
    }
    
    public PageReference redirectToConvertionPage() {
        PageReference nextPage = new PageReference('/lead/leadconvert.jsp'); //set the starting point for the page reference to which the User will be sent
        nextPage = encodeAndSetParam(nextPage, 'retURL', lead.Id); //set the retURL parameter in order to allow for returning to Lead if User cancels from page
        nextPage = encodeAndSetParam(nextPage, 'id', lead.Id); //set the id parameter so that the conversion page knows the proper record
        nextPage = encodeAndSetParam(nextPage, 'nooppti', '1'); //set the nooppti parameter to pre-populate the "Do not create a new opportunity upon conversion." checkbox
        nextPage = encodeAndSetParam(nextPage, 'nooverride', '1'); //set the nooverride parameter in order to prevent looping in the user interface
        nextPage.setRedirect(true); //indicate that the redirect should be performed on the client side
        return nextPage; //send the User to the Lead conversion page
    }
    
    public PageReference encodeAndSetParam(PageReference passedPageReference, String passedParameterId, String passedParameterValue){
        if (passedParameterValue != null) { //if the passedParameterValue is not null
            String encodedParameterValue = EncodingUtil.urlEncode(passedParameterValue, 'UTF-8'); //encode the value that was passed to eliminate conflicts with unsafe characters
            passedPageReference.getParameters().put(passedParameterId, EncodingUtil.urlDecode(encodedParameterValue, 'UTF-8')); //add the parameter to the page reference
        }
        return passedPageReference;
    }

}

Visual Force Page:

<apex:page action="{!redirectToConvertionPage}" extensions="AutoConvertLeads" standardController="Lead">
    <apex:sectionHeader title="Accept" subtitle="{!Lead.Name}" help="/htviewhelpdoc?id=leads_convert.htm&siteLang=en_US"></apex:sectionHeader>
    <apex:pageMessages ></apex:pageMessages>
</apex:page>


Thanks
TS

 
Hello

I have a custom button. On clicking on that, a field update with checkbox true has to be done. How this can be done with Apex and VF. Any code, Please suggest.

Thanks
TS
Hi there, I am trying to emulate the "convert lead" action on a custom object of mine which I've made a path for (see below)User-added image

When I click on the final stage in my Path, I would like it to generate a pop-up that will then let me create new records in related objects.  Is this possible?  Here is a picture of what im talking about.

User-added image

If anyone could should me how to do this I would really appreciate it!