1

when I am trying to deploy the component then I was getting this error like

system.limitexception too many soql queries 101

how to avoid this?

======================================

/**
* @author: Zohar Sinay (zsinay@salesforce.com)
* @date: 1/12/2016
* @description: Handler for Opportunity trigger
*
* @author: Pablo ALBA (SF)
* @date: 16/12/2016
* @description: Update to Trigger Handler FWK
*/
public with sharing class CTH_OpportunityHandler extends TriggerHandler {


    // Maps and list initialized from the Trigger context
    private Map<Id, Opportunity> oldMap;
    private Map<Id, Opportunity> newMap;
    private List<Opportunity> oldList;
    private List<Opportunity> newList;

    // Constructor
    //
    public CTH_OpportunityHandler() {
        this.oldMap = (Map<Id, Opportunity>) Trigger.oldMap;
        this.newMap = (Map<Id, Opportunity>) Trigger.newMap; 
        this.oldList = (List<Opportunity>) Trigger.Old;
        this.newList = (List<Opportunity>) Trigger.New;
    }


    // Handle "Account before insert" event
    //
    public override void beforeInsert(){
        List <Opportunity> opportunitiesToProcess = new List <Opportunity>();
        Set<Id> accountIds = new Set<Id>();

        system.debug('++ hcnewList '+newList);
        for(opportunity opp :newList){
            if(String.isNotBlank(opp.accountId)){
                opportunitiesToProcess.add(opp);
                accountIds.add(opp.accountId);
            }
        }
        linkOpportunityToIrisAccount(opportunitiesToProcess,accountIds); 
        changeMarketAndSubMarket(opportunitiesToProcess,accountIds);


        //DE573 : changeSalesOrganization(newList);

        //DE394
        initOpportunityStakeholders(newList);

        //DE573
        manageOpportunitySalesOrg(newList, oldMap);

        //Update Currency --Alrick
        UpdateCurrencyValues(newList); 
    }

    // Handle "Account before update" event
    //
    //public override void beforeUpdate(){}

    // Handle "Account before delete" event
    //
    //public override void beforeDelete(){}

    // Handle "Account after insert" event
    //
    public override void afterInsert(){
    }

    // Handle "Account after update" event
    //
    public override void beforeUpdate(){

        List <Opportunity> opportunitiesToProcess = new List <Opportunity>();
        List <Opportunity> opportunitiesToMarketProcessing = new List <Opportunity>();
        Set<Id> accountIds = new Set<Id>();
        for(integer i = 0; i < newList.size(); i++){
            if(String.isNotBlank(newList[i].accountId)){
                accountIds.add(newList[i].accountId);
                opportunitiesToMarketProcessing.add(newList[i]);
                if(newList[i].AccountId != oldList[i].accountId)
                    opportunitiesToProcess.add(newList[i]);
            }
        }

        linkOpportunityToIrisAccount(opportunitiesToProcess,accountIds); 
        changeMarketAndSubMarket(opportunitiesToMarketProcessing,accountIds);
        changeTerritory(newMap, oldMap);
        manageStatus(newList);

        List <Opportunity> opportunitiesToProcess1 = new List <Opportunity>();
        // for(Opportunity opp1 : newList)
        {
            //   opportunitiesToProcess1.add(opp1);
        }

        InActiveOffering(newList);
        //DE573
        manageOpportunitySalesOrg(newList, oldMap);
        //Update Currency --Alrick
        UpdateCurrencyValues(newList);
    }


    // Handle "Account after delete" event
    //
    //public override void afterDelete(){}

    // Handle "Account after undelete" event
    //
    //public override void afterUndelete(){}

    /*****************************************************************************************************************************************
* @description (DE573) Identify value of Sales Organization based on Leading Profit Center
* @param newOpportunityList: Opportunities received from the trigger
* @param oldOpportunityMap: Opportunities received from the trigger - old values
*/
    public static void manageOpportunitySalesOrg(List<Opportunity> newOpportunityList, Map<Id, Opportunity> oldOpportunityMap){
        // Process only opportunities where profit center is not null and value changed
        // Initialize also list of GBU+Country Code

        List<Opportunity> listOpportunityToProcess = new List<Opportunity>();
        Set<Id> pcIds = new Set<Id>();
        for (Opportunity opp : newOpportunityList){
            if (null != opp.Profit_Center__c && (null == oldOpportunityMap || opp.Profit_Center__c <> oldOpportunityMap.get(opp.Id).Profit_Center__c)){
                //This for cloning opp, we keep the Sales Org of Master opp
                if (oldOpportunityMap == null && opp.Sales_Organization__c != null) {
                    continue;
                } else {    
                    listOpportunityToProcess.add(opp);
                    pcIds.add(opp.Profit_Center__c);
                }
            }
        }

        // Get list of custom metadata types availables
        Map<String, String> pcToSalesOrg = new Map<String, String>();
        for (ProfitCenterToSalesOrg__mdt mapping :[SELECT Id, MasterLabel, DeveloperName, GBU__c, Country__c, SalesOrganization__c
                                                   FROM ProfitCenterToSalesOrg__mdt]){
                                                       pcToSalesOrg.put(mapping.MasterLabel, mapping.SalesOrganization__c);
                                                   }

        // Get Map of Profit centers
      Map<Id, Profit_Center__c> idToPC = new Map<Id, Profit_Center__c>(
            [SELECT Id, shortname_GBU__c, shortname_country__c
             FROM Profit_Center__c
             WHERE Id IN :pcIds]
        );
        system.debug('idtopc'+idToPC);

       /* Profit_Center__c idToPC1=[SELECT Id, shortname_GBU__c, shortname_country__c
             FROM Profit_Center__c
             WHERE Id IN :pcIds];
           idToPC.add(idToPC1);  */

        // Update sales org value on opportunities to process
        for (Opportunity opp : listOpportunityToProcess){
            Profit_Center__c pc = idToPC.get(opp.Profit_Center__c);
            if (null <> pc && null <> pcToSalesOrg.get(pc.shortname_GBU__c + pc.shortname_country__c)){
                opp.Sales_Organization__c = pcToSalesOrg.get(pc.shortname_GBU__c + pc.shortname_country__c);
            }

        }

    }


    /*****************************************************************************************************************************************
* @description Initialize the opportunity owner as Lead Generator, and the account owner as the Client Leader (DE394)
* @param newOpportunityList: Opportunities received from the trigger
*/
    public static void initOpportunityStakeholders(List<Opportunity> newOpportunityList){

        Set<Id> parentAccountIdSet = new Set<Id>();
        //List<OpportunityTeamMember> opportunityTeamMemberListToInsert = new List<OpportunityTeamMember>();

        for(Opportunity oppy : newOpportunityList){
            if(!String.isBlank(oppy.AccountId)){
                parentAccountIdSet.add(oppy.AccountId);
            }
        }
        Map<Id, Account> parentAccountByIdMap = new Map<Id, Account>([SELECT Id, OwnerId FROM Account WHERE Id IN :parentAccountIdSet]);

        for(Opportunity oppy : newOpportunityList) {            
            if(parentAccountByIdMap.containsKey(oppy.AccountId)){
                oppy.ClientLeader__c = parentAccountByIdMap.get(oppy.AccountId).OwnerId;
            }            
            oppy.LeadGenerator__c = oppy.OwnerId;
        }
    }

    /*
* @author: Hamza CHAGH (hchagh@salesforce.com)
* @date: 24/01/2017
* @description: This method change the value of the field IRIS_Account_tech__c of an opportunity to update it by the id of the parent of the related account
* @param: opportunitiesToProcess: Opportunities received from the trigger
* @return : nothing
*/
    public static void linkOpportunityToIrisAccount (List <Opportunity> opportunitiesToProcess, Set<Id>  accountIds){
        Map<Id,Account> accounts = new Map<Id,Account> ([SELECT ParentId  FROM Account WHERE Id in : accountIds ]);
        for(opportunity opp : opportunitiesToProcess){
            opp.IRIS_Account_tech__c = accounts.get(opp.accountId).ParentId;
        }
    } 

    //ATF:C7052646 
    //@description: Inform users on opportunities with inactive offerings 

     public static void InActiveOffering(List <Opportunity> opportunitiesToProcess){
         LIST<Id> oppid = new LIST<Id>();
         LIST<Id> oppLineid = new LIST<Id>();
         for(Opportunity o : opportunitiesToProcess)
         {
             oppid.add(o.id);
         }

         LIST<OpportunityLineItem> u1 = new LIST<OpportunityLineItem>();
         LIST<OpportunityLineItem> opplineitem = [select ProductCode,OpportunityId,Id, InActiveOfferings__c,OpportunityLineItem.product2.isactive from OpportunityLineItem where OpportunityId  In :opportunitiesToProcess and OpportunityLineItem.product2.isactive=false ];
        system.debug('opplineitem '+opplineitem);
        for (OpportunityLineItem oppline : opplineitem) 
        { 
            oppLineid.add(oppline.OpportunityId); 

            system.debug('oppline.InActiveOfferings__c : '+oppline.InActiveOfferings__c);
            oppline.InActiveOfferings__c = 1;

            u1.add(oppline); 
            system.debug('oppline.InActiveOfferings__c : '+oppline.InActiveOfferings__c);

        } 


          for(Opportunity opp2 : opportunitiesToProcess) 
        {
            if(oppLineid.contains(opp2.Id)){
            system.debug('opp2.InActiveOfferings__c : '+opp2.InActiveOfferings__c);
            opp2.InActiveOfferings__c = 1; 

            system.debug('opp2.InActiveOfferings__c : '+opp2.InActiveOfferings__c); 
            }
        }  
         update u1;
         System.debug('Query Limit SQOL from opp  :'+Limits.getQueries());

    } 

    /*
* @author: Hamza CHAGH (hchagh@salesforce.com)
* @date: 24/01/2017
* @description: This method change the value of fields Market__c , Sub_market__c  of an opportunity to update it by similar fields from related account
* @param: opportunitiesToProcess: Opportunities received from the trigger
* @return : nothing
*/
    public static void changeMarketAndSubMarket (List <Opportunity> opportunitiesToProcess ,  Set<Id> accountIds ){
        Map<Id,Account> accounts = new Map<Id,Account> ([SELECT Market__c , Sub_market__c FROM Account WHERE Id in : accountIds ]);
        for(Opportunity opp : opportunitiesToProcess){
            if(opp.Market__c != accounts.get(opp.accountId).Market__c){
                opp.Market__c = accounts.get(opp.accountId).Market__c;
            }
            else if( opp.Sub_market__c != accounts.get(opp.accountId).Sub_market__c){
                opp.Sub_market__c = accounts.get(opp.accountId).Sub_market__c;
            }
        }
    }

    /*
* @author: Pablo ALBA (palba@salesforce.com)
* @date: 26/01/2017
* @description: This method get sales organization from opprtunity owner
* @return : nothing

public static void changeSalesOrganization (List <Opportunity> opportunitiesToProcess){ 
// Set Id of owner users
Set<Id> userIds = new Set<Id>();
for (Opportunity op : opportunitiesToProcess){
userIds.add(op.OwnerId);
}

if (!userIds.isEmpty())
{
Map<Id, User> users = new Map<Id, User> ([SELECT Sales_Organization__c FROM User WHERE Id in : userIds]);

for(Opportunity opp : opportunitiesToProcess){
if(opp.Sales_Organization__c == null){
opp.Sales_Organization__c = users.get(opp.OwnerId).Sales_Organization__c;
}
}
}
} 
*/

    /*
* @author: Pablo ALBA (palba@salesforce.com)
* @date: 27/01/2017
* @description: This method update the territory of the opportunity if update on the Profit Center
* @return : nothing
*/
    public static void changeTerritory(Map<Id, Opportunity> newOpportunityMap, Map<Id, Opportunity> oldOpportunityMap){ 
        // Set Id of opportunities to process
        List<Id> opportunitiesId = new List<Id>();
        for (Id opId : newOpportunityMap.keySet()){
            if(newOpportunityMap.get(opId).Profit_Center__c <> oldOpportunityMap.get(opId).Profit_Center__c){
                opportunitiesId.add(opId);
            }
        }
        System.debug('In opp Handler '+opportunitiesId);

        CTH_OppTerrAssignFilter oppTerrFilter = new CTH_OppTerrAssignFilter();
        Map<Id,Id> oppIdTerritoryIdResult = oppTerrFilter.getOpportunityTerritory2Assignments(opportunitiesId);

        if (!oppIdTerritoryIdResult.isEmpty())
        {
            for (Id opId : oppIdTerritoryIdResult.keySet()){ 
                newOpportunityMap.get(opId).Territory2Id = oppIdTerritoryIdResult.get(opId);
            }
        }
    }

    /*
* @author: Pablo ALBA (palba@salesforce.com)
* @date: 27/01/2017
* @description: This method update opportunity status
* @return : nothing
*/
    public static void manageStatus(List<Opportunity> newList){ 
        // Set Id of opportunities to process
        for (Opportunity opp : newList)
        {
            if (String.isBlank(String.valueOf(opp.Status__c)))
            {
                opp.Status__c = Constants.OPPY_STATUS_ACTIVE;
            }
        }
    }

    /*
* @author: Alrick Bloomfield (alrick.bloomfield@atos.net)
* @date: 04/04/2018
* @description: This method update the values of all financial values prefix with USD_, GPB_, EUR_
* @param: opportunitiesToProcess: Opportunities received from the trigger
* @return : nothing
*/
    public static void UpdateCurrencyValues(List <Opportunity> opportunitiesToProcess ){

        for(Opportunity opp : opportunitiesToProcess){
            /*
//Order Entry 
opp.USD_Order_Entry__c =CurrencyConverter.convertFromCurrencyToCurrency(opp.CurrencyIsoCode,'USD', opp.Amount,opp.CloseDate);
opp.GBP_Order_Entry__c =CurrencyConverter.convertFromCurrencyToCurrency(opp.CurrencyIsoCode,'GBP', opp.Amount,opp.CloseDate);
opp.EUR_Order_Entry__c =CurrencyConverter.convertFromCurrencyToCurrency(opp.CurrencyIsoCode,'EUR', opp.Amount,opp.CloseDate);

//Weighted Order Entry 
opp.USD_Weighted_Order_Entry__c=CurrencyConverter.convertFromCurrencyToCurrency(opp.CurrencyIsoCode,'USD', opp.WeightedAmount__c,opp.CloseDate);
opp.GBP_Weighted_Order_Entry__c=CurrencyConverter.convertFromCurrencyToCurrency(opp.CurrencyIsoCode,'GBP', opp.WeightedAmount__c,opp.CloseDate);
opp.EUR_Weighted_Order_Entry__c=CurrencyConverter.convertFromCurrencyToCurrency(opp.CurrencyIsoCode,'EUR', opp.WeightedAmount__c,opp.CloseDate);

//Bid Budget
opp.USD_Bid_Budget__c=CurrencyConverter.convertFromCurrencyToCurrency(opp.CurrencyIsoCode,'USD', opp.Bid_Budget__c,opp.CloseDate);
opp.GBP_Bid_Budget__c=CurrencyConverter.convertFromCurrencyToCurrency(opp.CurrencyIsoCode,'GBP', opp.Bid_Budget__c,opp.CloseDate);
opp.EUR_Bid_Budget__c=CurrencyConverter.convertFromCurrencyToCurrency(opp.CurrencyIsoCode,'EUR', opp.Bid_Budget__c,opp.CloseDate);

//TCV Rainbow
opp.USD_TCV_Rainbow__c=CurrencyConverter.convertFromCurrencyToCurrency(opp.CurrencyIsoCode,'USD', opp.TCV_Rainbow__c,opp.CloseDate);
opp.GBP_TCV_Rainbow__c=CurrencyConverter.convertFromCurrencyToCurrency(opp.CurrencyIsoCode,'GBP', opp.TCV_Rainbow__c,opp.CloseDate);
opp.EUR_TCV_Rainbow__c=CurrencyConverter.convertFromCurrencyToCurrency(opp.CurrencyIsoCode,'EUR', opp.TCV_Rainbow__c,opp.CloseDate);

//Currency Rate
opp.USD_TO_EURO_RATE__c = CurrencyConverter.getCurrencyRate('USD',opp.CloseDate);
opp.GBP_TO_EURO_RATE__c = CurrencyConverter.getCurrencyRate('GBP',opp.CloseDate);

*/

            //New Currency conversion 
            //Currency Rate
            opp.USD_RATE_CONV__c= CurrencyConverter.getCurrencyRate('USD',opp.CloseDate);
            opp.GBP_RATE_CONV__c= CurrencyConverter.getCurrencyRate('GBP',opp.CloseDate);
            opp.EUR_RATE_CONV__c= CurrencyConverter.getCurrencyRate(opp.CurrencyIsoCode,opp.CloseDate);

        }
    }


}

closed as off-topic by glls, Pranay Jaiswal, Mr.Frodo, Mohith Shrivastava, battery.cord May 9 at 18:47

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions on problems in code you've written must describe the specific problem and include valid code to reproduce it. For help writing short, self-contained syntactically-valid examples, see: SSCCE.org" – glls, Pranay Jaiswal, Mr.Frodo, Mohith Shrivastava, battery.cord
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    When you deploy code generally your test classes run, so it is possible that issue is not in the trigger but in the related test classes. Please check those. – Mr.Frodo May 9 at 6:18
  • 2
    It looks like recursive call creating this issue. Which method is causing this error , i mean which DML command? – Dhanik Lal Sahni May 9 at 6:59

Browse other questions tagged or ask your own question.