• Amit Jadhav 13
  • NEWBIE
  • 140 Points
  • Member since 2019

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 29
    Questions
  • 26
    Replies
I am new when it comes to visualforce and creating custom controllers. 

I have a problem to solve where each Account needs the ability to quickly add an Invoice with only 1 Invoice line item. The ask is to be able to click a button on the Account and be prompted to enter the quantity prior to creating the invoice. 
The result should be after the quantity is entered, an Invoice record is created with 1 Invoice line item showing the fields price and quantity.

Help with how the code should be written would help a lot.

 
Apex Method
 
public static void updateOwner(Map<Id,Project__c> newMap){
        system.debug('Inside');
        set<Id> setProjectId = new set<Id>();
        set<Id> setOpportunityId = new set<Id>();
        for(Project__c objProject : newMap.values()){
            if(objProject.id != null){
                setProjectId.add(objProject.id); 
            }
        }
        //List<OpportunityLineItem> lstOpportunityLineItem =[Select id,Projects__c,opportunityId,opportunity.ownerId from OpportunityLineItem where Projects__c IN:setProjectId LIMIT 3000];
        map<Id,OpportunityLineItem> mapOpportunityLineItem = new map<Id,OpportunityLineItem>([Select id,Projects__c,opportunityId,opportunity.ownerId from OpportunityLineItem where Projects__c IN:setProjectId LIMIT 3000]);
        for(OpportunityLineItem objOpportunityLineItem : mapOpportunityLineItem.values()){
            if(objOpportunityLineItem.opportunityId != null){
                setOpportunityId.add(objOpportunityLineItem.opportunityId);
            }
        }
        map<Id,Opportunity> mapOpportunity = new map<Id,Opportunity>([Select id,ownerId,Total_Products_under_Opportunity__c,type,stageName,(Select id,opportunityId from OpportunityLineItems) from Opportunity where id IN :setOpportunityId AND isClosed =false AND type != null]);
        map<Id,Project__c> mapProject = new map<Id,Project__c>([Select id,name,Opportunity_owner__c,Renewal_owner__c,Program_Manager_U__c,(Select id,Projects__c from Opportunity_Product__r) from project__c where Id IN:setProjectId]); 
        for(OpportunityLineItem objOpportunityLineItem : mapOpportunityLineItem.values()){
            /*Project__c objProject = mapProject.get(objOpportunityLineItem.Projects__c);
            if(objOpportunityLineItem.opportunityId != null){
                Opportunity objOpportunity = mapOpportunity.get(objOpportunityLineItem.opportunityId);
                if( objOpportunity != null){ 
                    if(objProject.name =='The Linux Foundation' && objOpportunity.Total_Products_under_Opportunity__c <= 1 && objProject.Opportunity_owner__c !=null && objOpportunity.type =='New Business'){
                        system.debug('Inside Linux');
                        objOpportunity.OwnerId = objProject.Opportunity_Owner__c;
                        system.debug('objOpportunity'+objOpportunity);
                    }
                    
                    if( objProject.Opportunity_owner__c !=null && objOpportunity.type =='New Business' && objProject.name !='The Linux Foundation'){
                        objOpportunity.OwnerId = objProject.Opportunity_Owner__c;
                    }
                    if(objProject.Renewal_owner__c !=null && objOpportunity.type =='Renewal' ){
                        System.debug('Inside Renewal');
                        objOpportunity.OwnerId = objProject.Renewal_owner__c;
                        System.debug('objOpportunity'+objOpportunity);
                    }else if(objProject.Renewal_owner__c ==null && objProject.Program_Manager_U__c == null){
                        objOpportunity.OwnerId = objProject.Opportunity_Owner__c;
                    }
                    
                    if(objProject.Opportunity_owner__c ==null && objProject.Renewal_owner__c ==null && objProject.Program_Manager_U__c != null ){
                        objOpportunity.OwnerId = objProject.Program_Manager_U__c;
                    }
                    if(objProject.Opportunity_owner__c ==null && objProject.Renewal_owner__c ==null && objProject.Program_Manager_U__c == null ){
                        system.debug('Inside Null');
                        objOpportunity.OwnerId = objOpportunityLineItem.opportunity.ownerId;
                    }
                }
            
        }
        update mapOpportunity.values();

 
Test Class
@isTest
private class LeadConversionController_Test
{
     //Test Setup  
    @testSetup 
    static void setup() {
        Lead convertedLead = new Lead(LastName = 'Test Convert Lead No. 1',
                              Email='test@noreply.com');
        insert convertedLead;
        LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        Database.LeadConvert leadConvert = new Database.LeadConvert();
        leadConvert.setLeadId(convertedLead.Id);
        leadConvert.setDoNotCreateOpportunity(true);
        leadConvert.setOwnerId(UserInfo.getUserId());
        leadConvert.setConvertedStatus(convertStatus.MasterLabel);
        Database.convertLead(leadConvert);
        Lead lead = new Lead(LastName = 'Test Convert Lead No. 2',
                              Email='test@noreply.com');
        if(convertedLead.Email != lead.Email){
            insert lead;
        }
    }
    // Test Method: findDuplicates
    public static testmethod void Test_findDuplicates(){
        //Lead lead = [SELECT ID,Name,Email From Lead WHERE IsConverted = false];
        Lead lead = [SELECT ID,Name,Email From Lead];
        System.Assert(LeadConversionController.findDuplicates(lead) != null);
    }
    // Test Method: convertLeadRecord
    public static testmethod void Test_convertLeadRecord(){
        Account acc =TestFactory.getAccount();
        Contact con =TestFactory.getContact();
         Contact cont = new Contact(
         lastname='test',
         AccountId=acc.Id);
        insert cont;
        Lead lead =TestFactory.getLead();
        //Lead lead = [SELECT ID,Name,Email,OwnerId From Lead WHERE IsConverted = true];
        //Lead lead = [SELECT ID,Name,Email,OwnerId From Lead];
        //Alternate_Email__c alternateEmail = (Alternate_Email__c)System.JSON.deserialize(LeadConversionController.findDuplicates(lead).get('alternateEmail'), Alternate_Email__c.class);
        Alternate_Email__c alternateEmail= new Alternate_Email__c(
            Alternate_Email_Address__c = 'abc@gmail.com',
            Contact_Name__c = cont.Id,
            Active__c = true,
            Lead_name__c =lead.id
        );
        insert alternateEmail;
        string accountid = alternateEmail.Contact_Name__r.AccountId;
        string contactid = alternateEmail.Contact_Name__c;
        string leadid = lead.Id;
        string ownerId = lead.OwnerId;
        System.Assert(LeadConversionController.convertLeadRecord(accountid, contactid, leadid,ownerId) != '');
    }
    // Test Method: mergeLeadRecords
    public static testmethod void Test_mergeLeadRecords(){
        Lead masterlead = new Lead(LastName='Test Merge Lead #1',Email = 'test@noreply1.com');
        insert masterlead;
        Lead duplicateLeadNo1 = new Lead(LastName='Test Merge Lead #2',Email = 'test@noreply12.com');
        Lead duplicateLeadNo2 = new Lead(LastName='Test Merge Lead #3',Email = 'test@noreply13.com');
        List<Lead> duplicateLeads = new List<Lead>{duplicateLeadNo1,duplicateLeadNo2};
            insert duplicateLeads;
        string duplicateleadstring = JSON.serialize(duplicateLeads);
        System.Assert(LeadConversionController.mergeLeadRecords(masterlead, duplicateleadstring) != '');
    }
}
I'm new in test class plese help me below code to write test class
public class FindProject {
   public Id OppObj{get;set;}
    public string Accname {get;set;}
    public string ReciName {get;set;}
    public string ProjectName;
    public opportunity objopp{
        get{
           objopp=[Select id,name,Account.Name,Owner.Name,Amount from opportunity where id=:OppObj limit 1]; 
        return objopp;
        }set;
    }
    public OpportunityLineItem objPro{
        get{
            objPro=[Select id,Projects__r.name,Start_Date__c from OpportunityLineItem where opportunity.id=:OppObj limit 1];
            return objPro;
        }set;
    }
    
    public Project__c proobj{
        get{
        ProjectName=[Select id,Projects__r.name from OpportunityLineItem where opportunity.id=:OppObj limit 1].Projects__r.name;
        proobj=[Select id,Program_Manager__r.name from Project__c where name=:ProjectName];
        return proobj;
        }set;
    }
}

Test Class:
@isTest
public class FindProjectTest {

    @isTest
    public static void testDataSetup(){
         Product2 prod = new Product2(Name = 'Laptop X200', Family = 'Hardware');
        insert prod;
        
        Id pricebookId = Test.getStandardPricebookId();
        
        PricebookEntry standardPrice = new PricebookEntry(Pricebook2Id = pricebookId, 
                                                          Product2Id = prod.Id, 
                                                          UnitPrice = 10000, 
                                                          IsActive = true);
        insert standardPrice;
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
        PricebookEntry customPrice = new PricebookEntry(Pricebook2Id = customPB.Id, 
                                                        Product2Id = prod.Id, 
                                                        UnitPrice = 12000, 
                                                        IsActive = true);
        insert customPrice;
        Account acc = new Account(name='Test Account');
        insert acc;
        opportunity opp = new opportunity(name='Test Opportunity', 
                                          AccountId=acc.id,
                                          CloseDate =Date.newInstance(2016, 12, 9),
                                          stageName='Closed Lost',
                                          ForecastCategoryName='Pipeline',
                                          PaymentTerms__c='Net 30',
                                          type='New Business',
                                          Amount=5676,
                                          Pricebook2Id=customPB.Id
                                         );
        insert opp;
        
        OpportunityLineItem oppLineItem = new OpportunityLineItem(OpportunityId=opp.id,
                                                                  TotalPrice =664557,
                                                                  End_Date__c=Date.newInstance(2016, 12, 9),
                                                                  Quantity =56,
                                                                  PricebookEntryId = customPrice.Id);
        insert oppLineItem;
        
         FindProject obj = new FindProject();
        opportunity objopp = obj.objopp;
        OpportunityLineItem objPro = obj.objPro;
        
       
    }
    
}

​​​​​​​
public with sharing class OpportunitylistViewCom {
    @AuraEnabled
    public static List<OpportunityLineItem> getOpportunityLineItem(Id accountId,String sortField, boolean isAsc){
        String query = 'Select id,Opportunity.Name,Opportunity.Account.name,Opportunity.RecordType.Name,Opportunity.type,Opportunity.Amount,Opportunity.StageName,Opportunity.Parent_Asset__r.InstallDate,Product_Name__c,UnitPrice,TotalPrice,ListPrice,End_Date__c,Related_To__c ';
            query += 'From OpportunityLineItem where Opportunity.AccountId =:accountId';
        if (sortField != '') {
            query += ' order by ' + sortField;
            if (isAsc) {
                query += ' asc';
            } else {
                query += ' desc';
            }
        }
        list <OpportunityLineItem> oppList1;
        try {
            oppList1 = Database.query(query);
            List < OpportunityLineItem > oppList = new List < OpportunityLineItem > ();
            for (OpportunityLineItem c: oppList1) {
                oppList.add(c);
            }
            return oppList;
        } 
        catch (Exception ex) {
            // for handle Exception
            return null;
        }
    }
   
    @AuraEnabled
    public static list < Attachment > fetchopportunity(Id accountId) {
        set<ID> oppIDs = new set<ID>();
        for(Opportunity opp :[Select id from opportunity where AccountId=:accountId]){
            oppIDs.add(opp.id);
        }
        list < Attachment > returnoppList = new List <Attachment> ();
        List < Attachment > lstopp = [select id,name,LastModifiedDate,CreatedBy.name,Parent.Name, Owner.Name, BodyLength from Attachment where ParentId IN:oppIDs];
        for (Attachment c: lstopp) {
            returnoppList.add(c);
        }
        return returnoppList;
    }
}

 

Lightning Component
<aura:component controller="membershipOpportunityViewCMP_controller" implements="flexipage:availableForAllPageTypes,force:hasRecordId" access="global" >
	
    <aura:attribute name="foundationName" type="Sobject"/>
    <aura:attribute name="fields" type="String[]" default="['Comment__c']" />
    <aura:attribute name="foundationId" type="String"/>
    <aura:handler event="c:foundationName" action="{!c.foundationId}"/>
    
    <lightning:notificationsLibrary aura:id="notifLib" />
	<lightning:card title="{!v.foundationName.Name +' Comment'}">
        <lightning:recordForm recordId="{!v.foundationId}" 
                              objectApiName="Project__c"
                              fields="{!v.fields}"
                              columns="1"
                              mode="view"	
                              onsuccess="{!c.handleSuccess}"
        					  onerror="{!c.handleError}"/>    
    </lightning:card>
</aura:component>
JS Controller
({
    
    handleSuccess: function (cmp, event, helper) {
        cmp.find('notifLib').showToast({
            "title": "Record updated!",
            "message": "The record "+ event.getParam("id") + " has been updated successfully.",
            "variant": "success"
        });
    },

    handleError: function (cmp, event, helper) {
        cmp.find('notifLib').showToast({
            "title": "Something has gone wrong!",
            "message": event.getParam("message"),
            "variant": "error"
        });
    }
)}

Please help me I'm stuck there I'm new in lightning component
 
I'm stuck in error when validating changeset in production when in run test there is test coverage 89% please help me on that
Apex Code
public void finish(Database.BatchableContext bc){
        string emailbody = '' ;
            List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.saveAsActivity = false;
            mail.toAddresses = new String[] {emailAdd};
            mail.setSenderDisplayName('Marketing Lead Error');
            mail.setSubject('Adding Campaign Memeber');
            emailbody = 'Hi '+userName +',<br/><br/> Error occured while adding Campaign Member. Please visit <a href="' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + err.ID +'">this link</a> for more information';
            mail.setHtmlBody(emailbody);
            mails.add(mail);
            Messaging.sendEmail(mails);
            
        }
    }

handler :
global class AddCampaignMemberEmailHandler implements Messaging.InboundEmailHandler {
    Map < String ,Integer> headersMap = new Map < String ,Integer>();
    //integer abc = 1/0;
    Set<String> emailset =  new Set<String>();
    List<CampaignMember> cm = new List<CampaignMember>(); 
    Map<String,Id> campNameVsId = new  Map<String,Id>();
    public Map<string,integer> fieldNumberMap  = new Map<string,integer> ();
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        system.debug('Inbound Email class invoked'); //Added
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        Messaging.InboundEmail.BinaryAttachment[] tAttachments = email.binaryAttachments;
        String csvAsString = '';
        string strUserName = email.plainTextBody.substringBefore('\n');
        List<User> lstUser = new List<User>();
        string strEmail='';
        string UserName ='';
        lstUser= [SELECT Id,Email,name
                            FROM User 
                            WHERE Name = : strUserName 
                            LIMIT 1];
        system.debug('Name'+lstUser);
        if(lstUser.size()>0){
           strEmail = lstUser[0].Email; 
           UserName = lstUser[0].name;
         }
        for(Messaging.InboundEmail.BinaryAttachment btt: tAttachments){
            if (btt.filename.endsWithIgnoreCase('.csv')) {
                system.debug('before ' +btt.body.toString() );
                
                csvAsString =btt.body.toString() ;//blobToString(btt.body,'UTF-8');//btt.body.toString();
                System.debug('csvAsString' +csvAsString);
                String row = csvAsString.subString(0, csvAsString.indexOf('\n'));
                csvAsString = csvAsString.subString(csvAsString.indexOf('\n') + '\n'.length(),csvAsString.length());
                System.debug('row :' +row);
                getHeader(row);   
                System.debug('fieldNumberMap>>>>>>' +fieldNumberMap);
                  AddCampaignMemberBatch addcamp= new AddCampaignMemberBatch(csvAsString,fieldNumberMap,tAttachments[0].body,strEmail,btt.fileName,UserName); //Updated by pratik With User Mail id

                Database.executeBatch(addcamp,200); 
            }
        }
        return result;
    }
    
    private void getHeader(string row){
        string[] csvFieldNames = row.split(',');
        System.debug('csvFieldNames' +csvFieldNames);
        for (Integer i = 0; i < csvFieldNames.size(); i++) {
            csvFieldNames[i] = csvFieldNames[i].remove('"');
            fieldNumberMap.put(csvFieldNames[i].trim(), i);
            System.debug('fieldNumberMap' +fieldNumberMap);
        }
    }
    
    public static String blobToString(Blob input, String charset){
        final String hex = EncodingUtil.convertToHex(input);
        final Integer size = hex.length() >> 1;
        final List<String> bytes = new String[size];
        
        for (Integer i = 0; i < size; ++i) {
            bytes.set(i, hex.mid(i << 1, 2));
        }
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), charset);
    }
}

Test class :
@istest
public class AddCampaignMemberEmailHandlerTest {
    
    public static void sendEmail(String str){
        
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
        Messaging.InboundEmail.BinaryAttachment inboundAttachment = new Messaging.InboundEmail.BinaryAttachment();
        
        email.subject = 'testsub';
        email.fromAddress = 'test@gmail.in';
        email.plainTextBody = ('Pratik D');   //Added
        email.toAddresses =new String[] {'pratikd@proximabiz.com'};
        inboundAttachment.body = blob.valueOf(str);
        inboundAttachment.fileName = 'Email_Attachment.csv';
        
        
        email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { inboundAttachment }; 
            
            // create an instance of the EmailToSalesForce class and test it with the data in the testMethod
            AddCampaignMemberEmailHandler  addcampaignHandler = new AddCampaignMemberEmailHandler();
        addcampaignHandler.handleInboundEmail(email, env ); 
        
        
    }
    
    
    public static testMethod void LeadInsert(){
        string str = 'Campaign Name,First Name,Last Name,Email Address,Job Title,Company,Street,City,State,Country,Zip,Linkedin Id,Github Id,Phone,Industry,Lead Source,Lead Source Detail,Notes \n'
            +'TestCampaign,Jubbi,Pearce,sneh@gmail.com,PM,Splunk,,Plano,Texas,USA,,zbpears,,,Software,,,Tests notes \n'
            +'TestCampaign,Julia,Pearce,jul@sp.com,PM,Test,,Plano,Texas,USA,,zbpears,,,Software,,,"Tests notes" \n'
            +'TestCampaign,TestData,Pearce,hal.jordan@example.com,PM,Test,,Plano,Texas,USA,,zbpears,,,Software,,,"Tests notes" \n';
        
        
        TestFactory.getAccount();
        TestFactory.getContact();
        TestFactory.getCampaign();
        TestFactory.getUser();
        //TestFactory.getCampaignMember();
        Test.startTest();
        sendEmail(str);
        Test.stopTest();
        System.AssertEquals(2,[Select id From Lead].size() );
        
        
        
    }
    
    Public static testMethod void AlreadyMember(){
        string str = 'Campaign Name,First Name,Last Name,Email Address,Job Title,Company,Street,City,State,Country,Zip,Linkedin Id,Github Id,Phone,Industry,Lead Source,Lead Source Detail,Notes \n'
            +'TestCampaign,Jubbi,Pearce,jb@test.org,PM,Splunk,,Plano,Texas,USA,,zbpears,,,Software,,,"Tests ,notes" \n'
            +'TestCampaign,Julia,Pearce,jul@sp.com,PM,Test,,Plano,Texas,USA,,zbpears,,,Software,,,"Tests,notes" \n'
            +'TestCampaign,TestData,Pearce,hal.jordan@example.com,PM,Test,,Plano,Texas,USA,,zbpears,,,Software,,,"Tests notes" \n';
        
        
        TestFactory.getAccount();
        TestFactory.getContact();
        TestFactory.getCampaign();
        TestFactory.getCampaignMember();
        TestFactory.getUser();
        Test.startTest();
        sendEmail(str);
        Test.stopTest();
        System.assertEquals(2,[Select ContactId From CampaignMember WHERE ContactId != null].size());
    }
    
    public static testMethod void Errolog(){
        //Sending Wrong Email 
        string str = 'Campaign Name,First Name,Last Name,Email Address,Job Title,Company,Street,City,State,Country,Zip,Linkedin Id,Github Id,Phone,Industry,Lead Source,Lead Source Detail,Notes \n'
            +'TestCampaign,Jubbi,Pearce,jb@test.com,PM,Splunk,,Plano,Texas,USA,,zbpears,,,Software,,,Tests notes \n'
            +'TestCampaign,Julia,Pearce,j@test.com,PM,Test,,Plano,Texas,USA,,zbpears,,,Software,,,"Tests notes" \n'
            +'TestCampaign,TestData,Pearce,b@test.com,PM,Test,,Plano,Texas,USA,,zbpears,,,Software,,,"Tests notes" \n';
        
        TestFactory.getCampaign();
       Test.startTest(); 
        sendEmail(str);
      Test.stopTest();  
        
    }
    
    
    
    
    
}



 
trigger UpdateOppOwner on Project__c (before update, after update) {
    List<Opportunity> oppList = new List<Opportunity>();
    Map<Id,List<Opportunity>> OpportunityMap = new Map<Id,List<Opportunity>>();
    
    if(Trigger.isUpdate){
         
        for(Opportunity opp : [SELECT Id,Project__r.id,StageName,Type FROM Opportunity WHERE Project__r.id IN :Trigger.newMap.keySet()])
        {
            if(!OpportunityMap.containskey(opp.Project__c)){
                OpportunityMap.put(opp.Project__r.id,new List<Opportunity>());
            }
            OpportunityMap.get(opp.Project__r.id).add(opp);
            system.debug('OpportunityMap'+OpportunityMap);
        }
    }
    
               for(Project__c c:Trigger.new) {
                   
                   
                   if(OpportunityMap.get(c.Id) != Null){
                       for(Opportunity opp : OpportunityMap.get(c.Id)){ //get all contacts under account and update.
                           if(opp.StageName != 'Closed Won' || opp.StageName != 'Closed Lost'){
                               if(opp.Type == 'Renewal'){
                                   opp.OwnerId = c.Renewal_Owner__c;
                                   oppList.add(opp);
                                   system.debug('oppList'+oppList);
                               }else{
                                   opp.OwnerId = c.Opportunity_Owner__c;
                                   oppList.add(opp);
                                   system.debug('oppList'+oppList);
                               }
                           }
                           
                          
                       }
                   }
                   
               }
               
          
               try {
                   upsert oppList;
               } catch (Exception ex) {
                   System.debug('Could not update Last Survey Sent field on Account with cause: ' + ex.getCause());}
               }
Test Class
@isTest
public class TestUpdateOppOwner {
    
    static testMethod void testMethod1()
    {
        Account objacc = new Account(
            Name = 'Test'
        );
        insert objacc;
        
        Project__c objPro = new Project__c(
            Name = 'Test Demo',
            Type__c = 'Membership',
            Project_Type__c = 'Project',
            Category__c = 'Incorporated'           
        );
         insert objPro;
        
        Opportunity objOpp = new Opportunity(
            Name = 'Demo',
            AccountId = objacc.Id,
            CloseDate= System.today(),
            StageName = '3.Quote',
            ForecastCategoryName = 'Pipeline',
            PaymentTerms__c = 'Net 30',
            Project__c =objPro.id 
        );
        
       
       
        insert objOpp;
        
        
    }
    
}

 
Can is it possible when we insert CSV lead file using apex class if the insertion in fail the show the which CSV file row fails when inserting a record in Salesforce and store row number in salesforce object
Kill the process running on port 1717 or use a custom connected app and update OauthLocalPort in the sfdx-project.json file.
class :
public class RevertQuantityTriggerHandler {
    //public static Boolean runOnce = true;
    //RevertQuantityHelperClass helpobj = new RevertQuantityHelperClass();
    public List<Inventory__c> lstofinventory = new List<Inventory__c>([select id,Name,Inventory_Name__c,Account__c,Quantity__c,Product__c from Inventory__c]);
    Double difference;
    public double oldTotalQuantity, newTotalQuantity;
    
    public void onBeforeDelete(List<Cost_Price__c> listofcostprice)
    {
        
        for(Cost_Price__c obj : listofcostprice)
        {
            System.debug('cost Price --->'+obj);
            for(Inventory__c inventobj : lstofinventory)
            {
                
                if(obj.Product_From_Inventory__c == inventobj.id)
                {
                    inventobj.Quantity__c += obj.Quantity__c;
                }
                
            }
            update lstofinventory;
        }
    }
    
    public void onAfterUpdate(List<Cost_Price__c> listofcostprice, List<Cost_Price__c> triggerold)
    {
     	for(Cost_Price__c cp:listofcostprice )
        {
            system.debug('listofcostprice'+listofcostprice);
            newTotalQuantity=cp.Quantity_Per_Container__c*cp.Total_of_Containers__c; 
        }
        for(Cost_Price__c cp:triggerold )
        {
            system.debug('triggerold'+triggerold);
            oldTotalQuantity=cp.Quantity_Per_Container__c*cp.Total_of_Containers__c; 
        }
        
        if(triggerold[0].Product_From_Inventory__c != null)
        {
            
            if((oldTotalQuantity != null || oldTotalQuantity != 0) && (newTotalQuantity != null || newTotalQuantity != 0) )
            {
                //changed this if condition
                if(listofcostprice[0].Product_From_Inventory__c==triggerold[0].Product_From_Inventory__c)
                {
                    
                    for(Cost_Price__c obj : listofcostprice)
                    {
                        
                        if(listofcostprice[0].id ==  triggerold[0].id)
                        {
                            system.debug('newTotalQuantity'+newTotalQuantity);
                            system.debug('oldTotalQuantity'+oldTotalQuantity);
                            if(newTotalQuantity > oldTotalQuantity)
                            {
                                
                                //Calculate difference between new total quantity and old total quantity
                                difference = newTotalQuantity - oldTotalQuantity;
                                system.debug('diff --->'+difference);
                                for(Inventory__c inventobj : lstofinventory)
                                {
                                    system.debug('diff inside for --->'+difference);
                                    if(inventobj.Id == listofcostprice[0].Product_From_Inventory__c)
                                    {
                                        system.debug('diff in innerif --->'+difference);
                                        system.debug('invent id --->'+inventobj.Id);
                                        system.debug('listof cp id --->'+listofcostprice[0].Product_From_Inventory__c);
                                        inventobj.Quantity__c -= difference;
                                        system.debug('Updated invent-->'+inventobj.Quantity__c);
                                    }
                                }
                            }
                            
                            if(newTotalQuantity < oldTotalQuantity) 
                            {
                                system.debug('inside else');
                                
                                //Calculate difference between new total quantity and old total quantity
                                difference =  oldTotalQuantity - newTotalQuantity;
                                for(Inventory__c inventobj : lstofinventory)
                                {
                                    system.debug('diff inside for --->'+difference);
                                    if(inventobj.Id == listofcostprice[0].Product_From_Inventory__c)
                                    {
                                        system.debug('diff in inner if --->'+difference);
                                        system.debug('invent id --->'+inventobj.Id);
                                        system.debug('listof cp id --->'+listofcostprice[0].Product_From_Inventory__c);
                                        inventobj.Quantity__c += difference;
                                        system.debug('Updated invent-->'+inventobj.Quantity__c);
                                    }
                                }
                            }
                        }
                    }
                    update lstofinventory;
                    
                }
                
                
                
                else
                {
                    System.debug('1--->Inside Primium Else');
                    
                    system.debug('new total quantity '+newTotalQuantity);
                    system.debug('old total quantity '+oldTotalQuantity);
                    for(Cost_Price__c obj : listofcostprice)
                    {
                        
                        if(listofcostprice[0].id ==  triggerold[0].id)
                        {
                            system.debug('3---->listofcostprice[0].id ==  triggerold[0].id');
                         
                            
                            if(newTotalQuantity != oldTotalQuantity)
                            {
                             
                              
                                for(Inventory__c inventobj : lstofinventory)
                                {
                                    
                                    
                                    if(inventobj.Id == listofcostprice[0].Product_From_Inventory__c)
                                    {
                                        
                                        inventobj.Quantity__c -= newTotalQuantity;  //changes
                                        
                                        system.debug('8---->Updated invent-->'+inventobj.Quantity__c);
                                    }
                                    if(inventobj.id == triggerold[0].Product_From_Inventory__c)
                                    {
                                        inventobj.Quantity__c += oldTotalQuantity;      
                                        
                                        system.debug('9---->Updated invent old-->'+inventobj.Quantity__c);
                                    }
                                    
                                }
                                
                            }
                            
                            else if(newTotalQuantity == oldTotalQuantity)
                            {
                                for(Inventory__c inventobj : lstofinventory)
                                {
                                    if(inventobj.Id == listofcostprice[0].Product_From_Inventory__c)
                                    {
                                        
                                        inventobj.Quantity__c -= newTotalQuantity;
                                        
                                        system.debug('10---->Updated invent-->'+inventobj.Quantity__c);
                                    }
                                    if(inventobj.Id == triggerold[0].Product_From_Inventory__c)
                                    {
                                        inventobj.Quantity__c += newTotalQuantity;     
                                        
                                        system.debug('11---->Updated invent old-->'+inventobj.Quantity__c);
                                    }
                                    
                                }
                               
                            }
                        }
                    }
                    update lstofinventory; 
                   
                }  
            }
        }
    }
}


Test Class:
@isTest 
public class TestCostPriceRevertQuantityTrigger 
{
    public static testmethod void runTest()
    {
        //create object of handler class..
       
       Id RecordTypeIdacc = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Logistic').getRecordTypeId();
        system.debug('Record type-->' +RecordTypeIdacc );
        Account objacc = new Account();
        
        objacc.Account_Company_Name__c = 'Chetna';
        objacc.Type_of_Logistic__c = 'Warehousing';
        objacc.Name = 'ABC';
        objacc.Worked_By__c	= 'Chetna';
        objacc.Type ='Bank';
        objacc.CurrencyIsoCode = 'EUR';
        objacc.Business_Entity__c = 'TRADEASIA INTERNATIONAL INDIA';
        objacc.RecordTypeId = RecordTypeIdacc;
        insert objacc ;
        
        //Create Product
        Product2 objpro = new Product2();
        objpro.Name = 'Sodium';
        objpro.CurrencyIsoCode = 'EUR'; 
        insert objpro;
        
        
        // Create Port
        Port__c pt = new Port__c();
        pt.Name = 'Chetna';
        insert pt;
        
        //Create Inventory1..
        Inventory__c inv1 = new Inventory__c();
        inv1.Account__c=objacc.id;
        inv1.Quantity__c=10;
        inv1.Product__c = objpro.id;
      	insert inv1;
        system.debug('inv1-->'+inv1);
        
        //Create Inventory2..
        	Inventory__c inv2 = new Inventory__c();
			inv2.Account__c=objacc.id;
			inv2.Quantity__c=10;
			inv2.Product__c = objpro.id;
			insert inv2;
			system.debug('inv2-->'+inv2);
        
        
        /*List<Inventory__c> lstinv1 = new List<Inventory__c>();
			lstinv1.add(inv1);
			List<Inventory__c> lstinv2 = new List<Inventory__c>();
			lstinv2.add(inv2);*/
        
        
        
        //Create Opportunity...
        Opportunity opp = new Opportunity ();
        opp.Name = 'Chetna';
        opp.AccountId = objacc.Id;
        opp.CurrencyIsoCode = 'INR';
        opp.ForecastCategoryName = 'Commit';
        opp.StageName = 'Proforma Invoice';
        opp.Sub_Stage__c = 'Issued';
        opp.CloseDate = date.today();
        opp.Worked_by__c = 'Chetna';
        opp.Product_Name__c = objpro.Id;
        opp.Origin__c = 'O11';
        opp.Description_of_Goods__c = 'Good';
        opp.Packaging_Details__c = 'P11';
        opp.Quantity__c = 10;
        opp.H_S_Code__c = 'H11';
        opp.Total_of_Containers__c = 5;
        opp.Container_Size__c = 'Trucking';
        opp.Port_of_Discharge__c = pt.Id;
        opp.Business_Entity__c = 'TRADEASIA INDIA';
        insert opp;
        
        //Create Cost Price...
         List<Cost_Price__c> lstcostold = new List<Cost_Price__c>();
        Cost_Price__c cp = new Cost_Price__c();
        cp.Opportunity__c = opp.Id;
        cp.Business_Entity__c ='TRADEASIA INDIA';
        cp.Sub_Entity_Tradeasia__c = objacc.id;
        cp.Status_Deal__c = '1st Nego';
        cp.STATUS__c = 'EXECUTED';
        cp.Product_From_Inventory__c = inv1.Id;
        cp.UOM__c = 'KGs';
        cp.Quantity__c = 22.6;
        cp.Quantity_Per_Container__c = 10;
        cp.Total_of_containers__c = 8;
        cp.Worked_By__c = 'Chetna';
        cp.Country_of_Final_Destination__c = 'India';
        lstcostold.add(cp);
        insert lstcostold;
        system.debug('lstcostold'+lstcostold);
        List<Cost_Price__c> lstcostnew = new List<Cost_Price__c>();
        cp.Quantity_Per_Container__c = 10;
        cp.Total_of_containers__c = 7;
        lstcostold.add(cp);
        //update lstcostold;
        //system.debug('lstcostnew'+lstcostnew);*/
       
        //new list
        //List<Cost_Price__c> lstcostnew = new List<Cost_Price__c>();
        
        //update cost price
        cp.Quantity_Per_Container__c = 10;
        cp.Total_of_containers__c = 9;
        cp.Product_From_Inventory__c = inv2.Id;
       // update cp;
        lstcostnew.add(cp);
        
       
        Test.startTest();
        
        RevertQuantityTriggerHandler obj = new RevertQuantityTriggerHandler();
     
        obj.onBeforeDelete(lstcostold);
        system.debug('lstcostnew'+lstcostnew);
        system.debug('lstcostold'+lstcostold);
        obj.onAfterUpdate(lstcostnew,lstcostold);
        
        Test.stopTest();
        
    }
}

 
Apex Trigger:
trigger CreateClientTenant on Lease_Summary__c (after update) {
    integer i = 1;
    List<Tenant__c> lstTenant = new List<Tenant__c>();
    List<Client__c> lstClient = new List<Client__c>();  
    for(Lease_Summary__c objLease : trigger.new){
        system.debug('objLease.Rent_start_date__c'+objLease.Rent_start_date__c);
        If(objLease.Rent_start_date__c == DATE.TODAY()){
            Tenant__c objtenant = new Tenant__c();
            objtenant.Rent_Start_Date__c = objLease.Rent_Start_Date__c;
            objtenant.Lease_Summary__c = objLease.id;
            lstTenant.add(objtenant);
            
        }
        system.debug('lstTenant'+lstTenant);
        insert lstTenant;
     }
}

 
public class contactPaginationController {
    //variable used in page.
    Public Integer size{get;set;}
    Public Integer noOfRecords{get; set;}
    public List<SelectOption> paginationSizeOptions{get;set;}
    public static final Integer QUERY_LIMIT = 10000;
    public static final Integer PAGE_SIZE = 5;
    
    public List <WrapperClass> wrapperRecordList{get;set;}
    Map<Id, WrapperClass> mapHoldingSelectedRecords{get;set;}
    
    //constructor calling init method.
    public contactPaginationController(){
        mapHoldingSelectedRecords = new Map<Id, WrapperClass>();
        init();
        
    }
    
    //Init method which queries the records from standard set controller.
    public void init() {
        wrapperRecordList = new List<WrapperClass>();
        for (Account cont : (List<Account>)setCon.getRecords()) {
            if(mapHoldingSelectedRecords != null && mapHoldingSelectedRecords.containsKey(cont.id)){
                wrapperRecordList.add(mapHoldingSelectedRecords.get(cont.id));
                
            }
            else{
                wrapperRecordList.add(new WrapperClass(cont, false));
            }
        }
    }
    
    /** Instantiate the StandardSetController from a query locater*/
    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Id,Name, Phone FROM Account LIMIT : QUERY_LIMIT ]));
                
                // sets the number of records to show in each page view
                setCon.setPageSize(PAGE_SIZE);
            }
            return setCon;
        }
        set;
    }
    
    /** indicates whether there are more records after the current page set.*/
    public Boolean hasNext {
        get {
            return setCon.getHasNext();
        }
        set;
    }
    
    /** indicates whether there are more records before the current page set.*/
    public Boolean hasPrevious {
        get {
            return setCon.getHasPrevious();
        }
        set;
    }
    
    /** returns the page number of the current page set*/
    public Integer pageNumber {
        get {
            return setCon.getPageNumber();
        }
        set;
    }
    
    /** return total number of pages for page set*/
    Public Integer getTotalPages(){
        Decimal totalSize = setCon.getResultSize();
        Decimal pageSize = setCon.getPageSize();
        Decimal pages = totalSize/pageSize;
        return (Integer)pages.round(System.RoundingMode.CEILING);
    }
    
    /** returns the first page of the page set*/
    public void first() {
        updateSearchItemsMap();
        setCon.first();
        init();
    }
    
    /** returns the last page of the page set*/
    public void last() {
        updateSearchItemsMap();
        setCon.last();
        init();
    }
    
    /** returns the previous page of the page set*/
    public void previous() {
        updateSearchItemsMap();
        setCon.previous();
        init();
    }
    
    /** returns the next page of the page set*/
    public void next() {
        updateSearchItemsMap();
        setCon.next();
        init();
    }
    
    //This is the method which manages to remove the deselected records, and keep the records which are selected in map.
    private void updateSearchItemsMap() {
        for(WrapperClass wrp : wrapperRecordList){
            if(wrp.isSelected){
                mapHoldingSelectedRecords.put(wrp.contactRecord.id, wrp);
            }
            if(wrp.isSelected == false && mapHoldingSelectedRecords.containsKey(wrp.contactRecord.id)){
                mapHoldingSelectedRecords.remove(wrp.contactRecord.id);
            }
        }
    }
    
    //wrapper class being used for checkbox showing.
    public class WrapperClass {
        public Boolean isSelected {get;set;}
        public Account contactRecord {get;set;}
        public WrapperClass(Account contactRecord, Boolean isSelected) {
            this.contactRecord = contactRecord;
            this.isSelected = isSelected;
        }
    }
}
 
<apex:page controller="contactPaginationController" docType="html-5.0" tabStyle="Account">
   <apex:sectionHeader title="Contact" subtitle="Contact Pagination" />
    <apex:form id="theForm">
      <apex:pageBlock title="All Contacts" rendered="{!wrapperRecordList.size!=0}" id="pbId" >
        <apex:pageBlockTable value="{!wrapperRecordList}" var="cont">
           <apex:column headerValue="Select">
             <apex:inputCheckbox value="{!cont.isSelected}"/>
           </apex:column>
           <apex:column headerValue="Name">
             <apex:outputField value="{!cont.contactRecord.name}"/>
           </apex:column>
           
           <apex:column headerValue="Phone">
            <apex:outputField value="{!cont.contactRecord.Phone}"/>
           </apex:column>
       </apex:pageBlockTable>
          
          <apex:repeat value="{!mapHoldingSelectedRecords}" var="maper">
           <apex:outputText value="{!cont}" />
        <apex:outputText value="{!mapHoldingSelectedRecords[maper]}" />
       </apex:repeat>
 
 <!-- Action Buttons visible on bottom of page for pagination -->
       <apex:outputPanel style="text-align:center;" layout="block">
          <apex:commandButton value="First" reRender="pbId" action="{!first}" disabled="{!NOT(hasPrevious)}" status="paginationStatus"/>
          <apex:commandButton value="Previous" rerender="pbId" action="{!previous}" disabled="{!NOT(hasPrevious)}" status="paginationStatus"/>&nbsp;Page {!pageNumber} of {!totalPages}&nbsp;
          <apex:commandButton value="Next" rerender="pbId" action="{!next}" disabled="{!NOT(hasNext)}" status="paginationStatus"/>
          <apex:commandButton value="Last" rerender="pbId" action="{!last}" disabled="{!NOT(hasNext)}" status="paginationStatus"/>
          <apex:actionStatus id="paginationStatus">
             <apex:facet name="start">
                 Please wait...<img src="/img/loading32.gif" style="width: 18px;"/>
             </apex:facet>
          </apex:actionStatus>
       </apex:outputPanel>
 </apex:pageBlock>
 </apex:form>
</apex:page>
Can Any One Help..

 
Visualforce Page
<apex:page controller="thousandLimit">
    <apex:form>
        <apex:pageBlock >
            <apex:repeat value="{!thousandBlocks}" var="block">
                
            <apex:pageBlockTable value="{!block}" var="c">
               
            <apex:column value="{!c.cases.name}"/>
                            
            </apex:pageBlockTable>
        </apex:repeat>
        </apex:pageBlock>
    </apex:form>
</apex:page>

controller
public class thousandLimit {
 private List<limitWrapper> thousandBlocks = new List<limitWrapper>();
   
    private final integer listLimit;
   
    public thousandLimit()
    {
        listLimit = 1000;
    }
   
    public List<limitWrapper> getthousandBlocks()
    {
        thousandBlocks = new limitWrapper[]{};
       
        integer counter = 0;
        integer loopCount = 0;
        boolean Selected =true;
        List<Account> tmpcase = new List<Account>();
       
        for(Account c:[select id,name from Account])
        {
            if(counter < listLimit)
            {
                tmpcase.add(c);
                counter++;
            }
            else
            {
                loopCount++;
                thousandBlocks.add(new limitWrapper(tmpcase,Selected));
                tmpcase = new List<Account>();
                tmpcase.add(c);
                counter = 0;
            }           
        }
       
        if(thousandBlocks.size() == 0)
        {
            loopCount++;
            thousandBlocks.add(new limitWrapper(tmpcase,Selected));
        }
       
        return thousandBlocks;
    }
   
    public class limitWrapper
    {
        public List<Account> cases {get;set;}
         public boolean Selected {get;set;}
        //public integer blockNumber {get;set;}
        public limitWrapper(List<Account> accs, boolean i)
        {
            cases = accs;
            Selected = i;
        }
       
    }
}
Collection size 2,043 exceeds maximum size of 1,000  Error Face Any Solution
VisualForce Page :-

<apex:page standardController="Account"  tabstyle="account" sidebar="false" extensions="mergeAccount">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/datatables.min.js"> </script>
     <style> 
          
       
         .dataTables_wrapper .dataTables_paginate .paginate_button.current, .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover {
        color: white!important;
        border: 1px solid #cacaca;
        background-color: white;
        background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, white), color-stop(100%, gainsboro));
        background: -webkit-linear-gradient(top, white 0%, gainsboro 100%);
        background: -moz-linear-gradient(top, white 0%, gainsboro 100%);
        background: -ms-linear-gradient(top, white 0%, gainsboro 100%);
        background: -o-linear-gradient(top, white 0%, gainsboro 100%);
        border-radius: 7px;
        background: dodgerblue;
        }
        <!-- List View (DataTable CSS)-->
        
        .dataTable>tbody>tr:nth-child(even)>td, 
        .dataTable>tbody>tr:nth-child(even)>th {
        background-color: #e8e8e8 !important; 
        }
        
        .dataTable>tbody>tr:nth-child(odd)>td, 
        .dataTable>tbody>tr:nth-child(odd)>th {
        background-color: #d2deea!important; 
        }
        
        .header_styling{
        font-family:Raleway:200;
        background-color: #e1e1e1 !important ; 
        }
        
        .dataTables_length, .dataTables_filter, .dataTables_info, .dataTables_paginate {        
        padding: 3px;        
        }       

        
        
    </style>
 <apex:form id="dForm">
  <apex:pageBlock >
      
      <apex:pageBlockTable value="{!wrapAccountList}" var="a" id="d" styleclass="example" rendered="{!bolvar1}">
        <apex:column >
                        <apex:inputCheckbox value="{!a.selected}" >
                            <!-- <apex:actionSupport action="{!processSelected}"  event="onchange" />-->
                        </apex:inputCheckbox>
                    </apex:column>
        <apex:column value="{!a.acc.name}"/>
        <apex:column value="{!a.acc.type}" />
        <apex:column value="{!a.acc.phone}"/>
            </apex:pageBlockTable>
         <apex:commandButton value="Account Merge" action="{!nextButton}" reRender="dForm" rendered="{!bolvar1}"/>
        <br/>
             <apex:pageblock id="table" rendered="{!bolvar2}">
         choose master account&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    
            <apex:selectList value="{!SelectAccount}" size="1">                                 
                <apex:selectOptions value="{!lstSelectOption}"/>
                 
            </apex:selectList>
                <apex:commandbutton value="Get Selected" action="{!Selectedmaster}"  /> <br/>
                    
                </apex:pageblock>
         
                        
             
        </apex:pageBlock>   
                 
  </apex:form>
  <script>
    $('table.example').DataTable({
       
        "pagingType": "full_numbers"

        });
    </script>
</apex:page>


Controller :-

public class mergeAccount {
    
    public List<wrapAccount> wrapAccountList {get; set;}
    public List<wrapAccount> selectedAccounts{get;set;}
    public Boolean bolvar {get; set;}
    public Boolean bolvar1{get;set;}
    public Boolean bolvar2{get;set;} 
    public Boolean bolvar3{get;set;} 
    public String SelectAccount{get;set;}
    public Account objMasterAccount {get;set;}
    public List<SelectOption> lstSelectOption {get;set;}
    public String AccountId;
    public Account objAccount;
    public string AccountName ;
    public ID AccountID1;
    public List<Account> lstAccount = new List<Account>();
    public List<Account> lstAccount1 = new List<Account>();
    public mergeAccount(ApexPages.StandardController controller) {
        
        system.debug('lstAccount'+lstAccount);
        bolvar1 = true;
        bolvar2 = false;
        //objAccount= (Account)Controller.getRecord().id;
        system.debug('objAccount'+objAccount);
        
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap();
            String query='select id';
            for(String s : objectFields.keySet()) {
                if(s != 'Id'){
                    SObjectField test=objectFields.get(s); 
                    //system.debug('test' +test);
                    //if(test.getDescribe().isUpdateable()){ 
                    query += ', ' + s + ' ';
                }
                //}
            }
            
            query +=' FROM Account';
            System.debug(query);
            List<Account> lstAccount = new List<Account>();
            lstAccount = database.query(query);
            //System.debug(lstAccount);
            for(Account a: lstAccount) {
                wrapAccountList.add(new wrapAccount(a,bolvar));
                
                
            }
        }
    }
    
    public void getAccountNames() {
       lstSelectOption= new List<SelectOption>();
        lstSelectOption.add( new SelectOption('','--Select--'));
        for( wrapAccount wrapacc :  selectedAccounts) {
            lstSelectOption.add( new SelectOption(wrapacc.acc.Id,wrapacc.acc.name));
           system.debug('accOptions'+lstSelectOption);
        }   
    }
    
    public void nextButton(){
        selectedAccounts = new List<wrapAccount>();
        for(wrapAccount wrapAccountObj : wrapAccountList) {
            if(wrapAccountObj.selected == true) {
                selectedAccounts.add(new wrapAccount(wrapAccountObj.acc,wrapAccountObj.selected));  
            }
        }
        getAccountNames();
        bolvar1 = false;
        bolvar2 = true;
        
    }
    
    public PageReference  Selectedmaster(){
        objMasterAccount = new Account();
        objAccount = new Account();
        SobjectField[] fields =  Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap().values();
        System.debug(fields);
        for(wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id == SelectAccount) 
                objMasterAccount = wrapacc.acc;
            //AccountID1 = wrapacc.accId;
            system.debug('objMasterAccount'+objMasterAccount);
        }
        
        for( wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id != SelectAccount){
                for(SObjectField field:fields){  
                    if(field.getDescribe().isUpdateable()){   
                        system.debug('masterLead.get(field)'+objMasterAccount.get(field));
                        if(objMasterAccount.get(field)==null && wrapacc.acc.get(field)!=null ){     
                            objMasterAccount.put(field,wrapacc.acc.get(field));
                        }
                    }
                }
            }
        }
        update objMasterAccount;
        bolvar3 = false; 
        PageReference pageRef = new PageReference('/apex/PopUp');
        pageRef.setRedirect(true);
        return pageRef;
    }
    
    public PageReference ok(){
        PageReference pageRef = new PageReference('/001/o');
        pageRef.setRedirect(true);
        return pageRef; 
    }
    
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
        //public id accId {get;set;}
        public wrapAccount(Account a,Boolean bolvar) {
            acc = a;
            selected = bolvar;
            //accId = aId;
        }
    } 
}
Apex Class:

public class mergeAccount {
    
    public List<wrapAccount> wrapAccountList {get; set;}
    public List<wrapAccount> selectedAccounts{get;set;}
    public Boolean bolvar {get; set;}
    public Boolean bolvar1{get;set;}
    public Boolean bolvar2{get;set;} 
    public Boolean bolvar3{get;set;} 
    public String SelectAccount{get;set;}
    public Account objMasterAccount {get;set;}
    public List<SelectOption> lstSelectOption {get;set;}
    public String AccountId;
    public Account objAccount;
    public string AccountName ;
    public ID AccountID1;
    public List<Account> lstAccount = new List<Account>();
    public List<Account> lstAccount1 = new List<Account>();
    public mergeAccount(ApexPages.StandardController controller) {
        
        system.debug('lstAccount'+lstAccount);
        bolvar1 = true;
        bolvar2 = false;
        //objAccount= (Account)Controller.getRecord().id;
        system.debug('objAccount'+objAccount);
        
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap();
            String query='select id';
            for(String s : objectFields.keySet()) {
                if(s != 'Id'){
                    SObjectField test=objectFields.get(s); 
                    //system.debug('test' +test);
                    //if(test.getDescribe().isUpdateable()){ 
                    query += ', ' + s + ' ';
                }
                //}
            }
            
            query +=' FROM Account';
            System.debug(query);
            List<Account> lstAccount = new List<Account>();
            lstAccount = database.query(query);
            //System.debug(lstAccount);
            for(Account a: lstAccount) {
                wrapAccountList.add(new wrapAccount(a,bolvar));
                
                
            }
        }
    }
    
    public void getAccountNames() {
        system.debug('AccountId'+AccountId);
        /*AccountId=Apexpages.currentpage().getParameters().get('id');
        lstAccount1 =[Select id,name from Account where id =:AccountId];
        if(lstAccount1.size()>0)
        {
            AccountName =  lstAccount1[0].Name;
            AccountID1 = lstAccount1[0].id;
            system.debug('AccountName'+AccountName);
        }*/
        
        system.debug('AccountId'+AccountId);
        // selectedAccounts = new List<wrapAccount>();
        lstSelectOption= new List<SelectOption>();
        lstSelectOption.add( new SelectOption('','--Select--'));
        for( wrapAccount wrapacc :  selectedAccounts) {
            lstSelectOption.add( new SelectOption(wrapacc.acc.Id,wrapacc.acc.name));
            
            //lstSelectOption.add(new SelectOption(AccountID1,AccountName));
            system.debug('accOptions'+lstSelectOption);
        }
        
    }
    
    public void nextButton(){
        selectedAccounts = new List<wrapAccount>();
        
        for(wrapAccount wrapAccountObj : wrapAccountList) {
            if(wrapAccountObj.selected == true) {
                selectedAccounts.add(new wrapAccount(wrapAccountObj.acc,wrapAccountObj.selected));
                
            }
        }
        getAccountNames();
        bolvar1 = false;
        bolvar2 = true;
        
    }
    
    public PageReference  Selectedmaster(){
        objMasterAccount = new Account();
        objAccount = new Account();
        SobjectField[] fields =  Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap().values();
        System.debug(fields);
        for(wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id == SelectAccount)
                objMasterAccount = wrapacc.acc;
            //AccountID1 = wrapacc.accId;
            system.debug('objMasterAccount'+objMasterAccount);
        }
        for( wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id != SelectAccount){
                for(SObjectField field:fields){  
                    if(field.getDescribe().isUpdateable()){   
                        system.debug('masterLead.get(field)'+objMasterAccount.get(field));
                        if(objMasterAccount.get(field)==null && wrapacc.acc.get(field)!=null ){     
                            objMasterAccount.put(field,wrapacc.acc.get(field));
                        }
                    }
                }
            }
        }
        update objMasterAccount;
        bolvar3 = false; 
        PageReference pageRef = new PageReference('/apex/PopUp');
        pageRef.setRedirect(true);
        return pageRef;
    }
    
    public PageReference ok(){
        PageReference pageRef = new PageReference('/001/o');
        pageRef.setRedirect(true);
        return pageRef; 
    }
    
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
        //public id accId {get;set;}
        public wrapAccount(Account a,Boolean bolvar) {
            acc = a;
            selected = bolvar;
            //accId = aId;
        }
    } 
}



Test Class
@isTest
public class mergeAccountTest {
    
    public static testmethod void AccountMergeTest(){
        Map<string, schema.RecordTypeInfo> rtMap = Schema.SObjectType.Account.getRecordTypeInfosByName();
        Id VV=rtMap.get('VV').getRecordTypeId();
        Id MVS=rtMap.get('MVS - Remind A Pet').getRecordTypeId();
        Id VVR=rtMap.get('VVR').getRecordTypeId();
        Id VVANDVVR=rtMap.get('VV and VVR').getRecordTypeId();
        
        
        Account objAccount = new Account();
        objaccount.Name = 'Test';
        objaccount.RecordTypeId =VV;
        insert objAccount;
        
        PageReference pageRef = Page.PopUp;
        Test.setCurrentPage(pageRef);
        
        
        ApexPages.StandardController sc = new ApexPages.standardController(objAccount);
        mergeAccount controller = new mergeAccount(sc);
        Account objacc = new Account();
        Boolean selected = true; 
        controller.bolvar3 = true;
        controller.SelectAccount ='26551025862uiyty';
        
        mergeAccount.wrapAccount wrrap = new mergeAccount.wrapAccount(objacc,selected);
        
        
        controller.nextButton();
        controller.getAccountNames();
         PageReference objPageRef1 = controller.ok();
          for(mergeAccount.wrapAccount wrp : controller.selectedAccounts )
            {
                wrp.selected = true;
            }            
 
        PageReference objPageRef = controller.Selectedmaster();
       
    }
    
}
public class mergeAccount {
    
    public List<wrapAccount> wrapAccountList {get; set;}
    public List<wrapAccount> selectedAccounts{get;set;}
    public Boolean bolvar {get; set;}
    public Boolean bolvar1{get;set;}
    public Boolean bolvar2{get;set;} 
    public Boolean bolvar3{get;set;} 
    public String SelectAccount{get;set;}
    public Account objMasterAccount {get;set;}
    public List<SelectOption> lstSelectOption {get;set;}
    public String AccountId;
    public Account objAccount;
    public string AccountName ;
    public ID AccountID1;
    public List<Account> lstAccount = new List<Account>();
    public List<Account> lstAccount1 = new List<Account>();
    public mergeAccount(ApexPages.StandardController controller) {
    
        system.debug('lstAccount'+lstAccount);
        bolvar1 = true;
        bolvar2 = false;
        //objAccount= (Account)Controller.getRecord().id;
        system.debug('objAccount'+objAccount);
        
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap();
            String query='select id';
            for(String s : objectFields.keySet()) {
                if(s != 'Id'){
                SObjectField test=objectFields.get(s); 
                //system.debug('test' +test);
                //if(test.getDescribe().isUpdateable()){ 
                query += ', ' + s + ' ';
                }
                //}
            }
            
            query +=' FROM Account';
            System.debug(query);
            List<Account> lstAccount = new List<Account>();
            lstAccount = database.query(query);
            //System.debug(lstAccount);
            for(Account a: lstAccount) {
                wrapAccountList.add(new wrapAccount(a,bolvar,AccountID1));
                
                
            }
        }
    }
     
    public void getAccountNames() {
        system.debug('AccountId'+AccountId);
        AccountId=Apexpages.currentpage().getParameters().get('id');
        lstAccount1 =[Select id,name from Account where id =:AccountId];
        if(lstAccount1.size()>0)
        {
            AccountName =  lstAccount1[0].Name;
            AccountID1 = lstAccount1[0].id;
            system.debug('AccountName'+AccountName);
        }
       
        system.debug('AccountId'+AccountId);
        // selectedAccounts = new List<wrapAccount>();
        lstSelectOption= new List<SelectOption>();
        lstSelectOption.add( new SelectOption('','--Select--'));
        for( wrapAccount wrapacc :  selectedAccounts) {
            lstSelectOption.add( new SelectOption(wrapacc.acc.Id,wrapacc.acc.name));
            lstSelectOption.add(new SelectOption(AccountID1,AccountName));
            system.debug('accOptions'+lstSelectOption);
        }
        
    }
    
    public void nextButton(){
        selectedAccounts = new List<wrapAccount>();
        AccountId=Apexpages.currentpage().getParameters().get('id');
        lstAccount1 =[Select id,name from Account where id =:AccountId];
        if(lstAccount1.size()>0)
        {
            AccountName =  lstAccount1[0].Name;
            AccountID1 = lstAccount1[0].id;
            system.debug('AccountName'+AccountID1);
        }
        for(wrapAccount wrapAccountObj : wrapAccountList) {
            if(wrapAccountObj.selected == true) {
                selectedAccounts.add(new wrapAccount(wrapAccountObj.acc,wrapAccountObj.selected,wrapAccountObj.accId));
                
            }
        }
        getAccountNames();
        bolvar1 = false;
        bolvar2 = true;
        
    }
    
    public void  Selectedmaster(){
        System.debug(SelectAccount);
        

        //selectedAccounts = new List<wrapAccount>();
        objMasterAccount = new Account();
        objAccount = new Account();
        SobjectField[] fields =  Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap().values();
        System.debug(fields);
        for(wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id == SelectAccount)
                objMasterAccount = wrapacc.acc;
                AccountID1 = wrapacc.accId;
            system.debug('objMasterAccount'+objMasterAccount);
        }
        
        for( wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id != SelectAccount){
                for(SObjectField field:fields){  
                    if(field.getDescribe().isUpdateable()){   
                        system.debug('masterLead.get(field)'+objMasterAccount.get(field));
                        if(objMasterAccount.get(field)==null && wrapacc.acc.get(field)!=null ){     
                            objMasterAccount.put(field,wrapacc.acc.get(field));
                            objMasterAccount.put(field,wrapacc.accId);
                            system.debug('objMasterAccount'+objMasterAccount);
                            //masterLead.put(field,'Amit Shah');
                            system.debug('objMasterAccount'+objMasterAccount.get(field));
                        }
                    }
                }
            }
        }
        update objMasterAccount;
        bolvar3 = false; 

    }
    
    public PageReference ok(){
       PageReference pageRef = new PageReference('/001/o');
         pageRef.setRedirect(true);
         return pageRef; 
    }
    
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
        public id accId {get;set;}
        public wrapAccount(Account a,Boolean bolvar, id aId) {
            acc = a;
            selected = bolvar;
            accId = aId;
        }
    } 
}
@isTest
public class OpportunityAmountInWordsTest
{
  
    Public static testmethod void OpportunityAmountInWordsTM()
    {
        RecordType rt = [select id,Name from RecordType where SobjectType='Account' and Name='Supplier' Limit 1];
        Account Acc =New Account();
            Acc.RecordTypeId=rt.id;
            Acc.Name='Test';
            Acc.GST_Reg_No__c='test1';
            Acc.TAX_IDENTIFICATION_NUMBER_VAT__c='Test11';
            Acc.IMPORT_EXPORT_CODE_IEC__c='test12';
            Insert Acc;
       
       Product2 Pro =New Product2 ();
            Pro.Name ='tEST';
            Pro.CurrencyIsoCode='USD';
            Insert Pro;
       Order odd =New Order();
            odd.AccountId=acc.id;
            odd.EffectiveDate=System.today();
            odd.Status__c='Draft';
            odd.Product_Name__c=pro.id;
            odd.Quantity__c=1234;
            odd.Quantity_per_Container__c=23;
            odd.Quantity_per_Packaging_Material__c =55;
            odd.Status='Draft';
            Insert odd;
            
        Opportunity opp =New Opportunity();
            opp.Name='Test';
            opp.accountId = Acc.id;
            opp.CloseDate=system.today();
            opp.CurrencyIsoCode ='USD';
            opp.Worked_by__c='Neha';
            opp.Product_Name__c=pro.id;
            opp.Description_of_Goods__c='test';
            opp.Origin__c='test';
            opp.Packaging_Details__c='trueuus';
            opp.Quantity__c=10000;
            opp.H_S_Code__c='amit';
            opp.Container_Size__c='20 FCL';
            // opp.Agent_Name__c=Customer.id;
            opp.StageName='Enquiry';
            // opp.Agent_Fee_IO__c=123;
            Insert opp;
            
            List<Cost_Price__c> lCostPr = new List<Cost_Price__c>();
            Cost_Price__c Cost1 =New Cost_Price__c();
            Cost1.Opportunity__c=opp.id;
            Cost1.Supplier_Name__c=Acc.id;
            //Cost1.Opportunity__c=opp.Accountid;
            Cost1.Country_of_Final_Destination_Picklist__c='India';
            Cost1.CurrencyIsoCode='USD';
            Cost1.UOM__c='Tonnes';
            cost1.Payment_Status__c = 'DUE';
            cost1.Payment_Receivable_Date__c = System.now().date().addDays(-40);
               
           lCostPr.add(cost1);
            Insert lCostPr;          
           
}
    
}
I have created a 6 objects 
Test1
Test2
Test3
Test4
Test5
Test6

Test6(Lookup with Test5)
Test5(Lookup with Test4)
Test4(Lookup with Test3)
Test3(Lookup with Test2)
Test2(Lookup with Test1)

i want Test1 records in test 6 using soql

Please Help

Thanks,

Regards
Amit Jadhav
My requirement is Display Avg IN Visualforce page 
Field Is a Quantity__c so Show the Average Of Quantity 
for example 
Price__c * Qyt__c = Total_Price__c (Total price is formula field)
Total_Price__c * Disscount_per__c = Disscount__c (Disscount Is also formula field)
Disscount__c + Total_Price__c = Amount (Amount is  also formula field)


how to cover this filed in test class
I'm new in test class plese help me below code to write test class
public class FindProject {
   public Id OppObj{get;set;}
    public string Accname {get;set;}
    public string ReciName {get;set;}
    public string ProjectName;
    public opportunity objopp{
        get{
           objopp=[Select id,name,Account.Name,Owner.Name,Amount from opportunity where id=:OppObj limit 1]; 
        return objopp;
        }set;
    }
    public OpportunityLineItem objPro{
        get{
            objPro=[Select id,Projects__r.name,Start_Date__c from OpportunityLineItem where opportunity.id=:OppObj limit 1];
            return objPro;
        }set;
    }
    
    public Project__c proobj{
        get{
        ProjectName=[Select id,Projects__r.name from OpportunityLineItem where opportunity.id=:OppObj limit 1].Projects__r.name;
        proobj=[Select id,Program_Manager__r.name from Project__c where name=:ProjectName];
        return proobj;
        }set;
    }
}

Test Class:
@isTest
public class FindProjectTest {

    @isTest
    public static void testDataSetup(){
         Product2 prod = new Product2(Name = 'Laptop X200', Family = 'Hardware');
        insert prod;
        
        Id pricebookId = Test.getStandardPricebookId();
        
        PricebookEntry standardPrice = new PricebookEntry(Pricebook2Id = pricebookId, 
                                                          Product2Id = prod.Id, 
                                                          UnitPrice = 10000, 
                                                          IsActive = true);
        insert standardPrice;
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
        PricebookEntry customPrice = new PricebookEntry(Pricebook2Id = customPB.Id, 
                                                        Product2Id = prod.Id, 
                                                        UnitPrice = 12000, 
                                                        IsActive = true);
        insert customPrice;
        Account acc = new Account(name='Test Account');
        insert acc;
        opportunity opp = new opportunity(name='Test Opportunity', 
                                          AccountId=acc.id,
                                          CloseDate =Date.newInstance(2016, 12, 9),
                                          stageName='Closed Lost',
                                          ForecastCategoryName='Pipeline',
                                          PaymentTerms__c='Net 30',
                                          type='New Business',
                                          Amount=5676,
                                          Pricebook2Id=customPB.Id
                                         );
        insert opp;
        
        OpportunityLineItem oppLineItem = new OpportunityLineItem(OpportunityId=opp.id,
                                                                  TotalPrice =664557,
                                                                  End_Date__c=Date.newInstance(2016, 12, 9),
                                                                  Quantity =56,
                                                                  PricebookEntryId = customPrice.Id);
        insert oppLineItem;
        
         FindProject obj = new FindProject();
        opportunity objopp = obj.objopp;
        OpportunityLineItem objPro = obj.objPro;
        
       
    }
    
}

​​​​​​​
Can is it possible when we insert CSV lead file using apex class if the insertion in fail the show the which CSV file row fails when inserting a record in Salesforce and store row number in salesforce object
Apex Trigger:
trigger CreateClientTenant on Lease_Summary__c (after update) {
    integer i = 1;
    List<Tenant__c> lstTenant = new List<Tenant__c>();
    List<Client__c> lstClient = new List<Client__c>();  
    for(Lease_Summary__c objLease : trigger.new){
        system.debug('objLease.Rent_start_date__c'+objLease.Rent_start_date__c);
        If(objLease.Rent_start_date__c == DATE.TODAY()){
            Tenant__c objtenant = new Tenant__c();
            objtenant.Rent_Start_Date__c = objLease.Rent_Start_Date__c;
            objtenant.Lease_Summary__c = objLease.id;
            lstTenant.add(objtenant);
            
        }
        system.debug('lstTenant'+lstTenant);
        insert lstTenant;
     }
}

 
Visualforce Page
<apex:page controller="thousandLimit">
    <apex:form>
        <apex:pageBlock >
            <apex:repeat value="{!thousandBlocks}" var="block">
                
            <apex:pageBlockTable value="{!block}" var="c">
               
            <apex:column value="{!c.cases.name}"/>
                            
            </apex:pageBlockTable>
        </apex:repeat>
        </apex:pageBlock>
    </apex:form>
</apex:page>

controller
public class thousandLimit {
 private List<limitWrapper> thousandBlocks = new List<limitWrapper>();
   
    private final integer listLimit;
   
    public thousandLimit()
    {
        listLimit = 1000;
    }
   
    public List<limitWrapper> getthousandBlocks()
    {
        thousandBlocks = new limitWrapper[]{};
       
        integer counter = 0;
        integer loopCount = 0;
        boolean Selected =true;
        List<Account> tmpcase = new List<Account>();
       
        for(Account c:[select id,name from Account])
        {
            if(counter < listLimit)
            {
                tmpcase.add(c);
                counter++;
            }
            else
            {
                loopCount++;
                thousandBlocks.add(new limitWrapper(tmpcase,Selected));
                tmpcase = new List<Account>();
                tmpcase.add(c);
                counter = 0;
            }           
        }
       
        if(thousandBlocks.size() == 0)
        {
            loopCount++;
            thousandBlocks.add(new limitWrapper(tmpcase,Selected));
        }
       
        return thousandBlocks;
    }
   
    public class limitWrapper
    {
        public List<Account> cases {get;set;}
         public boolean Selected {get;set;}
        //public integer blockNumber {get;set;}
        public limitWrapper(List<Account> accs, boolean i)
        {
            cases = accs;
            Selected = i;
        }
       
    }
}
Apex Class:

public class mergeAccount {
    
    public List<wrapAccount> wrapAccountList {get; set;}
    public List<wrapAccount> selectedAccounts{get;set;}
    public Boolean bolvar {get; set;}
    public Boolean bolvar1{get;set;}
    public Boolean bolvar2{get;set;} 
    public Boolean bolvar3{get;set;} 
    public String SelectAccount{get;set;}
    public Account objMasterAccount {get;set;}
    public List<SelectOption> lstSelectOption {get;set;}
    public String AccountId;
    public Account objAccount;
    public string AccountName ;
    public ID AccountID1;
    public List<Account> lstAccount = new List<Account>();
    public List<Account> lstAccount1 = new List<Account>();
    public mergeAccount(ApexPages.StandardController controller) {
        
        system.debug('lstAccount'+lstAccount);
        bolvar1 = true;
        bolvar2 = false;
        //objAccount= (Account)Controller.getRecord().id;
        system.debug('objAccount'+objAccount);
        
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap();
            String query='select id';
            for(String s : objectFields.keySet()) {
                if(s != 'Id'){
                    SObjectField test=objectFields.get(s); 
                    //system.debug('test' +test);
                    //if(test.getDescribe().isUpdateable()){ 
                    query += ', ' + s + ' ';
                }
                //}
            }
            
            query +=' FROM Account';
            System.debug(query);
            List<Account> lstAccount = new List<Account>();
            lstAccount = database.query(query);
            //System.debug(lstAccount);
            for(Account a: lstAccount) {
                wrapAccountList.add(new wrapAccount(a,bolvar));
                
                
            }
        }
    }
    
    public void getAccountNames() {
        system.debug('AccountId'+AccountId);
        /*AccountId=Apexpages.currentpage().getParameters().get('id');
        lstAccount1 =[Select id,name from Account where id =:AccountId];
        if(lstAccount1.size()>0)
        {
            AccountName =  lstAccount1[0].Name;
            AccountID1 = lstAccount1[0].id;
            system.debug('AccountName'+AccountName);
        }*/
        
        system.debug('AccountId'+AccountId);
        // selectedAccounts = new List<wrapAccount>();
        lstSelectOption= new List<SelectOption>();
        lstSelectOption.add( new SelectOption('','--Select--'));
        for( wrapAccount wrapacc :  selectedAccounts) {
            lstSelectOption.add( new SelectOption(wrapacc.acc.Id,wrapacc.acc.name));
            
            //lstSelectOption.add(new SelectOption(AccountID1,AccountName));
            system.debug('accOptions'+lstSelectOption);
        }
        
    }
    
    public void nextButton(){
        selectedAccounts = new List<wrapAccount>();
        
        for(wrapAccount wrapAccountObj : wrapAccountList) {
            if(wrapAccountObj.selected == true) {
                selectedAccounts.add(new wrapAccount(wrapAccountObj.acc,wrapAccountObj.selected));
                
            }
        }
        getAccountNames();
        bolvar1 = false;
        bolvar2 = true;
        
    }
    
    public PageReference  Selectedmaster(){
        objMasterAccount = new Account();
        objAccount = new Account();
        SobjectField[] fields =  Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap().values();
        System.debug(fields);
        for(wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id == SelectAccount)
                objMasterAccount = wrapacc.acc;
            //AccountID1 = wrapacc.accId;
            system.debug('objMasterAccount'+objMasterAccount);
        }
        for( wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id != SelectAccount){
                for(SObjectField field:fields){  
                    if(field.getDescribe().isUpdateable()){   
                        system.debug('masterLead.get(field)'+objMasterAccount.get(field));
                        if(objMasterAccount.get(field)==null && wrapacc.acc.get(field)!=null ){     
                            objMasterAccount.put(field,wrapacc.acc.get(field));
                        }
                    }
                }
            }
        }
        update objMasterAccount;
        bolvar3 = false; 
        PageReference pageRef = new PageReference('/apex/PopUp');
        pageRef.setRedirect(true);
        return pageRef;
    }
    
    public PageReference ok(){
        PageReference pageRef = new PageReference('/001/o');
        pageRef.setRedirect(true);
        return pageRef; 
    }
    
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
        //public id accId {get;set;}
        public wrapAccount(Account a,Boolean bolvar) {
            acc = a;
            selected = bolvar;
            //accId = aId;
        }
    } 
}



Test Class
@isTest
public class mergeAccountTest {
    
    public static testmethod void AccountMergeTest(){
        Map<string, schema.RecordTypeInfo> rtMap = Schema.SObjectType.Account.getRecordTypeInfosByName();
        Id VV=rtMap.get('VV').getRecordTypeId();
        Id MVS=rtMap.get('MVS - Remind A Pet').getRecordTypeId();
        Id VVR=rtMap.get('VVR').getRecordTypeId();
        Id VVANDVVR=rtMap.get('VV and VVR').getRecordTypeId();
        
        
        Account objAccount = new Account();
        objaccount.Name = 'Test';
        objaccount.RecordTypeId =VV;
        insert objAccount;
        
        PageReference pageRef = Page.PopUp;
        Test.setCurrentPage(pageRef);
        
        
        ApexPages.StandardController sc = new ApexPages.standardController(objAccount);
        mergeAccount controller = new mergeAccount(sc);
        Account objacc = new Account();
        Boolean selected = true; 
        controller.bolvar3 = true;
        controller.SelectAccount ='26551025862uiyty';
        
        mergeAccount.wrapAccount wrrap = new mergeAccount.wrapAccount(objacc,selected);
        
        
        controller.nextButton();
        controller.getAccountNames();
         PageReference objPageRef1 = controller.ok();
          for(mergeAccount.wrapAccount wrp : controller.selectedAccounts )
            {
                wrp.selected = true;
            }            
 
        PageReference objPageRef = controller.Selectedmaster();
       
    }
    
}
@isTest
public class OpportunityAmountInWordsTest
{
  
    Public static testmethod void OpportunityAmountInWordsTM()
    {
        RecordType rt = [select id,Name from RecordType where SobjectType='Account' and Name='Supplier' Limit 1];
        Account Acc =New Account();
            Acc.RecordTypeId=rt.id;
            Acc.Name='Test';
            Acc.GST_Reg_No__c='test1';
            Acc.TAX_IDENTIFICATION_NUMBER_VAT__c='Test11';
            Acc.IMPORT_EXPORT_CODE_IEC__c='test12';
            Insert Acc;
       
       Product2 Pro =New Product2 ();
            Pro.Name ='tEST';
            Pro.CurrencyIsoCode='USD';
            Insert Pro;
       Order odd =New Order();
            odd.AccountId=acc.id;
            odd.EffectiveDate=System.today();
            odd.Status__c='Draft';
            odd.Product_Name__c=pro.id;
            odd.Quantity__c=1234;
            odd.Quantity_per_Container__c=23;
            odd.Quantity_per_Packaging_Material__c =55;
            odd.Status='Draft';
            Insert odd;
            
        Opportunity opp =New Opportunity();
            opp.Name='Test';
            opp.accountId = Acc.id;
            opp.CloseDate=system.today();
            opp.CurrencyIsoCode ='USD';
            opp.Worked_by__c='Neha';
            opp.Product_Name__c=pro.id;
            opp.Description_of_Goods__c='test';
            opp.Origin__c='test';
            opp.Packaging_Details__c='trueuus';
            opp.Quantity__c=10000;
            opp.H_S_Code__c='amit';
            opp.Container_Size__c='20 FCL';
            // opp.Agent_Name__c=Customer.id;
            opp.StageName='Enquiry';
            // opp.Agent_Fee_IO__c=123;
            Insert opp;
            
            List<Cost_Price__c> lCostPr = new List<Cost_Price__c>();
            Cost_Price__c Cost1 =New Cost_Price__c();
            Cost1.Opportunity__c=opp.id;
            Cost1.Supplier_Name__c=Acc.id;
            //Cost1.Opportunity__c=opp.Accountid;
            Cost1.Country_of_Final_Destination_Picklist__c='India';
            Cost1.CurrencyIsoCode='USD';
            Cost1.UOM__c='Tonnes';
            cost1.Payment_Status__c = 'DUE';
            cost1.Payment_Receivable_Date__c = System.now().date().addDays(-40);
               
           lCostPr.add(cost1);
            Insert lCostPr;          
           
}
    
}
I have created a 6 objects 
Test1
Test2
Test3
Test4
Test5
Test6

Test6(Lookup with Test5)
Test5(Lookup with Test4)
Test4(Lookup with Test3)
Test3(Lookup with Test2)
Test2(Lookup with Test1)

i want Test1 records in test 6 using soql

Please Help

Thanks,

Regards
Amit Jadhav
Please explain me soql subQuery.
when and how to use it in Apex Code(triggers) ?
in Map and in List
give me some examples
Hi,

I created an email action in the case feed and an apex class to show the default email template, but it doesn't work yet, the template doesn't load.

I have activated the default template checkbox in Support Settings as well, and the template is available for use.

Does anyone know why it doesn't work?

Thanks.

User-added image

User-added image
This is the class:
 
global class E1DefaultTemplateEmail implements Support.EmailTemplateSelector {

    global E1DefaultTemplateEmail() {    }

    global ID getDefaultEmailTemplateId(ID caseId) {

        Case c = [SELECT Subject, Description FROM Case WHERE Id=:caseId];

        EmailTemplate et;

        if (c.subject != null) {
            et = [SELECT id FROM EmailTemplate WHERE DeveloperName = 'E1HC_Send_e_mail_with_case_description'];
        }         

        return et.id;
    }
}

 
My requirement is Display Avg IN Visualforce page 
Field Is a Quantity__c so Show the Average Of Quantity 
I am new when it comes to visualforce and creating custom controllers. 

I have a problem to solve where each Account needs the ability to quickly add an Invoice with only 1 Invoice line item. The ask is to be able to click a button on the Account and be prompted to enter the quantity prior to creating the invoice. 
The result should be after the quantity is entered, an Invoice record is created with 1 Invoice line item showing the fields price and quantity.

Help with how the code should be written would help a lot.

 
for example 
Price__c * Qyt__c = Total_Price__c (Total price is formula field)
Total_Price__c * Disscount_per__c = Disscount__c (Disscount Is also formula field)
Disscount__c + Total_Price__c = Amount (Amount is  also formula field)


how to cover this filed in test class
Controller:

public with sharing class costsheet {
   
    

    public String OrderId;
    public Order ord;
    
    
    public costsheet(ApexPages.StandardController controller) {
      listIex =0.0;
      CFSList =0.0;
      CHAList =0.0;
      CHAListS =0.0;
      ord= (Order)Controller.getRecord();
      OrderId=Apexpages.currentpage().getParameters().get('id');
      system.debug('listStemer>>'+OrderId);
      listStemer=[Select Id,subtotal__c,Supplier_Order__c from Shipper_Info_India__c where Supplier_Order__c =:ord.id AND RecordType.Name='Steamer Charges' limit 1]  ;
      system.debug('listStemer>>'+listStemer);
     if(listStemer.size()>0)
     {
     listIex =listStemer[0].subtotal__c;
     system.debug('listStemer>>'+listIex );
     }
     listCHAChargesR=[Select Id,subtotal__c,Supplier_Order__c  from Shipper_Info_India__c where Supplier_Order__r.id =:ord.id AND RecordType.Name='CHA Charges' AND Bill_Type__c = 'Reimbursement Type'] ;
     if(listCHAChargesR.size()>0)
     {
     CHAList =listCHAChargesR[0].subtotal__c;
     }
     listCHAChargesS=[Select Id,subtotal__c,Supplier_Order__c  from Shipper_Info_India__c where Supplier_Order__r.id =:ord.id AND RecordType.Name='CHA Charges' AND Bill_Type__c = 'Service Type'] ;
     if(listCHAChargesS.size()>0)
     {
     CHAListS =listCHAChargesS[0].subtotal__c;
     }
     listCFSCharges=[Select Id,subtotal__c,Supplier_Order__c  from Shipper_Info_India__c where Supplier_Order__r.id =:ord.id AND RecordType.Name='CFS Charges' limit 1] ;
     if(listCFSCharges.size()>0)
     {
     CFSList =(listCFSCharges[0].subtotal__c).setScale(2);
     }
     
     Calculation();
    
    
    }
    
        public List<Shipper_Info_India__c > listStemer;
        public List<Shipper_Info_India__c > listCFSCharges;
        public List<Shipper_Info_India__c > listCHAChargesR;
        public List<Shipper_Info_India__c > listCHAChargesS;
        public Decimal CFSList {get;set;}
        public Decimal CHAList {get;set;}
        Public Decimal listIex {get;set;}
        public Decimal CHAListS {get;set;}
        public List<Order> ordList = new List<Order>();
        public Decimal TotalAmount_3{get;set;}
        public Decimal TotalFreightAmount_19{get;set;}
        public Decimal TotalFreightAmount_21{get;set;}
        public Decimal TotalFreightAmount_c21{get;set;}
        public Decimal TotalFreightAmount_d21{get;set;}
        public Decimal BasicDuty_c23{get;set;}
        public Decimal BasicDuty_d23{get;set;}
        public Decimal Cess_c24{get;set;}
        public Decimal Cess_d24{get;set;}
        public Decimal TotalCustomDuty_g25{get;set;}
        public Decimal TotalCustomDuty_c25{get;set;}
        public Decimal TotalCustomDuty_d25{get;set;}
        public Decimal ShippingLine_c27 {get;set;}
        public Decimal ShippingLine_d27 {get;set;}
        public Decimal StorageCFS_c32 {get;set;}
        public Decimal StorageCFS_d32 {get;set;}
        public Decimal Others_c30 {get;set;} 
        public Decimal Others_d30 {get;set;} 
        public Decimal Clearing_c31 {get;set;}
        public Decimal Clearing_d31 {get;set;}
        public Decimal TotalC {get;set;}
        public Decimal TotalCost{get;set;}
        public decimal TotalC_c37 {get;set;}
        public decimal TotalC_d37 {get;set;}
        public decimal TotalCost_c38 {get;set;}
        public decimal TotalCost_d38 {get;set;}
        
            
        public void Calculation(){
         TotalAmount_3 = 0;
         TotalFreightAmount_19= 0;
         if(ord.Quantity__c != NULL && ord.Unit_Price__c != null){
            TotalAmount_3 = (ord.Unit_Price__c *ord.Quantity__c).setScale(2);
          }else{
           TotalAmount_3=0;
          }
          if(ord.Total_Insurance__c != null){
          // Need to update this with adding Freight charges
           TotalFreightAmount_19= (ord.Total_Insurance__c+ord.Total_Sea_Freight_Charges__c+TotalAmount_3).setscale(2) ;
           }else{
           TotalFreightAmount_19=0;
           }
           if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalFreightAmount_21 = (TotalFreightAmount_19*ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          }else{
            TotalFreightAmount_21=(0+TotalFreightAmount_19).setscale(2);
          }
          if(TotalFreightAmount_19 != 0)
           {
           TotalFreightAmount_c21 = (TotalFreightAmount_21/ord.Quantity__c/1000).setscale(2);
          }
           
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalFreightAmount_d21 = (TotalFreightAmount_c21*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          }else{
          TotalFreightAmount_d21=0;
          }
          if(ord.Basic_Customs_Duty_value__c != null)
           {
           BasicDuty_c23 = (ord.Basic_Customs_Duty_value__c/ord.Quantity__c/1000).setscale(2);
          }else{
           BasicDuty_c23=0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           BasicDuty_d23 = (BasicDuty_c23*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          }else{
           BasicDuty_d23=0;
          }  
          if(ord.Social_Welfare_Surcharge__c != null)
           {
           Cess_c24 = (ord.Social_Welfare_Surcharge__c/ord.Quantity__c/1000).setscale(2);
          }else{
           Cess_c24=0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           Cess_d24 = (Cess_c24*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          }else{
           Cess_d24=0;
          }  
          if(ord.Basic_Customs_Duty_value__c != null && ord.Social_Welfare_Surcharge__c != null)
          {
           TotalCustomDuty_g25=(ord.Basic_Customs_Duty_value__c+ord.Social_Welfare_Surcharge__c).setscale(2);
          }else{
            TotalCustomDuty_g25=0;
          }
          if(TotalCustomDuty_g25 != 0)
           {
           TotalCustomDuty_c25 = (TotalCustomDuty_g25/ord.Quantity__c/1000).setscale(2);
          }else{
           TotalCustomDuty_c25 =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalCustomDuty_d25 = (TotalCustomDuty_c25*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           TotalCustomDuty_d25 =0;
          }
          if(listIex != null)
           {
           ShippingLine_c27 = (listIex/ord.Quantity__c/1000).setscale(2);
          }else{
           ShippingLine_c27 =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           ShippingLine_d27 = (ShippingLine_c27*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           ShippingLine_d27 =0;
          }
          if(CFSList != null)
           {
           StorageCFS_c32 = (CFSList/ord.Quantity__c/1000).setscale(2);
          }else{
           StorageCFS_c32 =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           StorageCFS_d32 = (StorageCFS_c32*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           StorageCFS_d32 =0;
          }
          
          if(CHAList != null)
           {
           Others_c30 = (CHAList/ord.Quantity__c/1000).setscale(2);
          }else{
           Others_c30  =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           Others_d30  = (Others_c30 *1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           Others_d30  =0;
          }
          
          if(CHALists != null)
           {
           Clearing_c31 = (CHALists/ord.Quantity__c/1000).setscale(2);
          }else{
           Clearing_c31  =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           Clearing_d31  = (Clearing_c31 *1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           Clearing_c31  =0;
          }
          
          
          TotalC = (listIex+CHAList+CHAListS+CFSList).setscale(2);
          TotalCost = (TotalC+TotalFreightAmount_21+TotalCustomDuty_g25).setscale(2);
          
          if(TotalC != null)
           {
           TotalC_c37= (TotalC/ord.Quantity__c/1000).setscale(2);
          }else{
           TotalC_c37=0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalC_d37= (TotalC_c37*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           TotalC_d37=0;
          }
          
           if(TotalCost != null)
           {
           TotalCost_c38= (TotalCost/ord.Quantity__c/1000).setscale(2);
          }else{
           TotalCost_c38=0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalCost_d38= (TotalCost_c38*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           TotalCost_d38=0;
          }
          
          
        }
          
       
        
           
      
   //Method to Save Attachments   
    
    public PageReference  SaveAttachmentpdf() {
        system.debug('In save');
        blob pdfBody;
        PageReference thePDF =  new PageReference('/apex/costsheetpdf?id='+OrderId);
        system.debug('ORD--'+OrderId);
        thePDF.setRedirect(true);
           
          if(Test.isRunningTest()) { 
             pdfBody = blob.valueOf('Unit.Test');
            } else {
             pdfBody = thePDF.getContentAsPDF();
           }
            Attachment attach = new Attachment();
            attach.body = pdfBody;
            attach.Name='CostSheetPdf '+System.Now();
            system.debug('OrderId'+OrderId);
            attach.ParentId=OrderId;
            attach.ContentType = 'application/pdf';
            Insert attach;
            
        if (attach == null){
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Error will Saving a file .Please check the content of the file'));  
           }
        if (attach != null){
             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Quote Pdf generated successfully'));
            
          }
      PageReference qtpage = new PageReference('/'+OrderId);
      qtpage.setRedirect(true); 
      
      return thePDF;
   }