> 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/services.md).

# Services

The ctx.services layer scripts use to read, create, update and query ERP data.

In VARIO Cloud, scripts access the full ERP functionality through `ctx.services`. This shared service layer is the backbone of all scripting — it is available in both workflow and batch scripts, and every service works identically in either context.

The services and methods shown below are examples. For the complete list of available services, methods, and parameters, see the Scripting Reference.

***

## Service Catalogue

These services are available in `ctx.services`. Only methods marked for scripting are exposed; the script editor's autocompletion shows the exact signatures.

| Area              | Services                                                                                                                                                                                                                          | Highlights                                                                                                                                                                   |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Addresses         | `accountService`, `accountListingService`, `commissionAssignmentService`                                                                                                                                                          | CRUD, templates, addresses, persons, relations, `sendNotification()`                                                                                                         |
| Articles & prices | `articleService`, `articleListingService`, `articleStorageService`, `articleSupplierService`, `articleCustomerService`, `bundleSchemaService`, `priceService`, `productService`, `productGroupService`, `productMainGroupService` | `findByNumber()`, sales and purchase prices and discounts, label print batches                                                                                               |
| Variants          | `variantSchemaService`, `variantAttributeService`, `variantValueService`, `variantAttributeListingService`, `variantValueListingService`                                                                                          | Maintain variant schemas, attributes and values                                                                                                                              |
| Documents         | `documentService`, `openItemService`, `dunningService`                                                                                                                                                                            | Create, update, copy, `transferToType()`, `transferToState()`, `print()`, `sendViaMail()`                                                                                    |
| Stock             | `stockService`                                                                                                                                                                                                                    | `bookManualStockMovement()`, `bookStockTransfer()`, `bookBulkStockTransfer()`                                                                                                |
| CRM               | `crmActivityService`, `crmDealService`, `crmProjectService`, `crmTaskService`, `crmDocumentRefService`                                                                                                                            | CRUD, templates, states, `dealWon()`, link documents                                                                                                                         |
| Master data       | `deliveryMethodService`, `deliveryTermService`, `paymentMethodService`, `paymentTermService`, `textTemplateService`, `textEnumerationService`, `tagService`, `assetService`, `assetTypeService`, `scenarioService`                | Lookups such as `findByLabel()`                                                                                                                                              |
| DMS               | `shelfDocumentService`                                                                                                                                                                                                            | `downloadIntoDMS()`, `create()`, `createDmsOutputStream()`, attributions                                                                                                     |
| Files             | `ioFactory`                                                                                                                                                                                                                       | `createPlainWriter()`, `createXmlWriter()`, `createStringCollector()`, see [Files & Export](https://developer.vario-software.de/documentation/scripting/files-and-export.md) |
| Output            | `outputHelper`, `freePrintingService`                                                                                                                                                                                             | Build output requests for mail, print, file export, DMS, see [Output](https://developer.vario-software.de/documentation/scripting/output.md)                                 |
| Integration       | `httpClientService`                                                                                                                                                                                                               | Outgoing HTTP with whitelist and secrets, see [HTTP & Secrets](https://developer.vario-software.de/documentation/scripting/http-and-secrets.md)                              |
| Query             | `vqlService`                                                                                                                                                                                                                      | `queryAll()`, `query()`                                                                                                                                                      |
| System            | `userAndGroupService`, `freeSequencerService`, `utils`, `logger`, `dtoFactory`                                                                                                                                                    | Users and groups, number ranges, helpers, logging, DTO creation                                                                                                              |

### Field Names in Scripts

Scripts use the same data objects as the REST API, with a few fields renamed for scripting. For example, the default address of an account is `account.defaultAddress` in a script (REST: `address`), and a contact's type is `ctType` (REST: `type`). When in doubt, rely on the autocompletion in the script editor or the [type definitions](https://developer.vario-software.de/documentation/scripting/introduction.md#type-definitions).

***

## Entity Services

Entity services are the primary way to read, create, update, and deactivate business objects in VARIO Cloud. They manage core ERP records — accounts, articles, documents, CRM objects, and more. Most share a common method pattern:

| Method                         | Description                                       |
| ------------------------------ | ------------------------------------------------- |
| `getNewDto()`                  | Create a new empty DTO                            |
| `createNewDtoByTemplate(name)` | Create a new DTO pre-filled from a named template |
| `readById(id)`                 | Read an entity by ID                              |
| `create(dto)`                  | Persist a new entity                              |
| `update(dto)`                  | Update an existing entity                         |
| `deactivate(id)`               | Deactivate an entity                              |

Not every service exposes every method — the available methods depend on the entity type.

```javascript
const account = ctx.services.accountService.readById(accountId);
account.custom.myapp.externalId = 'EXT-123';
ctx.services.accountService.update(account);
```

***

## VQL Service

The VARIO Cloud `vqlService` executes [VQL](https://developer.vario-software.de/documentation/fundamentals/vql.md) queries from within scripts, giving you full access to the query language for lookups, aggregations, and existence checks. `queryAll()` returns a `List<Map>` — access fields directly by their attribute path.

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

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

{% hint style="info" %}
For the full VQL syntax — operators, relative dates, subqueries, JOINs — see [VQL](https://developer.vario-software.de/documentation/fundamentals/vql.md).
{% endhint %}

***

## User & Group Service

`userAndGroupService` resolves users and groups in the system — for example to check who created an entity or to assign a user to a task.

```javascript
const user = ctx.services.userAndGroupService.findUserById(account.info.createdFrom);
ctx.services.logger.info('Created by: ' + user.username);
```

***

## DTO Factory

In VARIO Cloud, entity services like `accountService.getNewDto()` create the top-level entity object, but not the nested objects within it. When you need to add an address, a contact, a business relationship, or similar sub-objects to an entity, you must create them separately via `dtoFactory` and then attach them — typically by assigning to a field or pushing into an array.

The factory covers all DTO types in the system — addresses, contacts, business relationships, article identifiers, metrics, and many more. The naming follows the pattern `create<TypeName>()`. The full list is available via autocompletion in the script editor.

### Adding Nested Objects to an Entity

```javascript
const account = ctx.services.accountService.getNewDto();

// Create and assign the default address
const address = ctx.services.dtoFactory.createAccountAddress();
address.name1 = 'Mustermann GmbH';
address.street = 'Hauptstraße 1';
address.postcode = '50667';
address.city = 'Köln';
account.defaultAddress = address;

// Create contacts and push them into the address
const phone = ctx.services.dtoFactory.createContact();
phone.ctType = 'PHONE';
phone.ctLabel = 'Telefon';
phone.value = '+49 221 12345';
account.defaultAddress.contacts.push(phone);

// Create the business relationship
const customer = ctx.services.dtoFactory.createCustomer();
customer.number = '10001';
account.customer = customer;

ctx.services.accountService.create(account);
```

***

## Utilities

`utils` provides helper functions used across all scripting contexts — most importantly `toApiReference()` for reference fields, but also `dateTimeNow()`, `concatLists()`, and others.

### API References

Any DTO field ending in `Ref` — such as `paymentMethodRef`, `deliveryTermRef`, `taxSchemaRef`, or `productGroupRef` — expects an API reference object. You cannot assign a plain ID string or entity directly. Use `toApiReference()` to convert an ID into the required format.

The recommended approach is to pass the ID directly:

```javascript
article.taxSchemaRef = utils.toApiReference('1434873425719062528');
article.productGroupRef = utils.toApiReference(existingGroup[0].id);
```

When using a lookup service, you can also pass the resolved entity:

```javascript
const deliveryMethod = ctx.services.deliveryMethodService.findByLabel('DL');
document.deliveryMethodRef = utils.toApiReference(deliveryMethod);
```

```javascript
account.custom.myapp.syncedAt = ctx.services.utils.dateTimeNow();
```

***

## Logger

`logger` writes log entries visible in the workflow execution log or batch import log. It provides `info()`, `warn()`, and `error()` methods.

```javascript
ctx.services.logger.info('Account ' + account.number + ' updated successfully');
ctx.services.logger.warn('Missing field — using default value');
ctx.services.logger.error('Failed to update document ' + documentId);
```

***

## Destructuring

When a script uses multiple services you can destructure them for readability:

```javascript
const { documentService, accountService, paymentMethodService, utils, logger } = ctx.services;

const document = documentService.readById(documentId);
const account = accountService.readById(document.accountId);
logger.info('Processing document for account ' + account.number);
```

***


---

# 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/services.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.
