• Mahesh Babu 187
  • NEWBIE
  • 75 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 23
    Questions
  • 24
    Replies
Hi Team,

I have a requirement to calculate average wait time in live agent. I have went through many articles but nothing is working.
Could you please guide me if I need to create a lightning component or VF page.Also please share some sample code.
 
Hi Team,

I have written a trigger. It is working fine when the quote lines are less but when the quote lines are increased I am getting error.
Please help me in bulkifying this code:

APEX CODE:

trigger SpendDiscountCalc on SBQQ__QuoteLine__c (before insert, before update) {
    
    Decimal tierAmount = 3000000;
    Decimal percent1 = 0.00;
    Decimal percent2 = 0.12;
    Decimal percent3 = 0.14;
    Decimal percent4 = 0.16;
    Decimal percent5 = 0.18;
    Decimal percent6 = 0.20;
    Decimal tierdiscountamt1 = 0.00;
    Decimal tierdiscountamt2 = 0.00;
    Decimal tierdiscountamt3 = 0.00;
    Decimal tierdiscountamt4 = 0.00;
    Decimal tierdiscountamt5 = 0.00;
    Decimal tierdiscountamt6 = 0.00;
    Decimal pct1 = 0.00;
    Decimal pct2 = 0.00;
    Decimal pct3 = 0.00;
    Decimal pct4 = 0.00;
    Decimal pct5 = 0.00;
    Decimal pct6 = 0.00;
    
    for(SBQQ__QuoteLine__c quoteLine : Trigger.new){
        
        if((quoteLine.Quote_Avg_Net_Price__c!=0 && quoteLine.Account_Name__c!=null && quoteLine.SBQQ__Quote__c != null && quoteLine.Eligible_for_Spend_Discount__c == true && quoteline.Lightbox_Pricing__c == true)
           && (quoteLine.Quote_Avg_Net_Price__c > tierAmount))
        {   
            
            System.debug('quoteLine.Quote_Avg_Net_Price__c: '+quoteLine.Quote_Avg_Net_Price__c); 
            Decimal tierdiscountamt1 = quoteLine.Quote_Avg_Net_Price__c - tierAmount;
            System.debug('tierdiscountamt1 :'+tierdiscountamt1); 
            Decimal pct1 = (tierAmount * percent1);  
            System.debug('pct1: '+pct1); 
            
            if(tierdiscountamt1 > tierAmount ){
                Decimal tierdiscountamt2 = tierdiscountamt1 - tierAmount;
                System.debug('tierdiscountamt2 :'+tierdiscountamt2); 
                Decimal pct2 = (tierAmount * percent2);
                System.debug('pct2: '+pct2); 
            }
            else
            {
                Decimal pct2 = (tierdiscountamt1 * percent2);
                System.debug('pct2: '+pct2);
                
                if(tierdiscountamt2 > tierAmount){
                    Decimal tierdiscountamt3 = tierdiscountamt2 - tierAmount; 
                    System.debug('tierdiscountamt3 :'+tierdiscountamt3); 
                    Decimal pct3 = (tierAmount * percent3);
                    System.debug('pct3: '+pct3); 
                }
                else{
                    Decimal pct3 = (tierdiscountamt2 * percent3);
                    
                    if(tierdiscountamt3 > tierAmount){
                        Decimal tierdiscountamt4 = tierdiscountamt3 - tierAmount;
                        System.debug('tierdiscountamt4 :'+tierdiscountamt4);
                        Decimal pct4 = (tierAmount * percent4);
                        System.debug('pct4: '+pct4); 
                    }
                    else{
                        Decimal pct4 = (tierdiscountamt3 * percent4);
                        if(tierdiscountamt4 > tierAmount){
                            Decimal tierdiscountamt5 = tierdiscountamt4 - tierAmount;
                            System.debug('tierdiscountamt5 :'+tierdiscountamt5); 
                            Decimal pct5 = (tierAmount * percent5); 
                            System.debug('pct5: '+pct5); 
                        }
                        else{
                            Decimal pct5 = (tierdiscountamt4 * percent5); 
                            if(tierdiscountamt5 > tierAmount){
                                Decimal tierdiscountamt6 = tierdiscountamt5 - tierAmount;
                                System.debug('tierdiscountamt6 :'+tierdiscountamt6);
                                Decimal pct6 = (tierdiscountamt6 * percent6);
                                System.debug('pct6: '+pct6);
                            }
                            else{
                                Decimal pct6 = (tierdiscountamt5 * percent6);  
                                quoteLine.Spend_Discount__c = (((pct1+pct2+pct3+pct4+pct5+pct6) / quoteLine.Quote_Avg_Net_Price__c) * 100);    
                                System.debug('quoteLine.Spend_Discount__c: '+quoteLine.Spend_Discount__c);
                            }
                        }                        
                    }
                }
            }
                                
        }        
        else{
            quoteLine.Spend_Discount__c = 0;
        }
        
    } 
}

Thank you,
Mahesh
Hi Team,

My requirement is like:

Suppose there are multilpe quotes for an Account. Now I want to have a invoice for a particular quote and we want to apply special discount for that quote. The discount will be applicable based on a date field and percentage field. So based on the date field, I need to check the previous quotes i.e if the date is 17th March 2021 for the current quote, then i need to check the if the quotes of Janaury or December or November for that particular account had percent field as 20%. 

So whenever there is invoicing for a particular quote, I need to exclude the recent previous quote and check back the other previous 3 quotes and make the checkbox checked for the quote which we are invoicing. 

I tried to write a trigger but it is throwing error: 'Logical operator can only be applied to Boolean'

TRIGGER:

trigger Eligibleforspenddisc on SBQQ__Quote__c (before insert,before update) {
    for(SBQQ__Quote__c sb : Trigger.new){
        if(sb.SBQQ__Account__c != null){
     List<SBQQ__Quote__c>  sbList = [Select id, SBQQ__Account__c, Activity_Date_PB__c, PA_Coverage__c from SBQQ__Quote__c
                                where SBQQ__Account__c =:sb.SBQQ__Account__c and PA_Coverage__c=20];
            if(((sb.Activity_Date_PB__c.addMonths(-2)) || (sb.Activity_Date_PB__c.addMonths(-3)) || (sb.Activity_Date_PB__c.addMonths(-4))) && 
               sb.PA_Coverage__c == 19.5){
                   sb.Eligible_for_Spend_Discount__c = true;
               }
        }
    }

}

Please help in solving this issue.

Thank You,
Mahesh
 
Hi Team,

My test classes are failing due to a custom validation rule.

VALIDATION RULE:
(Price_Book_Exist__c = false) && NOT(ISNEW())

I am getting below error: 
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_EXECUTE_FLOW_TRIGGER, We can't save this record because the “Deactivate Product if changed” process failed. Give your Salesforce admin these details. This error occurred when the flow tried to update records: FIELD_CUSTOM_VALIDATION_EXCEPTION: Custom Price book must be added to the product to proceed further. You can look up ExceptionCode values in the SOAP API Developer Guide.: []

Please find my one APEX CLASS and it's TEST CLASS.

APEX CLASS:

global with sharing class CreatePriceBookClass {
    private static boolean run = true;
    public static boolean runOnce(){
        if(run){
            run=false;
            return true;
        }else{
            return run;
        }
    }
    
    public static void createPriceBook(Product2 product){
        List<Pricebook2> pbs = [SELECT Id,IsStandard FROM Pricebook2 WHERE IsStandard = TRUE];
        
        for(Pricebook2 pb : pbs) { PriceBookEntry pbe1 = new PriceBookEntry();
            pbe1.Pricebook2Id = pb.Id;
            pbe1.Product2Id = product.Id;
            pbe1.UnitPrice = 0;
            pbe1.CurrencyIsoCode = product.CurrencyIsoCode;
            pbe1.IsActive = true;
            insert pbe1;
        }
        List<Pricebook2> pb2s = new List<Pricebook2>();
        if(product.CurrencyIsoCode!= null && product.CurrencyIsoCode.indexOf('USD') >= 0){
            pb2s = [SELECT Id,IsStandard FROM Pricebook2 WHERE Name = 'USD'];
        } else if(product.CurrencyIsoCode!= null && product.CurrencyIsoCode.indexOf('CAD') >= 0){
            pb2s = [SELECT Id,IsStandard FROM Pricebook2 WHERE Name = 'CAD'];
        } else if(product.CurrencyIsoCode!= null && product.CurrencyIsoCode.indexOf('GBP') >= 0){
            pb2s = [SELECT Id,IsStandard FROM Pricebook2 WHERE Name = 'GBP'];
        }
        for(Pricebook2 pb2 : pb2s) {
            PriceBookEntry pbe2 = new PriceBookEntry();
            pbe2.Pricebook2Id = pb2.Id;
            pbe2.Product2Id = product.Id;
            pbe2.UnitPrice = 0;
            pbe2.CurrencyIsoCode = product.CurrencyIsoCode;
            pbe2.IsActive = true;
            pbe2.UseStandardPrice = false;
            insert pbe2;
        }
    }
}

TEST CLASS:

@isTest(seeAllData=false)
public class CreatePriceBookClassTest {

    @TestSetup 
    static void doSetup(){
        TestDataUtility.createTriggerFlag();        

        List<Account> accs = TestDataUtility.createAccounts(3);
        accs[1].vertical__c = 'Mortgage';
        accs[2].vertical__c = 'Personal Loans';
        update accs;
        
        List<Product2> prods = TestDataUtility.createProducts(1,accs[0].Id);
        Id pricebookId  =Test.getStandardPricebookId();
       }
    
    @isTest
    public static void basicTest(){
        List<Product2> prods = [SELECT Id,Lightbox_Pricing__c,CurrencyIsoCode FROM Product2];
       
        for(Product2 prod : prods) {
            Id pricebookId  =Test.getStandardPricebookId();
            PricebookEntry standardPrice = new PricebookEntry();
            standardPrice.Pricebook2Id = pricebookId;
            standardPrice.Product2Id = prod.Id;
            standardPrice.UnitPrice = 1; 
            standardPrice.IsActive = true;
            standardPrice.UseStandardPrice = false;
            insert standardPrice;
            
            Pricebook2 customPB = new Pricebook2();
            customPB.Name='Custom Pricebook';
            customPB.isActive=true;
            insert customPB;
            
            Pricebook2 customPB1 = new Pricebook2();
            customPB1.Name='USD';
            customPB1.isActive=true;
            insert customPB1;
            
            PriceBookEntry pbe = new PriceBookEntry();
            pbe.Pricebook2Id = customPB.Id;
            pbe.Product2Id = prod.Id;
            pbe.UnitPrice = 0;
            pbe.UseStandardPrice = false;
            pbe.CurrencyIsoCode = prod.CurrencyIsoCode;
            pbe.IsActive = true;
            insert pbe;
        
        
            prod.Activated_End_Date__c = System.today();
            update prod;
            CreatePriceBookClass.createPriceBook(prod);
        }
    }
    
    @isTest
    public static void basicCADTest(){
        List<Product2> prods = [SELECT Id,Lightbox_Pricing__c,CurrencyIsoCode FROM Product2];
       
        for(Product2 prod : prods) {
            prod.CurrencyIsoCode = 'CAD';
            Id pricebookId  =Test.getStandardPricebookId();
            PricebookEntry standardPrice = new PricebookEntry();
            standardPrice.Pricebook2Id = pricebookId;
            standardPrice.Product2Id = prod.Id;
            standardPrice.UnitPrice = 1; 
            standardPrice.IsActive = true;
            standardPrice.UseStandardPrice = false;
            standardPrice.CurrencyIsoCode = prod.CurrencyIsoCode;
            insert standardPrice;
            
            Pricebook2 customPB = new Pricebook2();
            customPB.Name='Custom Pricebook';
            customPB.isActive=true;
            insert customPB;
            
            Pricebook2 customPB1 = new Pricebook2();
            customPB1.Name='CAD';
            customPB1.isActive=true;
            insert customPB1;
            
            PriceBookEntry pbe = new PriceBookEntry();
            pbe.Pricebook2Id = customPB.Id;
            pbe.Product2Id = prod.Id;
            pbe.UnitPrice = 0;
            pbe.UseStandardPrice = false;
            pbe.CurrencyIsoCode = prod.CurrencyIsoCode;
            pbe.IsActive = true;
            insert pbe;
        
        
            prod.Activated_End_Date__c = System.today();
            update prod;
            CreatePriceBookClass.createPriceBook(prod);
        }
    }
    
    @isTest
    public static void basicGBPTest(){
        List<Product2> prods = [SELECT Id,Lightbox_Pricing__c,CurrencyIsoCode FROM Product2];
       
        for(Product2 prod : prods) {
            prod.CurrencyIsoCode = 'GBP';
            Id pricebookId  =Test.getStandardPricebookId();
            PricebookEntry standardPrice = new PricebookEntry();
            standardPrice.Pricebook2Id = pricebookId;
            standardPrice.Product2Id = prod.Id;
            standardPrice.UnitPrice = 1; 
            standardPrice.IsActive = true;
            standardPrice.UseStandardPrice = false;
            standardPrice.CurrencyIsoCode = prod.CurrencyIsoCode;
            insert standardPrice;
            
            Pricebook2 customPB = new Pricebook2();
            customPB.Name='Custom Pricebook';
            customPB.isActive=true;
            insert customPB;
            
            Pricebook2 customPB1 = new Pricebook2();
            customPB1.Name='GBP';
            customPB1.isActive=true;
            insert customPB1;
            
            PriceBookEntry pbe = new PriceBookEntry();
            pbe.Pricebook2Id = customPB.Id;
            pbe.Product2Id = prod.Id;
            pbe.UnitPrice = 0;
            pbe.UseStandardPrice = false;
            pbe.CurrencyIsoCode = prod.CurrencyIsoCode;
            pbe.IsActive = true;
            insert pbe;
        
        
            prod.Activated_End_Date__c = System.today();
            update prod;
            CreatePriceBookClass.createPriceBook(prod);
        }
    }
 
}

Please help in solving this issue.

Thank You,
Mahesh
Hi Team,

I have a requirement to clone case records with it's related Open Activities(Task and Event), Case Comments, Emails and Attachments.
i have written a Apex class and created a VF Page. The VF page is called on a button click. But through my code only the record is getting cloned but it's related list items are not getting cloned.
I took help from below articles:

Help Link 1 (https://blog.jeffdouglas.com/2009/11/19/apex-deep-clone-controller/) :https://blog.jeffdouglas.com/2009/11/19/apex-deep-clone-controller/
Help Link-2 (https://developer.salesforce.com/forums/?id=906F0000000AbWJIA0) :https://developer.salesforce.com/forums/?id=906F0000000AbWJIA0

APEX CODE:

global with sharing class CaseCloneController {
    
    private final Id recordId;
    private final Case record;
    private final ApexPages.StandardController controller; 

    public CaseCloneController(ApexPages.StandardController controller) {
        this.controller = controller;
        this.record = (Case)(this.controller.getRecord());
        this.recordId = this.controller.getId();
        System.debug('this.recordId'+recordId); // it is retrieving null
    }    

    public PageReference cloneWithItems() {
        Case newCase = this.record.clone(false, true);
        System.debug('newCase'+newCase);
        insert newCase;

        List<Attachment> clonedAttachments = new List<Attachment>();
        for (Attachment attachment: [select ParentId, Body, BodyLength from Attachment where ParentId = :this.recordId]) {
            System.debug('attachment.ParentId'+attachment.ParentId);
            Attachment clonedAttachment = attachment.clone(false, true);
            clonedAttachment.ParentId = newCase.Id;
            clonedAttachments.add(clonedAttachment);
        }
        insert clonedAttachments;
        
        List<CaseComment> casecomments = new List<CaseComment>();
             for(CaseComment cc : [Select Id, ParentId, IsPublished, CommentBody, CreatedById, CreatedDate, SystemModstamp, LastModifiedDate, LastModifiedById, IsDeleted From CaseComment where ParentId=:this.recordId]){
                 CaseComment newcasecomment = cc.clone(false, true);
                 newcasecomment.ParentId = newCase.id;
                 casecomments.add(newcasecomment);
             }
             insert casecomments;
        
        List<Task> clonedTasks = new List<Task>();
        for(Task t : [Select id, WhatId, Subject, Status from Task where WhatId =:this.recordId]){
            Task newtask = t.clone(false, true);
            newtask.WhatId = newCase.id;
            clonedTasks.add(newtask);
        }
        insert clonedTasks;
        
        List<Event> clonedEvent = new List<Event>();
        for(Event e : [Select id, Location, Description, Type, WhatId from Event where WhatId =: this.recordId]){
            Event newevent = e.clone(false, true);
            newevent.WhatId = newCase.id;
            clonedEvent.add(newevent);
        }
        insert clonedEvent;
        
        List<EmailMessage> clonedEmail = new List<EmailMessage>();
        for(EmailMessage email : [Select id, ParentId, ActivityId, BccAddress, CcAddress, FromAddress, FromName, Subject, TextBody from EmailMessage where ParentId =: this.recordId]){
            EmailMessage newemail = email.clone(false, true);
            newemail.ParentId = newCase.id;
            clonedEmail.add(newemail);
        }
        insert clonedEmail;

        return new ApexPages.StandardController(newCase).view();
    }  
    
}

VISULAFORCE PAGE:

<apex:page standardController="Case" extensions="CaseCloneController" action="{!cloneWithItems}">
     <apex:pageMessages />
</apex:page>

Please help me in solving this issue.

Thank You,
Mahesh
Hi Team,

I have a Apex class which is called in trigger. It is throwing Apex CPU time limit exceeded Error. I have searched and found that my code is not bulkified but I am facing issue in bulkifying it.

APEX CODE:

public class QuoteLineClass {
    
    public static void UpdatePricingCategory(List<SBQQ__QuoteLine__c> qLine){
        
        System.Debug('UpdatePricingCategory begin');     
        for(SBQQ__QuoteLine__c quoteLine : qLine)  {
            Id VantageRecordTypeId = Schema.SObjectType.SBQQ__ContractedPrice__c.getRecordTypeInfosByName().get('Vantage').getRecordTypeId();
            Id NonVanProdRecordTypeId = Schema.SObjectType.SBQQ__ContractedPrice__c.getRecordTypeInfosByName().get('Non Vantage').getRecordTypeId(); 
            if(quoteLine.SBQQ__Product__c!=null && (quoteLine.Offer_Name__c == null || quoteLine.Offer_Name__c == '')){
                
                List<SBQQ__ContractedPrice__c> cps=[Select id,RecordTypeId,Pricing_Master_Version__c,SBQQ__Price__c,Pricing_Category__c,SBQQ__EffectiveDate__c,SBQQ__ExpirationDate__c, SBQQ__Product__c from SBQQ__ContractedPrice__c where SBQQ__Product__c =:quoteLine.SBQQ__Product__c
                                                    AND Status__c='Approved' AND SBQQ__EffectiveDate__c <=:quoteLine.Activity_Date__c AND SBQQ__ExpirationDate__c >=:quoteLine.Activity_Date__c];
                System.Debug('1... SBQQ__ContractedPrice__c size' + cps.size());
             
                for(SBQQ__ContractedPrice__c cp :cps){
                    if(cp.RecordTypeId == VantageRecordTypeId){
                        quoteLine.CP_Pricing_Category__c = cp.Pricing_Category__c;
                        quoteLine.CP_Vantage_Pricing_Version__c = cp.Pricing_Master_Version__c;
                        quoteLine.SBQQ__ContractedPrice__c = null;
                        quoteLine.SBQQ__SpecialPriceType__c = null;
                        quoteLine.CP_Lightbox_Pricing__c = true; 
                        System.Debug('inside if');
                    } 
                    else if(cp.RecordTypeId == NonVanProdRecordTypeId){    
                        quoteLine.SBQQ__ContractedPrice__c = cp.Id;
                        quoteLine.CP_Lightbox_Pricing__c = false;
                        System.Debug('inside else if');
                    }                 
                }                
            }
        }
    }    
    
    public static void UpdateQuoteLine(List<SBQQ__QuoteLine__c> qLine){
        List<SBQQ__QuoteLine__c> q = new List<SBQQ__QuoteLine__c>();
        for(SBQQ__QuoteLine__c quoteLine : qLine){
            if(quoteLine.Score_Band__c == 'No Score Band'){
                quoteLine.SBQQ__ContractedPrice__c = null;
                quoteLine.SBQQ__SpecialPriceType__c = null;
            }
        }
    }     
}

TRIGGER:

trigger QuoteLineTrigger on SBQQ__QuoteLine__c (before insert, after insert, before update, after update, before delete, after delete) {
    QuoteLineTriggerDispatcher dispatcher = new QuoteLineTriggerDispatcher();
    dispatcher.dispatchEvent();
    System.Debug('inside trigger before if');
   if(Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)){
        if(checkRecursive.runOnce()){
            System.Debug('inside trigger after if');
        QuoteLineClass.UpdatePricingCategory(Trigger.new);
       QuoteLineClass.UpdateQuoteLine(Trigger.new);  
        System.Debug('inside trigger after if.... completed');
        }
    }  
}

Please help me in bulkifying it.

Thank You,
Mahesh
Hi Team,
I have a requirement to convert my picklist value to date in a new field.
My picklist values are as May 2020, June 2021. Now I want to convert this value to a date format in the new field as 05/01/2020.
And all my values should be converted to 1st day of the month which is selected in the picklist.
Example:

Jan 2020-  01/01/2020
March 2021- 03/01/2021
April 2013 -  04/01/2013

It should be mm/dd/yyyy. And "dd" should be always 01.
i have searched many formulas to convert it to the required format, but could not achieve.
Please help me in achieving it.

Thanks,
Mahesh  
Hi Team,

I have written a trigger to insert a new contact through web to case only when a custom field on Case is checked. I have written test class for it.
But it is covering on first 2 lines. 
Please help me to increase it's code coverage.

TRIGGER

trigger CreateContactOnCaseCreation on Case (before insert, before update) {
    
    for(Case caseobj : Trigger.new){ 
       if(caseobj.Create_Contact__c) {
           if(caseobj.ContactId == null && caseobj.SuppliedEmail!=''){
            List<Contact> listContacts = [Select Id, Email From Contact Where Email =:caseobj.SuppliedEmail];
              if(listContacts.size() == 0) {
                 Contact cont = new Contact();
                 cont.LastName=caseobj.SuppliedName;
                 cont.Email=caseobj.SuppliedEmail;
                 cont.Phone=caseobj.SuppliedPhone;
                 Account account = [Select Id from Account where Name = 'Web-2-Case' limit 1];
                 cont.AccountId=account.Id;
                 insert cont;
                 caseobj.ContactId = cont.Id;
                 caseobj.Create_Contact__c = false;
              } else {
                Trigger.New[0].addError('Contact cannot be created; reason: The contact with the email address already exist in system');
                caseobj.Create_Contact__c = false;
              }
           } else {
               Trigger.New[0].addError('Contact cannot be created; reason: The criteria to create contact does not meet');
               caseobj.Create_Contact__c = false;
           }
       }
    }
}

TEST CLASS

@isTest
private class CreateContactOnCaseCreationTest {
     @isTest static void Test1(){
         Case cs = new Case();
         cs.Status = 'New';
         cs.Origin = 'Web';
         cs.SuppliedName = 'Test Test';
         cs.SuppliedPhone = '1234567890';
         cs.SuppliedEmail = 'test@test.com';
         cs.Subject = 'Test';
         cs.Create_Contact__c= false; 
         Test.startTest();
         insert cs;
         Account a = new Account();
         a.Name = 'Test';
         a.BillingCountry = 'Afghanistan';
         insert a;
         Contact con = new Contact();
         con.LastName = cs.SuppliedName;
         con.Email = cs.SuppliedEmail;
         con.Phone = cs.SuppliedPhone;
         Account account = [Select Id from Account where Name = 'Test' limit 1];
         con.AccountId = account.Id;
         insert con;
         Test.stopTest();
        // System.assertEquals(1,Contact.size());
     }
}


Thanks,
Mahesh
 
Hi Team,
I have a requirement to auto-create an account and contact through web-to-case. I am able to create contact through trigger if the email id doesn't exists.As the contact is created it becomes private conatct because it not associated to any account. So I need to create the account from 'Suppliedcompany' field and map this account to the contact.

APEX CODE

trigger CreateContact on Case (before insert) {
    
        List<String> emailAddresses = new List<String>();
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null && caseObj.SuppliedEmail!='')
        {
            emailAddresses.add(caseObj.SuppliedEmail);             
        }
    }
    List<Contact> listContacts = [Select Id, Email From Contact Where Email in :emailAddresses];
    Set<String> takenEmails = new Set<String>();
    for (Contact c:listContacts) {
        takenEmails.add(c.Email);
    }
    Map<String,Contact> emailToContactMap = new Map<String,Contact>();
    List<Case> casesToUpdate = new List<Case>();
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null && caseObj.SuppliedName!=null && caseObj.SuppliedName!='' && caseObj.SuppliedEmail!=null &&
            caseObj.SuppliedEmail!='' && caseObj.SuppliedPhone!=null && caseObj.SuppliedPhone!='' && !takenEmails.contains(caseObj.SuppliedEmail))
         {
            String[] nameParts = caseObj.SuppliedName.split(' ',2);
            if (nameParts.size() == 2)
            {
             Contact cont = new Contact(FirstName=nameParts[0], LastName=nameParts[1], Email=caseObj.SuppliedEmail, Phone=caseObj.SuppliedPhone);
                emailToContactMap.put(caseObj.SuppliedEmail,cont);
                casesToUpdate.add(caseObj);
            }
        }
    }
    List<Contact> newContacts = emailToContactMap.values();
    insert newContacts;
    for (Case caseObj:casesToUpdate) {
        Contact newContact = emailToContactMap.get(caseObj.SuppliedEmail);
        caseObj.ContactId = newContact.Id;
    }
}

Thanks,
Mahesh
Hi Team,

We have a Apex class which is called in a trigger. I have writen a test class for that Apex class but my code coverage is only 5%. Only first 2 lines are getting covered. I have tried multiple approaches but all in vain. Please assist me to do the changes.

APEX CODE:

public class BQDetailsUpdateClass {

    public static void createBQDetails(Product2 product){
               if(product.Vertical__c != null && product.Vertical__c.equals('Credit Cards') && product.Approval_Status__c != null && product.Approval_Status__c.equals('Approved')) {
                List<PriceBookEntry> pbes = [Select Id,UnitPrice,CurrencyIsoCode,BQ_Detail__c from PriceBookEntry where Product2Id =: product.Id and Pricebook2Id != '01s41000007uZohAAE' and IsActive = true];
                for(PriceBookEntry pbe : pbes) {
                    BQ_Detail__c bqd = new BQ_Detail__c();
                    if(product.Lightbox_Pricing__c) {
                        bqd.Product__c = product.Id;
                        bqd.Vantage_Pricing__c = true;
                        bqd.Price__c = pbe.UnitPrice;
                        bqd.CurrencyIsoCode = pbe.CurrencyIsoCode;
                    } else {
                        bqd.Product__c = product.Id;
                        bqd.Price__c = pbe.UnitPrice;
                        bqd.CurrencyIsoCode = pbe.CurrencyIsoCode;
                    }
                    bqd.Eligible_for_BQ__c = true;
                    if(String.IsBlank(pbe.BQ_Detail__c)) {
                        insert bqd;
                        pbe.BQ_Detail__c = bqd.Id;
                        update pbe;
                    } else {
                        bqd.Id = pbe.BQ_Detail__c;
                        update bqd;
                    }
                    
                }
                List<Product_Offering__c> poffers = [Select Id ,CurrencyIsoCode, Offer_Name__c ,BQ_Detail__c,List_Price__c, End_Date__c, Start_Date__c from Product_Offering__c where Product__c =: product.Id and Active__c = true];
                
                for(Product_Offering__c poffer : poffers) {
                    BQ_Detail__c bqd = new BQ_Detail__c();
                    bqd.Product__c = product.Id;
                    bqd.Price__c = poffer.List_Price__c;
                    bqd.CurrencyIsoCode = poffer.CurrencyIsoCode;
                    bqd.Offer_Name__c = poffer.Offer_Name__c;
                    bqd.Start_Date__c = poffer.Start_Date__c;
                    bqd.End_Date__c = poffer.Start_Date__c;
                    bqd.Eligible_for_BQ__c = true;
                    if(String.IsBlank(poffer.BQ_Detail__c)) {
                        insert bqd;
                        poffer.BQ_Detail__c = bqd.Id;
                        update poffer;
                    } else {
                        bqd.Id = poffer.BQ_Detail__c;
                        update bqd;
                    }
                }
              }    
}

TEST CLASS:

@isTest(SeeAllData=true)
public class BQDetailsUpdateClassTest {
    
    @isTest
    public static void Test1(){
        
            Product2 prod = new Product2();
            PricebookEntry standardPrice = new PricebookEntry();
            BQ_Detail__c bqd1 = new BQ_Detail__c();        
            bqd1.Product__c=prod.Id;        
            bqd1.Price__c=standardPrice.UnitPrice;
            bqd1.Vantage_Pricing__c=true;
            bqd1.CurrencyIsoCode=standardPrice.CurrencyIsoCode;
            insert bqd1;      
       

    //PricebookEntry updatePriceBookEntry = new PricebookEntry( id = standardPrice.Id,UnitPrice = 30.00);
    //update updatePriceBookEntry;    
       
       /*public static void  test2(){
            BQ_Detail__c bqd = new BQ_Detail__c();
            Product2 prod = new Product2();
              PricebookEntry pbes = new PricebookEntry();
           bqd.Id=pbes.BQ_Detail__c;
           update bqd; 
        }*/
    
   /* @isTest
     public static void Test2(){
      Product2 prod = new Product2();
     PricebookEntry standardPrice = new PricebookEntry();
            BQ_Detail__c bqd2 = new BQ_Detail__c();
        
            bqd2.Product__c=prod.Id;
        
        bqd2.Price__c=standardPrice.UnitPrice;
        bqd2.Vantage_Pricing__c=true;
        bqd2.CurrencyIsoCode=standardPrice.CurrencyIsoCode;
        insert bqd2; 
*/              
       
       BQDetailsUpdateClass.createBQDetails(prod);
        
    } 
    
          /*Pricebook2 customPB = new Pricebook2(
          Name='Custom Pricebook',
          isActive=true);
        insert customPB;*/   
      
        /*PricebookEntry pbes = new PricebookEntry(
            Pricebook2Id = customPB.Id, 
            Product2Id = prod.Id,
            UnitPrice = 12000, IsActive = true);
        insert pbes;
        
  
        List<PricebookEntry> pbes1 = [SELECT ID, Product2Id, 
        Pricebook2.isStandard, Pricebook2.isActive, isActive FROM PricebookEntry];*/   
    
        /*Id pricebookId = Test.getStandardPricebookId();
        Product2 p =new Product2();
        p.Name = 'Test';
        p.Description = 'Test';
        p.Vertical__c = 'Credit Cards';
        p.Lightbox_Pricing__c = false;
        p.Location__c = '100 - SF 760 Market St';
        p.CurrencyIsoCode='CAD - Canadian Dollar';
        insert p;
        List<PriceBookEntry> pbes = [Select Id,UnitPrice,CurrencyIsoCode,BQ_Detail__c from PriceBookEntry where Product2Id =: p.Id];
     PriceBookEntry pbe = new PriceBookEntry();
     pbe.UnitPrice = 5;
      pbe.Pricebook2Id = '01s02000000xDR3AAM';
     insert pbe;  
        
    }*/      
}

Thanks,
Mahesh
Hi Team,

I am stuck in a trigger. I have 2 look-up fields on Product obejct. Through first look-up field i.e  'Parent Id'  we can select Account Name and through second look-up field we select Account Manager Name. Now my requirement is as i select the Account Name in first look-up field, it should automatically populate respective Account Manager Name in second look-up field  .
I have created the trigger.

trigger AddAccountManager on Product2 (before update) {
        Set<Id> Ids = new Set<Id>();
    for(Product2 p : Trigger.new){
        Ids.add(p.Parent_ID__c);
    }
    Map<Id, Account> accountownername = new Map<Id , Account>([SELECT id, Name, AccountManager__c FROM Account WHERE Id IN: Ids]);
    for(Product2 p : Trigger.new){
        if(p.Parent_ID__c != null && accountownername.containsKey(p.Parent_ID__c))   {
            p.Account_Manager__c = accountownername.get(p.Parent_ID__c).AccountManager__c;
        }
    }
     }  

I am getting this error:

Apex trigger AddAccountManager caused an unexpected exception, contact your administrator: AddAccountManager: execution of AfterUpdate caused by: System.FinalException: Record is read-only: ()

Please help me to solve this.

Thanks,
Mahesh
I have a requirement to create a new record of a custom object. This custom object should be populated with List Price field value of Standard Price Object. I was trying to create it with Process Builder. But process builder doesn't have option of Standard Price Object in add object section. Please help me what approach needs to be followed.
If it can be done through trigger, please share a sample code.

Thanks,
Mahesh
I have three objects A, B and C . I want to create new record of obj. A having name field value from obj. B and price field value from obj. C. A and B are child object of B but C doesn't have any relation with A. 

1. If it is possible through flow.Can anyone share the steps.
2. If it is possible through trigger. Please share a sample code.

Thanks,
Mahesh
Hi Team,

I have a requirement to create new records for a custom object in Salesforce.
My conditions are:
1. On my Product Object, there is a picklist field 'Verticals' and a     checkbox field 'Pricing'. Now if the value of Picklist field is 'A' and checkbox is unchecked, then it should create a new record for my custom object. That custom object should be populated with my Product name and a Price field's value. But the issue is Price field's value which needs to be populated will come from another Object named Product Offering which is a related list on Product Object. 

2.  On my Product Object, there is a picklist field 'Verticals'. Now if the value of Picklist field is 'B', then it should create a new record for my custom object. That custom object should be populated with my Product name and a Price field's value. But the issue is Price field's value which needs to be populated will come from another Object named Block Prices which is a related list on Product Object.

Can anyone tell how this can we created?
Hi Team,

I have a requirement where I have an external website outside Salesforce.The customer fills out a form on this website and also adds attachment in the form. On submit of this form, I want a new case object record to be created in salesforce with customer filled data.The attachment should be visible to the agent who will work on the case and also the agent should get notified when an attachment is added in the form. Any help would be appreciated.

Thanks in Advance,
Mahesh
I have written a Apex class which is getting called in a trigger. Now I have written a test class for the Apex class. But my code coverage is 0%.

APEX CLASS

public class ChangeOwnerClass{

    public static void changeOwner(Quote quote){
        
        Opportunity opp = [Select ID, CreatedById, OwnerId from Opportunity where Id =: quote.OpportunityId];
        System.debug(opp.OwnerId);
        if(opp.OwnerId != null) {}
            User user = [Select Id,ProfileId from User where Id=: opp.OwnerId];
            System.debug(user.Id);
            if(user!= null && user.ProfileId != null) {
                Profile profile = [Select name from Profile where Id =: user.ProfileId ];
                System.debug(profile.name);
                if(profile !=null && profile.name != null && profile.name == 'TriLink Sales & Service') {
                    quote.ownerId = opp.CreatedById;
                }            
            }
        }
    }

TRIGGER

trigger ChangeOwner on Quote (before insert) {
    
        for(Quote q: Trigger.new)
        {
            ChangeOwnerClass.changeOwner(q);
        }        
    }

TEST CLASS

@isTest
public class ChangeOwnerTest {

    @isTest static void changeOwnerTest(){
        Opportunity opp = new Opportunity();
        opp.Name = 'Test';
        opp.LeadSource = 'Test';
        opp.StageName = 'Identification';
        opp.CloseDate = Date.newInstance(2020, 12, 14);
        opp.OwnerId = '0056A00000264YcQAI';
        insert opp;
        if(opp.OwnerId != null) {}
        User user = [Select Id,ProfileId from User where Id=: opp.OwnerId];
        if(user!= null && user.ProfileId != null){
            Profile profile = [Select name from Profile where Id =: user.ProfileId ];
            if(profile !=null && profile.name != null && profile.name == 'TriLink Sales & Service'){
                Quote q = new Quote();
                q.Id = opp.Id;
                q.ownerId = opp.CreatedById;
                insert q;
            }
        }
    }
}

Please help me to modify it to get the code coverage.
I have written an Apex class for changing the Quote owner as the Opportunity owner for a Profile named 'TriLink Sales & Service'. I have called this class in Trigger. But it is not updating anything.

APEX CODE:
public class changeOwnerClass{
public list<Opportunity> lstOpp = [Select id, name, ownerId from Opportunity] ;
public void changeOwner(list<Quote> lstQuote){
Profile p = [select id,Name from Profile where id=:Userinfo.getProfileid()];
System.debug(p);
for (Opportunity opp : lstOpp){
for(Quote objQuote : lstQuote){
if(p.Name == 'TriLink Sales & Service' && p.Name!= 'TriLink GMP'){
objQuote.OwnerId = opp.OwnerId;
System.debug(opp.OwnerId);
System.debug(objQuote.OwnerId);
}} } }
}

TRIGGER:
trigger changeOwner on Quote (before insert) {
changeOwnerClass clsChangeOwner = new changeOwnerClass ();
if(trigger.isInsert && trigger.isBefore){ clsChangeOwner.changeOwner(trigger.new);
} }

I can see that the opportunity owner id is not coming here. But how to get opportunity owner id here.
Please help me to solve this error.
Hi Team,

Please help to write a test class for a after delete trigger.

TRIGGER

trigger MaketheCheckboxUnused on Order_Line_Item_Serials__c (after delete) {
     //Serial_Number__c    
    List<Serial_Number__c> snumlist = New List<Serial_Number__c>();
    List<Id> orderitemlist = New List<Id>();
    For(Order_Line_Item_Serials__c oli : Trigger.Old){
        orderitemlist.add(oli.Serial_Number__c);
    }
    List<Serial_Number__c> Olis = 
        [Select Id, Name,Serial_Number__c,  
         Product__r.Id,Status__c
         From Serial_Number__c Where
         Status__c = TRUE AND
         ID IN : orderitemlist];
    
    For(Order_Line_Item_Serials__c orim : Trigger.Old){
        For(Serial_Number__c olisn : Olis){
            If(Trigger.IsDelete){
                olisn.Status__c = FALSE;
                snumlist.add(olisn);
            }
        }
    }
    update snumlist; 
}

Thanks in Advance,
Mahesh


 
Hi Team,
I have written a wrapper class contaning the search functionality. But I can't understand how to write it's test class.

APEX CODE 

Public class fetchserials{
    
    Public string OrderID {get; set;}
    Public order OrderInstance {get; set;}
    Public List<OrderItem> OrderItemList {get; set;}
    Public Set<id> ProductIdSet {get; set;} //list to add product Ids
    Public list<Serial_Number__c> SerialList {get; set;}
    Public list<Serial_Number__c> SelectedSerialList {get; set;}
    Public Map<OrderItem,list<Serial_Number__c>> OrderVSerial{get; set;} // list to add OrderItem with their Serial Numbers
    Public List<wrapperfetch> fetchseriallist {get; set;}
    // public Integer Counter;
    Public List<Order_Line_Item_Serials__c> insertordersn {get; set;} // list to add the selected orders
    Public map<id,Serial_Number__c> smap = new map<id,Serial_Number__c>();
    public List<Serial_Number__c> serialNumbers;
    public string fullname{get;set;}
    public string finalSearchValue{get;set;}
    
    //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.error,'Enter the List');
    // ApexPages.addMessage(myMsg);
    
    Public fetchserials(){
        OrderItemList = new List<OrderItem>(); // intialize
        OrderVSerial = new Map<OrderItem,List<Serial_Number__c>>();
        fetchseriallist = new List<wrapperfetch>();
        insertordersn = new List<Order_Line_Item_Serials__c>();
        SelectedSerialList = new list<Serial_Number__c>();
        SerialList = new list<Serial_Number__c>();
        OrderID = ApexPages.currentPage().getParameters().get('Id'); //Getting the id of current order
      OrderInstance = [SELECT Id FROM Order where Id=:OrderID ];
       OrderItemList=[SELECT Id,OrderId,product2Id,PricebookEntry.Product2.Name, Quantity FROM OrderItem where OrderId =:OrderID];
       loadSerials();
    }
    //adding page reference of the current page
  /*  public PageReference step1() {
        loadSerials();
          if(SerialList==null){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 
'Please select the serial number'));

        return Page.fetchserials;
    }*/
    
    public PageReference cancel() {
        PageReference c=new PageReference('/'+OrderID);
        return c;
    }   
    
    Public void loadSerials(){
        ProductIdSet = new set<Id>();
        For(OrderItem items :OrderItemList){
            ProductIdSet.add(items.Product2Id);// order items products add into productidset 
        }
        SerialList = [SELECT Id,Serial_Number__c,Product_Name__c ,Name,Product__c,Status__c,Bin_Number__c,Location__c
                      FROM Serial_Number__c where Status__c=FALSE And Product__c In:ProductIdSet limit 200 ];
        system.debug('Serialx' +SerialList );
        
        /*if(SerialList == NULL)
{
SerialList.addError('There are no values in the Serials List.'); 
}*/
        // add error exception handling
        system.debug('Serialx' +SerialList );
        For(OrderItem item :OrderItemList){
            //counter = 0;
            For(Serial_Number__c sn :SerialList ){
                If( sn.Product__c == item.Product2Id) // && counter < item.Quantity)
                {   SelectedSerialList = new list<Serial_Number__c>();
                 //     mahesh   fetchseriallist.add(new wrapperfetch(sn,item));
                 fetchseriallist.add(new wrapperfetch(sn));
                 SelectedSerialList.add(sn);
                 //counter = counter +1; 
                }
                else{continue;}
            }
            OrderVSerial.put(item,SelectedSerialList);
            /*=====
try{
if(SerialList == NULL ){ ApexPages.addMessages(e); }

catch (DMLException e){
ApexPages.addMessages(myMsg);
// Code for sending Email
}
============*/
        }
    }
    
    public void search(){
        finalSearchValue = '%' + fullname + '%';
       System.debug(finalSearchValue);
        fetchseriallist = new list<wrapperfetch>();
        List<Serial_Number__c> serialList =  [Select Id, Serial_Number__c, Product_Name__c, Status__c, Bin_Number__c, Location__c FROM Serial_Number__c
                                  where Serial_Number__c like :finalSearchValue];
            System.debug(serialList.size());
        for(Serial_Number__c s : serialList){
                                      System.debug(s);
                                      fetchseriallist.add(new wrapperfetch(s));    
                                      System.debug(s);
                                  }
        
    }
    
    Public class wrapperfetch{
        Public Boolean selected {get; set;}
        Public Serial_Number__c sno{get; set;}
        Public string prodname {get; set;}
        Public OrderItem Oitem{get; set;}
        Public string serialno {get; set;}
        Public Boolean status {get; set;}
        Public String locatn{get;set;}
        Public String binNo{get;set;}
        Public Id stid {get; set;}
        Public Id opid {get; set;}
        
        //    Public wrapperfetch(Serial_Number__c sn,OrderItem Oi){
        Public wrapperfetch(Serial_Number__c sn){  
            //this.selected=check;
            //    this.Oitem= Oi;
            //    this.opid =Oi.Id;
            this.prodname =sn.Product_Name__c;
            this.sno=sn;
            this.locatn=sn.Location__c;
            this.binNo=sn.Bin_Number__c;
            this.serialno = sn.Serial_Number__c;
            this.status=sn.status__c;
            this.stid=sn.id;
            
        }
    }
    
    Public PageReference AddSerailNumbertoOrder(){
        
        for (wrapperfetch st: fetchseriallist ){
            
            If (st.selected == true ){
                Order_Line_Item_Serials__c ordersn= new Order_Line_Item_Serials__c();
                //Order_Line_Item_Serials__c make it to true
                //make a new Order_Line_Item_Serials__c list and make it to true.
                // put that into   ordersn.Serial_Number__c=st.stid;  a new list 
                ordersn.Serial_Number__c=st.stid;
                ordersn.Order_Product__c=st.opid;
                insertordersn.add(ordersn);
                
                Serial_Number__c  serials = new Serial_Number__c();
                serials.id = st.stid;
                serials.Status__c = TRUE;
                serials.Location__c=st.locatn;
                serials.Bin_Number__c = st.binNo;
                SelectedSerialList.add(serials);
                smap.put(serials.id,serials );
                
            }
            
        }
        if (insertordersn.size() > 0){    
                insert insertordersn;    
              //  update smap.values();    
            }
        return Page.fetchserials;    
    }       
}

Please help me to write test class for this code.

Thanks,
Mahesh
Hi Team,

I am trying to display all search results in a wrapper class, but there's this error showing up every time I save the controller:

Error: Constructor not defined: [fetchserials.wrapperfetch].<Constructor>(Serial_Number__c)

The error points to this line of code:  serialNumbers.add(new wrapperfetch(a));

APEX CLASS

Public class fetchserials{
    
    Public string OrderID {get; set;}
    Public order OrderInstance {get; set;}
    Public List<OrderItem> OrderItemList {get; set;}
    Public Set<id> ProductIdSet {get; set;} //list to add product Ids
    Public list<Serial_Number__c> SerialList {get; set;}
    Public list<Serial_Number__c> SelectedSerialList {get; set;}
    Public Map<OrderItem,list<Serial_Number__c>> OrderVSerial{get; set;} // list to add OrderItem with their Serial Numbers
    Public List<wrapperfetch> fetchseriallist {get; set;}
    public Integer Counter;
    Public List<Order_Line_Item_Serials__c> insertordersn {get; set;} // list to add the selected orders
    public List<Serial_Number__c> serialNumbers;
    public string fullname{get;set;}
    public string finalSearchValue{get;set;}
   //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.error,'Enter the List');
// ApexPages.addMessage(myMsg);
       Public fetchserials(){
        OrderItemList = new List<OrderItem>(); // intialize
        OrderVSerial = new Map<OrderItem,List<Serial_Number__c>>();
        fetchseriallist = new List<wrapperfetch>();
        insertordersn = new List<Order_Line_Item_Serials__c>();
        SelectedSerialList = new list<Serial_Number__c>();
        OrderID = ApexPages.currentPage().getParameters().get('Id'); //Getting the id of current order
        OrderInstance = [SELECT Id FROM Order where Id=:OrderID ];
        OrderItemList=[SELECT Id,OrderId,product2Id,PricebookEntry.Product2.Name, Quantity FROM OrderItem where OrderId =:OrderID];
        loadSerials();
    }
    //adding page reference of the current page
    public PageReference step1() {
        loadSerials();
      /*  if(SerialList==null){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 
                                                           'Please select the serial number'));
        } */
        return Page.fetchserials;
    }
    
    public PageReference cancel() {
        PageReference c=new PageReference('/'+OrderID);
        return c;
    }   
    
    Public void loadSerials(){
        ProductIdSet = new set<Id>();
        For(OrderItem items :OrderItemList){
            ProductIdSet.add(items.Product2Id);// order items products add into productidset 
        }
        SerialList = [SELECT Id,Serial_Number__c,Product_Name__c ,Name,Product__c,Status__c
                      FROM Serial_Number__c where Status__c=FALSE And Product__c In:ProductIdSet limit 200 ];
        
        
        /*if(SerialList == NULL)
{
SerialList.addError('There are no values in the Serials List.'); 
}*/
        // add error exception handling
        system.debug('Serialx' +SerialList );
        For(OrderItem item :OrderItemList){
            counter = 0;
            For(Serial_Number__c sn :SerialList ){
                If( sn.Product__c == item.Product2Id && counter < item.Quantity)
                {   SelectedSerialList = new list<Serial_Number__c>();
                    fetchseriallist.add(new wrapperfetch(sn,item));
                    SelectedSerialList.add(sn);
                    counter = counter +1; }
                else{continue;}
            }
            OrderVSerial.put(item,SelectedSerialList);
            /*=====
            try{
                if(SerialList == NULL ){ ApexPages.addMessages(e); }

catch (DMLException e){
    ApexPages.addMessages(myMsg);
    // Code for sending Email
}
            ============*/
        }
    }
    
    public pagereference Search()
    {
        String finalSearchValue = '%' + fullname + '%';
        serialNumbers = [Select Id, Serial_Number__c, Product_Name__c, Status__c FROM Serial_Number__c
                    where Name like :finalSearchValue];
        fetchseriallist = new list<wrapperfetch>();  
        for(Serial_Number__c a: serialNumbers)
        {
            serialNumbers.add(new wrapperfetch(a));
        }
       return null;
   }
    
    Public class wrapperfetch{
        Public Boolean selected {get; set;}
        Public Serial_Number__c sno{get; set;}
        Public string prodname {get; set;}
        Public OrderItem Oitem{get; set;}
        Public string serialno {get; set;}
        Public Boolean status {get; set;}
        Public Id stid {get; set;}
        Public Id opid {get; set;}
        
        Public wrapperfetch(Serial_Number__c sn,OrderItem Oi){
            //this.selected=check;
            this.Oitem= Oi;
            this.opid =Oi.Id;
            this.prodname =sn.Product_Name__c;
            this.sno=sn;
            this.serialno = sn.Serial_Number__c;
            this.status=sn.status__c;
            this.stid=sn.id;
            
            }
    }
    
    Public PageReference AddSerailNumbertoOrder(){
        
        for (wrapperfetch st: fetchseriallist ){
            
            If (st.selected == true ){
                Order_Line_Item_Serials__c ordersn= new Order_Line_Item_Serials__c();
                //Order_Line_Item_Serials__c make it to true
                //make a new Order_Line_Item_Serials__c list and make it to true.
                // put that into   ordersn.Serial_Number__c=st.stid;  a new list 
                ordersn.Serial_Number__c=st.stid;
                ordersn.Order_Product__c=st.opid;
                insertordersn.add(ordersn);
                
                Serial_Number__c  serials = new Serial_Number__c();
                serials.id = st.stid;
                serials.Status__c = TRUE;
                SelectedSerialList.add(serials);
            }
            if(SelectedSerialList == NULL){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 
                                                           'Please select the serial number'));
            }
        }
        insert  insertordersn;
        update SelectedSerialList;
        PageReference orderpage = new PageReference('/'+OrderID);
        orderpage.setRedirect(true);
        orderpage.getParameters().put('myId', OrderID);
        return orderpage;
       
    }
}
-----------------------------------

VISUALFORCE Page

<apex:page controller="fetchserials" lightningstylesheets="true" readonly="true">
    <script>
  function confirmCancel() {
      var isCancel = confirm("Are you sure you wish to cancel?");
      if (isCancel) return true;
     return false;
  }  
  </script>
<Apex:form >
<apex:pageBlock >
<apex:pageMessages id="showmsg"></apex:pageMessages>
    <apex:pageBlock>
        <apex:inputText value="{!fullname}" html-placeholder="Search" />
        <apex:commandButton value="search" action="{!Search}" />
    </apex:pageBlock>
  <apex:pageBlockTable value="{!fetchseriallist }" var="u"  style="width:100%">
    
  <apex:column headerValue="Select" > 
                        <Apex:inputcheckbox value="{!u.Selected}"  /> 
                    </apex:column>  
                    <apex:column headerValue="Serial Number" > 
                        <Apex:outputText value="{!u.serialno }"   /> 
                    </apex:column> 
                   <apex:column headerValue="Product Name" > 
                        <Apex:outputText value="{!u.prodname }"  /> 
                    </apex:column> 
                    <apex:column headerValue="Status" > 
                       <Apex:outputText value="{!u.status}"   />
                    </apex:column> 
  </apex:pageBlockTable>                  
  <apex:commandButton value="Add to Order" action="{!AddSerailNumbertoOrder}" style="margin-top: -2pt;" rerender="showmsg"/>
  <apex:commandButton action="{!cancel}" value="Cancel" onclick="return confirmCancel()" immediate="true" id="cancel"/>

</apex:pageBlock>
  </Apex:form>
</apex:page>

Please help me to solve this issue.
Hi Team,

I am new to integration. I need to send PDF files from Salesforce to Netsuite when a checkbox is selected in Salesforce. I just know the approach that I need to convert the pdf to xml format in a restlet. But how to do this. 

Thanks in Advance 
Hi Team,

My requirement is like:

Suppose there are multilpe quotes for an Account. Now I want to have a invoice for a particular quote and we want to apply special discount for that quote. The discount will be applicable based on a date field and percentage field. So based on the date field, I need to check the previous quotes i.e if the date is 17th March 2021 for the current quote, then i need to check the if the quotes of Janaury or December or November for that particular account had percent field as 20%. 

So whenever there is invoicing for a particular quote, I need to exclude the recent previous quote and check back the other previous 3 quotes and make the checkbox checked for the quote which we are invoicing. 

I tried to write a trigger but it is throwing error: 'Logical operator can only be applied to Boolean'

TRIGGER:

trigger Eligibleforspenddisc on SBQQ__Quote__c (before insert,before update) {
    for(SBQQ__Quote__c sb : Trigger.new){
        if(sb.SBQQ__Account__c != null){
     List<SBQQ__Quote__c>  sbList = [Select id, SBQQ__Account__c, Activity_Date_PB__c, PA_Coverage__c from SBQQ__Quote__c
                                where SBQQ__Account__c =:sb.SBQQ__Account__c and PA_Coverage__c=20];
            if(((sb.Activity_Date_PB__c.addMonths(-2)) || (sb.Activity_Date_PB__c.addMonths(-3)) || (sb.Activity_Date_PB__c.addMonths(-4))) && 
               sb.PA_Coverage__c == 19.5){
                   sb.Eligible_for_Spend_Discount__c = true;
               }
        }
    }

}

Please help in solving this issue.

Thank You,
Mahesh
 
Hi Team,

I have a requirement to clone case records with it's related Open Activities(Task and Event), Case Comments, Emails and Attachments.
i have written a Apex class and created a VF Page. The VF page is called on a button click. But through my code only the record is getting cloned but it's related list items are not getting cloned.
I took help from below articles:

Help Link 1 (https://blog.jeffdouglas.com/2009/11/19/apex-deep-clone-controller/) :https://blog.jeffdouglas.com/2009/11/19/apex-deep-clone-controller/
Help Link-2 (https://developer.salesforce.com/forums/?id=906F0000000AbWJIA0) :https://developer.salesforce.com/forums/?id=906F0000000AbWJIA0

APEX CODE:

global with sharing class CaseCloneController {
    
    private final Id recordId;
    private final Case record;
    private final ApexPages.StandardController controller; 

    public CaseCloneController(ApexPages.StandardController controller) {
        this.controller = controller;
        this.record = (Case)(this.controller.getRecord());
        this.recordId = this.controller.getId();
        System.debug('this.recordId'+recordId); // it is retrieving null
    }    

    public PageReference cloneWithItems() {
        Case newCase = this.record.clone(false, true);
        System.debug('newCase'+newCase);
        insert newCase;

        List<Attachment> clonedAttachments = new List<Attachment>();
        for (Attachment attachment: [select ParentId, Body, BodyLength from Attachment where ParentId = :this.recordId]) {
            System.debug('attachment.ParentId'+attachment.ParentId);
            Attachment clonedAttachment = attachment.clone(false, true);
            clonedAttachment.ParentId = newCase.Id;
            clonedAttachments.add(clonedAttachment);
        }
        insert clonedAttachments;
        
        List<CaseComment> casecomments = new List<CaseComment>();
             for(CaseComment cc : [Select Id, ParentId, IsPublished, CommentBody, CreatedById, CreatedDate, SystemModstamp, LastModifiedDate, LastModifiedById, IsDeleted From CaseComment where ParentId=:this.recordId]){
                 CaseComment newcasecomment = cc.clone(false, true);
                 newcasecomment.ParentId = newCase.id;
                 casecomments.add(newcasecomment);
             }
             insert casecomments;
        
        List<Task> clonedTasks = new List<Task>();
        for(Task t : [Select id, WhatId, Subject, Status from Task where WhatId =:this.recordId]){
            Task newtask = t.clone(false, true);
            newtask.WhatId = newCase.id;
            clonedTasks.add(newtask);
        }
        insert clonedTasks;
        
        List<Event> clonedEvent = new List<Event>();
        for(Event e : [Select id, Location, Description, Type, WhatId from Event where WhatId =: this.recordId]){
            Event newevent = e.clone(false, true);
            newevent.WhatId = newCase.id;
            clonedEvent.add(newevent);
        }
        insert clonedEvent;
        
        List<EmailMessage> clonedEmail = new List<EmailMessage>();
        for(EmailMessage email : [Select id, ParentId, ActivityId, BccAddress, CcAddress, FromAddress, FromName, Subject, TextBody from EmailMessage where ParentId =: this.recordId]){
            EmailMessage newemail = email.clone(false, true);
            newemail.ParentId = newCase.id;
            clonedEmail.add(newemail);
        }
        insert clonedEmail;

        return new ApexPages.StandardController(newCase).view();
    }  
    
}

VISULAFORCE PAGE:

<apex:page standardController="Case" extensions="CaseCloneController" action="{!cloneWithItems}">
     <apex:pageMessages />
</apex:page>

Please help me in solving this issue.

Thank You,
Mahesh
Hi Team,
I have a requirement to convert my picklist value to date in a new field.
My picklist values are as May 2020, June 2021. Now I want to convert this value to a date format in the new field as 05/01/2020.
And all my values should be converted to 1st day of the month which is selected in the picklist.
Example:

Jan 2020-  01/01/2020
March 2021- 03/01/2021
April 2013 -  04/01/2013

It should be mm/dd/yyyy. And "dd" should be always 01.
i have searched many formulas to convert it to the required format, but could not achieve.
Please help me in achieving it.

Thanks,
Mahesh  
Hi Team,

I have written a trigger to insert a new contact through web to case only when a custom field on Case is checked. I have written test class for it.
But it is covering on first 2 lines. 
Please help me to increase it's code coverage.

TRIGGER

trigger CreateContactOnCaseCreation on Case (before insert, before update) {
    
    for(Case caseobj : Trigger.new){ 
       if(caseobj.Create_Contact__c) {
           if(caseobj.ContactId == null && caseobj.SuppliedEmail!=''){
            List<Contact> listContacts = [Select Id, Email From Contact Where Email =:caseobj.SuppliedEmail];
              if(listContacts.size() == 0) {
                 Contact cont = new Contact();
                 cont.LastName=caseobj.SuppliedName;
                 cont.Email=caseobj.SuppliedEmail;
                 cont.Phone=caseobj.SuppliedPhone;
                 Account account = [Select Id from Account where Name = 'Web-2-Case' limit 1];
                 cont.AccountId=account.Id;
                 insert cont;
                 caseobj.ContactId = cont.Id;
                 caseobj.Create_Contact__c = false;
              } else {
                Trigger.New[0].addError('Contact cannot be created; reason: The contact with the email address already exist in system');
                caseobj.Create_Contact__c = false;
              }
           } else {
               Trigger.New[0].addError('Contact cannot be created; reason: The criteria to create contact does not meet');
               caseobj.Create_Contact__c = false;
           }
       }
    }
}

TEST CLASS

@isTest
private class CreateContactOnCaseCreationTest {
     @isTest static void Test1(){
         Case cs = new Case();
         cs.Status = 'New';
         cs.Origin = 'Web';
         cs.SuppliedName = 'Test Test';
         cs.SuppliedPhone = '1234567890';
         cs.SuppliedEmail = 'test@test.com';
         cs.Subject = 'Test';
         cs.Create_Contact__c= false; 
         Test.startTest();
         insert cs;
         Account a = new Account();
         a.Name = 'Test';
         a.BillingCountry = 'Afghanistan';
         insert a;
         Contact con = new Contact();
         con.LastName = cs.SuppliedName;
         con.Email = cs.SuppliedEmail;
         con.Phone = cs.SuppliedPhone;
         Account account = [Select Id from Account where Name = 'Test' limit 1];
         con.AccountId = account.Id;
         insert con;
         Test.stopTest();
        // System.assertEquals(1,Contact.size());
     }
}


Thanks,
Mahesh
 
Hi Team,

We have a Apex class which is called in a trigger. I have writen a test class for that Apex class but my code coverage is only 5%. Only first 2 lines are getting covered. I have tried multiple approaches but all in vain. Please assist me to do the changes.

APEX CODE:

public class BQDetailsUpdateClass {

    public static void createBQDetails(Product2 product){
               if(product.Vertical__c != null && product.Vertical__c.equals('Credit Cards') && product.Approval_Status__c != null && product.Approval_Status__c.equals('Approved')) {
                List<PriceBookEntry> pbes = [Select Id,UnitPrice,CurrencyIsoCode,BQ_Detail__c from PriceBookEntry where Product2Id =: product.Id and Pricebook2Id != '01s41000007uZohAAE' and IsActive = true];
                for(PriceBookEntry pbe : pbes) {
                    BQ_Detail__c bqd = new BQ_Detail__c();
                    if(product.Lightbox_Pricing__c) {
                        bqd.Product__c = product.Id;
                        bqd.Vantage_Pricing__c = true;
                        bqd.Price__c = pbe.UnitPrice;
                        bqd.CurrencyIsoCode = pbe.CurrencyIsoCode;
                    } else {
                        bqd.Product__c = product.Id;
                        bqd.Price__c = pbe.UnitPrice;
                        bqd.CurrencyIsoCode = pbe.CurrencyIsoCode;
                    }
                    bqd.Eligible_for_BQ__c = true;
                    if(String.IsBlank(pbe.BQ_Detail__c)) {
                        insert bqd;
                        pbe.BQ_Detail__c = bqd.Id;
                        update pbe;
                    } else {
                        bqd.Id = pbe.BQ_Detail__c;
                        update bqd;
                    }
                    
                }
                List<Product_Offering__c> poffers = [Select Id ,CurrencyIsoCode, Offer_Name__c ,BQ_Detail__c,List_Price__c, End_Date__c, Start_Date__c from Product_Offering__c where Product__c =: product.Id and Active__c = true];
                
                for(Product_Offering__c poffer : poffers) {
                    BQ_Detail__c bqd = new BQ_Detail__c();
                    bqd.Product__c = product.Id;
                    bqd.Price__c = poffer.List_Price__c;
                    bqd.CurrencyIsoCode = poffer.CurrencyIsoCode;
                    bqd.Offer_Name__c = poffer.Offer_Name__c;
                    bqd.Start_Date__c = poffer.Start_Date__c;
                    bqd.End_Date__c = poffer.Start_Date__c;
                    bqd.Eligible_for_BQ__c = true;
                    if(String.IsBlank(poffer.BQ_Detail__c)) {
                        insert bqd;
                        poffer.BQ_Detail__c = bqd.Id;
                        update poffer;
                    } else {
                        bqd.Id = poffer.BQ_Detail__c;
                        update bqd;
                    }
                }
              }    
}

TEST CLASS:

@isTest(SeeAllData=true)
public class BQDetailsUpdateClassTest {
    
    @isTest
    public static void Test1(){
        
            Product2 prod = new Product2();
            PricebookEntry standardPrice = new PricebookEntry();
            BQ_Detail__c bqd1 = new BQ_Detail__c();        
            bqd1.Product__c=prod.Id;        
            bqd1.Price__c=standardPrice.UnitPrice;
            bqd1.Vantage_Pricing__c=true;
            bqd1.CurrencyIsoCode=standardPrice.CurrencyIsoCode;
            insert bqd1;      
       

    //PricebookEntry updatePriceBookEntry = new PricebookEntry( id = standardPrice.Id,UnitPrice = 30.00);
    //update updatePriceBookEntry;    
       
       /*public static void  test2(){
            BQ_Detail__c bqd = new BQ_Detail__c();
            Product2 prod = new Product2();
              PricebookEntry pbes = new PricebookEntry();
           bqd.Id=pbes.BQ_Detail__c;
           update bqd; 
        }*/
    
   /* @isTest
     public static void Test2(){
      Product2 prod = new Product2();
     PricebookEntry standardPrice = new PricebookEntry();
            BQ_Detail__c bqd2 = new BQ_Detail__c();
        
            bqd2.Product__c=prod.Id;
        
        bqd2.Price__c=standardPrice.UnitPrice;
        bqd2.Vantage_Pricing__c=true;
        bqd2.CurrencyIsoCode=standardPrice.CurrencyIsoCode;
        insert bqd2; 
*/              
       
       BQDetailsUpdateClass.createBQDetails(prod);
        
    } 
    
          /*Pricebook2 customPB = new Pricebook2(
          Name='Custom Pricebook',
          isActive=true);
        insert customPB;*/   
      
        /*PricebookEntry pbes = new PricebookEntry(
            Pricebook2Id = customPB.Id, 
            Product2Id = prod.Id,
            UnitPrice = 12000, IsActive = true);
        insert pbes;
        
  
        List<PricebookEntry> pbes1 = [SELECT ID, Product2Id, 
        Pricebook2.isStandard, Pricebook2.isActive, isActive FROM PricebookEntry];*/   
    
        /*Id pricebookId = Test.getStandardPricebookId();
        Product2 p =new Product2();
        p.Name = 'Test';
        p.Description = 'Test';
        p.Vertical__c = 'Credit Cards';
        p.Lightbox_Pricing__c = false;
        p.Location__c = '100 - SF 760 Market St';
        p.CurrencyIsoCode='CAD - Canadian Dollar';
        insert p;
        List<PriceBookEntry> pbes = [Select Id,UnitPrice,CurrencyIsoCode,BQ_Detail__c from PriceBookEntry where Product2Id =: p.Id];
     PriceBookEntry pbe = new PriceBookEntry();
     pbe.UnitPrice = 5;
      pbe.Pricebook2Id = '01s02000000xDR3AAM';
     insert pbe;  
        
    }*/      
}

Thanks,
Mahesh
Hi Team,

I am stuck in a trigger. I have 2 look-up fields on Product obejct. Through first look-up field i.e  'Parent Id'  we can select Account Name and through second look-up field we select Account Manager Name. Now my requirement is as i select the Account Name in first look-up field, it should automatically populate respective Account Manager Name in second look-up field  .
I have created the trigger.

trigger AddAccountManager on Product2 (before update) {
        Set<Id> Ids = new Set<Id>();
    for(Product2 p : Trigger.new){
        Ids.add(p.Parent_ID__c);
    }
    Map<Id, Account> accountownername = new Map<Id , Account>([SELECT id, Name, AccountManager__c FROM Account WHERE Id IN: Ids]);
    for(Product2 p : Trigger.new){
        if(p.Parent_ID__c != null && accountownername.containsKey(p.Parent_ID__c))   {
            p.Account_Manager__c = accountownername.get(p.Parent_ID__c).AccountManager__c;
        }
    }
     }  

I am getting this error:

Apex trigger AddAccountManager caused an unexpected exception, contact your administrator: AddAccountManager: execution of AfterUpdate caused by: System.FinalException: Record is read-only: ()

Please help me to solve this.

Thanks,
Mahesh
I have a requirement to create a new record of a custom object. This custom object should be populated with List Price field value of Standard Price Object. I was trying to create it with Process Builder. But process builder doesn't have option of Standard Price Object in add object section. Please help me what approach needs to be followed.
If it can be done through trigger, please share a sample code.

Thanks,
Mahesh
I have three objects A, B and C . I want to create new record of obj. A having name field value from obj. B and price field value from obj. C. A and B are child object of B but C doesn't have any relation with A. 

1. If it is possible through flow.Can anyone share the steps.
2. If it is possible through trigger. Please share a sample code.

Thanks,
Mahesh
Hi Team,

I have a requirement to create new records for a custom object in Salesforce.
My conditions are:
1. On my Product Object, there is a picklist field 'Verticals' and a     checkbox field 'Pricing'. Now if the value of Picklist field is 'A' and checkbox is unchecked, then it should create a new record for my custom object. That custom object should be populated with my Product name and a Price field's value. But the issue is Price field's value which needs to be populated will come from another Object named Product Offering which is a related list on Product Object. 

2.  On my Product Object, there is a picklist field 'Verticals'. Now if the value of Picklist field is 'B', then it should create a new record for my custom object. That custom object should be populated with my Product name and a Price field's value. But the issue is Price field's value which needs to be populated will come from another Object named Block Prices which is a related list on Product Object.

Can anyone tell how this can we created?
Hi Team,

I have a requirement where I have an external website outside Salesforce.The customer fills out a form on this website and also adds attachment in the form. On submit of this form, I want a new case object record to be created in salesforce with customer filled data.The attachment should be visible to the agent who will work on the case and also the agent should get notified when an attachment is added in the form. Any help would be appreciated.

Thanks in Advance,
Mahesh
I have written an Apex class for changing the Quote owner as the Opportunity owner for a Profile named 'TriLink Sales & Service'. I have called this class in Trigger. But it is not updating anything.

APEX CODE:
public class changeOwnerClass{
public list<Opportunity> lstOpp = [Select id, name, ownerId from Opportunity] ;
public void changeOwner(list<Quote> lstQuote){
Profile p = [select id,Name from Profile where id=:Userinfo.getProfileid()];
System.debug(p);
for (Opportunity opp : lstOpp){
for(Quote objQuote : lstQuote){
if(p.Name == 'TriLink Sales & Service' && p.Name!= 'TriLink GMP'){
objQuote.OwnerId = opp.OwnerId;
System.debug(opp.OwnerId);
System.debug(objQuote.OwnerId);
}} } }
}

TRIGGER:
trigger changeOwner on Quote (before insert) {
changeOwnerClass clsChangeOwner = new changeOwnerClass ();
if(trigger.isInsert && trigger.isBefore){ clsChangeOwner.changeOwner(trigger.new);
} }

I can see that the opportunity owner id is not coming here. But how to get opportunity owner id here.
Please help me to solve this error.
Hi Team,

Please help to write a test class for a after delete trigger.

TRIGGER

trigger MaketheCheckboxUnused on Order_Line_Item_Serials__c (after delete) {
     //Serial_Number__c    
    List<Serial_Number__c> snumlist = New List<Serial_Number__c>();
    List<Id> orderitemlist = New List<Id>();
    For(Order_Line_Item_Serials__c oli : Trigger.Old){
        orderitemlist.add(oli.Serial_Number__c);
    }
    List<Serial_Number__c> Olis = 
        [Select Id, Name,Serial_Number__c,  
         Product__r.Id,Status__c
         From Serial_Number__c Where
         Status__c = TRUE AND
         ID IN : orderitemlist];
    
    For(Order_Line_Item_Serials__c orim : Trigger.Old){
        For(Serial_Number__c olisn : Olis){
            If(Trigger.IsDelete){
                olisn.Status__c = FALSE;
                snumlist.add(olisn);
            }
        }
    }
    update snumlist; 
}

Thanks in Advance,
Mahesh


 
Hi Team,
I have written a wrapper class contaning the search functionality. But I can't understand how to write it's test class.

APEX CODE 

Public class fetchserials{
    
    Public string OrderID {get; set;}
    Public order OrderInstance {get; set;}
    Public List<OrderItem> OrderItemList {get; set;}
    Public Set<id> ProductIdSet {get; set;} //list to add product Ids
    Public list<Serial_Number__c> SerialList {get; set;}
    Public list<Serial_Number__c> SelectedSerialList {get; set;}
    Public Map<OrderItem,list<Serial_Number__c>> OrderVSerial{get; set;} // list to add OrderItem with their Serial Numbers
    Public List<wrapperfetch> fetchseriallist {get; set;}
    // public Integer Counter;
    Public List<Order_Line_Item_Serials__c> insertordersn {get; set;} // list to add the selected orders
    Public map<id,Serial_Number__c> smap = new map<id,Serial_Number__c>();
    public List<Serial_Number__c> serialNumbers;
    public string fullname{get;set;}
    public string finalSearchValue{get;set;}
    
    //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.error,'Enter the List');
    // ApexPages.addMessage(myMsg);
    
    Public fetchserials(){
        OrderItemList = new List<OrderItem>(); // intialize
        OrderVSerial = new Map<OrderItem,List<Serial_Number__c>>();
        fetchseriallist = new List<wrapperfetch>();
        insertordersn = new List<Order_Line_Item_Serials__c>();
        SelectedSerialList = new list<Serial_Number__c>();
        SerialList = new list<Serial_Number__c>();
        OrderID = ApexPages.currentPage().getParameters().get('Id'); //Getting the id of current order
      OrderInstance = [SELECT Id FROM Order where Id=:OrderID ];
       OrderItemList=[SELECT Id,OrderId,product2Id,PricebookEntry.Product2.Name, Quantity FROM OrderItem where OrderId =:OrderID];
       loadSerials();
    }
    //adding page reference of the current page
  /*  public PageReference step1() {
        loadSerials();
          if(SerialList==null){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 
'Please select the serial number'));

        return Page.fetchserials;
    }*/
    
    public PageReference cancel() {
        PageReference c=new PageReference('/'+OrderID);
        return c;
    }   
    
    Public void loadSerials(){
        ProductIdSet = new set<Id>();
        For(OrderItem items :OrderItemList){
            ProductIdSet.add(items.Product2Id);// order items products add into productidset 
        }
        SerialList = [SELECT Id,Serial_Number__c,Product_Name__c ,Name,Product__c,Status__c,Bin_Number__c,Location__c
                      FROM Serial_Number__c where Status__c=FALSE And Product__c In:ProductIdSet limit 200 ];
        system.debug('Serialx' +SerialList );
        
        /*if(SerialList == NULL)
{
SerialList.addError('There are no values in the Serials List.'); 
}*/
        // add error exception handling
        system.debug('Serialx' +SerialList );
        For(OrderItem item :OrderItemList){
            //counter = 0;
            For(Serial_Number__c sn :SerialList ){
                If( sn.Product__c == item.Product2Id) // && counter < item.Quantity)
                {   SelectedSerialList = new list<Serial_Number__c>();
                 //     mahesh   fetchseriallist.add(new wrapperfetch(sn,item));
                 fetchseriallist.add(new wrapperfetch(sn));
                 SelectedSerialList.add(sn);
                 //counter = counter +1; 
                }
                else{continue;}
            }
            OrderVSerial.put(item,SelectedSerialList);
            /*=====
try{
if(SerialList == NULL ){ ApexPages.addMessages(e); }

catch (DMLException e){
ApexPages.addMessages(myMsg);
// Code for sending Email
}
============*/
        }
    }
    
    public void search(){
        finalSearchValue = '%' + fullname + '%';
       System.debug(finalSearchValue);
        fetchseriallist = new list<wrapperfetch>();
        List<Serial_Number__c> serialList =  [Select Id, Serial_Number__c, Product_Name__c, Status__c, Bin_Number__c, Location__c FROM Serial_Number__c
                                  where Serial_Number__c like :finalSearchValue];
            System.debug(serialList.size());
        for(Serial_Number__c s : serialList){
                                      System.debug(s);
                                      fetchseriallist.add(new wrapperfetch(s));    
                                      System.debug(s);
                                  }
        
    }
    
    Public class wrapperfetch{
        Public Boolean selected {get; set;}
        Public Serial_Number__c sno{get; set;}
        Public string prodname {get; set;}
        Public OrderItem Oitem{get; set;}
        Public string serialno {get; set;}
        Public Boolean status {get; set;}
        Public String locatn{get;set;}
        Public String binNo{get;set;}
        Public Id stid {get; set;}
        Public Id opid {get; set;}
        
        //    Public wrapperfetch(Serial_Number__c sn,OrderItem Oi){
        Public wrapperfetch(Serial_Number__c sn){  
            //this.selected=check;
            //    this.Oitem= Oi;
            //    this.opid =Oi.Id;
            this.prodname =sn.Product_Name__c;
            this.sno=sn;
            this.locatn=sn.Location__c;
            this.binNo=sn.Bin_Number__c;
            this.serialno = sn.Serial_Number__c;
            this.status=sn.status__c;
            this.stid=sn.id;
            
        }
    }
    
    Public PageReference AddSerailNumbertoOrder(){
        
        for (wrapperfetch st: fetchseriallist ){
            
            If (st.selected == true ){
                Order_Line_Item_Serials__c ordersn= new Order_Line_Item_Serials__c();
                //Order_Line_Item_Serials__c make it to true
                //make a new Order_Line_Item_Serials__c list and make it to true.
                // put that into   ordersn.Serial_Number__c=st.stid;  a new list 
                ordersn.Serial_Number__c=st.stid;
                ordersn.Order_Product__c=st.opid;
                insertordersn.add(ordersn);
                
                Serial_Number__c  serials = new Serial_Number__c();
                serials.id = st.stid;
                serials.Status__c = TRUE;
                serials.Location__c=st.locatn;
                serials.Bin_Number__c = st.binNo;
                SelectedSerialList.add(serials);
                smap.put(serials.id,serials );
                
            }
            
        }
        if (insertordersn.size() > 0){    
                insert insertordersn;    
              //  update smap.values();    
            }
        return Page.fetchserials;    
    }       
}

Please help me to write test class for this code.

Thanks,
Mahesh
I have a requirement where I have an external website outside Salesforce.The customer fills out a form on this website with name & other information. On submit of this form, I want a new custom object record to be created in salesforce with customer filled data on the form.Any help plz.