# Batch Processing

VARIO Cloud Batch Processing lets you run server-side JavaScript scripts that process imported data (CSV/JSON) row by row. Batch scripts are not limited to importing new records — they can also update existing entities in bulk, create related objects in mass, or combine both approaches. Since the full service layer is available, anything you can do in a workflow script can also be done per row in a batch script.

***

## Script Structure

Every VARIO Cloud batch script starts with an import and registers one or more callbacks:

```javascript
import batchAction from 'batch_script';

batchAction.setGuard((ctx) =>
{
  // Return false to skip this row
  return ctx.importData.ID !== '';
});

batchAction.setAction((ctx) =>
{
  // Process a single row — return true on success, false on failure
  const id = ctx.importData.ID;
  // ...
  return true;
});

batchAction.setAfterBatch((ctx) =>
{
  // Runs once after all rows are processed
  // ctx.importData is empty here — use ctx.importSession for accumulated data
});
```

### Callbacks

| Callback        | Runs                | Return                                        | Purpose                                       |
| --------------- | ------------------- | --------------------------------------------- | --------------------------------------------- |
| `setGuard`      | Per row             | `boolean` — `false` skips the row             | Filter rows before processing                 |
| `setAction`     | Per row             | `boolean` — `true` = success, `false` = error | Process a single import row                   |
| `setAfterBatch` | Once after all rows | —                                             | Finalize the batch (e.g. trigger a print job) |

***

## The Context Object

Almost every callback in a VARIO Cloud batch script receives a context object `ctx` with the following properties:

| Property            | Description                                                                                   |
| ------------------- | --------------------------------------------------------------------------------------------- |
| `ctx.importData`    | The current CSV/JSON row as a map. Keys are column headers.                                   |
| `ctx.importSession` | A shared map that persists across all rows in a run. Use it to accumulate state.              |
| `ctx.services`      | Same services as in workflow scripts (`vqlService`, `accountService`, `articleService`, etc.) |
| `ctx.parameters`    | Import parameters configured on the rule set                                                  |
| `ctx.errorMessages` | Accumulate error messages for the current row                                                 |

***

## Typical Pattern — Create or Update

Most VARIO Cloud batch scripts follow this pattern when importing data: check if the entity already exists via VQL, then create or update accordingly:

```javascript
import batchAction from 'batch_script';

batchAction.setAction((ctx) =>
{
  const number = ctx.importData.Artikelnummer;

  // Check if article already exists
  const existing = ctx.services.vqlService.queryAll(
    `SELECT id FROM article.query WHERE number = '${number}' LIMIT 1`
  );

  let article;

  if (!existing || existing.length === 0)
  {
    article = ctx.services.articleService.getNewDto();
    article.number = number;
  }
  else
  {
    article = ctx.services.articleService.readById(existing[0].id);
  }

  // Map import data to entity fields
  article.description = ctx.importData.Bezeichnung;
  article.custom.mygroup.FIELD = ctx.importData.CustomValue;

  // Persist
  if (!existing || existing.length === 0)
  {
    ctx.services.articleService.create(article);
  }
  else
  {
    ctx.services.articleService.update(article);
  }

  return true;
});
```

***

## Logging

Use `ctx.services.logger` the same way as in workflow scripts:

```javascript
ctx.services.logger.info('Article created: ' + number);
ctx.services.logger.warn('Missing field, skipping row.');
ctx.services.logger.error('Failed to create article.');
```

{% hint style="info" %}
Each row is processed in its own transaction. Workflows and webhooks can be suppressed during batch processing via the import configuration.
{% endhint %}

***

## Scheduled Execution

VARIO Cloud batch imports can be scheduled to run automatically using Cron expressions. Configure the schedule directly in the ERP on the import rule set — the system will trigger the import at the defined intervals without manual interaction. This is useful for recurring imports such as nightly stock updates, daily price syncs, or periodic data feeds from external systems.
