function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SalesforceCrm AccountCRMSalesforceCrm AccountCRM 

System.LimitException: Too many SOQL queries: while running a test code

Can any one help me on this error :
I'm running the test class in developer console for the trigger named as :CreateSubscriptionopptyclone ,but i get the error for the other trigger ...and i have not used the owd concept in trigger or test class.Any suggestion plz
System.LimitException: Too many SOQL queries: 101
Trigger.thankYouNoteMail: line 52, column 1

This is other trigger and line 52 is :


    OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = 'customercare@enterprisedb.com'];
Test Classes :
@isTest
public class TestCreateSubscriptionOpptyClone 
{

static testMethod void TestCreateSubscription()
{
//Create Account 

Account acc1 = new Account();
acc1.Name='Testing SubscriptionClone';
acc1.BillingStreet='Banjara hills';
acc1.BillingCity='Hyd';
acc1.BillingState='TS';
acc1.BillingPostalCode = '500084';
acc1.BillingCountry = 'India';
acc1.Phone = '100';
acc1.Industry = 'Banking';         
acc1.Type = 'Paid';
acc1.Customer_Type__c = 'Customer';
acc1.Customer_List__c = true;
insert acc1 ;

//Create Contact

contact cc = new contact();
cc.FirstName ='Test Contact Subscription';
cc.LastName ='Opptyclone';
cc.Role__c='Subscription Administrator';
cc.AccountId=acc1.Id;
insert cc;

//Create Opportunity

Opportunity opty = new Opportunity();
opty.Name = 'Test SubscriptionOppty';
opty.StageName ='Proposal/Price Quote';
opty.Probability =60;
opty.LeadSource = 'Subscription Renewal';
opty.CloseDate = System.Today();                
opty.Type = 'Existing Customer';
opty.Assigned_Sales_Engineer__c = null;
opty.Payment_Type__c = 'Order Form';
opty.Update_Complete__c = true;
opty.Partner__c = 'None';
opty.Anchor__c='Non Anchor';
opty.AccountId = acc1.Id;
opty.StageName = 'Closed Won';
insert opty;

//Create Opportunity Contact Role 
 list<OpportunityContactRole> opptyConRolelist1 =  new list<OpportunityContactRole>();   
OpportunityContactRole opptyConRole =  new OpportunityContactRole();   
opptyConRole.ContactId = cc.Id;
opptyConRole.OpportunityId = opty.Id;   
opptyConRole.IsPrimary = false;
opptyConRole.Role = 'Subscription Administrator';
opptyConRolelist1.add(opptyConRole);
insert opptyConRolelist1;
 
 opty.UPDATE_COMPLETE__c = false;
 opty.Contracts_Processed__c =  false;
 opty.Contain_Renewable_Subscription__c=false;
 opty.StageName ='Stage4 :Proposal Delivery';
 opty.Closed_Won__c =false;
 opty.Activate_Notification_to_Finance__c=false;
 opty.Stage_won_lost_set__c=false;
 opty.ForecastCategoryName ='Pipeline';
 //opty.Parent_Opportunity__c=opty.Id;
 update opty;

//Add oppty line items
  string stdpdId = '01s500000001e6k';
//Create OpportunityLineitem 

 List<OpportunityLineItem> ooliList = new List<OpportunityLineItem>();

//Create Product

product2 p2 = new product2();
p2.Name ='Postgres Plus Enterprise Edition Unicores';
p2.Product_Name1__C='Product - Subscription';
p2.Product_Group__c='PPAS';
p2.IsActive = true;
p2.Description='Postgres Plus Enterprise Edition Unicores';

insert p2;

//Create PriceBookEntry 

PricebookEntry pbey = new PricebookEntry();
 pbey.Product2ID=p2.id;
 pbey.Pricebook2ID=stdpdId;
 pbey.UnitPrice=50; 
 pbey.isActive=true;
insert pbey;

Opportunitylineitem ooli = new Opportunitylineitem();
ooli.OpportunityId = opty.Id;    
ooli.PricebookEntryId = pbey.Id;
ooli.Quantity =4;
//ooli.Product_Code__c='PREE-UCC-001';
//ooli.Unit_of_Measure__c='Unicore';
ooli.Start_Date__c = System.today();
ooli.End_Date__c =  System.today() + 100;
ooli.Type_of_Contract__c='None';
ooli.Term__c =12;
ooli.Type_Of_Product__c='Single Year Subscription';
ooli.Type_of_ARR__c= 'New Addition ARR';
ooli.TotalPrice=1750;
ooliList.add(ooli);
insert ooliList;

opty.UPDATE_COMPLETE__c = true;
update opty;

 opty.UPDATE_COMPLETE__c = false;
 opty.Contracts_Processed__c =  false;
 update opty;
 
 //Create Product

product2 pr2 = new product2();
pr2.Name ='Postgres Plus Standard Edition Unicores';
pr2.Product_Name1__C='Product - Subscription';
pr2.Product_Group__c='PPAS';
pr2.IsActive = true;
pr2.Description='Postgres Plus Standard Edition Unicores';

insert pr2;

//Create PriceBookEntry 

PricebookEntry pbety = new PricebookEntry();
 pbety.Product2ID=pr2.id;
 pbety.Pricebook2ID=stdpdId;
 pbety.UnitPrice=50; 
 pbety.isActive=true;
insert pbety;

/*Opportunitylineitem ooli1 = new Opportunitylineitem();
ooli1.OpportunityId = opty.Id;    
ooli1.PricebookEntryId = pbety.Id;
ooli1.Quantity =4;
//ooli.Product_Code__c='PREE-UCC-001';
//ooli.Unit_of_Measure__c='Unicore';
ooli1.Start_Date__c = System.today();
ooli1.End_Date__c =  System.today() + 100;
ooli1.Type_of_Contract__c='None';
ooli1.Term__c =12;
ooli1.Type_Of_Product__c='Single Year Subscription';
ooli1.Type_of_ARR__c= 'New Addition ARR';
ooli1.TotalPrice=1750;
ooliList.add(ooli1);
insert ooliList;*/

opty.UPDATE_COMPLETE__c = true;
update opty;

 opty.UPDATE_COMPLETE__c = false;
 opty.Contracts_Processed__c =  false;
 update opty;
 
 
 //update contact roles - to test the subscription product type
        for(OpportunityContactRole r1: opptyConRolelist1)
        {
            r1.Role = 'Subscription Administrator';                                              
        }
        update opptyConRolelist1;                
        opty.UPDATE_COMPLETE__c = true;                
        update opty;               
        
        opty.UPDATE_COMPLETE__c = false;
        opty.Contracts_Processed__c =  true;
        update opty;
        
        opty.UPDATE_COMPLETE__c =  true;           
        update opty;  

}

}
Trigger :
 
trigger CreateSubscriptionOpptyClone on Opportunity (after update) 
{
    if(!AvoidRecursiveCloning.hasAlreadyCreatedClone())
    {
        List<Opportunity> closedWonOpportunities = new List<Opportunity>();
        Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>();
        
        List<Id> closedLostOpportunities = new List<Id>();
        List<Id> allOpportunities = new List<Id>();
        
        for(Opportunity opp: Trigger.new)
        {
            ////Get Opportunity which have been Closed Won///
            if(opp.StageName == 'Closed Won' && Trigger.oldMap.get(opp.Id).StageName != 'Closed Won')
            {
                closedWonOpportunities.add(opp);
                oppMap.put(opp.Id, opp);
            }
            ///////Get Opportunity which have been Closed Lost///////////
            if(opp.StageName == 'Closed Lost' && Trigger.oldMap.get(opp.Id).StageName != 'Closed Lost')
            {
                closedLostOpportunities.add(opp.Id);               
            }
            /////If any of the 4 fields changes
            if(opp.StageName != Trigger.oldMap.get(opp.Id).StageName || opp.Probability != Trigger.oldMap.get(opp.Id).Probability || opp.OwnerId != Trigger.oldMap.get(opp.Id).OwnerId || opp.Comments__c != Trigger.oldMap.get(opp.Id).Comments__c)
            {
                allOpportunities.add(opp.Id);
            }
        }
        ///Creating subscription clone
        if(closedWonOpportunities.size() > 0)
        {
            //Get all Opportunity Line Items
        List<OpportunityLineItem>  oppProdList = [Select Id,Orig_Total_Price__c,Parent_Opportunity_Product_Id__c, Original_Amount__c, Original_ARR__c, Original_In_Year_Billing__c, Actual_Renewal_Date__c, OpportunityId, SortOrder, PricebookEntryId, Quantity, Discount, UnitPrice, ListPrice, ServiceDate, HasRevenueSchedule, HasQuantitySchedule, Description, HasSchedule, Attendee_Email__c, Start_Date__c, End_Date__c, Term__c, Overall_Value__c, Description__c, Attendee_Name__c, Attendee_Phone__c, Number_of_Contacts__c, Term_Days__c, Venue__c, Product_Name__c, Service_Type__c, ARR_Impacts__c, Annual_Recurring_Revenue__c, Product_Segmentation__c, Product_Categories__c, Product_Bucket__c, ARR2__c, Test_Number__c, Transfer_Price__c, Total_Transfer_price__c, No_ARR__c, Price_Per_Socket_Per_Annum__c, In_Year_Billing__c, Type_Of_Product__c,            Annual_Contract_Value__c, T_E__c, Type_of_Contract__c, Total_Days_Sold__c, No_of_Seats_Delivered__c, No_of_Days_Delivered__c, No_of_Seats_Pending__c, No_of_Days_Pending__c, Special_Deals__c, Notes__c, of_Discount__c, Delivered_By__c, Delivery_Dates__c, Trainer_Name__c, Average_Revenue_per_day__c, Requires_Services_Head_Approval__c, Multi_year_Sub_extension_contract__c FROM OpportunityLineItem  where OpportunityId in: closedWonOpportunities AND No_ARR__c = false AND Service_Type__c = 'Product - Subscription' AND ARR_Impacts__c =: 'Yes'];
            
            //Get all Opportunity Contact Roles
            List<OpportunityContactRole>  oppContactRoleList = [Select Id,ContactId ,Contact.ContactType__c,IsPrimary ,OpportunityId,Role from OpportunityContactRole where OpportunityId in : closedWonOpportunities];
            ////////////Creating Opp - Opp Contact Role Map////////////
            Map<Id,List<OpportunityContactRole>> oppContactRoleMap = new Map<Id,List<OpportunityContactRole>>();
            List<OpportunityContactRole> tmpOCR;
            for(OpportunityContactRole ocr : oppContactRoleList)
            {
                if(oppContactRoleMap.containsKey(ocr.OpportunityId))
                {
                    tmpOCR = oppContactRoleMap.get(ocr.OpportunityId);
                    tmpOCR.add(ocr);
                }
                else
                {
                    tmpOCR = new List<OpportunityContactRole>();
                    tmpOCR.add(ocr);
                    oppContactRoleMap.put(ocr.OpportunityId, tmpOCR);
                }
            }
            ///////////////////////////////////////////////////////////
            
            Map<string,List<OpportunityLineItem>> oppProductMapEndDate = new Map<string,List<OpportunityLineItem>>();       
            List<OpportunityWrapper> owList = new List<OpportunityWrapper>();
            
            /////////Creating Opportunity Wrapper List////////
            List<OpportunityLineItem> tmpList;
            for(OpportunityLineItem oli: oppProdList)
            {
                string key = oli.OpportunityId + '~' + String.valueOf(oli.End_Date__c);         
                if(oppProductMapEndDate.containsKey(key))
                {
                    tmpList = oppProductMapEndDate.get(key);
                    tmpList.add(oli);
                }
                else
                {
                    //Create Opportunity Wrapper 
                    OpportunityWrapper ow = new OpportunityWrapper();
                    ow.opp = oppMap.get(oli.OpportunityId);
                    ow.endDate = oli.End_Date__c;
                    owList.add(ow);
                    
                    tmpList = new List<OpportunityLineItem>();
                    tmpList.add(oli);
                    oppProductMapEndDate.put(key, tmpList);
                }
            }
            
            ///////////////////////////////////////////////////////////
            List<Opportunity> newOpportunities = new List<Opportunity>();
            
            List<OpportunityLineItem> newOpportunityLineItems = new List<OpportunityLineItem>();
            Map<string, List<OpportunityLineItem>> newOLIMap = new Map<string, List<OpportunityLineItem>>();
            
            List<OpportunityContactRole> newOpportunityContactRoles = new List<OpportunityContactRole>();
            Map<string, List<OpportunityContactRole>> newContactRolesMap = new Map<string, List<OpportunityContactRole>>();
                    
            ////Create Opportunity/Opporunity Line Items/Opportunity Contact Role Clone///
            System.debug('oppProductMapEndDate::' + oppProductMapEndDate);
            System.debug('owList::' + owList);
            for(OpportunityWrapper ow: owList)
            {
                Opportunity opp = ow.opp;
                Opportunity newOpp = opp.clone(false, true, false, false);
                newOpp.StageName = 'Stage 4: Proposal Delivery';          
                newOpp.Probability = 60;                      
                newOpp.LeadSource = 'Subscription Renewal';
                newOpp.CloseDate = ow.endDate.addDays(1);
                newOpp.Type = 'Existing Customer';
                ///Added by MK - 29 July 2015///
                newOpp.Assigned_Sales_Engineer__c = null;
                string nameStr = opp.Name;
                /*if(nameStr.indexOf('-Renewal') > -1)    
                {               
                    string substr = nameStr.substring(nameStr.indexOf('-Renewal'), nameStr.length());
                    nameStr = nameStr.remove(substr);
                }
                newOpp.Name = nameStr + '-Renewal ' + String.valueOf(ow.endDate.Year());*/
                if(nameStr.startsWith('Renewal ('))    
                {               
                    string substr = nameStr.substring(0, nameStr.indexOf(' - ') + 3); //plus 3 for ' - '
                    nameStr = nameStr.remove(substr);
                }
                newOpp.Name = 'Renewal (' + String.valueOf(ow.endDate.Year()) + ') - ' + nameStr;
                integer nameLength = newOpp.Name.length();
                if(nameLength > 120)
                    Trigger.new[0].addError('The Renewal Opportunity Name exceeds the maximum length of 120. Please trim the Opportunity Name to create the Renewal Opportunity.');
                newOpp.Parent_Opportunity__c = opp.Id;
                newOpp.Contain_Renewable_Subscription__c = true;
                newOpp.Update_Complete__c = false;
                newOpp.Contracts_Processed__c = false;  
                newOpp.Closed_Won__c = false;
                newOpp.Activate_Notification_to_Finance__c = false;
                newOpp.Stage_won_lost_set__c = false;      
                newOpp.ForecastCategoryName = 'Pipeline';               
                
                string key = opp.Id + '~' + String.valueOf(ow.endDate);
                string key1 = opp.Id + '~' + String.valueOf(newOpp.CloseDate);
                double inYearBillingAmount = 0;
                if(oppProductMapEndDate.containsKey(key))
                {
                    List<OpportunityLineItem> tmp1;
                    //Create Opportunity Line Item Clone////
                    for(OpportunityLineItem oli: oppProductMapEndDate.get(key))
                    {           
                        OpportunityLineItem newOli = oli.clone(false, true, false, false);
                        newOli.Start_Date__c = oli.End_Date__c.addDays(1);
                        newOli.End_Date__c = oli.End_Date__c.addMonths(12);
                        /*newOli.Term__c =  12;
                        newOli.UnitPrice = oli.UnitPrice/(oli.Term__c/12);
                        newOli.In_Year_Billing__c = oli.In_Year_Billing__c/(oli.Term__c/12); */
                        newOli.Term__c =  oli.Term__c;                  
                        newOli.UnitPrice = oli.UnitPrice;
                        newOli.In_Year_Billing__c = oli.In_Year_Billing__c;
                        newOli.Parent_Opportunity_Product_Id__c =   oli.Id; 
                        newOli.Original_Amount__c = oli.Orig_Total_Price__c; 
            newOli.Original_ARR__c = oli.Annual_Recurring_Revenue__c; 
            newOli.Original_In_Year_Billing__c = oli.In_Year_Billing__c; 
                        newOli.Actual_Renewal_Date__c = oli.End_Date__c.addDays(1);
                        inYearBillingAmount = inYearBillingAmount + newOli.In_Year_Billing__c;
                        if(newOLIMap.containsKey(key1))
                        {
                            tmp1 = newOLIMap.get(key1);
                            tmp1.add(newOli);                   
                        }
                        else
                        {
                            tmp1 = new List<OpportunityLineItem>();
                            tmp1.add(newOli);
                            newOLIMap.put(key1,tmp1);
                        }
                    }                   
                }
                
                newOpp.X1st_3_months_Invoice__c = inYearBillingAmount;               
                newOpportunities.add(newOpp);
                
                ///Creating Contact Roles////
                if(oppContactRoleMap.containsKey(opp.Id))
                {
                    List<OpportunityContactRole> oppContactRoles = oppContactRoleMap.get(opp.Id);
                    List<OpportunityContactRole> tmp2;
                    //Create Opportunity Contact Role Clone////
                    for(OpportunityContactRole ocr: oppContactRoles)
                    {           
                        OpportunityContactRole newOCR = ocr.clone(false, true, false, false);                   
                        if(newContactRolesMap.containsKey(key1))
                        {
                            tmp2 = newContactRolesMap.get(key1);
                            tmp2.add(newOCR);                   
                        }
                        else
                        {
                            tmp2 = new List<OpportunityContactRole>();
                            tmp2.add(newOCR);
                            newContactRolesMap.put(key1,tmp2);
                        }
                    }
                } 
            }
           ///////////////////////////////////////////////////////////
           System.debug('newOpportunities::' + newOpportunities);
            try
            {
                if(newOpportunities.size() > 0)         
                    insert newOpportunities;
                    
                //Updating Oppotunity Id in Opportunity Product            
                for(Opportunity o:newOpportunities)
                {
                    string key = o.Parent_Opportunity__c + '~' + String.valueOf(o.CloseDate);
                    if(newOLIMap.containsKey(key))
                    {
                        List<OpportunityLineItem> nOliList = newOLIMap.get(key); 
                        for(OpportunityLineItem nOli: nOliList)
                        {
                            nOli.OpportunityId = o.Id;
                            newOpportunityLineItems.add(nOli);
                        }
                    }
                    if(newContactRolesMap.containsKey(key))
                    {
                        List<OpportunityContactRole> nOCRList = newContactRolesMap.get(key); 
                        for(OpportunityContactRole nOCR: nOCRList)
                        {
                            nOCR.OpportunityId = o.Id;
                            newOpportunityContactRoles.add(nOCR);
                        }
                    }
                }
                
                if(newOpportunityLineItems.size() > 0)
                    insert newOpportunityLineItems;
                if(newOpportunityContactRoles.size() > 0)
                    insert newOpportunityContactRoles;
                //////////////////////////////////////////////////////////////////////////////////////////////////////
                
                //////////////////Update Parent Contract with Renewal Opporunity Info/////////////////////////////////////////////////
                if(newOpportunityLineItems.size() > 0)
                {
                    List<OpportunityLineItem> oliAll = [Select Id,Parent_Opportunity_Product_Id__c,Opportunity.StageName,Opportunity.Probability, Opportunity.OwnerId,Opportunity.Comments__c,In_Year_Billing__c,Type_Of_Product__c,
                    Annual_Contract_Value__c from OpportunityLineItem where Id in: newOpportunityLineItems];
                    updateParentContract(oliAll);
                }
                //////////////////////////////////////////////////////////////////////////////////////////////////////
                
                //////////////////Update Parent Account by tagging the Product Groups of the Opportunity Line Items//////////////////
                
            //Update Accounts   
            updateParentAccount(closedWonOpportunities);
                //////////////////////////////////////////////////////////////////////////////////////////////////////
            }        
            catch(Exception e)
            {
                System.debug('ERROR::' + e.getMessage());
            }       
        }
        ///////////////////Updating Parent Contract with Lost Info///////////////////////
        if(closedLostOpportunities.size() > 0)
        {
            ////Get Opportunity Products for lost Opportunities////
            List<OpportunityLineItem>  oppProdListLost = [Select Id,Parent_Opportunity_Product_Id__c, OpportunityId, Opportunity.Reason_Lost__c FROM OpportunityLineItem  where OpportunityId in: closedLostOpportunities]; 
            
            Set<Id>  parentOLIIds = new Set<Id>();
            Map<Id,string> parentOliMap = new Map<Id,string>(); 
            
            ////Get Parent Opportunity Product Ids////
            for(OpportunityLineItem oli: oppProdListLost)
            {
                if(oli.Parent_Opportunity_Product_Id__c != null && oli.Parent_Opportunity_Product_Id__c != '')
                {
                    parentOLIIds.add(oli.Parent_Opportunity_Product_Id__c);
                    parentOliMap.put(oli.Parent_Opportunity_Product_Id__c,oli.Opportunity.Reason_Lost__c);
                }
            }
            
            ////Get Contracts where Opportunity Product Id matches the Parent Opportunity Product Ids////           
            List<Contract> parentContracts = [Select Id, Opportunity_Product_Id__c, Renewal_Status__c, Adjusted_Comments__c from Contract where Opportunity_Product_Id__c in: parentOLIIds];
            ////Update Renewal Status and Reason lost for these Contracts////   
            for(Contract c : parentContracts)
            {
                c.Renewal_Status__c = 'Renewal Lost';
                if(c.Opportunity_Product_Id__c != null && c.Opportunity_Product_Id__c != '' && parentOliMap.containsKey(c.Opportunity_Product_Id__c))
                {
                    c.Adjusted_Comments__c = parentOliMap.get(c.Opportunity_Product_Id__c);                 
                }
            }
            try
            {
                update parentContracts;
            }
            catch(Exception e)
            {
                Trigger.new[0].addError(e.getMessage());
            }
        }
            
        //////////////////If Opportunity is modified then the parent contract should get updated////////////
        if(allOpportunities.size() > 0)
        {       
            List<OpportunityLineItem> oliAll = [Select Id,Parent_Opportunity_Product_Id__c,Opportunity.StageName,Opportunity.Probability, Opportunity.OwnerId,Opportunity.Comments__c,In_Year_Billing__c,Type_Of_Product__c,
            Annual_Contract_Value__c from OpportunityLineItem where OpportunityId in: allOpportunities];
            updateParentContract(oliAll);
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        
        AvoidRecursiveCloning.setAlreadyCreatedClone();
    }
    void updateParentContract(List<OpportunityLineItem> oliList)
    {
        List<ID> oliParentId = new List<ID>();
        Map<Id,OpportunityLineItem> parentOliMap = new Map<Id,OpportunityLineItem>(); 

        for(OpportunityLineItem oli: oliList)
        {
            if(oli.Parent_Opportunity_Product_Id__c != null && oli.Parent_Opportunity_Product_Id__c != '')
            {
                oliParentId.add(oli.Parent_Opportunity_Product_Id__c);
                parentOliMap.put(oli.Parent_Opportunity_Product_Id__c,oli);
            }
        }
        List<Contract> parentContracts = [Select Id, Opportunity_Product_Id__c, Renewal_Status__c, Adjusted_Comments__c, Stage__c, Probability__c, Notes__c, Owner__c,Contracts_In_Year_Billing__c,Type_Of_Product__c,
        Annual_Contract_Value__c from Contract where Opportunity_Product_Id__c in: oliParentId];
        for(Contract c : parentContracts)
        {
            if(c.Opportunity_Product_Id__c != null && c.Opportunity_Product_Id__c != '' && parentOliMap.containsKey(c.Opportunity_Product_Id__c))
            {
                OpportunityLineItem oli = parentOliMap.get(c.Opportunity_Product_Id__c);
                c.Stage__c = oli.Opportunity.StageName;
                c.Probability__c = oli.Opportunity.Probability;
                c.Owner__c = oli.Opportunity.OwnerId;
                c.Notes__c = oli.Opportunity.Comments__c;
                c.Type_Of_Product__c = oli.Type_Of_Product__c;
                c.Annual_Contract_Value__c = oli.Annual_Contract_Value__c;
                c.Contracts_In_Year_Billing__c = oli.In_Year_Billing__c;
            }
        }
        try
        {
            update parentContracts;
        }
        catch(Exception e)
        {
            Trigger.new[0].addError(e.getMessage());
        }   
    }
    //Method - Update Parent Account
    void updateParentAccount(List<Opportunity> optyList)
    {
    List<Account> accsToUpdate = new List<Account>(); 
    Account[] accList = new Account[]{};
    Map<ID,Set<String>> aIdToUniqueProductSetMap = new Map<ID,Set<String>> ();
    List<String> impactedOpps = new List<String>();  
    for(Opportunity io : optyList){
        impactedOpps.add(io.Id);
    }
    
    System.debug('#####closed won opps inside updateParent:'+impactedOpps.size() );
    //Go through each impacted Oppo and collect a unique set of Product names from all OLI
    for (Opportunity o : [select id, accountId, (select id, PricebookEntry.Product2.Name, PricebookEntry.Product2.Product_Group__c from OpportunityLineItems) from Opportunity where id IN :impactedOpps] ) {
        Set<String> productsInOppoSet = new Set<String> (); // reset the set for this Oppo
        for (OpportunityLineItem olip : o.opportunityLineItems) 
        {
        if(olip.PricebookEntry.Product2.Product_Group__c != null && olip.PricebookEntry.Product2.Product_Group__c != '')
        productsInOppoSet.add(olip.PricebookEntry.Product2.Product_Group__c);
        }
        // With the unique set, add it into our Map associating each account to its unique product set
        if(aIdToUniqueProductSetMap.containsKey(o.accountId)) {
        Set<String> uniqueProdSet = aIdToUniqueProductSetMap.get(o.accountId); // add this Oppo's unique set to whatever we have so far
        uniqueProdSet.addAll(productsInOppoSet);
        aIdToUniqueProductSetMap.put(o.accountId,uniqueProdSet); // put it back in the Map
        }    
        else
        aIdToUniqueProductSetMap.put(o.accountId,productsInOppoSet); // first Oppo for this Account; simply do a put      
    }

    // displays all keys
    System.debug('####all keys in the map: ' + aIdToUniqueProductSetMap.keySet()); 
    // displays all values
    System.debug('####a all values in the map (as a List): ' + aIdToUniqueProductSetMap.values());

    accList =  [Select id,SteelEye__c, Jump_Start_Subscription__c,PEM__c, xDB__c, PPAS__c, PPCD__c,PPSP__c,PGSQL__c, PPAS_Developer_Sub__c, PPSP_Developer_Sub__c, PGSQL_Developer_Sub__c, RDBA__c, Services__c, Training__c from Account WHERE Id in :aIdToUniqueProductSetMap.keySet()];

    System.debug('accList::' +accList);
    //For each account in the list
    for(Account acc : accList){     

    Set<String> prodGroupSet = aIdToUniqueProductSetMap.get(acc.Id);
    
    system.debug('prodGroupSet:' +prodGroupSet);
    
    for(String groupName : prodGroupSet){
        if(groupName.contains('PEM'))
        acc.PEM__c = true;

        if(groupName.contains('xDB'))
        acc.xDB__c = true;

        if(groupName.contains('PPAS'))
        acc.PPAS__c = true;

        if(groupName.contains('PPCD'))
        acc.PPCD__c = true;

        if(groupName.contains('PPSP'))
        acc.PPSP__c = true;

        if(groupName.contains('PGSQL'))
        acc.PGSQL__c = true;

        if(groupName.contains('PPAS_Developer_Sub'))
        acc.PPAS_Developer_Sub__c = true;

        if(groupName.contains('PPSP_Developer_Sub'))
        acc.PPSP_Developer_Sub__c = true;

        if(groupName.contains('PGSQL_Developer_Sub'))
        acc.PGSQL_Developer_Sub__c = true;

        if(groupName.contains('RDBA'))
        acc.RDBA__c = true;

        if(groupName.contains('Services'))
        acc.Services__c = true;

        if(groupName.contains('Training'))
        acc.Training__c = true;             

        if(groupName.contains('SteelEye'))
        acc.SteelEye__c = true;             

        if(groupName.contains('Jump_Start_Subscription'))
        acc.Jump_Start_Subscription__c = true;             
        }
    //add accounts to be updated to the list    
    accsToUpdate.add(acc); 
    }   
    try
    {
    //update accounts 
    if (accsToUpdate != null && !accsToUpdate.isEmpty())
    Database.update(accsToUpdate); 
    }
    catch(Exception e)
    {
    Trigger.new[0].addError(e.getMessage());
    }   
    }
    
    public class OpportunityWrapper
    {
        public Date endDate{get;set;}
        public Opportunity opp {get;set;}
    }
}
Any help very much appreciated.


 
Sai Kalyan SanisettySai Kalyan Sanisetty
Hi,

Please check whether you spesified the that SOQL inside the for loop?

Thanks
Sai
SalesforceCrm AccountCRMSalesforceCrm AccountCRM
@Sai Kalyan Sanisetty
Thanks for your response.The Soql is outside the for loop and its for the other trigger .
The trigger and test class which i posted ...i would like it to move into production but the system keeps throwing the error.
Is the test class which i have written is correct for the trigger.Any suggestion plz.
Any help very much appreciated
Sai Kalyan SanisettySai Kalyan Sanisetty
for the Quick fix , you can use the try catch in the test class
SalesforceCrm AccountCRMSalesforceCrm AccountCRM
@Sai Kalyan Sanisetty :
The trigger code is showing 0%.How to get the code coverage and deploy it.
Praveen KHariPraveen KHari
Hi,

Please use Test.startTest(); amd Test.stopTest(); for using your limit smart in test classes.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_start_stop_test.htm

-Praveen K Hari
Praveen KHariPraveen KHari
For an example, in your code you are inserting account, contact etc... they are not required to be in this test scope for this trigger. so keep only Opportunity  object related DML operations test scope.

Test.startTest();
//Code for Opportunity object transactions
Test.stopTest();


-Praveen K Hari
 
RatanRatan
@isTest
public class TestCreateSubscriptionOpptyClone1 
{
    static testMethod void test1()
    {
        Account acc1 = new Account(Name='Testing SubscriptionClone', BillingStreet='Banjara hills', BillingCity='Hyd', BillingState='TS',
                                    BillingPostalCode = '500084', BillingCountry = 'India', Phone = '100', Industry = 'Banking',
                                    Type = 'Paid', Customer_Type__c = 'Customer', Customer_List__c = true);
        insert acc1 ;
        contact cc = new contact(FirstName ='Test Contact Subscription', LastName ='Opptyclone', Role__c='Subscription Administrator',AccountId=acc1.Id);
        insert cc;
        
        Opportunity opty = new Opportunity(Name = 'Test SubscriptionOppty', StageName ='Proposal/Price Quote', Probability =60, 
                                            CloseDate = System.Today(), Type = 'Existing Customer', Assigned_Sales_Engineer__c = null, 
                                            Update_Complete__c = true, Partner__c = 'None', Anchor__c='Non Anchor', AccountId = acc1.Id,
                                            Payment_Type__c = 'Order Form', LeadSource = 'Subscription Renewal');
        insert opty;
        
        
        
        
        list<OpportunityContactRole> opptyConRolelist1 =  new list<OpportunityContactRole>{
            new OpportunityContactRole(ContactId = cc.Id, OpportunityId = opty.Id, IsPrimary = false, Role = 'Subscription Administrator')
        };   
        insert opptyConRolelist1;
        
        product2 p2 = new product2(Name ='Postgres Plus Enterprise Edition Unicores', Product_Name1__C='Product - Subscription', Product_Group__c='PPAS',
                                    IsActive = true, Description='Postgres Plus Enterprise Edition Unicores', ARR_Impact1__c = 'Yes');
        insert p2;
        
        PricebookEntry pbey = new PricebookEntry(Product2ID=p2.id, Pricebook2ID= test.getStandardPricebookId(), UnitPrice=50, isActive=true);
        insert pbey;
        
        Opportunitylineitem ooli = new Opportunitylineitem(OpportunityId = opty.Id, PricebookEntryId = pbey.Id, Quantity =4, 
                                    Start_Date__c = System.today(), End_Date__c =  System.today() + 100, Type_of_Contract__c='None',
                                    Term__c =12, Type_Of_Product__c='Single Year Subscription', Type_of_ARR__c= 'New Addition ARR',
                                    TotalPrice=1750, No_ARR__c = false, In_Year_Billing__c = 10);
        insert ooli;
        
        Opportunitylineitem ooli1 = new Opportunitylineitem(OpportunityId = opty.Id, PricebookEntryId = pbey.Id, Quantity =4, 
                                    Start_Date__c = System.today(), End_Date__c =  System.today() + 100, Type_of_Contract__c='None',
                                    Term__c =12, Type_Of_Product__c='Single Year Subscription', Type_of_ARR__c= 'New Addition ARR',
                                    TotalPrice=1750, No_ARR__c = false, In_Year_Billing__c = 10, Parent_Opportunity_Product_Id__c=ooli.Id);
        insert ooli1;
        
         Contract contr = new Contract(CurrencyIsoCode='USD', Annual_Contract_Value__c =5000, Type_Of_Product__c='Single Year Subscription',
                                        Notes__c='Contract is getting created', Opportunity_Product_Id__c= ooli.Id, Contracts_In_Year_Billing__c=1500,
                                        AccountId=acc1.Id);
        insert contr;
        
        opty.StageName = 'Closed Won';
        AvoidRecursiveCloning.cloneCreated = false;
        
        Test.startTest();
        update opty;
        
        opty.StageName = 'Closed Lost';
        AvoidRecursiveCloning.cloneCreated = false;
        update opty;
        
        Test.stopTest();
    }
}

This will work for you..