The automation engine is the clinic's reflex layer. It listens to events (a session is Done, a lead is created, a payment fails) and reacts (send a confirmation, create a follow-up task, alert a manager). Most clinics underuse it. The first dozen rules you enable will pay for the year. This article walks the model, gives a working example library you can copy, and shows how to test before you ship.

Where it lives#

  • Automations → Built-in automations is the locked catalog. Enable, disable, configure per-tenant knobs on platform-shipped rules.
  • Automations → Custom automations is where you build your own rules. List, create, edit, enable, disable, delete, Preview.
  • Reports → Automations → Run history is not yet shipped in the UI.
Coming soon. The behaviour described below is on the roadmap. Today: every fire is recorded in the backend log, but the only way to read it is via support. Ask for the run history of a specific rule and an engineer pulls it for you.

The model, three parts#

1. Trigger#

An event the system emits. The trigger picker is a typeahead over the registered event names (for example booking.session.created.v2, sales.invoice.created.v2) plus the special scheduler.cron for time-based rules. Common ones:

  • booking.session.created.v2, arrived.v2, cancelled.v2, no_show.v2, rescheduled.v2, completed.v2
  • sales.invoice.created.v2, sales.payment.paid.v2, sales.cashback.awarded.v2
  • marketing.lead.created.v2, assigned.v2, stage_changed.v2
  • customers.patient.created.v2
  • scheduler.cron, paired with a schedule expression in the Schedule section

Friendly names like "Invoice overdue T+14", "Birthday T-0", "No-show streak", and "Package about to expire" are not registered events today. They need scheduled-tick handlers to be added by engineering before they appear in the picker. Choose the exact trigger offered by the catalog. Preview checks a sample payload; use a controlled live test to verify that the real event reaches the rule.

All production events are v2. The engine matches on the underlying event id.

2. Condition#

Optional filters narrow the trigger. Examples:

  • Patient is VIP-tagged.
  • Session is at branch X.
  • Invoice amount > AED 500.
  • Lead source = Meta.
  • Patient marketing-consent = yes.
  • Time-of-day inside / outside quiet hours.
  • Patient is > 18 years old.
  • Provider is Dr. X.

In the designer you get a flat list of rule rows (field, operator, value) combined with a single ALL (and) or ANY (or) switch. Operators: eq, ne, gt, gte, lt, lte, in, contains, starts_with, ends_with, matches, is_null, is_not_null, is_empty, is_not_empty, is_true, is_false.

For nested groups ((A and B) or (C and D)) or NOT, the engine accepts the full JSON-Logic tree but the FE designer does not render it. Power users hand-edit the rule's JSON via the API. Read your condition out loud before saving. A wrong condition is the most common rule-bug.

3. Action#

What to do. The released action types in the runner today:

  • send_whatsapp renders a template plus variables and dispatches via the messaging layer.
  • send_sms has the same shape, SMS channel.
  • send_email takes subject, body, optional attachment.
  • create_task takes title, assignee, due date, linked record.
  • award_club_points and deduct_club_points credit or debit the patient's loyalty wallet.
  • add_customer_tag and remove_customer_tag manipulate tags.
  • add_lead_note appends a note to a lead.
  • http_webhook calls POST / GET / PUT / PATCH to a tenant-supplied URL. The SSRF guard blocks private IPs and redirects.
  • emit_event puts a follow-up event on the bus. Other rules can subscribe.
  • if evaluates a sub-condition and runs a then-branch or an else-branch.

Actions not in this list ("update lead stage", "fire in-app notification", "wait N hours", "push to mobile") are not available from the designer yet. Some land via emit_event chained to an existing listener. Others wait for the roadmap (see Coming soon).

Example library, the rules every clinic should consider#

Patient lifecycle#

  • Welcome new patient: trigger Patient created → action send WhatsApp welcome template with clinic intro.
  • Birthday wish: trigger Birthday T-0 → condition Marketing consent = yes → action send WhatsApp birthday template, optionally include a small offer.
  • First-visit follow-up: trigger Session Done where session number = 1 → wait 24h → action send WhatsApp "how was your visit" template.

Booking and attendance#

  • Appointment confirmation: trigger Session booked → action send confirmation template.
  • Reminder T-24h: trigger scheduled relative to session start (-24h) → action send reminder.
  • Reminder T-2h: trigger scheduled relative to session start (-2h) → action send reminder.
  • No-show recovery: trigger Session missed → action create "call patient" task on the responsible rep.
  • No-show streak: trigger 3 no-shows within 60 days → action tag patient watch + create task for manager.

Sales and payment#

  • Invoice issued reminder: trigger Invoice issued (unpaid) → wait 3 days → action send WhatsApp payment-reminder template.
  • Overdue collection task: trigger Invoice overdue T+14 → action create collection task for accountant.
  • Receipt on payment: trigger Invoice paid → action send receipt by email + WhatsApp.
  • Package credit low: trigger Package credits remaining = 1 → action send "your last session is coming up, top up" message.
  • Package expiry warning: trigger Package about to expire T-30 → action send "do not lose your unused sessions" message.

Lead funnel#

  • SLA breach: trigger Lead created where Open > 1h → action notify rep + create task.
  • Auto-nurture day 3: trigger Lead created → wait 3 days → condition Lead still Open → action send "thinking of trying us out" message.
  • Lost reactivation T+90: trigger Lead stage = Lost for 90 days → action target with reactivation campaign.

Clinical#

  • Critical result alert: trigger Clinical result critical → action in-app + push to ordering provider + create review task.
  • Stalled treatment plan: trigger Plan with no session in 30 days → action create re-engage task for provider.
  • Post-procedure check: trigger Session Done where service category = post-op-eligible → wait 7 days → action send "how are you healing" message.

Inventory#

  • Low stock reorder: trigger Stock below reorder point → action create reorder task for inventory manager.
  • Near-expiry batch: trigger Batch within 30 days of expiry → action notify inventory + create dispense-first task.

Operations#

  • Daily morning brief: trigger Scheduled 08:00 → action send to manager: today's appointments, open balances, low stock.
  • End-of-day reconciliation reminder: trigger Scheduled 20:00 → action send to reception: "reconcile the cash drawer".
  • Month-end checklist: trigger Scheduled day 28 → action send month-end checklist to accountant.

Multi-step automations#

Two shapes exist, and the boundary matters.

  • Same-tick chain (custom automations): the actions list runs top to bottom inside a single trigger. Use this for "send the WhatsApp and create the task and award points", all on the same event.
  • Sequenced delay flow: "send today, wait 3 days, check stage, send again". The backend ships a workflow engine with delay, condition, branch, parallel steps via WorkflowDefinition plus WorkflowStep.
Coming soon. The behaviour described below is on the roadmap. Today: the FE designer for the sequenced delay flow is not built. There is no Wait block in the custom-automation designer. Author multi-day sequences via API or ask engineering.

If you need a Day-0 → Day-3 → Day-7 sequence today, the workaround is to schedule three separate cron-triggered automations that look at the patient's last-visit date and decide whether to fire.

Testing before you ship#

Preview#

Preview does not send messages. It runs the saved rule in dry-run mode and returns resolved action details. A live execution performs real side effects; use a controlled test recipient when checking actual delivery.
  • Save the rule. Open it. Click Preview.
  • The preview panel shows each resolved action, including fields that did not resolve. It does not confirm real message delivery.

Limited-scope test#

  • Add a condition that only matches a test patient (for example customer.id == 12345) or a test branch.
  • Trigger a real event for that patient. Check that the action ran.
  • Remove the test condition before going live.

What we do not have yet#

Coming soon. The behaviour described below is on the roadmap. Today: Preview provides dry-run evaluation. A separate draft lifecycle and replay of historical events are not available. Keep an unfinished rule disabled.
  • Preview evaluates conditions and resolves action values without dispatching them.
  • Drafts are not shipped. Keep the rule disabled until it is ready.
  • Backfill is planned, not shipped. There is no "run this rule on the last 30 days of events" button. The closest thing is Preview on a single payload.

Common test failures#

  • Trigger picks the wrong event. "Session done" can fire from a service-report submission or from a manager override. Check which.
  • Action uses an unapproved template. WhatsApp drops it silently.
  • Condition references a field the trigger payload does not have. Rule never fires.

Monitoring live rules#

  • Run history: every fire, the trigger payload, the condition outcome, the action result.
  • Failure log: actions that errored (template rejected, recipient opted out, webhook 500).
  • Volume per rule: a rule firing 10,000 times a day was probably misdesigned.
  • Disable and re-design rather than letting a noisy rule erode trust.

Governance discipline#

Coming soon. The behaviour described below is on the roadmap. Today: there is no draft state, no manager-approval gate, and no per-rule version history. Once you save, the prior version is gone.
  • Publishing a rule is a single save. There is no draft to manager-approval gate yet.
  • There is no version history per rule. Save infrequently and Preview before each save.
  • Use the per-rule rate limit to cap fires per period. It is your safety net against a runaway misconfiguration.
  • Quarterly review: open the run log (via support today, in the UI later) and decide which rules earn their keep.

Rate limits and abuse protection#

  • Per-rule rate limit: max fires per period (minutes). Default is unlimited (0). Set this on every rule that can plausibly flood. A misconfigured trigger that fires 1000 times in a minute will be capped.
  • Subscription quota: see Plan quota. A blocked run is logged with reason subscription_quota_exhausted.
  • Recipient safeguards: channel dispatch applies the relevant preferences, marketing suppression, and outbound guards. There is no universal quiet-hours deferral or automatic fallback to another channel. Configure scheduling explicitly and test the selected action.
Coming soon. The behaviour described below is on the roadmap. Today: per-patient daily caps are not enforced. The doc previously claimed "3 transactional + 1 marketing per day", which is not shipped. Tenants self-cap by tuning rule rate limits and template windows for now.

Debugging, my rule didn't fire, read the skip_reason ladder#

The engine writes a row for every dispatched event, including skips. Until the FE run-log view ships, ask support to pull the audit by correlation_id. The answer is one of six skip reasons:

  • disabled: the rule is off (is_enabled = false). Toggle it on.
  • rate_limited: over the per-rule cap. Wait for the period to roll, or raise the cap.
  • branch_filtered: the event's branch is not in the rule's branch list. Either widen the rule's scope or check the source event's branch_id.
  • conditions_not_met: one of the condition rows returned false. Read the payload that was actually emitted. The field name in your condition probably doesn't match the payload shape.
  • quota_blocked: subscription quota exhausted (see Overview).
  • no_actions: the actions list is empty. Add at least one.

If there is no row at all, the event was never emitted, or the trigger event name in the rule does not match any registered event. Verify the source action actually emits. For example, a "session confirmed" rule needs the user to actually save the session to Confirmed.

Debugging, my rule fired but did the wrong thing#

Every run records a list of per-action outcomes in the log. Each entry has:

  • status: sent, emitted, failed, skipped, or branched.
  • detail: the upstream error message or the rendered URL for a webhook.
  • provider_code and upstream_message_id: the messaging provider's id, useful for grepping logs.
  • child_results (only for if actions): the same shape, one per branch action.

Common patterns: a failed with detail: "template not approved" means the WhatsApp body template hasn't been approved by the messaging account. Fix on the template, the rule is fine. A sent but the patient says they didn't get it usually means the patient's number isn't WhatsApp-enabled. A branched with empty child_results means the if-condition matched a branch that had no actions.

Editing a rule while it's in flight#

For same-tick rules (custom automations), every event triggers a fresh evaluation against the current rule. Editing is safe. The next event uses the new version immediately.

For sequenced workflows (the API-only multi-step flow), a WorkflowInstance snapshot of the definition is taken when it starts. Edits to the parent definition do not migrate running instances. They finish on the old steps. If you need to flush in-flight runs, cancel them via support and re-trigger.

Stop a runaway rule#

The kill switch is the Disable toggle on the rule. The next event won't trigger it. There is no partial revert. Runs that already fired actions (sent WhatsApps, posted credits, created tasks) are not reversed.

If you need to revoke side effects (for example un-credit 200 wallets), open a support ticket. The engine logs every action with its target id so reversal is possible per-row, but it is not a one-click operation.

Prevention: set a per-rule rate limit on every new rule, even if you think the trigger is rare. A typo in a condition can turn "rare" into 50 fires per second.

Avoiding loops#

Loop footgun. The emit_event action has no hop limit. The engine does not detect or block circular event chains. The per-rule rate limit eventually caps the loop, but only after a flood of side effects (real WhatsApps, real wallet credits, real webhook calls). Design for prevention, not detection.

Two patterns to avoid:

  • Self-trigger: Rule X emits order.escalated.v2, and X itself is subscribed to order.escalated.v2. The engine does not block this. It would re-fire forever. Pick a different event name per stage.
  • Mutual recursion: X emits Y, Y emits X. Same outcome. Use a guard condition (for example a payload flag __stage) to short-circuit on the second pass, or chain via the same rule's actions list instead of emit_event.

When the trigger event version bumps#

Every backend event is versioned (for example booking.session.created.v2). When engineering bumps a payload shape, the version goes up and the old name stops emitting. A rule pinned to the old name silently stops firing, with no FE warning today.

Two safeguards:

  • The platform runs a one-shot migration command at bump time that updates locked-rule trigger names. Custom-automation triggers also flip automatically as part of the release.
  • After any major release, open Automations → Custom automations, scan the trigger column for any name that ends in an old .vN, and Preview each. Anything that fails on the new payload shape needs a quick condition edit.

Common mistakes#

  • Too many "send message" rules: patients get blasted, opt out, channel reputation falls. Prune ruthlessly.
  • No conditions: rule fires for everyone, including the wrong cohort. Always condition.
  • Hard-coded template instead of variable: every message reads identically, looks like spam.
  • Forgot the marketing-consent condition: opens you to regulator complaints. Always condition marketing rules on consent = yes.
  • Skipping dry-run: first live fire is to the wrong cohort. Test always.
  • Wait blocks in the wrong unit: 3 instead of 3-hours sends weeks later.
  • Rule depends on a deprecated field: silently never fires. Run history catches this.

How automations connect to the rest of the system#

  • All modules: every module emits events the engine listens to.
  • Messaging: most actions land in a message via the messaging layer.
  • Tasks: rules create operational tasks.
  • Campaigns: rules feed lists into campaigns.
  • Notifications: in-app and push come from rules.
  • Reports: rule run history feeds engine-health reports.
  • Audit: every fire and change is auditable.