Sub topic 10
Automating follow-up tasks and stage-change logging
Earlier chapters covered logging by hand and automatic capture of email and meetings. This chapter covers a third layer: rules that run when a deal changes and create the follow-up work or the history entry for you.
This chapter assumes you can do four things:
- Move a deal or opportunity between stages.
- Create a task linked to a deal and a contact.
- Read a simple SOQL query or a JSON response.
- Explain what an association is.
The code samples use Apex and Python, but you can follow the chapter without running them.
What automation should and should not do
Automation is good at work that is predictable and tied to an event. A deal reaching a stage is such an event. The follow-up that always comes after it is the predictable work.
Good candidates:
- Create a "send proposal follow-up" task three days after a deal enters the proposal stage.
- Create a "confirm kickoff date" task when a deal is marked won.
- Create a task for the owner when a deal has had no activity for 14 days.
- Keep a record of every stage change, with the old stage, the new stage, the date and the person who made the change.
Poor candidates:
- Writing the content of a call note. The outcome and next step have to come from the person who was on the call.
- Moving a deal forward because an email arrived. A reply is not evidence that the buyer agreed to anything.
- Creating a task for every minor edit. Reps learn to ignore a task list that fills up with noise, and then they miss the tasks that matter.
A rule is worth building when the answer to "should this task exist?" is almost always yes for that event.
The anatomy of a rule
Salesforce and HubSpot name the parts differently, but every rule has the same three parts.
| Part | Question it answers | Salesforce term | HubSpot term |
|---|---|---|---|
| Trigger | What event starts the rule? | Record-triggered flow start, or Apex trigger | Enrollment trigger |
| Condition | Does this particular record qualify? | Entry conditions, decision element | Filters, if/then branches |
| Action | What should happen? | Create Records, Update Records | Create task, set property, send notification |
Two things in the diagram matter in practice. The check for an existing task prevents duplicates, which is the most common automation defect. The history entry is a separate path, because the CRM records stage history whether or not you build any rule.
Salesforce: Flow first, Apex when needed
For most follow-up tasks, build a record-triggered Flow. A Flow is Salesforce's visual automation tool. It needs no code, and an admin can edit it later.
A typical setup looks like this:
- Create a record-triggered flow on the Opportunity object.
- Set it to run when a record is updated, after the record is saved.
- Add entry conditions:
StageNameequalsProposal/Price Quote, and the stage has changed. The "only when the record is updated to meet the condition requirements" option, or the$Record__Priorglobal, gives you the "has changed" check. - Add a Create Records element for a Task. Set
WhatIdto the opportunity Id,OwnerIdto the opportunity owner, a subject, and a due date such as three days from today.
Write Apex when the logic outgrows a Flow. Examples are checks across many related records, or calls to an external system. The trigger below does the same job as the Flow above:
trigger OpportunityStageFollowUp on Opportunity (after update) {
List<Task> newTasks = new List<Task>();
for (Opportunity opp : Trigger.new) {
Opportunity before = Trigger.oldMap.get(opp.Id);
Boolean stageChanged = opp.StageName != before.StageName;
if (stageChanged && opp.StageName == 'Proposal/Price Quote') {
newTasks.add(new Task(
Subject = 'Follow up on proposal for ' + opp.Name,
Status = 'Not Started',
Priority = 'Normal',
ActivityDate = Date.today().addDays(3),
WhatId = opp.Id,
OwnerId = opp.OwnerId
));
}
}
if (!newTasks.isEmpty()) {
insert newTasks;
}
}The trigger shows three habits worth copying:
- It compares
Trigger.newMapvalues toTrigger.oldMapvalues, so it fires only when the stage changes. Without that comparison, any later edit to the opportunity (a new amount, for example) would create another task. - It collects tasks in a list and inserts them once. Salesforce limits the number of database operations per transaction, and a data import can update hundreds of opportunities at once. An insert inside the loop would fail on a bulk update.
- It sets
WhatIdexplicitly. This is the association from the earlier chapter. A task withoutWhatIdfloats free of the deal and will not appear in the deal's activity timeline.
The stage name is a string. If your admin renamed the stage, the comparison silently never matches. Check your org's actual picklist values before you deploy.
HubSpot: deal-based workflows
HubSpot automation lives in workflows. Workflow access depends on your Sales Hub or Service Hub tier, so check your plan before you plan around them.
A follow-up rule is built like this:
- Create a deal-based workflow.
- Set the enrollment trigger to "Deal stage is any of" the target stage, such as Contract sent.
- Add a delay if the task should not appear immediately.
- Add a "Create task" action. Set the title, notes, assignee (usually the deal owner) and the due date relative to enrollment, such as 3 days after.
- Review the re-enrollment setting.
Tasks created by a deal workflow are associated with the deal automatically, so they show up in the deal's timeline and in the task queue of the assignee.
Re-enrollment decides whether a deal can pass through the workflow again. It is off by default. That is safe against duplicates but wrong for deals that regularly move backward and forward through a stage. Turn it on only after you decide what should happen the second time. One option is to create a second task. The other is to skip creation if an open task exists. A branch that checks for an open task with the same title is a reasonable guard.
Workflows can also write to the deal itself, for example setting a "Last stage change date" property when the stage changes. That field is useful in reports, as shown later in this chapter.
Logging stage changes
You rarely need to build a rule to record that a stage changed. Both CRMs keep this history.
Salesforce stores one OpportunityHistory row each time stage, amount, close date or forecast category changes. This query returns the path of one opportunity:
SELECT StageName, Amount, CloseDate, CreatedDate, CreatedBy.Name
FROM OpportunityHistory
WHERE OpportunityId = :opportunityId
ORDER BY CreatedDate ASCIf you also want history for custom fields, turn on field history tracking for them in Setup. Salesforce only starts recording a field from the moment you enable tracking, so older changes cannot be recovered.
HubSpot keeps a history for each property. You can read it through the API by asking for propertiesWithHistory:
import os
import requests
deal_id = os.environ["DEAL_ID"]
url = f"https://api.hubapi.com/crm/v3/objects/deals/{deal_id}"
headers = {"Authorization": f"Bearer {os.environ['HUBSPOT_TOKEN']}"}
params = {"propertiesWithHistory": "dealstage"}
resp = requests.get(url, headers=headers, params=params, timeout=30)
resp.raise_for_status()
history = resp.json()["propertiesWithHistory"]["dealstage"]
for entry in sorted(history, key=lambda e: e["timestamp"]):
print(entry["timestamp"], entry["value"], entry.get("sourceType"))Each entry has the stage ID in value, a timestamp, and a sourceType that tells you whether a person, an import, an integration or a workflow made the change. The values are internal stage IDs, so map them to labels in your own account.
The system history records what changed but not why. If a deal moved to Closed lost, the history shows the date and the user, not the reason. Add a required "Closed lost reason" field, or a rule that creates a note prompt, when the reason matters. A rule can notify the owner and create a task titled "Record loss reason", but a person still has to fill it in.
Failure modes
Automation fails in a small number of repeatable ways. Check for each one before you turn a rule on.
- Duplicate tasks. Causes include a trigger that fires on every update, re-enrollment turned on, or two rules (one Flow, one Apex trigger) doing the same job. Compare old and new values, and check for an open task with the same subject before you create another.
- Loops. A rule that updates a deal field can start another rule that updates it back. Salesforce stops runaway recursion with limits and errors, and HubSpot may enroll the deal repeatedly. Keep each rule's output from matching another rule's trigger.
- Wrong owner. If a task is assigned to a default user instead of the deal owner, the right person never sees it. If the owner is deactivated, creation can fail or the task is orphaned. Decide on a fallback, such as the owner's manager or a queue.
- Stale conditions. A rule written for the stage name "Proposal" stops working when the stage is renamed or when a new pipeline is added. Review rules whenever the pipeline changes.
- Bulk and import effects. A data import that sets stages on thousands of deals can create thousands of tasks at once. Many teams add a condition to skip records created by an integration user or an import, or they switch the rule off during imports.
- Time zones and weekends. A due date of "today plus 3 days" can land on a Saturday. Decide whether weekends count, and what time zone the due time uses.
- Missing associations. A task attached to the deal but not to a contact is hard to act on. When the follow-up is a call to a particular person, associate the primary contact too.
Deciding how much to automate
Choose the least automation that solves the problem. A short decision guide:
| Situation | Suggested approach |
|---|---|
| Same task after every move to a stage | Flow or workflow creates the task |
| Task content depends on the conversation | Rep creates it by hand, with a template as a starting point |
| Need to know when a stage changed | Use the built-in history, no rule needed |
| Need a stage-change date in a report | Use a date property or field set by a rule, or the history object |
| Need logic across systems | Apex, or an integration platform, with a developer reviewing it |
Keep a short document that lists each active rule: its trigger, what it creates, who owns it and when it was last reviewed. Rules are easy to add and rarely removed. Without the list, nobody knows why a deal received a task on Tuesday.
Checking that a rule works
Verify the result the same way you verify any logged data.
- Move a test deal into the target stage and confirm exactly one task appears, with the right owner, due date and associations.
- Edit another field on the same deal and confirm no second task appears.
- Move the deal out of the stage and back in, and confirm the behavior you chose for the second pass.
- Run the history query or API call and confirm the stage change was recorded with the expected user.
- After a week live, run a report that counts tasks created by the rule per deal. A count above one per stage visit points to duplicates.
Exercise
A Salesforce Apex trigger on Opportunity creates a "Follow up on proposal" task whenever the stage equals "Proposal/Price Quote". Reps report that a task appears every time they edit the amount on a deal in that stage. What is wrong, and what is the fix?
Show answer
The trigger tests only the current stage value, so it fires on every update to an opportunity that is in that stage. The fix is to compare the new value with the old one (Trigger.oldMap.get(opp.Id).StageName != opp.StageName) so the task is created only when the stage actually changes. A further guard is to check for an existing open task with the same subject on that opportunity.
Exercise
In HubSpot, a deal-based workflow creates a "Send contract reminder" task when a deal reaches Contract sent. A deal moves from Contract sent back to Negotiation and then to Contract sent again, but no second task is created. Why, and when might you change this?
Show answer
Re-enrollment is off by default, so a deal that has already been through the workflow does not enter it again. Turn on re-enrollment for the stage trigger if deals legitimately repeat the stage and each visit needs its own reminder. Pair it with a check for an open task of the same title so that an impatient rep who moves the deal back and forth does not generate duplicates.
Exercise
Your manager wants a report of how long each deal spent in each stage. Do you need to build a workflow that logs every stage change?
Show answer
No. Salesforce already stores OpportunityHistory rows with the stage and the change date, and HubSpot keeps property history for the deal stage, which you can read with propertiesWithHistory or use in deal-stage duration reports. A rule is only needed for something the built-in history lacks, such as a reason for a loss.