> For the complete documentation index, see [llms.txt](https://docs.thewalletcrew.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/push-updates.md).

# Push updates

Let a scheduled task ask a script which passes to update and what to change on each, with runtime.scriptable.pushUpdates.

A push updates script builds, each time a scheduled task fires, the list of passes to update and what to change on them: new additional data, another theme, a benefit to grant, a notification. The Wallet Crew then queues one update per pass, paced at the throughput the script asks for. It is the tool for updates whose audience comes from a query on a system the brand owns, such as "every member whose tier changed since yesterday" from a data warehouse or a CRM. This page is the reference for `runtime.scriptable.pushUpdates.{scriptId}`.

When the list of updates arrives as a file instead, the bulk import is simpler, and its rows can be adapted by the [bulk pass update row transformation](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/bulk-pass-update-row-transformation.md). When the audience can be expressed with the pass filters of the scheduler, a standard push update task needs no script at all.

<details>

<summary><strong>Real-world examples</strong></summary>

* Every night, a brand reads from its data warehouse the members whose points balance changed and pushes the new balance into each pass's additional data.
* Before an event, a ticketing integration lists the tickets whose gate changed and sends a localized notification to their holders.
* After a CRM segmentation run, the passes of the new VIP segment are moved to the VIP theme.

</details>

## Registration

The script registers `runtime.scriptable.pushUpdates.{scriptId}`, and a task of type `wallet.scriptablePushUpdates` in `server/scheduler.yml` names the same `{scriptId}` in `settings.scriptName`:

```yaml
tasks:
  - id: nightly-points-refresh
    type: wallet.scriptablePushUpdates
    isEnabled: true
    trigger:
      type: recurrence
      scheduleExpression: "0 0 3 * * *"
    settings:
      scriptName: pointsRefresh
```

The `recurrence` trigger takes a cron expression with a seconds field (six fields: seconds, minutes, hours, day of month, month, day of week), here every day at 03:00:00. A one-off run uses a `fixedDate` trigger with `runAt`, an ISO 8601 date and time.

{% hint style="info" %}
The `{scriptId}` in the key and `settings.scriptName` in the task are the same identifier under two names. Camel case, as for the other script ids, keeps the naming consistent.
{% endhint %}

The minimal skeleton is:

```js
export default function (context) {
  context.register('runtime.scriptable.pushUpdates.pointsRefresh', {
    GetPasses: async () => ({ PassInformations: [] })
  });
}
```

## When it runs

The script runs in the background job of its task, each time the trigger fires, never inside a holder's request. The updates themselves run later, at their planned time, exactly like the updates of any other push update task. The number of passes queued is recorded as the result of the task's execution.

The lifecycle of one run:

```mermaid
flowchart LR
  A[Scheduler fires the task] --> B[GetPasses runs once]
  B --> C[Platform resolves each entry]
  C --> D[One update queued per pass]
  D --> E[Updates delivered at the throughput]
```

## Handlers

| Method      | Parameters | Returns                                                 | Required |
| ----------- | ---------- | ------------------------------------------------------- | -------- |
| `GetPasses` | none       | `{ Throughput?, PassInformations }`, or a promise of it | Required |

## Return value

The returned object uses PascalCase keys:

| Key                | Type   | Meaning                                                                                                     |
| ------------------ | ------ | ----------------------------------------------------------------------------------------------------------- |
| `PassInformations` | array  | Required. One entry per update, described below. An empty array updates nothing.                            |
| `Throughput`       | number | Pass updates per second. `3` when omitted. Must be greater than zero; values above 1000 are capped at 1000. |

Each entry of `PassInformations` is an update description. This page owns the table below; the [Bulk pass update row transformation](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/bulk-pass-update-row-transformation.md) uses the same description. Every key left out or `null` leaves that part of the pass unchanged.

| Key                         | Meaning                                                                                                                                                                                                                                            |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Identifiers`               | Required. The passes to update. An `id` key selects one pass by its pass id; otherwise `id.<name>` keys select every pass carrying all the given identifiers (`{ 'id.crm.customerId': '1042' }`). Every key other than `id` must start with `id.`. |
| `PassType`                  | The pass type to convert the passes to.                                                                                                                                                                                                            |
| `ThemeId`                   | The theme to apply. An empty string `""` removes the current theme.                                                                                                                                                                                |
| `BenefitTemplateId`         | A benefit template granted to each pass before the update.                                                                                                                                                                                         |
| `AdditionalData`            | Keys merged into the pass's additional data, as strings. A `null` or empty value removes the key.                                                                                                                                                  |
| `UpdateMetadata`            | `true` recomputes the pass metadata with the update, which runs the pass data providers and the benefit provider. Slower. `false` by default.                                                                                                      |
| `NewIdentifiers`            | Identifiers to set on the passes, keyed by identifier name (an `id.` prefix is accepted and ignored). Every value is required.                                                                                                                     |
| `Notification`              | The notification text for devices whose language has no entry in `NotificationLocalizations`.                                                                                                                                                      |
| `NotificationLocalizations` | Notification text per language code, such as `{ fr: 'Vos points ont changé' }`. When this and `Notification` are both empty, no notification is sent.                                                                                              |

Values of `AdditionalData` are strings: the script converts numbers and booleans with `String(value)`, and serializes a value that must keep its structure with `JSON.stringify`.

## Errors and edge cases

* **GetPasses throws or its promise rejects**: the task execution fails and nothing is updated.
* **`GetPasses` is missing from the registered object**: the handler is required, so the task fails and nothing is updated.
* **No script registers the key** named by `scriptName`: the task logs an error stating that the script does not exist, and no pass is updated.
* **An entry names a pass type, theme or benefit template the tenant does not have, or a `NewIdentifiers` value is empty**: that entry is skipped with an error logged with its position, the others continue.
* **An entry matches no pass**: a warning is logged and nothing is queued for it.
* **An entry matches several passes**: each matching pass is updated; one pass named by two entries is updated twice.
* **`Throughput` is zero or negative**: the task fails when it plans the updates.
* **Several files register the key**: the last registered wins, and the load order of files is not defined.

## Example

The script reads the changed balances from a reporting API page by page. A hard cap on the number of pages protects the task from an API that never stops paging, and reaching the cap is logged rather than silent. A failed page throws, so the task fails visibly instead of updating half of the audience.

```js
import { getSecret } from 'twc/secrets';

const API_URL = 'https://reporting.example.com/api/loyalty/changes';
const PAGE_SIZE = 500;
const MAX_PAGES = 40;

async function getPasses() {
  const token = await getSecret('REPORTING-TOKEN');
  const since = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
  const updates = [];

  let page = 1;
  for (; page <= MAX_PAGES; page++) {
    const response = await fetch(`${API_URL}?since=${encodeURIComponent(since)}&page=${page}&size=${PAGE_SIZE}`, {
      Headers: { Authorization: `Bearer ${token}` }
    });
    const body = JSON.parse(response.ResponseText);

    for (const member of body.items) {
      updates.push({
        Identifiers: { 'id.crm.customerId': String(member.customerId) },
        AdditionalData: {
          points: String(member.points),
          tier: member.tier ?? null
        },
        UpdateMetadata: false
      });
    }

    if (body.items.length < PAGE_SIZE) {
      break;
    }
  }

  if (page > MAX_PAGES) {
    console.warn(`Stopped after ${MAX_PAGES} pages: some changes are left for the next run`);
  }

  console.info(`${updates.length} pass updates prepared`);
  return { Throughput: 5, PassInformations: updates };
}

export default function (context) {
  context.register('runtime.scriptable.pushUpdates.pointsRefresh', {
    GetPasses: getPasses
  });
}
```

## Checking the result

The executions of the task show whether it ran and how many passes it queued. A smaller number than expected usually means entries that matched no pass (identifier keys without the `id.` prefix, or values in another format than the one the passes carry) or entries refused for an unknown pass type, theme or benefit template; both are logged per entry. After the planned time, the pass in the admin console, or `GET /api/{tenantId}/passes/{passId}`, shows the new additional data or theme.

## Common pitfalls

* An identifier key written as `customerId` instead of `id.customerId`.
* A throughput so low that the updates of one run are still being delivered when the next run starts.
* A one-off task with a `fixedDate` trigger that is forgotten in the configuration after it ran.

## FAQ

<details>

<summary><strong>How long do the updates take to reach the devices?</strong></summary>

The updates are spread from the moment the task runs, one every `1 / Throughput` seconds: 3 000 passes at a throughput of 5 take ten minutes to be delivered.

</details>

<details>

<summary><strong>Can the script receive parameters from the task?</strong></summary>

No. The task only names the script. A script that serves two audiences is registered under two script ids, each named by its own task, with the shared logic in helpers of the same file.

</details>


---

# 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://docs.thewalletcrew.io/developers-guides/scripting/endpoints/push-updates.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.
