# Creatives sync

> **TL;DR** — Pull approved ad creatives incrementally: pass your last checkpoint as `updated_since`, follow `next_cursor` to the end, overwrite records by `creative_id`, and move the checkpoint only after the whole run succeeded. Re-check a stored creative with `GET /creatives/{id}`; stop using it after the UTC day of `rights.ends_at`.

## Before you start
- A key with `creatives:export` for the job, in `WANDURA_API_KEY`. The marketing job never needs `playback`.
- The record and the envelope: [Creatives](https://docs.wandura.ai/developers/concepts/creatives).

## The procedure
1. **First run:** `GET /creatives?limit=100` without `updated_since`; while `data.next_cursor` is not `null`, call again with `cursor=<next_cursor>`.
2. **Upsert** every record by `creative_id`. A record can come twice (`updated_at` is rounded down to the second, and `updated_since` is strict): overwrite it.
3. **Checkpoint:** after the run **completed**, save the largest `updated_at` you received.
4. **Later runs:** the same, with `updated_since=<checkpoint>` on every page of the run.
5. **On failure** (including `422` `4222`, a cursor no longer valid): keep the old checkpoint; the next run starts again from it. Nothing is skipped.
6. **Withdrawn creatives** are not announced. Before you use a stored creative, or once a day, call `GET /creatives/{id}`: `404` `4040` means stop using it.
7. **Rights:** usable until the end of the UTC day `rights.ends_at` points at (`ends_at + 86400`).

A few runs an hour is well within the creatives limit.

## How the creative was approved
`status: approved` alone does not mean an admin reviewed the creative. The `approval` field says which way it got there:

| `approval` | Meaning |
|---|---|
| `self_published` | Its maker published it directly with Submit & publish, without review. |
| `self_approved` | Its maker approved it with their own admin rights; no second person is on record as having reviewed it. |
| `reviewed` | Someone other than its maker approved it. |

It never names who approved.

## Policy scan status
> **It is a real scan result only when `rubric` is not `null`, does NOT start with `derive-`, and `stale` is `false`. A `rubric` starting with `derive-` = a preliminary result, `level` 2–4: scan for real before launching a campaign. `rubric` = `null` = no result yet, `level` 3 is an assigned default.**

Every record carries a `policy` block with exactly three fields: a summary of the latest Meta ad-policy scan of the creative on Wandura (a scan of its draft preview, started by a member of the owning organisation on the partner portal or over the API). It never contains the individual findings; a member of the owning organisation sees those on the creative's page (`links.view`).

| Field | Value |
|---|---|
| `level` | Always a number, 0 to 4. A real scan: its level, or `2` when the scan finished but could not check part of the creative. A preliminary result: the derived level, never below `2` (never below `3` when `rubric` ends in `-src`). No result: the assigned default `3`. |
| `rubric` | The rule set the result was scored with. A real scan: e.g. `meta70-2026-10-28+axb-2026-10-29`. A preliminary result: the derivation version, always starting with `derive-` (e.g. `derive-2026-11-17`); the `derive-` prefix is part of the contract, the rest is an opaque label, except a trailing `-src` (e.g. `derive-2026-11-17-src`): derived from the source footage only. `null` when there is no result: never scanned, scanning now, the scan failed or its result cannot be read, and no preliminary result. |
| `stale` | `true` when Wandura's real scan of the creative no longer holds: the creative was edited after the scan, or the scan was scored on a different scale from today's L0–L4 (an older scan engine). `level` and `rubric` are then the preliminary result of the current edit if there is one, otherwise `3` with the rule set of the older scan. A later adjustment of the rules on the same scale does not make a result stale. Always `false` when `rubric` is `null`. |

**Preliminary results** are derived from the scans of the episodes and clips the creative uses, without scanning the creative itself: free, computed in the background for approved creatives without a usable real scan (and again when the creative changes), less exact than a real scan, so they never show below level 2. When the creative has added text or images, those are not checked: the result comes from the episode and clip footage only, `rubric` ends in `-src`, and it never shows below level 3.

| `level` | Meaning | Recommendation |
|---|---|---|
| 0–1 | Likely to pass | Usable. |
| 2 | Needs a review | Review the flagged moments. |
| 3 | Likely to be rejected | Think carefully, or scan it yourself again, before launching a campaign. |
| 4 | Likely to be rejected, serious issue | Better not used. |

These are **recommendations only: Wandura does not block anything**, and the scan itself is advisory.

A scan does not change `updated_at`, so an incremental run with `updated_since` does not bring a new scan result. Before you rely on `policy` (for example right before launching a campaign), read the creative with `GET /creatives/{id}`, the same call as in step 6. Reading `policy` is free and never starts a scan.

## Code
```ts
export async function syncCreatives(store: CreativeStore, o: CallOptions = {}): Promise<boolean> {
  const since = await store.checkpoint();
  let cursor: string | null = null;
  let max = since ?? 0;
  try {
    do {
      const qs = new URLSearchParams({ limit: '100' });
      if (since !== null) qs.set('updated_since', String(since)); // the same value on every page of a run
      if (cursor) qs.set('cursor', cursor);
      const { data }: { data: Envelope } = await call<Envelope>('GET', `/api/delivery/v1/creatives?${qs}`, { policy: BACKGROUND, ...o });
      for (const c of data.data.items) { await store.upsert(c); max = Math.max(max, c.updated_at); }
      cursor = data.data.next_cursor;
    } while (cursor);
  } catch (e) {
    // 422 / code 4222 (cursor no longer valid) or anything else: the next run restarts from the old checkpoint.
    log('creatives_sync_failed', { status: (e as { status?: number }).status, code: (e as { errorCode?: string }).errorCode });
    return false;
  }
  await store.saveCheckpoint(max); // only after the whole run: nothing is ever skipped
  return true;
}
```

## Campaign signals
Wandura needs to know which creatives go on campaigns, and what the ad platforms decide about them. Two signals tell it, both added to the record without changing anything else.

### Clean-copy fetches
Every successful open of a share link (`final.file_url`, `preview.file_url`) is counted: `fetches.count`, `fetches.first_at` and `fetches.last_at` (Unix seconds). The clean copy is only for uploading to ad platforms, so **a fetch of `final.file_url` means the creative is about to go, or went, on a campaign. It is not proof that an ad is running**: report the ads themselves for that (next section).

| Field | Value |
|---|---|
| `final.fetches` | Fetches of the clean final, counted over every share link of it (yours, and those of keys that read your creatives). Shown only to a key with `creatives:export`; `null` for a key with only `creatives:read`, and `null` while the numbers are temporarily unavailable. |
| `preview.fetches` | The same for the watermarked preview: reviews and shares, not a campaign signal. |

A fetch does not change `updated_at`, so an incremental run does not bring new numbers: read `GET /creatives/{id}` when you need them fresh. `HEAD` requests and refused requests (revoked link, rate limited) are not counted.

### Report your ads back
When your marketing system launches an ad with a creative, stops it, or gets the platform's review result, tell Wandura:

```bash
curl -s -X POST "https://www.wandura.ai/api/delivery/v1/creatives/$CREATIVE_ID/ads" \
  -H "Authorization: Bearer $WANDURA_API_KEY" -H "Content-Type: application/json" \
  -d '{"platform":"meta","ad_id":"120210000000000001","ad_account_id":"act_1234567890","campaign_id":"120210000000000100","ad_set_id":"120210000000000200","started_at":1790650000,"review_status":"approved","reviewed_at":1790652000}'
```

| Field | Required | Value |
|---|---|---|
| `platform` | yes | `meta`, `tiktok`, `google` or `other`. |
| `ad_id` | yes | The ad's ID on the platform. `platform` + `ad_id` identify the ad. |
| `ad_account_id`, `campaign_id`, `ad_set_id` | no | IDs on the platform: letters, digits, `.`, `_`, `:`, `-`, up to 128 characters. |
| `started_at`, `ended_at` | no | Unix seconds when the ad was switched on and off. |
| `review_status` | no | The platform's review result: `approved`, `rejected`, `in_review`, `unknown` (the default). |
| `review_reason` | no | The platform's reason (for example the policy named in a rejection), up to 1,000 characters. |
| `reviewed_at` | no | Unix seconds of the review. |

- **Report the same ad again to update it** (`201` the first time, `200` after); it is never duplicated. Fields you leave out keep their value, and `null` clears one. Report again when the ad stops (`ended_at`) and when the platform reviews it (`review_status`, `review_reason`, `reviewed_at`): Wandura compares the real review results with its own policy scan of the creative to tune the scan.
- **Read them back:** `GET /creatives/{id}/ads` lists the reported ads (`limit` up to 500, `next_cursor`). The record carries a summary, `ads`: `count`, `running` (switched on, not switched off, not rejected), `rejected`, and `first_started_at` (when the creative first went on a campaign). Like fetches, a report does not change `updated_at`.
- **Who sees what:** a key with `creatives:export` sees and updates every ad of your creatives. A key with only `creatives:read` sees and updates only the ads it reported itself (`409` `4093` for an ad another key reported). You cannot report ads on a creative your key cannot read (`404` `4040`). An invalid body returns `422` `4223`, with the field named in `message`.

## Done when
- [ ] A second run with no changes on Wandura's side returns nothing new.
- [ ] A run interrupted half-way does not move the checkpoint.
- [ ] A creative past its rights day is no longer used.

## Related
- [List creatives](https://docs.wandura.ai/developers/reference/creatives-list), [Get a creative](https://docs.wandura.ai/developers/reference/creatives-get), [Report an ad](https://docs.wandura.ai/developers/reference/creatives-ads-report), [List the ads of a creative](https://docs.wandura.ai/developers/reference/creatives-ads-list)
