> For the complete documentation index, see [llms.txt](https://adatrack.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://adatrack.gitbook.io/docs/documentation/features/workflows.md).

# Workflows

**AdaTrack Flow** is a powerful, low-code automation engine that allows you to create event-driven workflows for your IoT fleet. Using a visual, node-based interface, you can chain together triggers, logic gates, data transformations, and external actions to automate your operations.

### Key Capabilities

* **Visual Node Editor:** Build automation logic using a drag-and-drop canvas (powered by React Flow).
* **Schema Inference:** Automatically detect and propagate data schemas between nodes to simplify variable mapping.
* **Event-Driven Triggers:** Start workflows based on telemetry arrival, geofence breaches, or fixed schedules.
* **Integrated Intelligence:** Use "Stats Query" nodes to incorporate historical data patterns into your real-time logic.
* **JavaScript Transformations:** Use the built-in JavaScript engine with full ES6+ support (arrow functions, `const`/`let`, template literals, destructuring) to manipulate data and create custom payloads. Scripts are compiled once and cached for performance.
* **Multi-Channel Actions:** Beyond simple alerts—integrate with external APIs, trigger webhooks, or send Slack/Email notifications.
* **Detailed Execution Logs:** Monitor every workflow run with success/failure tracking and error debugging.

### Core Concepts

#### 1. Schema Inference (Variable Mapping)

A key differentiator in AdaTrack Flow is **Schema Inference**. When you connect a trigger (like a Device Profile), the engine automatically "sniffs" the available telemetry fields.

* **Variable Picker:** When configuring subsequent nodes (like a Webhook or Email), you can use a visual picker to select variables (e.g., `payload.temperature`, `device.name`) without manual typing.
* **Data Consistency:** The engine ensures that the data structure is consistent across the entire flow.

#### 2. Triggers (The "When")

Triggers are the starting point of every workflow.

* **Telemetry Received:** Fires whenever a specific device (or profile) sends a valid packet.
* **Geofence Transition:** Fires when a device enters or leaves a defined geofence zone.
* **Geofence Rule:** Fires when a specific [Alert Rule](/docs/documentation/features/alerting.md) matches during a geofence transition. Use this when you want to trigger automation only for a named rule, not every geofence event. Carries the full alert event payload (device name, geofence name, direction, coordinates, severity, message). An optional rule filter restricts triggering to specific rules; leaving it empty matches all rules.
* **Trip Started / Trip Completed:** Fires when the Travel Log detects a trip beginning or ending. Carries device name, coordinates, distance, duration, stop count, and speed.
* **Schedule (Cron):** Fires at fixed intervals (e.g., "Every Monday at 9:00 AM").

#### 3. Nodes (The "What")

Nodes are the building blocks that perform tasks:

* **Logic (IF/ELSE):** Branch the workflow based on data values (e.g., `if (temperature > 50)`).
* **Stats Query:** Fetch historical trends (e.g., "Average speed over the last hour") to use in your logic.
* **JS Transform:** Write an ES6+ JavaScript script to clean or reformat data before sending it to another node. The editor provides real-time syntax validation as you type.
* **Notification Channels:** Dedicated nodes for **Slack**, **Email**, and **Telegram** with rich formatting.
* **Reporting:** Trigger the generation of a [Custom Report](/docs/documentation/features/reporting.md) as part of a workflow.
* **HTTP Request:** Call an external REST API with dynamic data.
* **AI Analysis** *(requires AI Assistant plugin)*: Send a prompt template to an LLM and inject telemetry values using `{{field_name}}` placeholders. Returns the response as `text` or parsed `json` for use in downstream nodes. Each run is metered against your account's [AI Tokens quota](/docs/documentation/administration/quotas.md); the node fails with a quota-exceeded error if the run would go over your monthly limit.

#### 4. Edges (The Flow)

Edges are the connections between nodes. They define the path data takes through your workflow.

### Example Workflow: Cold Chain Monitoring

Imagine you are monitoring a fleet of refrigerated trucks:

1. **Trigger:** Telemetry Received (Profile: Fridge-Tracker).
2. **Stats Query:** Calculate the average temperature of the last 3 hours.
3. **Condition:** If `avg_temp > 5` degrees Celsius.
4. **Branch TRUE:**
   * **Action 1:** Send a high-priority Slack alert to the logistics team.
   * **Action 2:** Trigger a **Generate Report** node to create a detailed audit log of the incident.
   * **Action 3:** Call an external Webhook to log the incident in your ERP system.

### Sub-Workflows

Once a piece of automation logic gets used in more than one place, it's worth building it once and calling it — that's what **sub-workflows** are for. Instead of duplicating the same chain of nodes across several workflows, you build it once as a self-contained workflow and invoke it from any other workflow via a **Sub-Workflow** action node.

A workflow becomes callable by starting it with a **Sub-Workflow Input** trigger instead of a telemetry, geofence, or schedule trigger. That trigger lets you declare the input fields the workflow expects — a name, type (String, Number, Boolean, Object, Array), and whether each one is required or optional with a default. This gives the sub-workflow a clear, self-documenting contract: anyone calling it can see exactly what it needs.

From the calling workflow, adding a **Sub-Workflow** node only shows you workflows that are actually callable — those built with a Sub-Workflow Input trigger, or simple manually-triggered workflows. Once you pick a target, the node's settings panel shows a mapping row for each of the child's declared fields, so you can wire in values from earlier in the parent workflow (via the Variable Picker) or leave a literal value. Required fields you haven't mapped are flagged so you catch it before running the workflow, not after.

When the parent workflow runs, it passes the mapped values in, the sub-workflow executes on its own, and its result flows back to the parent as the Sub-Workflow node's output — ready to use in whatever comes next. This makes sub-workflows a clean way to build reusable building blocks: a shared "notify the on-call team" flow, a shared "look up device and enrich payload" step, or any other logic you don't want to maintain in five places at once.

### Building a Workflow

1. Navigate to the **Workflows** page and click **New Workflow**.
2. **Add a Trigger:** Select your starting event.
3. **Add Nodes:** Drag nodes from the library onto the canvas. Use the search to find specific nodes like "Stats Query" or "Slack".
4. **Configure Nodes:** Click a node to open its settings. Use the **Variable Picker** to map fields from previous nodes.
5. **Connect:** Drag lines (edges) between nodes to define the logic flow.
6. **Test:** Use the **Test Run** feature with sample data to verify your logic before enabling it.
7. **Enable:** Toggle the "Active" switch to start processing live data.

### Quotas & Limits

Workflows are resource-intensive. Depending on your subscription tier, limits may apply to:

* The number of active workflows.
* The maximum number of nodes per workflow.
* Monthly execution limits (tracked in your [Usage Quotas](/docs/documentation/administration/quotas.md)).

### Best Practices

* **Modular Logic:** Keep your workflows focused and simple. If a workflow becomes too complex, consider splitting it into smaller, modular flows.
* **Error Handling:** Use "Error" output handles on critical nodes to handle failures gracefully (e.g., if an external API is down).
* **Monitor Execution Logs:** Regularly check the **History** tab to ensure your workflows are running as expected and to identify any recurring errors.
