• Rohan Telang
  • NEWBIE
  • 20 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 11
    Replies
I have written RESTAPI on Account and Contact object. There is POST method. I am passing JSON data from POSTMAN and it's getting inserted in Account object and it's related Contact.

Endpoint is-  "https://egssolutions--developer.my.salesforce.com/services/apexrest/APIForWebTeam/"

I wanted to write the TEST class. Can anybody help me?

Main Class-

@RestResource(urlMapping='/APIForWebTeam/*')
global class EGS_APIForWebTeam {
    
    public class AccountData{
      //public Id accountId;
        public String customer_code;
        public String web_customer_id;
        public String web_customer_mapping_id;
        public String account_name;
        public String account_source;
        public String email;
        public String email_pec;
        public String vat_number;
        public String social_security_number;
        public String phone;
        public String mobile_phone;
        public String type;
      //public String billingAddress;
        public String billing_street_address;
        public String billing_city;
        public String billing_state;
        public String billing_zipcode;
        public String billing_country;
      //public String shippingAddress;
        public String shipping_street_address;
        public String shipping_city;
        public String shipping_state;
        public String shipping_zipcode;
        public String shipping_country;
        public String product_category;
        public String product_subcategory;
      //public String country;
      //public String stateProvince;
      //public String country1;
        public String first_name;
        public String last_name;
    }
    
    @httpPost
    global static void createAccountData(){
        try{
            RestRequest req = RestContext.request;
            String jsonString = req.requestBody.tostring();
            List<AccountData> receivedData= (List<AccountData>)System.JSON.deserialize(jsonString, List<AccountData>.class);
            
            List<Account> accountList = new List<Account>();
            List<Contact> conList=New List<Contact>();
            
            for(AccountData accountData : receivedData){
                Account acc=New Account();
                
                acc.Name=accountData.account_name;
                acc.Customer_Code__c=accountData.customer_code;
                acc.AccountSource=accountData.account_source;
                acc.Email__c=accountData.email;
                acc.Email_PEC__c=accountData.email_pec;
                acc.VAT_number__c=accountData.vat_number;
                acc.Social_security_number__c=accountData.social_security_number;
                acc.Phone=accountData.phone;
                acc.Mobile_phone__c=accountData.mobile_phone;
                acc.Type=accountData.type;
              //acc.BillingAddress=accountData.billingAddress;
                acc.BillingStreet=accountData.billing_street_address;
                acc.BillingCity=accountData.billing_city;
                acc.BillingState=accountData.billing_state;
                acc.BillingPostalCode=accountData.billing_zipcode;
                acc.BillingCountry=accountData.billing_country;
              //acc.Country_C__c=accountData.country;
              //acc.State_province__c=accountData.stateProvince;
              //acc.ShippingAddress=accountData.shippingAddress;
                acc.ShippingStreet=accountData.shipping_street_address;
                acc.web_customer_id__c=accountData.web_customer_id;
                acc.web_customer_mapping_id__c=accountData.web_customer_mapping_id;
                acc.ShippingCity=accountData.shipping_city;
                acc.ShippingState=accountData.shipping_state;
                acc.ShippingPostalCode=accountData.shipping_zipcode;
                acc.ShippingCountry=accountData.shipping_country;
                acc.Product_Category__c=accountData.product_category;
                acc.Product_Subcategory__c=accountData.product_subcategory;
                
              //acc.Country__c=accountData.country;
                accountList.add(acc);
                
                
            }
            if(!accountList.isEmpty()){
            insert accountList;
            }
            
            for(AccountData accountData : receivedData){
                Contact varCon = New Contact();
                varCon.FirstName = accountData.first_name;
                varCon.LastName = accountData.last_name;
                varCon.Email = accountData.email;  
                varCon.MobilePhone = accountData.mobile_phone;
                varCon.Phone = accountData.phone;
                varCon.AccountId = accountList[0].id;
                conList.add(varCon);
            
            }
            
            if(!conList.isEmpty()){
            insert conList;    
            }
            
            RestResponse res = RestContext.response;
            res.statusCode = 200;
            String webCustomerId = accountList[0].web_customer_id__c;
            String webCustomerMappingId = accountList[0].web_customer_mapping_id__c;
            String customerCode = accountList[0].Customer_Code__c;
            res.responseBody= Blob.valueOf('Web Customer Id = '+webCustomerId+',  Salesforce Account Id = '+accountList[0].id+', Web Customer Mapping Id = '+webCustomerMappingId+', Customer Code = '+customerCode);
        }catch(Exception e){
            RestResponse res = RestContext.response;
            res.statusCode = 404;
            res.responseBody = Blob.valueOf('Something went wrong! Error Message : '+e.getMessage());
        }
     }
  }




 
Hello,
We have created a form in our website to submit info that will create a Order in Salesforce.  Three of the Fields we have in Order object are 
"EffectiveDate","License_activation_date__c" and "License_Expiration_date__c". I am submitting the date in the correct format of yyyy-MM-dd and the API request is correct and the response back is successful. However, when I am submmiting the request in the body, it's giving error.
I am submitting the JSON in the body as follows-

[
{
    "accountId":"0015E00001eJboYQAS",
    "licenseActivationDate":"2020-08-03",
    "licenseExpirationDate":"2021-10-11",
    "orderStartDate":"2021-08-21",
    "status":"Draft",
    "contractNumber":"8005E000002VXzxQAG"
}
]


But, it's giving error as Expected EGS_Order_API.DateValue but found "2020-08-03" at [line:3, column:37]

My REST API Class is as follows-

@RestResource(urlMapping='/OrderForWebTeam/*')
global class EGS_OrderForWebTeam {
    
    public class OrderData{
        public Id accountId;
        public String orderName;
        public String customerId;
        public Decimal currencys;
        public String billingStreet;
        public String billingCity;
        public String billingState;
        public String billingPostalCode;
        public String billingCountry;
        public String status;
        public String orderAmount;
        public DateValue orderStartDate;
        public String orderType;
        public DateValue licenseActivationDate;
        public DateValue licenseExpirationDate;
        public Id productId;
        public String entitlementId;    
        public Id contractNumber;    
    }
    
    public class DateValue{
        public Integer day;
        public Integer month;
        public Integer year;
    }
    
    @httpPost
    global static void createOrderData(){
        try{
            RestRequest req = RestContext.request;
            String jsonString = req.requestBody.tostring();
            List<OrderData> receivedData = (List<OrderData>)System.JSON.deserialize(jsonString, List<OrderData>.class);
            
            List<Order> orderList = new List<Order>();
            for(OrderData oData:receivedData){
                Order orderObject= New Order();
                orderObject.AccountId=oData.accountId;
                orderObject.Name=oData.orderName;
                orderObject.Customer_ID__c=oData.customerId;
                orderObject.Currency__c=oData.currencys;
                orderObject.BillingStreet=oData.billingStreet;
                orderObject.BillingCity=oData.billingCity;
                orderObject.BillingState=oData.billingState;
                orderObject.BillingPostalCode=oData.billingPostalCode;
                orderObject.BillingCountry=oData.billingCountry;
                orderObject.Status=oData.status;
                orderObject.Type=oData.orderType;
                orderObject.License_activation_date__c= Date.newInstance(oData.licenseActivationDate.year,oData.licenseActivationDate.month,oData.licenseActivationDate.day);
                orderObject.License_Expiration_date__c= Date.newInstance(oData.licenseExpirationDate.year,oData.licenseExpirationDate.month,oData.licenseExpirationDate.day);
                orderObject.EffectiveDate= Date.newInstance(oData.orderStartDate.year,oData.orderStartDate.month,oData.orderStartDate.day);
                orderObject.Product_name__c=oData.productId;
                orderObject.Entitlement_ID__c=oData.entitlementId;
                orderObject.ContractId=oData.contractNumber;
                
                orderList.add(orderObject);
            }
            insert orderList;
            RestResponse res = RestContext.response;
            res.statusCode = 200;
            res.responseBody = Blob.valueOf('Order Inserted Successfully..');
        }catch(Exception e){
            RestResponse res = RestContext.response;
            res.statusCode = 404;
            res.responseBody = Blob.valueOf('Something went wrong! Error Message : '+e.getMessage());
        }
    }
    
}



Does anyone have any idea what could be the problem?

Thanks !!
Hi Developers,
I am getting error in Test class. Kindly help. I am getting error as "System.NullPointerException: Attempt to de-reference a null object".
Stack Trace- Class.EGS_ProductForWebTeam.sendProductData: line 140, column 1
Class.EGS_ProductForWebTeamTestClass.createTestRecord: line 50, column 1
Class.EGS_ProductForWebTeamTestClass.testProduct: line 4, column 1

Below is the Rest service Class and Test Class.

Main Class (REST API)-

@RestResource(urlMapping='/ProductForWebTeam/*')
global class EGS_ProductForWebTeam {
    public class ProductData {
        
        public String sf_product_id;
        public String name;
        public String type;
        public Decimal regular_price;
        public String description;
        public String short_description;
        public List<Categories> categories;
        public List<Attribute> attributes;
        public List<Variation> variations;
    }       
        public class Categories {
            public Integer id;
            public String name;
        }
        
        public class Attributes_Z {
            public Integer id;
            public String option;
        }
        
        public class Attribute {
            public Integer id ;
            public Boolean variation;
            public Boolean visible;
            public List<String> options;
        }
    
/*           public class Option{
            public Integer id;
            public String month;    
                
            }*/
        
        public class Variation {
            public Decimal regular_price;
            public List<Attributes_Z> attributes;
        }
                   

    @httpGet
    global static void sendProductData() {
        try {
            List<ProductData> productWrapperList = new List<ProductData>();
            Map<Id, Product2> productMap = new Map<Id, Product2>([SELECT Id, Name, Description, Product_Category__c, Product_Subcategory__c FROM Product2 WHERE Is_sent_to_web__c = false LIMIT 1]);
            System.debug(productMap);
            
            
            Pricebook2 priceBook = [SELECT Id FROM Pricebook2 WHERE Id = '01s0900000DSd7HAAT'];
            
            List<PriceBookEntry> priceBookEntryList = [SELECT Product2Id, UnitPrice 
                                                   FROM PriceBookEntry 
                                                   WHERE pricebook2id = :priceBook.Id AND Product2Id =: productMap.keySet()];
                                                   
            Map<Id, PriceBookEntry> MapOfProductToPBE = new Map<Id, PriceBookEntry>();
            for(PriceBookEntry pbe : priceBookEntryList)
            {
               MapOfProductToPBE.put(pbe.Product2Id, pbe);
            }
            System.debug(MapOfProductToPBE);
            
            List<Product2> productListToBeUpdated = new List<Product2>();
            
            for(Product2 product : productMap.values()) {
                ProductData productData = new ProductData();
                productData.sf_product_id = product.Id;
                productData.name = product.Name;
                productData.type = 'variable';
                
             //   if(MapOfProductToPBE.get(product.id).Product2id == product.id && MapOfProductToPBE.get(product.id).UnitPrice != null){
                    productData.regular_price = 100;
             //   }else{
             //       productData.regular_price = 0;
              //  }
                    
                       
                
                productData.description = product.Description;
                List<categories> categoryList = new List<categories>();
                Categories c = new Categories();
                
                if(product.Product_Category__c == 'Bundle') {
                    c.id = 60;
                    c.name = product.Product_Category__c;
                } else if(product.Product_Category__c == 'Additional module') {
                    c.id = 61;
                    c.name = product.Product_Category__c;
                } else if(product.Product_Category__c == 'Stand Alone') {
                    c.id = 62;
                    c.name = product.Product_Category__c;
                }
                categoryList.add(c);
                productData.categories = categoryList;
                
                //Code for attribute
                List<Attribute> attributeList = new List<Attribute>();
                Attribute varAttr = New Attribute();
                varAttr.id = 2; 
                varAttr.variation = true;
                varAttr.visible = true;
                List<String> OptionList = new List<String>();
                OptionList.add('3 Months');
                OptionList.add('6 Months');
                OptionList.add('1 Year');
                varAttr.options = OptionList;
                attributeList.add(varAttr);
                productData.attributes = attributeList;
         
                List<variation> VariationList = new List<variation>();
                for(String i : OptionList)
                {
                  variation v = new variation();
                  v.regular_price = 100;
                  List<Attributes_Z> AttrList = new List<Attributes_Z>();
                  Attributes_Z attrInstance = new Attributes_Z();
                  attrInstance.id = 2;
                  attrInstance.option = i;
                  AttrList.add(attrInstance);
                  v.attributes = AttrList;
                  VariationList.add(v);
                }
                productData.variations = VariationList;
                
                product.Is_sent_to_web__c = true;
                productListToBeUpdated.add(product);
                productWrapperList.add(productData);
            }
        //    update productListToBeUpdated;
            
            System.debug(JSON.serialize(productWrapperList));
            RestResponse res = RestContext.response;
            res.statusCode = 200;
            res.responseBody = Blob.valueOf(JSON.serialize(productWrapperList));
            
        } catch(Exception e) {
            RestResponse res = RestContext.response;
            res.statusCode = 404;
            res.responseBody = Blob.valueOf('Something went wrong! Error Message : '+e.getMessage()+'  '+'line number '+e.getLineNumber()+ ' '+e.getCause());
       }
        
    }
}

Test Class- 

@isTest
private class EGS_ProductForWebTeamTestClass {
    @isTest static void testProduct() {
        Product2 varProd= createTestRecord();
        // Set up a test request
        RestRequest request = new RestRequest();
        request.requestUri = 'https://egssolutions--developer.lightning.force.com/services/apexrest/ProductForWebTeam/';
        //   request.requestUri =  '/services/apexrest/ProductForWebTeam/';
        request.httpMethod = 'GET';
        RestContext.request = request;
        // Call the method to test
       
    }
    
    static Product2 createTestRecord() {
        // Create test record
        Product2 varP = new Product2(
            Name = 'Product 1',
            Description='Test Description',
            Product_Category__c='Bundle',
            Product_Subcategory__c='Light',
            Is_sent_to_web__c=false);
        
        insert varP;
        system.debug('Product '+varP);
        
        
        Pricebook2 priceBook = new Pricebook2(
            Name = 'End User');
        
        insert priceBook;
        system.debug('PriceBook '+priceBook);
        
        PriceBookEntry standardPriceBookEntry = new PriceBookEntry(
            Product2Id = varP.Id,
            pricebook2id = Test.getStandardPricebookId(),
            UnitPrice = 2000);
        
        insert standardPriceBookEntry;
        system.debug('StandardPriceBookEntry '+standardPriceBookEntry);
        
        PriceBookEntry priceBookEntry = new PriceBookEntry(
            UnitPrice = 6000,
            pricebook2id=priceBook.id,
            Product2Id = varP.Id);
        
        insert priceBookEntry;
        system.debug('PriceBookEntry '+priceBookEntry);
        test.startTest();
        EGS_ProductForWebTeam.sendProductData();
        test.stopTest();
        return varP;
    }      
    
}
@RestResource(urlMapping='/ProductForWebTeam/*')
global class EGS_ProductForWebTeam {
    public class ProductData {
        
        public String sf_product_id;
        public String name;
        public String type;
        public Decimal regular_price;
        public String description;
        public String short_description;
        public List<Categories> categories;
        public List<Attribute> attributes;
        public List<Variation> variations;
    }       
        public class Categories {
            public Integer id;
            public String name;
        }
        
        public class Attributes_Z {
            public Integer id;
            public String option;
        }
        
        public class Attribute {
            public Integer id ;
            public Boolean variation;
            public Boolean visible;
            public List<String> options;
        }
    
/*           public class Option{
            public Integer id;
            public String month;    
                
            }*/
        
        public class Variation {
            public Decimal regular_price;
            public List<Attributes_Z> attributes;
        }
                   

    @httpGet
    global static void sendProductData() {
        try {
            List<ProductData> productWrapperList = new List<ProductData>();
            Map<Id, Product2> productMap = new Map<Id, Product2>([SELECT Id, Name, Description, Product_Category__c, Product_Subcategory__c FROM Product2 WHERE Is_sent_to_web__c = false LIMIT 1]);
            System.debug(productMap);
            
            
            Pricebook2 priceBook = [SELECT Id FROM Pricebook2 WHERE Id = '01s0900000DSd7HAAT'];
            
            List<PriceBookEntry> priceBookEntryList = [SELECT Product2Id, UnitPrice 
                                                   FROM PriceBookEntry 
                                                   WHERE pricebook2id = :priceBook.Id AND Product2Id =: productMap.keySet()];
                                                   
            Map<Id, PriceBookEntry> MapOfProductToPBE = new Map<Id, PriceBookEntry>();
            for(PriceBookEntry pbe : priceBookEntryList)
            {
               MapOfProductToPBE.put(pbe.Product2Id, pbe);
            }
            System.debug(MapOfProductToPBE);
            
            List<Product2> productListToBeUpdated = new List<Product2>();
            
            for(Product2 product : productMap.values()) {
                ProductData productData = new ProductData();
                productData.sf_product_id = product.Id;
                productData.name = product.Name;
                productData.type = 'variable';
                
             //   if(MapOfProductToPBE.get(product.id).Product2id == product.id && MapOfProductToPBE.get(product.id).UnitPrice != null){
                    productData.regular_price = 100;
             //   }else{
             //       productData.regular_price = 0;
              //  }
                    
                       
                
                productData.description = product.Description;
                List<categories> categoryList = new List<categories>();
                Categories c = new Categories();
                
                if(product.Product_Category__c == 'Bundle') {
                    c.id = 60;
                    c.name = product.Product_Category__c;
                } else if(product.Product_Category__c == 'Additional module') {
                    c.id = 61;
                    c.name = product.Product_Category__c;
                } else if(product.Product_Category__c == 'Stand Alone') {
                    c.id = 62;
                    c.name = product.Product_Category__c;
                }
                categoryList.add(c);
                productData.categories = categoryList;
                
                //Code for attribute
                List<Attribute> attributeList = new List<Attribute>();
                Attribute varAttr = New Attribute();
                varAttr.id = 2; 
                varAttr.variation = true;
                varAttr.visible = true;
                List<String> OptionList = new List<String>();
                OptionList.add('3 Months');
                OptionList.add('6 Months');
                OptionList.add('1 Year');
                varAttr.options = OptionList;
                attributeList.add(varAttr);
                productData.attributes = attributeList;
         
                List<variation> VariationList = new List<variation>();
                for(String i : OptionList)
                {
                  variation v = new variation();
                  v.regular_price = 100;
                  List<Attributes_Z> AttrList = new List<Attributes_Z>();
                  Attributes_Z attrInstance = new Attributes_Z();
                  attrInstance.id = 2;
                  attrInstance.option = i;
                  AttrList.add(attrInstance);
                  v.attributes = AttrList;
                  VariationList.add(v);
                }
                productData.variations = VariationList;
                
                product.Is_sent_to_web__c = true;
                productListToBeUpdated.add(product);
                productWrapperList.add(productData);
            }
        //    update productListToBeUpdated;
            
            System.debug(JSON.serialize(productWrapperList));
            RestResponse res = RestContext.response;
            res.statusCode = 200;
            res.responseBody = Blob.valueOf(JSON.serialize(productWrapperList));
            
        } catch(Exception e) {
            RestResponse res = RestContext.response;
            res.statusCode = 404;
            res.responseBody = Blob.valueOf('Something went wrong! Error Message : '+e.getMessage()+'  '+'line number '+e.getLineNumber()+ ' '+e.getCause());
        }
    }
}
I want to create a Custom Button on Account Detail Page. When I click that Button, I want to create a custom Clone functionality to clone an Account record with their related record using Lightning Web Component
When i enter "Policy Holder ID" and click on "Submit" then below result should appear.
There is one primary object i.e  "Policy_Holder__c"
and two secondary objects  i.e "Life_Insurance__c" and "Motor_Insurance__c" ...

"Policy_Holder__c" object contains "Policy Holder ID" field.

"Life_Insurance__c" object contains Policy ID,Policy Type,Premium Amount, Due Date fields.

"Motor_Insurance__c" object contains Policy ID,Policy Type,Premium Amount, Due Date fields.

So when i enter Policy Holder ID then below fields should be retrieved of related list in "Visual Force page"

User-added image

 
I have written RESTAPI on Account and Contact object. There is POST method. I am passing JSON data from POSTMAN and it's getting inserted in Account object and it's related Contact.

Endpoint is-  "https://egssolutions--developer.my.salesforce.com/services/apexrest/APIForWebTeam/"

I wanted to write the TEST class. Can anybody help me?

Main Class-

@RestResource(urlMapping='/APIForWebTeam/*')
global class EGS_APIForWebTeam {
    
    public class AccountData{
      //public Id accountId;
        public String customer_code;
        public String web_customer_id;
        public String web_customer_mapping_id;
        public String account_name;
        public String account_source;
        public String email;
        public String email_pec;
        public String vat_number;
        public String social_security_number;
        public String phone;
        public String mobile_phone;
        public String type;
      //public String billingAddress;
        public String billing_street_address;
        public String billing_city;
        public String billing_state;
        public String billing_zipcode;
        public String billing_country;
      //public String shippingAddress;
        public String shipping_street_address;
        public String shipping_city;
        public String shipping_state;
        public String shipping_zipcode;
        public String shipping_country;
        public String product_category;
        public String product_subcategory;
      //public String country;
      //public String stateProvince;
      //public String country1;
        public String first_name;
        public String last_name;
    }
    
    @httpPost
    global static void createAccountData(){
        try{
            RestRequest req = RestContext.request;
            String jsonString = req.requestBody.tostring();
            List<AccountData> receivedData= (List<AccountData>)System.JSON.deserialize(jsonString, List<AccountData>.class);
            
            List<Account> accountList = new List<Account>();
            List<Contact> conList=New List<Contact>();
            
            for(AccountData accountData : receivedData){
                Account acc=New Account();
                
                acc.Name=accountData.account_name;
                acc.Customer_Code__c=accountData.customer_code;
                acc.AccountSource=accountData.account_source;
                acc.Email__c=accountData.email;
                acc.Email_PEC__c=accountData.email_pec;
                acc.VAT_number__c=accountData.vat_number;
                acc.Social_security_number__c=accountData.social_security_number;
                acc.Phone=accountData.phone;
                acc.Mobile_phone__c=accountData.mobile_phone;
                acc.Type=accountData.type;
              //acc.BillingAddress=accountData.billingAddress;
                acc.BillingStreet=accountData.billing_street_address;
                acc.BillingCity=accountData.billing_city;
                acc.BillingState=accountData.billing_state;
                acc.BillingPostalCode=accountData.billing_zipcode;
                acc.BillingCountry=accountData.billing_country;
              //acc.Country_C__c=accountData.country;
              //acc.State_province__c=accountData.stateProvince;
              //acc.ShippingAddress=accountData.shippingAddress;
                acc.ShippingStreet=accountData.shipping_street_address;
                acc.web_customer_id__c=accountData.web_customer_id;
                acc.web_customer_mapping_id__c=accountData.web_customer_mapping_id;
                acc.ShippingCity=accountData.shipping_city;
                acc.ShippingState=accountData.shipping_state;
                acc.ShippingPostalCode=accountData.shipping_zipcode;
                acc.ShippingCountry=accountData.shipping_country;
                acc.Product_Category__c=accountData.product_category;
                acc.Product_Subcategory__c=accountData.product_subcategory;
                
              //acc.Country__c=accountData.country;
                accountList.add(acc);
                
                
            }
            if(!accountList.isEmpty()){
            insert accountList;
            }
            
            for(AccountData accountData : receivedData){
                Contact varCon = New Contact();
                varCon.FirstName = accountData.first_name;
                varCon.LastName = accountData.last_name;
                varCon.Email = accountData.email;  
                varCon.MobilePhone = accountData.mobile_phone;
                varCon.Phone = accountData.phone;
                varCon.AccountId = accountList[0].id;
                conList.add(varCon);
            
            }
            
            if(!conList.isEmpty()){
            insert conList;    
            }
            
            RestResponse res = RestContext.response;
            res.statusCode = 200;
            String webCustomerId = accountList[0].web_customer_id__c;
            String webCustomerMappingId = accountList[0].web_customer_mapping_id__c;
            String customerCode = accountList[0].Customer_Code__c;
            res.responseBody= Blob.valueOf('Web Customer Id = '+webCustomerId+',  Salesforce Account Id = '+accountList[0].id+', Web Customer Mapping Id = '+webCustomerMappingId+', Customer Code = '+customerCode);
        }catch(Exception e){
            RestResponse res = RestContext.response;
            res.statusCode = 404;
            res.responseBody = Blob.valueOf('Something went wrong! Error Message : '+e.getMessage());
        }
     }
  }




 
Hello,
We have created a form in our website to submit info that will create a Order in Salesforce.  Three of the Fields we have in Order object are 
"EffectiveDate","License_activation_date__c" and "License_Expiration_date__c". I am submitting the date in the correct format of yyyy-MM-dd and the API request is correct and the response back is successful. However, when I am submmiting the request in the body, it's giving error.
I am submitting the JSON in the body as follows-

[
{
    "accountId":"0015E00001eJboYQAS",
    "licenseActivationDate":"2020-08-03",
    "licenseExpirationDate":"2021-10-11",
    "orderStartDate":"2021-08-21",
    "status":"Draft",
    "contractNumber":"8005E000002VXzxQAG"
}
]


But, it's giving error as Expected EGS_Order_API.DateValue but found "2020-08-03" at [line:3, column:37]

My REST API Class is as follows-

@RestResource(urlMapping='/OrderForWebTeam/*')
global class EGS_OrderForWebTeam {
    
    public class OrderData{
        public Id accountId;
        public String orderName;
        public String customerId;
        public Decimal currencys;
        public String billingStreet;
        public String billingCity;
        public String billingState;
        public String billingPostalCode;
        public String billingCountry;
        public String status;
        public String orderAmount;
        public DateValue orderStartDate;
        public String orderType;
        public DateValue licenseActivationDate;
        public DateValue licenseExpirationDate;
        public Id productId;
        public String entitlementId;    
        public Id contractNumber;    
    }
    
    public class DateValue{
        public Integer day;
        public Integer month;
        public Integer year;
    }
    
    @httpPost
    global static void createOrderData(){
        try{
            RestRequest req = RestContext.request;
            String jsonString = req.requestBody.tostring();
            List<OrderData> receivedData = (List<OrderData>)System.JSON.deserialize(jsonString, List<OrderData>.class);
            
            List<Order> orderList = new List<Order>();
            for(OrderData oData:receivedData){
                Order orderObject= New Order();
                orderObject.AccountId=oData.accountId;
                orderObject.Name=oData.orderName;
                orderObject.Customer_ID__c=oData.customerId;
                orderObject.Currency__c=oData.currencys;
                orderObject.BillingStreet=oData.billingStreet;
                orderObject.BillingCity=oData.billingCity;
                orderObject.BillingState=oData.billingState;
                orderObject.BillingPostalCode=oData.billingPostalCode;
                orderObject.BillingCountry=oData.billingCountry;
                orderObject.Status=oData.status;
                orderObject.Type=oData.orderType;
                orderObject.License_activation_date__c= Date.newInstance(oData.licenseActivationDate.year,oData.licenseActivationDate.month,oData.licenseActivationDate.day);
                orderObject.License_Expiration_date__c= Date.newInstance(oData.licenseExpirationDate.year,oData.licenseExpirationDate.month,oData.licenseExpirationDate.day);
                orderObject.EffectiveDate= Date.newInstance(oData.orderStartDate.year,oData.orderStartDate.month,oData.orderStartDate.day);
                orderObject.Product_name__c=oData.productId;
                orderObject.Entitlement_ID__c=oData.entitlementId;
                orderObject.ContractId=oData.contractNumber;
                
                orderList.add(orderObject);
            }
            insert orderList;
            RestResponse res = RestContext.response;
            res.statusCode = 200;
            res.responseBody = Blob.valueOf('Order Inserted Successfully..');
        }catch(Exception e){
            RestResponse res = RestContext.response;
            res.statusCode = 404;
            res.responseBody = Blob.valueOf('Something went wrong! Error Message : '+e.getMessage());
        }
    }
    
}



Does anyone have any idea what could be the problem?

Thanks !!
Hi Developers,
I am getting error in Test class. Kindly help. I am getting error as "System.NullPointerException: Attempt to de-reference a null object".
Stack Trace- Class.EGS_ProductForWebTeam.sendProductData: line 140, column 1
Class.EGS_ProductForWebTeamTestClass.createTestRecord: line 50, column 1
Class.EGS_ProductForWebTeamTestClass.testProduct: line 4, column 1

Below is the Rest service Class and Test Class.

Main Class (REST API)-

@RestResource(urlMapping='/ProductForWebTeam/*')
global class EGS_ProductForWebTeam {
    public class ProductData {
        
        public String sf_product_id;
        public String name;
        public String type;
        public Decimal regular_price;
        public String description;
        public String short_description;
        public List<Categories> categories;
        public List<Attribute> attributes;
        public List<Variation> variations;
    }       
        public class Categories {
            public Integer id;
            public String name;
        }
        
        public class Attributes_Z {
            public Integer id;
            public String option;
        }
        
        public class Attribute {
            public Integer id ;
            public Boolean variation;
            public Boolean visible;
            public List<String> options;
        }
    
/*           public class Option{
            public Integer id;
            public String month;    
                
            }*/
        
        public class Variation {
            public Decimal regular_price;
            public List<Attributes_Z> attributes;
        }
                   

    @httpGet
    global static void sendProductData() {
        try {
            List<ProductData> productWrapperList = new List<ProductData>();
            Map<Id, Product2> productMap = new Map<Id, Product2>([SELECT Id, Name, Description, Product_Category__c, Product_Subcategory__c FROM Product2 WHERE Is_sent_to_web__c = false LIMIT 1]);
            System.debug(productMap);
            
            
            Pricebook2 priceBook = [SELECT Id FROM Pricebook2 WHERE Id = '01s0900000DSd7HAAT'];
            
            List<PriceBookEntry> priceBookEntryList = [SELECT Product2Id, UnitPrice 
                                                   FROM PriceBookEntry 
                                                   WHERE pricebook2id = :priceBook.Id AND Product2Id =: productMap.keySet()];
                                                   
            Map<Id, PriceBookEntry> MapOfProductToPBE = new Map<Id, PriceBookEntry>();
            for(PriceBookEntry pbe : priceBookEntryList)
            {
               MapOfProductToPBE.put(pbe.Product2Id, pbe);
            }
            System.debug(MapOfProductToPBE);
            
            List<Product2> productListToBeUpdated = new List<Product2>();
            
            for(Product2 product : productMap.values()) {
                ProductData productData = new ProductData();
                productData.sf_product_id = product.Id;
                productData.name = product.Name;
                productData.type = 'variable';
                
             //   if(MapOfProductToPBE.get(product.id).Product2id == product.id && MapOfProductToPBE.get(product.id).UnitPrice != null){
                    productData.regular_price = 100;
             //   }else{
             //       productData.regular_price = 0;
              //  }
                    
                       
                
                productData.description = product.Description;
                List<categories> categoryList = new List<categories>();
                Categories c = new Categories();
                
                if(product.Product_Category__c == 'Bundle') {
                    c.id = 60;
                    c.name = product.Product_Category__c;
                } else if(product.Product_Category__c == 'Additional module') {
                    c.id = 61;
                    c.name = product.Product_Category__c;
                } else if(product.Product_Category__c == 'Stand Alone') {
                    c.id = 62;
                    c.name = product.Product_Category__c;
                }
                categoryList.add(c);
                productData.categories = categoryList;
                
                //Code for attribute
                List<Attribute> attributeList = new List<Attribute>();
                Attribute varAttr = New Attribute();
                varAttr.id = 2; 
                varAttr.variation = true;
                varAttr.visible = true;
                List<String> OptionList = new List<String>();
                OptionList.add('3 Months');
                OptionList.add('6 Months');
                OptionList.add('1 Year');
                varAttr.options = OptionList;
                attributeList.add(varAttr);
                productData.attributes = attributeList;
         
                List<variation> VariationList = new List<variation>();
                for(String i : OptionList)
                {
                  variation v = new variation();
                  v.regular_price = 100;
                  List<Attributes_Z> AttrList = new List<Attributes_Z>();
                  Attributes_Z attrInstance = new Attributes_Z();
                  attrInstance.id = 2;
                  attrInstance.option = i;
                  AttrList.add(attrInstance);
                  v.attributes = AttrList;
                  VariationList.add(v);
                }
                productData.variations = VariationList;
                
                product.Is_sent_to_web__c = true;
                productListToBeUpdated.add(product);
                productWrapperList.add(productData);
            }
        //    update productListToBeUpdated;
            
            System.debug(JSON.serialize(productWrapperList));
            RestResponse res = RestContext.response;
            res.statusCode = 200;
            res.responseBody = Blob.valueOf(JSON.serialize(productWrapperList));
            
        } catch(Exception e) {
            RestResponse res = RestContext.response;
            res.statusCode = 404;
            res.responseBody = Blob.valueOf('Something went wrong! Error Message : '+e.getMessage()+'  '+'line number '+e.getLineNumber()+ ' '+e.getCause());
       }
        
    }
}

Test Class- 

@isTest
private class EGS_ProductForWebTeamTestClass {
    @isTest static void testProduct() {
        Product2 varProd= createTestRecord();
        // Set up a test request
        RestRequest request = new RestRequest();
        request.requestUri = 'https://egssolutions--developer.lightning.force.com/services/apexrest/ProductForWebTeam/';
        //   request.requestUri =  '/services/apexrest/ProductForWebTeam/';
        request.httpMethod = 'GET';
        RestContext.request = request;
        // Call the method to test
       
    }
    
    static Product2 createTestRecord() {
        // Create test record
        Product2 varP = new Product2(
            Name = 'Product 1',
            Description='Test Description',
            Product_Category__c='Bundle',
            Product_Subcategory__c='Light',
            Is_sent_to_web__c=false);
        
        insert varP;
        system.debug('Product '+varP);
        
        
        Pricebook2 priceBook = new Pricebook2(
            Name = 'End User');
        
        insert priceBook;
        system.debug('PriceBook '+priceBook);
        
        PriceBookEntry standardPriceBookEntry = new PriceBookEntry(
            Product2Id = varP.Id,
            pricebook2id = Test.getStandardPricebookId(),
            UnitPrice = 2000);
        
        insert standardPriceBookEntry;
        system.debug('StandardPriceBookEntry '+standardPriceBookEntry);
        
        PriceBookEntry priceBookEntry = new PriceBookEntry(
            UnitPrice = 6000,
            pricebook2id=priceBook.id,
            Product2Id = varP.Id);
        
        insert priceBookEntry;
        system.debug('PriceBookEntry '+priceBookEntry);
        test.startTest();
        EGS_ProductForWebTeam.sendProductData();
        test.stopTest();
        return varP;
    }      
    
}
@RestResource(urlMapping='/ProductForWebTeam/*')
global class EGS_ProductForWebTeam {
    public class ProductData {
        
        public String sf_product_id;
        public String name;
        public String type;
        public Decimal regular_price;
        public String description;
        public String short_description;
        public List<Categories> categories;
        public List<Attribute> attributes;
        public List<Variation> variations;
    }       
        public class Categories {
            public Integer id;
            public String name;
        }
        
        public class Attributes_Z {
            public Integer id;
            public String option;
        }
        
        public class Attribute {
            public Integer id ;
            public Boolean variation;
            public Boolean visible;
            public List<String> options;
        }
    
/*           public class Option{
            public Integer id;
            public String month;    
                
            }*/
        
        public class Variation {
            public Decimal regular_price;
            public List<Attributes_Z> attributes;
        }
                   

    @httpGet
    global static void sendProductData() {
        try {
            List<ProductData> productWrapperList = new List<ProductData>();
            Map<Id, Product2> productMap = new Map<Id, Product2>([SELECT Id, Name, Description, Product_Category__c, Product_Subcategory__c FROM Product2 WHERE Is_sent_to_web__c = false LIMIT 1]);
            System.debug(productMap);
            
            
            Pricebook2 priceBook = [SELECT Id FROM Pricebook2 WHERE Id = '01s0900000DSd7HAAT'];
            
            List<PriceBookEntry> priceBookEntryList = [SELECT Product2Id, UnitPrice 
                                                   FROM PriceBookEntry 
                                                   WHERE pricebook2id = :priceBook.Id AND Product2Id =: productMap.keySet()];
                                                   
            Map<Id, PriceBookEntry> MapOfProductToPBE = new Map<Id, PriceBookEntry>();
            for(PriceBookEntry pbe : priceBookEntryList)
            {
               MapOfProductToPBE.put(pbe.Product2Id, pbe);
            }
            System.debug(MapOfProductToPBE);
            
            List<Product2> productListToBeUpdated = new List<Product2>();
            
            for(Product2 product : productMap.values()) {
                ProductData productData = new ProductData();
                productData.sf_product_id = product.Id;
                productData.name = product.Name;
                productData.type = 'variable';
                
             //   if(MapOfProductToPBE.get(product.id).Product2id == product.id && MapOfProductToPBE.get(product.id).UnitPrice != null){
                    productData.regular_price = 100;
             //   }else{
             //       productData.regular_price = 0;
              //  }
                    
                       
                
                productData.description = product.Description;
                List<categories> categoryList = new List<categories>();
                Categories c = new Categories();
                
                if(product.Product_Category__c == 'Bundle') {
                    c.id = 60;
                    c.name = product.Product_Category__c;
                } else if(product.Product_Category__c == 'Additional module') {
                    c.id = 61;
                    c.name = product.Product_Category__c;
                } else if(product.Product_Category__c == 'Stand Alone') {
                    c.id = 62;
                    c.name = product.Product_Category__c;
                }
                categoryList.add(c);
                productData.categories = categoryList;
                
                //Code for attribute
                List<Attribute> attributeList = new List<Attribute>();
                Attribute varAttr = New Attribute();
                varAttr.id = 2; 
                varAttr.variation = true;
                varAttr.visible = true;
                List<String> OptionList = new List<String>();
                OptionList.add('3 Months');
                OptionList.add('6 Months');
                OptionList.add('1 Year');
                varAttr.options = OptionList;
                attributeList.add(varAttr);
                productData.attributes = attributeList;
         
                List<variation> VariationList = new List<variation>();
                for(String i : OptionList)
                {
                  variation v = new variation();
                  v.regular_price = 100;
                  List<Attributes_Z> AttrList = new List<Attributes_Z>();
                  Attributes_Z attrInstance = new Attributes_Z();
                  attrInstance.id = 2;
                  attrInstance.option = i;
                  AttrList.add(attrInstance);
                  v.attributes = AttrList;
                  VariationList.add(v);
                }
                productData.variations = VariationList;
                
                product.Is_sent_to_web__c = true;
                productListToBeUpdated.add(product);
                productWrapperList.add(productData);
            }
        //    update productListToBeUpdated;
            
            System.debug(JSON.serialize(productWrapperList));
            RestResponse res = RestContext.response;
            res.statusCode = 200;
            res.responseBody = Blob.valueOf(JSON.serialize(productWrapperList));
            
        } catch(Exception e) {
            RestResponse res = RestContext.response;
            res.statusCode = 404;
            res.responseBody = Blob.valueOf('Something went wrong! Error Message : '+e.getMessage()+'  '+'line number '+e.getLineNumber()+ ' '+e.getCause());
        }
    }
}
I want to create a Custom Button on Account Detail Page. When I click that Button, I want to create a custom Clone functionality to clone an Account record with their related record using Lightning Web Component
When i enter "Policy Holder ID" and click on "Submit" then below result should appear.
There is one primary object i.e  "Policy_Holder__c"
and two secondary objects  i.e "Life_Insurance__c" and "Motor_Insurance__c" ...

"Policy_Holder__c" object contains "Policy Holder ID" field.

"Life_Insurance__c" object contains Policy ID,Policy Type,Premium Amount, Due Date fields.

"Motor_Insurance__c" object contains Policy ID,Policy Type,Premium Amount, Due Date fields.

So when i enter Policy Holder ID then below fields should be retrieved of related list in "Visual Force page"

User-added image

 
Hi, I need to write a test class for my httppost method which uses json as input. i have tried implementing a test class using the HttpCalloutMock Interface but the apex class gets 0% code coverage in that case. Please suggest how can i go about this.

My apex class:
@RestResource(urlMapping='/abc/xyz/*')
global class MyClass{

    @HttpPost
    global static void updateMethod(){    
        try {        
            //get the json from the request
            RestRequest req1=RestContext.request;           
            String jsonInput= req1.requestBody.toString();       

            //create map for the obtained json input
            Map<String, Object> jsonMap = (Map<String, Object>) JSON.deserializeUntyped(jsonInput); 
            Id opptyId = String.valueOf(jsonMap.get('opportunity_SF_Id')) ;            
            
            //get the opportunity object       
            Sobject oppty = [SELECT id, description FROM opportunity WHERE id=:opptyId];
            //some more processing
            update oppty;        
        }catch(Exception e){
               System.debug('The following exception has occurred: ' + e.getMessage());
       }
    } 
}
Hello everyone I could use some help on the using future Methods trailhead. Please keep in mind I am not an Apex coder at all but I am trying to learn as much as I can.

Here is the Task

Create an Apex class with a method using the @future annotation that accepts a List of Account IDs and updates a custom field on the Account object with the number of contacts associated to the Account. Write unit tests that achieve 100% code coverage for the class.
Create a field on the Account object called 'Number_of_Contacts__c' of type Number. This field will hold the total number of Contacts for the Account.
Create an Apex class called 'AccountProcessor' that contains a 'countContacts' method that accepts a List of Account IDs. This method must use the @future annotation.
For each Account ID passed to the method, count the number of Contact records associated to it and update the 'Number_of_Contacts__c' field with this value.
Create an Apex test class called 'AccountProcessorTest'.
The unit tests must cover all lines of code included in the AccountProcessor class, resulting in 100% code coverage.
Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.

I have written an Apex class and a Test class but I think I am doing them both Wrong: because when I try to check the challenge i Get this error

Challenge Not yet complete... here's what's wrong: 
The 'AccountProcessorTest' test class doesn't appear to be calling the 'AccountProcessor.countContacts' method between Test.startTest() and Test.stopTest().


When I run the Test class I get this error :

System.QueryException: List has no rows for assignment to SObject

Here is the CLASS:
 
public class AccountProcessor {
     @future

  public static void someFutureMethod(List<id> scope) {

   Account[] updates = new Account[] {};
        for (AggregateResult ar : [
                select AccountId a, count(Id) c
                from Contact
                where AccountId in :scope
                group by AccountId
                ]) {
            updates.add(new Account(
                    Id = (Id) ar.get('a'),
                    Number_of_Contacts__c = (Decimal) ar.get('c')
                    ));
        }
        update updates;
    }

}

Here is the Test Class:
 
@IsTest
public class AccountProcessorTest {
  public static testmethod void TestAccountProcessorTest() {
 
Test.startTest();
     Account a = new Account();
        a.Name = 'Test Account';
        Insert a;
      
      Contact cont = New Contact();
      
      cont.FirstName ='Bob';
      cont.LastName ='Masters';
      cont.AccountId = a.Id;
      Insert cont;

    Test.stopTest() ;
     Contact ACC = [select AccountId from Contact where id = :a.id LIMIT 1];

 
        System.assert(Cont.AccountId != null);
        System.assertequals(cont.id, ACC.AccountId);

  }}

I have used alot or diffrent google searches to get me this far. But I have not Idea if Im even remotly close to the right answer or not.


 

Hi all,

I have this code into a class in which I have to program to execute daily in SalesForce.

 

list<User> registrosUser = [select id, title, firstname, lastname, email, phone, ContactId
                                FROM User WHERE ContactId <>: null AND LastLoginDate = YESTERDAY];
            
        for(User rUser : registrosUser){
            
            Contact ctc = [select id, Inicio_Sesion__c, Ultimo_inicio_de_sesion__c FROM Contact WHERE id=: rUser.ContactId LIMIT 1];
            System.debug(ctc.Ultimo_inicio_de_sesion__c);
            ctc.Ultimo_inicio_de_sesion__c = rUser.LastLoginDate;
            ctc.Inicio_Sesion__c = true;
            update ctc;
        }

 

I have tried this code within the developer shell, and the query returns the correct register, but this line appears on the debug output:

 

13:06:13.033 (33547000)|EXCEPTION_THROWN|[8]|System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: User.LastLoginDate
13:06:13.033 (33585000)|HEAP_ALLOCATE|[8]|Bytes:95
13:06:13.033 (33725000)|FATAL_ERROR|System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: User.LastLoginDate

 

Could you help me about this exception??

 

Thanks in advance!