We wrote Apex code which changes the owner id in accounts and leads. The code runs in the background when a new account or lead is created.
The apex code checks the record, and changes the owner id to the correct owner, who is assigned to the record’s territory (Billing/ shipping address for account and .
The actual responsible person for each territory is taken from Territory Models, so it was first configured there.
When a user creates an account or lead, our code sets a service flag in the record which prohibits the record from being edited until our apex code checks it for the current ownerID and sets the correct owner for the territory.
Let’s see an example:
Tim, the head of Tilequip Sales in NewYork attends a conference in Houston,
where he meets the CEO of Marazzi. He creates an account. Marazzi’s HQ is located in Sassuolo, Italy.
Tim doesn’t know what team is in charge of Sassuolo, but he finds the Zip code of the company and indicates this on the account.
As soon as he saves the account, our code places a special flag on the handler of the account, to process and prohibit editing the record. This is necessary so that during the change of the ownerid, the user does not break the application.
Then, our code checks the zip code of the new account against the assigned owner. It changes the account owner from Tim to Rosa, who is the sales agent assigned to Sassuolo.
After this, all other record access settings apply, and Tim is no longer able to view the Marazzi account.
Our Apex code runs on an hourly schedule. It goes through all records that have this special flag every hour and compares their zip codes with the rules in territory Models.
Following the rules from territory models, it creates a list of users responsible for the different territories and then, selects the least loaded user in the last month and assigns them as the new record owner.
This solves the problem of unequal workload distribution between old and new employees.
If there were 2 users originally assigned to a territory with 100 accounts/leads each, and then a new agent is assigned to the territory. What happens?
Since our code checks for workload for the last month, the new agent will not receive the next 100 leads. Rather, he will receive them on par with the old users.
After a new owner is assigned to the record, the service flag that forbade editing the record is removed.
This evaluation and owner assignment is carried out ONLY once. The process is not repeated every time the record is updated.