> For the complete documentation index, see [llms.txt](https://developer.vario-software.de/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.vario-software.de/documentation/scripting/workflows.md).

# Workflows

Event-driven scripts that react to entity lifecycle events in the ERP.

VARIO Cloud Workflows let you run server-side JavaScript in response to entity lifecycle events in the ERP — an account being saved, a document being created, a CRM deal changing state, and more. Workflows are the primary mechanism for automating business processes, validating data before it is persisted, and orchestrating multi-step logic with user interactions.

***

## Workflow Structure

A parent workflow consists of a **trigger** and a chain of **elements** connected by successors. A sub-workflow contains connected elements and is invoked by a **Sub-workflow** element; it has no trigger of its own:

```
Trigger (e.g. account.BEFORE_SAVE)
  → START_EVENT
    → SCRIPT_TASK
      → EXCLUSIVE_SPLIT_GATEWAY
        → SCRIPT_TASK (Branch A)
        → SCRIPT_TASK (Branch B)
      → EXCLUSIVE_JOIN_GATEWAY
    → END_EVENT_SUCCESS
```

***

## Triggers

The trigger determines **when** a VARIO Cloud workflow runs and **what data** is available to your scripts.

### One Active Parent Workflow per Trigger

VARIO Cloud allows **at most one active parent workflow per trigger**. Activating a second, unrelated workflow for the same trigger is rejected and leaves the existing workflow active. This is intentional behavior.

A successor version of the existing workflow can be activated; it replaces and deactivates its predecessor. A successor is a new version of the same automation, not an additional subscriber to the trigger.

For several automations reacting to the same trigger, extend the existing parent workflow and compose the individual tasks as **sub-workflows**. See [Sub-Workflows for Multiple Automations](#sub-workflows-for-multiple-automations).

### BEFORE\_SAVE vs AFTER\_SAVE

Use the **complete trigger name**, including its entity topic, to determine execution and input. The suffix `BEFORE_SAVE` alone does not mean that a workflow is synchronous.

| Trigger                                                                                         | Execution and timing                                                                                            | Input and modification                                                                                                                                                               | Effect of an unhandled error                                                                                              |
| ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `account.BEFORE_SAVE`, `article.BEFORE_SAVE`, `crm-task.BEFORE_SAVE` and `crm-deal.BEFORE_SAVE` | Synchronous; runs within the save operation                                                                     | The entity to save, such as `accountToSave`, `articleToSave`, `crmTaskToSave` or `crmDealToSave`, and its previous version. Changes to the workflow result are included in the save. | Aborts the save operation.                                                                                                |
| `document.ON_MERGE_CHANGES`                                                                     | Synchronous; runs while document changes are merged                                                             | `documentToSave` and `previousDocument`. Changes to `documentToSave` are included in the merge.                                                                                      | Aborts the merge operation.                                                                                               |
| `document.BEFORE_SAVE`                                                                          | **Asynchronous**; starts after the document has been persisted during `END_EDITING`, before post-save tasks run | `documentId`, `previousDocument` and document workflow context. There is **no `documentToSave` input**.                                                                              | The default failure target is editing (`EDIT`); this is a later state transition, not an undo of the initial persistence. |
| Entity `AFTER_SAVE` triggers, such as `account.AFTER_SAVE`                                      | Asynchronous; run after saving                                                                                  | The saved entity's ID and trigger-specific previous state. Read and update the entity through services.                                                                              | Cannot cancel the save that already took place.                                                                           |

For example, `article.BEFORE_SAVE` can validate and modify `articleToSave` before the save finishes. The document trigger with the same suffix has a different role: `document.BEFORE_SAVE` pauses the document's transition in `IN_WORKFLOW_ON_END_EDITING`. By default, successful workflow completion continues to `SAVED`. Use `document.ON_MERGE_CHANGES` when you need synchronous access to `documentToSave`.

Do not treat a successful request that starts an asynchronous workflow as confirmation that the workflow has completed. Subsequent document operations must respect its current state and any document locks. If a lock or validation blocks the final state transition, the workflow can be interrupted while that transition is pending. Remove the cause and resume the workflow to complete it; an unexpected completion error is recorded as an error. Explicit workflow parameters can also override or skip the default final transition.

### Other Triggers

Beyond BEFORE\_SAVE and AFTER\_SAVE, triggers exist for specific lifecycle events such as `document.CREATE`, `document.TRANSFER`, and `document.BEGIN_EDITING`. These behave like AFTER\_SAVE — they run asynchronously and provide IDs rather than entity objects.

The data available to each trigger is accessible via `ctx.availableInput` and `ctx.parameters`. The exact fields depend on the trigger and are visible in the workflow editor.

***

## Sub-Workflows for Multiple Automations

Use one parent workflow to coordinate all tasks for a trigger. Keep each reusable task in its own sub-workflow, with conditions and execution order defined in the parent flow.

1. Edit the existing active parent workflow to create a successor draft.
2. Create each additional workflow with the **Sub-workflow** option enabled (German UI: **Unter-Workflow**). A sub-workflow has **no trigger of its own**. Configure its start, processing and end elements, then activate it.
3. In the parent draft, add a **Sub-workflow** element (`SUB_WORKFLOW`) for each task and select the active sub-workflow.
4. Connect the elements in the required order. Use conditions to route past a task when it is not applicable, then continue with the next task.
5. Check the complete flow, including the previous automation, before activating the parent draft.

For a defined sequence:

```
Parent trigger
  → START_EVENT
  → SUB_WORKFLOW: Validate account data
  → SUB_WORKFLOW: Create a follow-up task when needed
  → END_EVENT_SUCCESS
```

Do not deactivate an existing parent merely to activate an additional automation for its trigger: that would stop the previous automation from receiving the event. Extend its successor draft instead. The [handbook setup guide](https://help.vario-software.de/vario-cloud-handbuch/system/workflows/workflows-erstellen#mehrere-automatisierungen-fur-denselben-ausloser) describes the UI steps.

### Execution and Shared Context

A sub-workflow runs **inside the same workflow instance** as its parent. It shares the trigger input (`ctx.availableInput`) and parameter context (`ctx.parameters`). Changes can affect subsequent elements, so use distinct parameter names for unrelated tasks and coordinate writes to the same entity.

The parent's connected next element runs after the sub-workflow reaches its successful end. Connecting A → B explicitly establishes that sequence; separate branches should not be used to imply a fixed execution order.

Sub-workflows provide modular composition within one flow. They are **not independently triggered or failure-isolated runs**. An unhandled exception puts the common workflow instance into an error state. An error end in a sub-workflow aborts its invoking `SUB_WORKFLOW` element and any enclosing sub-workflow elements; their successors do not continue automatically. Account for this when deciding which steps depend on each other.

### Synchronous Compatibility

The parent trigger determines whether execution is synchronous or asynchronous. A sub-workflow has no separate execution mode.

For a synchronous parent, all invoked sub-workflows must use elements that support synchronous execution. In particular, **`USER_TASK`, `TIMER` and `INTERMEDIATE_EVENT` are not permitted in a synchronous flow**. A sub-workflow without these elements can also be used by an asynchronous parent. Check nested sub-workflows as well when preparing a synchronous flow.

***

## Script Structure

Every workflow script in VARIO Cloud starts with an import that determines its type. Scripts can be written inline in each element or saved centrally as [Script Modules](https://developer.vario-software.de/documentation/scripting/script-modules.md) and referenced by name.

### SCRIPT\_TASK

```javascript
import workItem from "work_item_script";

workItem.setAction((ctx) =>
{
  // Your business logic
});
```

You can optionally add a **guard** to skip the element, and a **prepare** step to set up variables before the action:

```javascript
workItem.setPrepare((ctx) =>
{
  // Optional — runs before setAction, e.g. to initialize variables
});

workItem.setGuard((ctx) =>
{
  // Return true to execute setAction, false to skip this element
  return ctx.availableInput.accountToSave.customer !== null;
});

workItem.setAction((ctx) =>
{
  // Only runs if guard returned true
});
```

### EXCLUSIVE\_SPLIT\_GATEWAY

```javascript
import workItem from "work_item_split_gateway";

workItem.setSplit((ctx) =>
{
  const targetCategory = ctx.availableInput.targetCategory;

  const creditNoteTypes = [
    'CUSTOMER_CREDIT_NOTE_WITH_STOCK',
    'CUSTOMER_CREDIT_NOTE_WITHOUT_STOCK',
    'SUPPLIER_CREDIT_NOTE_WITH_STOCK',
    'SUPPLIER_CREDIT_NOTE_WITHOUT_STOCK'
  ];

  if (creditNoteTypes.includes(targetCategory))
  {
    return 'TRANSFER_INTO_CREDIT_NOTE';
  }

  return 'END_WORKFLOW';
});
```

The returned string must match a key in the element's `successors` map.

***

## The Context Object (ctx)

Every script in a VARIO Cloud workflow receives a context object `ctx` with the following properties:

| Property             | Description                                                            |
| -------------------- | ---------------------------------------------------------------------- |
| `ctx.availableInput` | Trigger-specific data — the entity being saved, IDs, previous versions |
| `ctx.services`       | All available scripting services                                       |
| `ctx.parameters`     | Workflow parameters and user task results                              |

***

## Reading and Modifying Data

How you read and modify ERP data in VARIO Cloud depends on the trigger type.

### BEFORE\_SAVE — Direct Modification

For **synchronous entity BEFORE\_SAVE triggers**, `ctx.availableInput` contains the entity to save, named with a `ToSave` suffix. Changes to that workflow result are included in the save without an additional service update. An unhandled error aborts the save.

For example, a `crm-task.BEFORE_SAVE` workflow can remove surrounding whitespace from the task label:

```javascript
import workItem from "work_item_script";

workItem.setAction((ctx) =>
{
  const task = ctx.availableInput.crmTaskToSave;
  if (!task || task.label == null) return;

  task.label = task.label.trim();
});
```

#### Documents: ON\_MERGE\_CHANGES

For documents, direct modification belongs to **`document.ON_MERGE_CHANGES`**, not `document.BEFORE_SAVE`. For example, this synchronous workflow removes surrounding whitespace from the name of the ordering person while document changes are merged:

```javascript
import workItem from "work_item_script";

workItem.setAction((ctx) =>
{
  const document = ctx.availableInput.documentToSave;
  if (!document || document.orderedBy == null) return;

  document.orderedBy = document.orderedBy.trim();
});
```

### AFTER\_SAVE — Read, Modify, Update

In AFTER\_SAVE triggers, read the entity by ID, modify it, and call the service's update method:

```javascript
import workItem from "work_item_script";

workItem.setAction((ctx) =>
{
  if (ctx.availableInput.previousAccount != null)
  {
    return;
  }

  const account = ctx.services.accountService.readById(ctx.availableInput.accountId);
  const createdBy = ctx.services.userAndGroupService.findUserById(account.info.createdFrom);

  if (createdBy?.username !== 'niko.neumann') return;

  let taskDto = ctx.services.crmTaskService.createNewDtoByTemplate('Adress-Prüfung');
  ctx.services.crmTaskService.create(taskDto);
});
```

### Document Updates

When updating documents via service (e.g. in AFTER\_SAVE or CREATE triggers), `documentService` requires a request wrapper. In `document.ON_MERGE_CHANGES`, the document is available as `documentToSave` and can be modified directly as part of that synchronous merge. `document.BEFORE_SAVE` provides `documentId` instead; it does not expose a mutable `documentToSave` object. Service updates and state transitions remain subject to the document's current state and locks.

```javascript
workItem.setAction((ctx) =>
{
  const { documentId } = ctx.parameters;
  const { documentService, accountService, deliveryMethodService, paymentMethodService, utils, logger } = ctx.services;

  const document = documentService.readById(documentId);
  const account = accountService.readById(document.accountId);

  if (account.types.includes('CUSTOMER'))
  {
    return;
  }

  if (!document.deliveryMethodRef)
  {
    logger.info('Setze Versandart: DL');
    const deliveryMethod = deliveryMethodService.findByLabel('DL');
    document.deliveryMethodRef = utils.toApiReference(deliveryMethod);
  }

  if (!document.paymentMethodRef)
  {
    logger.info('Setze Zahlungsart: UEB');
    const paymentMethod = paymentMethodService.findByLabel('UEB');
    document.paymentMethodRef = utils.toApiReference(paymentMethod);
  }

  const updateRequest = documentService.getUpdateDocumentRequest();
  updateRequest.document = document;
  documentService.update(updateRequest);
});
```

***

## Validation and Cancellation

In synchronous entity BEFORE\_SAVE triggers, throw an error to cancel the save. The same principle applies to the synchronous document merge in `document.ON_MERGE_CHANGES`:

```javascript
workItem.setAction((ctx) =>
{
  const account = ctx.availableInput.accountToSave;

  if (!account.defaultAddress || !account.defaultAddress.postcode)
  {
    throw 'A postal code is required.';
  }

  if (account.defaultAddress.countryCode === 'DE'
    && !/^[0-9]{5}$/.test(account.defaultAddress.postcode))
  {
    throw 'German postal codes must be exactly 5 digits.';
  }
});
```

The error message is displayed to the user and the current synchronous operation is aborted. This does not cancel a save that already completed before an asynchronous workflow started.

### Service Errors and Transactions

Catching an exception controls how the script continues; it does **not** reset the database transaction. A transactional service method can mark a shared transaction as **rollback-only** before its error reaches your script. If you catch that error, later script statements may still run, but the transaction cannot commit.

For example:

1. A synchronous workflow changes its `ToSave` entity.
2. It calls a service method that fails and marks the shared transaction rollback-only.
3. A `try/catch` handler logs the error and continues.
4. Committing the save still fails, and the changes in that transaction are not persisted.

For a concrete example, `articleService.readById(id)` uses a transactional service and raises a not-found error when the article does not exist. In a synchronous save, the call participates in the shared transaction. This deliberately failing demonstration uses a nonexistent article ID:

```javascript
import workItem from "work_item_script";

workItem.setAction((ctx) =>
{
  const task = ctx.availableInput.crmTaskToSave;
  if (!task) return;

  try
  {
    ctx.services.articleService.readById(-1); // Deliberately nonexistent ID
  }
  catch (error)
  {
    ctx.services.logger.warn('Article lookup failed; catching the error does not repair the transaction.');
  }

  if (task.label != null)
  {
    task.label = task.label.trim();
  }
});
```

The handler catches the lookup error, but it does not make a transaction marked rollback-only committable again. Reaching the label assignment does not mean that the label will be saved. For an expected missing article identified by number, use `articleService.findByNumber(number)`, which returns `null` when no article is found, instead of using a failing `readById` as a presence check.

This is different from catching an error raised only by your JavaScript code before it reaches a transactional service boundary. Whether a caught error prevents committing depends on the service and transaction involved; `catch` is not a guarantee of recovery or a partial save.

Use validation and the service's documented lookup methods for expected alternatives. Let failures that invalidate the operation abort it. Do not continue writing on the assumption that catching a service error makes the transaction usable again.

Asynchronous workflows also have transaction boundaries. Their failure does not roll back the earlier save that started them. In particular, the default failure path of `document.BEFORE_SAVE` targets `EDIT` rather than deleting the already persisted document. This state change can remain pending if completion is interrupted. This does not undo independently committed work or external side effects.

***

## Logging

Use `ctx.services.logger` to write log entries:

```javascript
ctx.services.logger.info('PLZ-Validierung erfolgreich abgeschlossen.');
ctx.services.logger.warn('Unexpected value encountered.');
ctx.services.logger.error('Failed to update document.');
```

| Method              | Description           |
| ------------------- | --------------------- |
| `logger.info(msg)`  | Informational message |
| `logger.warn(msg)`  | Warning               |
| `logger.error(msg)` | Error                 |

Log entries are visible in the workflow execution log in the ERP.

***

## VQL in Workflows

Use `ctx.services.vqlService` to query ERP data within scripts:

```javascript
const results = ctx.services.vqlService.queryAll(
  `SELECT id, number FROM article.query WHERE number = '12345' LIMIT 1`
);

if (results && results.length > 0)
{
  const articleId = results[0].id;
}
```

{% hint style="info" %}
`vqlService.queryAll()` returns a `List<Map>`. Access fields directly by their attribute path: `results[0].id`, `results[0].number`.
{% endhint %}

***

## User Tasks

VARIO Cloud workflows support user interaction through `USER_TASK` elements. A user task pauses workflow execution and prompts the user for input. The user's response is available in subsequent scripts via `ctx.parameters`:

```javascript
// In the element after a USER_TASK with resultName 'closingReasonId'
workItem.setAction((ctx) =>
{
  const crmDealService = ctx.services.crmDealService;
  const dealId = ctx.parameters['crmId'];
  const closingReasonId = ctx.parameters['closingReasonId'];

  crmDealService.dealWon(dealId, closingReasonId);
});
```

***

## Custom Fields

VARIO Cloud [Custom Fields](https://developer.vario-software.de/documentation/fundamentals/custom-fields.md) are accessed directly on entity objects in scripts:

```javascript
// Read
const externalId = account.custom.myapp.externalId;
```

```javascript
// Write (on the entity input of a synchronous trigger)
account.custom.myapp.externalId = 'EXT-123';
account.custom.myapp.syncedAt = ctx.services.utils.dateTimeNow();
```

***

## Comparing with Previous State

Use the previous version provided by the selected trigger to detect field-level changes. Input names differ by trigger: for example, `crmDealPrevious` in `crm-deal.BEFORE_SAVE`, `previousAccount` in `account.AFTER_SAVE`, and `previousDocument` in document workflows. Handle a missing previous version when the entity is new:

```javascript
workItem.setAction((ctx) =>
{
  const current = ctx.availableInput.crmTaskToSave;
  const previous = ctx.availableInput.crmTaskPrevious;

  // Only act if an existing task's label actually changed
  if (!current || !previous || current.label === previous.label) return;

  ctx.services.logger.info('Task label changed.');
});
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://developer.vario-software.de/documentation/scripting/workflows.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
