Assigning Territories to Opportunities can be done manually, but there is an option by which you can automate this process. This blog post is all about writing Apex class to automate the Territory assignment to Opportunity record.
Before I start explaining the Apex code, let me explain two important objects –
- Territory2Type: This represents the category of Territories(Territory2). Every territory must have a Territory2Type. The important field within this object is Priority, which is used in Opportunity filter to assign Territory to Opportunity.
- ObjectTerritory2Association: This represents the association between Territory and Object record, which is Account. This is available only if Enterprise Territory Management is enabled.
- If the Opportunity’s Account record is assigned to no Territory, then Opportunity’s territory2Id field will be null.
- If the Opportunity’s Account record is assigned to 1 Territory, then Opportunity’s territory2Id field will be assigned to same Territory record.
- If the Opportunity’s Account record is assigned to more than 1 Territories, then Opportunity’s territory2Id field will be assigned to that territory record which is having highest priority.
- If multiple territories are having the same priority, then Opportunity’s territory2Id field will null.
- The class OppTerrAssignDefaultLogicFilter is provided by Salesforce. But you can write your own class to implement logic as per your business need and use that. You need to make sure that you class is implementing TerritoryMgmt.OpportunityTerritory2AssignmentFilter interface.
- This class will execute only for those Opportunities where IsExcludedFromTerritory2Filter = false. This is the field named as “Exclude from the territory assignment filter logic” found in Opportunity record. You need to include this field in Opportunity page layout to select/de-select. Otherwise you can use the api to set the value of field IsExcludedFromTerritory2Filter.
- This apex class can work on maximum 1000 opportunities.