# Documentazione API · GroceryAI

> Il riferimento OpenAPI 3.1 verificato contro il codice che serve, le guide per chi integra e gli esempi provati.

- Versione 1.0.0 · 36 operazioni · 12 ambiti · 5 eventi
- Indirizzo dell'API: https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api
- Il contratto OpenAPI 3.1, senza chiave: https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/openapi.json
- Il catalogo dei codici d'errore, senza chiave: https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors
- HTML: https://groceryai.ai/it/sviluppatori · Markdown: https://groceryai.ai/it/sviluppatori.md · llms-full.txt: https://groceryai.ai/llms-full.txt
- Versioni e deprecazione: 10. Versioni e deprecazione
- Il registro delle modifiche: https://groceryai.ai/it/sviluppatori/registro-modifiche
- Il server MCP per gli agenti AI: https://groceryai.ai/it/sviluppatori/mcp

## API di GroceryAI · per cominciare (5 passi)

Dal nulla a un catalogo caricato e a un ordine ricevuto, nell'ambiente di **prova** (`test`). I dati di prova sono
separati da quelli veri: niente di ciò che si fa qui arriva a un cliente vero.

Indirizzo di base (ogni percorso qui sotto si aggiunge in coda):

```
https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api
```

Il riferimento completo è il documento OpenAPI 3.1, leggibile **senza chiave**: `GET /v1/openapi.json` (in inglese, la
lingua di chi integra). Ogni operazione ha un esempio di richiesta e di risposta provato contro l'ambiente di prova.

### 1. Una chiave di prova

Nel portale di GroceryAI: **Sviluppatori → Chiavi API → Crea chiave**. Ambiente `test` e solo gli ambiti che servono, per
esempio `catalog:read` e `catalog:write` (un ambito non ne contiene un altro). La chiave ha la forma
`gai_test_ab12cd34_…` e si vede **una volta sola**: va in un gestore di segreti o in una variabile d'ambiente, mai nel
codice.

```bash
export GROCERYAI_API_KEY='gai_test_…'          # la tua chiave; mai in un commit
export GROCERYAI_BASE='https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api'
```

### 2. Il contratto, senza chiave

```bash
curl -s "$GROCERYAI_BASE/v1/openapi.json" -o openapi.json
```

Da qui si genera un client, o lo si dà al proprio agente di programmazione. La risposta porta un `ETag`: rimandato in
`If-None-Match`, dà `304` se non è cambiato niente.

### 3. La prima chiamata

```bash
curl -s "$GROCERYAI_BASE/v1/products?limit=1" \
  -H "Authorization: Bearer $GROCERYAI_API_KEY"
```

Un `200` con `{"data": [...], "next_cursor": ..., "request_id": "..."}` vuol dire che la chiave funziona (ogni negozio nuovo
ha accanto il suo negozio di prova con i prodotti d'esempio: crea lì la chiave `test`; i prodotti d'esempio non vanno mai in vendita). Un `401` o un `403` portano `error.code` ed `error.doc_url`: la pagina dice
che cosa non va e come correggerlo.

### 4. Il catalogo

Le scritture vanno a lotti di al più 500 elementi e portano **sempre** un'`Idempotency-Key` (un UUID nuovo per ogni
operazione; la stessa solo per ritentare la stessa identica richiesta).

```bash
curl -s -X PUT "$GROCERYAI_BASE/v1/products" \
  -H "Authorization: Bearer $GROCERYAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"products":[{"sku":"EXAMPLE-SPAGHETTI-500","title":"Spaghetti 500 g","price":1.29,"stock_qty":140}]}'
```

La risposta dice quanti elementi sono arrivati (`received`), scritti (`written`) e rifiutati (`rejected`). Un elemento
rifiutato non fa cadere il lotto: è in `errors[]` con `index`, `code` e `message`. Poi prezzi e giacenze si tengono
freschi con `PUT /v1/inventory` (cambia solo ciò che si manda).

### 5. Gli ordini

Due vie, gli stessi dati. Se ne sceglie una:

- **Ritiro (pull)**, senza un endpoint in ingresso: `GET /v1/orders?status=new` rende gli ordini confermati; salvato
  l'ordine nel proprio sistema, lo si conferma con `POST /v1/orders/{order_id}/ack` (con `Idempotency-Key`) e non torna più.
- **Webhook**: si registra un endpoint nel portale (Sviluppatori → Webhook), si verifica ogni consegna con la libreria
  ufficiale di Standard Webhooks (`standardwebhooks` su npm e PyPI; esempi in `docs/api/examples/`), si risponde `2xx`
  entro 15 secondi e si scartano i doppioni per `webhook-id`.

Consegnato l'ordine, si dice com'è andata: `POST /v1/orders/{order_id}/status` con `delivered`, `substituted`,
`not_delivered` o `returned`.

### In produzione

Una chiave `gai_live_…` con gli stessi ambiti, e nient'altro da cambiare: percorsi, corpi ed errori sono identici. I due
ambienti non vedono i dati l'uno dell'altro, chiavi d'idempotenza comprese.

### Quando qualcosa non va

- Si programma su `error.code`, mai su `message` (il testo può cambiare).
- Si segue `error.doc_url` (o `GET /v1/errors/{code}`): la pagina dice che cosa è successo, come correggerlo e se ripetere
  la stessa richiesta può bastare (`retryable`).
- `429 LIMITE_RICHIESTE`: si aspettano i secondi di `Retry-After`. `5xx`: si ritenta con la stessa `Idempotency-Key`, non
  si applica mai due volte.
- Se ci si scrive, si manda il `request_id`.

Altro: la guida completa (`docs/api/guida.it.md`), le regole per gli agenti di programmazione (`docs/api/AGENTS.md`) e un
prompt pronto per Claude Code, Codex o Cursor (`docs/api/agent-prompt.md`).

## Per gli agenti AI

Per far integrare GroceryAI a un agente di programmazione (Claude Code, Codex, Cursor o un altro) nel tuo repository: il prompt da incollare, il file AGENTS.md da tenere nel repository e i codici d'errore con la pagina di ciascuno. Tutto è pubblico; l'unico segreto è la chiave di prova che metti nell'ambiente.

Questi tre testi sono in inglese: sono quelli che l'agente legge.

### Integration prompt for coding agents

Paste the block below into Claude Code, Codex, Cursor or any coding agent working in **your** repository. Replace the
two lines marked `<…>`. The agent needs nothing else from GroceryAI: the contract, the examples and the error pages are
public, and the only secret is the test key you put in the environment.

---

```text
You are integrating this repository with the GroceryAI Platform API.

Goal: <describe what to build, e.g. "push our product catalog every night and pull confirmed orders into our order table">.
Our stack: <language, framework, where config and secrets live>.

Sources of truth (fetch them, do not answer from memory):
- OpenAPI 3.1 contract, no key needed: https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/openapi.json
  Every operation has a tested request and response example; response schemas are closed, never invent fields.
- Error catalog, no key needed: GET /v1/errors and GET /v1/errors/{code} on the same base URL. Every error response
  carries error.doc_url pointing to its page: read it when a call fails, it says how to fix the request.

Credentials:
- The API key is in the environment variable GROCERYAI_API_KEY. It is a test key (gai_test_...): it only sees test
  data. Never print, log, commit or hard-code the key, and never send it anywhere except the GroceryAI base URL.
  Do not switch to a live key (gai_live_...); that is a human decision.

Working steps:
1. Download the contract and list the operations and scopes the goal needs.
2. Make the first call before writing any code: GET /v1/products?limit=1 with "Authorization: Bearer $GROCERYAI_API_KEY".
   A 200 proves the key; a 401/403 tells you why in error.code and error.doc_url. If the key lacks a scope, stop and
   tell me which scope to add; do not work around it.
3. Implement against the contract, applying the rules that concern the operations your goal uses:
   - every write carries a fresh Idempotency-Key (UUID v4) per logical operation, reused only to retry the same body;
   - batch writes take at most 500 items; always check errors[] and warnings[] in the 200 response;
   - paginate with next_cursor -> cursor until it is null (it is present only when there really is another page, so
     the last page, even a full one, needs no extra request);
   - branch on error.code (never on message); on 429 wait Retry-After; on 5xx retry with the same Idempotency-Key;
   - log the request_id of every failed call;
   - error.code, error.type and values such as stato are stable Italian identifiers; error.message is Italian free
     text for humans: never parse it.
4. Prove it against the test environment: run the integration end to end, show me the real responses (status, counts,
   errors[]), and add automated tests that use the documented examples as fixtures.
5. Report: the operations used, the scopes required, what you ran and what it returned, and anything you could not
   verify. Do not claim success without a real response from the API.
```

---

Why each line is there: the public contract and error pages let the agent work without our help; the test key keeps
every experiment away from real customers; idempotency, batch checks and `error.code` branching are the rules that
otherwise get guessed wrong; the last step stops an agent from declaring "done" on code it never ran.

The same rules, as a file to keep in your repository: `AGENTS.md`. The five steps for a person: `quickstart.md`.

### AGENTS.md · integrating with the GroceryAI API

Copy this file into the repository that integrates with GroceryAI (as `AGENTS.md`, or merge it into yours, or into
`CLAUDE.md`). It tells a coding agent (Claude Code, Codex, Cursor, Copilot or any other) the rules that hold for every
call, so it does not have to guess.

#### Source of truth

- Contract: `https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/openapi.json` (OpenAPI 3.1, no key needed,
  `ETag` + `Cache-Control`). Fetch it; do not rely on memory. Every operation has a tested request and response example.
- Error catalog: `GET /v1/errors` and `GET /v1/errors/{code}` (no key needed). Every error response carries
  `error.doc_url` pointing to its page.
- Service status: `GET /v1/status` (no key needed): per component `operational`, `degraded`, `outage` or `unknown`.
  Before blaming your code for a `5xx`, check it; `unknown` means not measured, never «up».
- Schemas are closed (`additionalProperties: false` on responses): never invent fields, read them from the document.

#### Configuration

- Base URL: `https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api`. Keep it in configuration, not scattered in
  code.
- Key: read it from the environment (`GROCERYAI_API_KEY`). Never hard-code it, never print or log it, never commit it,
  never send it to a third party. Logs may show the public prefix (`gai_test_ab12cd34`) only.
- Environments: develop and test with a `gai_test_…` key only. Switching to `gai_live_…` is a human decision; the code
  does not change.
- Recommended header for lower latency from outside Europe: `x-region: eu-central-1`.

#### Rules for every call

1. `Authorization: Bearer <key>` on every operation except `GET /v1/openapi.json`, `GET /v1/errors` and `GET /v1/status`.
2. Every write (`PUT`, `POST`, `DELETE` with `Idempotency-Key` in the document) carries a fresh `Idempotency-Key`
   (UUID v4) per logical operation. On retry, reuse the **same** key and the **same** body. A different body with a used
   key is `409 IDEMPOTENCY_KEY_RIUSATA`.
3. Batch writes (`PUT /v1/products`, `PUT /v1/inventory`, `PUT /v1/customers`, `PUT /v1/order_history`) take at most 500
   items. Always inspect `errors[]` (rejected items, with `index` and `code`) and `warnings[]` of the response: a `200`
   does not mean every item was written.
4. Pagination is by cursor: pass `next_cursor` as `cursor` until it is `null`. It is present only when there really is
   another page, so the last page (even a full one) ends the loop with no extra request.
5. Branch on `error.code`, never on `error.message`. Use `error.param` to locate the field. Codes, `error.type` and values
   such as `stato` are stable Italian identifiers; `error.message` is Italian free text and may change.
6. Rate limit: it comes from the store's plan (guide §4: from 5 requests per second on trial to 100 on `enterprise` live, with a burst
   absorbed by a bucket). Every keyed response carries `RateLimit: "key";r=<left now>;t=<seconds>` (and `RateLimit-Policy:
   "key";q=<per second>;w=1;burst=<burst>`; a key with its own per-minute cap adds a `"key-minute"` item to both lists);
   when `r` gets low in any item, spread the remaining requests over its `t` seconds instead of running into the `429`.
   Retries: `429` → wait `Retry-After` seconds (equal to `t`); `5xx` → exponential backoff with the same `Idempotency-Key`; codes whose
   page says `retryable: false` → do not retry unchanged, fix the request.
7. Log the `request_id` of every failed call; it is what GroceryAI support asks for.
8. If your key is an **agent key**, operations that remove or cancel something (`DELETE /v1/products/{sku}`, a snapshot
   commit without `dry_run`, an order status `not_delivered` or `returned`) answer `202` with an approval and change
   nothing. Do not work around it and do not retry in a loop: tell the human that a person must approve it in the portal
   (Developers → Approvals), poll `GET /v1/approvals/{approval_id}` at most once a minute, and when `status` is `approved`
   send the same request again with `GroceryAI-Approval-Id: <id>`. `APPROVAZIONE_RIFIUTATA` is final.
9. A `401 CHIAVE_SOMMA_ERRATA` means the key in your configuration is truncated or mistyped (its last six characters are a
   checksum): ask the human for the key again, do not try variations. A `403 IP_NON_AMMESSO` means the key is restricted to
   other addresses: ask the human, do not switch keys.

#### Catalog

- `PUT /v1/products` is an upsert by `sku` that MERGES: only the fields you send change. `PUT /v1/inventory` changes
  only prices, stock and offers of existing products.
- To declare "this is the whole catalog" use a snapshot: `POST /v1/products/snapshots`, the batches with its
  `snapshot_id`, then `POST /v1/products/snapshots/{snapshot_id}/commit` first with `{"dry_run": true}`, then with
  `{"expected_off": <to_switch_off>}`. Never withdraw products one by one to emulate a full sync.
- For the whole catalog in one call use `POST /v1/catalog/imports` (up to 50,000 products, or the `url` of a file): it
  answers `202` with `Location`; poll `GET /v1/catalog/imports/{import_id}` at most every 30 seconds until `status` is
  `succeeded`, `partial` or `failed`, then read `GET /v1/catalog/imports/{import_id}/errors`. Do not split a whole catalog
  into hundreds of `PUT /v1/products` calls.
- `gtin` is optional; if present it must have a valid check digit. Prices are in the shop currency, never converted.

#### Orders

- Pull: `GET /v1/orders?status=new`, store the order, then `POST /v1/orders/{order_id}/ack`. Make your storage idempotent
  by `order_id` (an order can be read again before the ack).
- Webhooks follow Standard Webhooks (https://www.standardwebhooks.com): verify with the official library
  (`standardwebhooks` on npm and PyPI: `new Webhook(secret).verify(rawBody, headers)`), with the endpoint secret exactly as
  shown (`whsec_<base64>`); it checks `webhook-id`, `webhook-timestamp` (300 seconds tolerance) and `webhook-signature`
  (`v1,<base64>`, two signatures during a secret rotation). Answer `2xx` within 15 seconds and process asynchronously;
  deduplicate by `webhook-id`; `410 Gone` deactivates the endpoint. Verify against the **raw** body bytes, before parsing.
- Report the outcome after delivery: `POST /v1/orders/{order_id}/status`. The same call reports progress before it
  (`preparing`, `ready`, `out_for_delivery`, `delayed`, `rescheduled`, with `eta`, `reason`, `tracking_url`); after an
  outcome progress answers `409 TRANSIZIONE_NON_AMMESSA`. Guide, section 7-bis.

#### Definition of done for an integration change

- The calls it adds are in the OpenAPI document, with the scopes the key really has.
- It ran against the test environment and the responses were checked (status, `errors[]`, schema).
- Failures are handled per `error.code` and logged with `request_id`; no key appears in code, logs or commits.

### Error codes

Every code the GroceryAI API can return. Program against `error.code` (never against `message`, which may change).
Each error response also carries `error.doc_url`, the live JSON version of the page below, readable without a key.

| code | what happened | retry unchanged? |
|---|---|---|
| [`AMBIENTE_DEL_NEGOZIO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/AMBIENTE_DEL_NEGOZIO) | The key's environment does not match the shop's environment for this setting. | no |
| [`AMBITO_MANCANTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/AMBITO_MANCANTE) | The key is valid but does not have the scope this operation requires. | no |
| [`APPROVAZIONE_DIVERSA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/APPROVAZIONE_DIVERSA) | The request is not the one that was approved. | no |
| [`APPROVAZIONE_GIA_USATA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/APPROVAZIONE_GIA_USATA) | This approval already executed its operation. | no |
| [`APPROVAZIONE_IN_ATTESA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/APPROVAZIONE_IN_ATTESA) | The approval is still waiting for a person to decide. | yes |
| [`APPROVAZIONE_RIFIUTATA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/APPROVAZIONE_RIFIUTATA) | A person at the shop rejected this operation. | no |
| [`APPROVAZIONE_SCADUTA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/APPROVAZIONE_SCADUTA) | The approval expired before it was used (72 hours). | no |
| [`APPROVAZIONE_SCONOSCIUTA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/APPROVAZIONE_SCONOSCIUTA) | No approval with this id exists for this key. | no |
| [`APPROVAZIONI_ASSENTI`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/APPROVAZIONI_ASSENTI) | Approvals for agent keys are not in service on this instance yet. | yes |
| [`ATTESO_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ATTESO_NON_VALIDO) | `expected_off` is missing or is not a whole number. | no |
| [`BIC_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/BIC_NON_VALIDO) | The BIC/SWIFT code is not valid. | no |
| [`BOOLEANO_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/BOOLEANO_NON_VALIDO) | A yes/no field is not a boolean. | no |
| [`CADENZA_NON_VALIDA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CADENZA_NON_VALIDA) | `every_hours` is outside the allowed range. | no |
| [`CAMPO_IN_DUE_POSTI`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CAMPO_IN_DUE_POSTI) | The same field is both on the item and inside `attributes`, with two different values. | no |
| [`CAMPO_NON_PER_PUNTO_VENDITA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CAMPO_NON_PER_PUNTO_VENDITA) | With `store_code`, the item carries a field that applies to the whole shop. | no |
| [`CAMPO_OBBLIGATORIO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CAMPO_OBBLIGATORIO) | A required field is missing. | no |
| [`CAMPO_SCONOSCIUTO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CAMPO_SCONOSCIUTO) | The body has a field this operation does not know. | no |
| [`CHIAVE_ASSENTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CHIAVE_ASSENTE) | The request has no API key. | no |
| [`CHIAVE_INCOERENTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CHIAVE_INCOERENTE) | The visible prefix of the key does not match its secret part. | no |
| [`CHIAVE_MALFORMATA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CHIAVE_MALFORMATA) | The value after `Bearer` is not shaped like a GroceryAI key. | no |
| [`CHIAVE_REVOCATA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CHIAVE_REVOCATA) | This key has been revoked. | no |
| [`CHIAVE_SCADUTA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CHIAVE_SCADUTA) | This key has passed its expiry date. | no |
| [`CHIAVE_SCONOSCIUTA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CHIAVE_SCONOSCIUTA) | The key is well formed but does not exist. | no |
| [`CHIAVE_SOMMA_ERRATA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CHIAVE_SOMMA_ERRATA) | The key has the current GroceryAI format, but its last six characters (the checksum) do not match the rest: it was truncated, mistyped or altered. | no |
| [`CLIENTE_SCONOSCIUTO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CLIENTE_SCONOSCIUTO) | No customer with this reference exists for this shop and environment. | no |
| [`CODICE_AMICO_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CODICE_AMICO_NON_VALIDO) | The friend-code settings are not valid. | no |
| [`CODICE_ERRORE_SCONOSCIUTO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CODICE_ERRORE_SCONOSCIUTO) | This API never returns the error code in the path. | no |
| [`CONTEGGIO_CAMBIATO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CONTEGGIO_CAMBIATO) | The number of products to withdraw changed since your dry run: nothing was withdrawn. | yes |
| [`COORDINATE_BANCARIE_ASSENTI`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/COORDINATE_BANCARIE_ASSENTI) | `bank_transfer` is enabled but the shop has no bank details. | no |
| [`CORPO_NON_JSON`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CORPO_NON_JSON) | The request body is not valid JSON. | no |
| [`CORPO_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CORPO_NON_VALIDO) | The JSON body does not have the shape this operation expects. | no |
| [`CORPO_TROPPO_GRANDE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CORPO_TROPPO_GRANDE) | The request body is larger than this operation accepts: 1 MiB, or 16 MiB for `POST /v1/catalog/imports`. | no |
| [`CUSTOMER_REF_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/CUSTOMER_REF_NON_VALIDO) | `customer_ref` is missing or malformed. | no |
| [`DATA_NON_VALIDA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/DATA_NON_VALIDA) | A date is missing, malformed or not plausible. | no |
| [`DATE_INVERTITE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/DATE_INVERTITE) | The offer ends before it starts. | no |
| [`DB_URL_ASSENTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/DB_URL_ASSENTE) | This API instance is not fully configured. | yes |
| [`DIPENDENZA_NON_DISPONIBILE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/DIPENDENZA_NON_DISPONIBILE) | A service this operation depends on is temporarily unavailable. | yes |
| [`DISPONIBILITA_NON_VALIDA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/DISPONIBILITA_NON_VALIDA) | `available` is not a boolean. | no |
| [`DURATA_NON_VALIDA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/DURATA_NON_VALIDA) | `expires_in` is not a whole number of seconds between 30 and 600. | no |
| [`ELEMENTO_NON_OGGETTO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ELEMENTO_NON_OGGETTO) | A batch item is not a JSON object. | no |
| [`EMAIL_NON_VALIDA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/EMAIL_NON_VALIDA) | The `email` is not an email address. | no |
| [`ENERGIA_NON_COERENTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ENERGIA_NON_COERENTE) | Warning: `energy_kj` and `energy_kcal` do not match (1 kcal = 4.184 kJ). | no |
| [`ERRORE_INTERNO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ERRORE_INTERNO) | Something failed on our side. | yes |
| [`ETA_MANCANTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ETA_MANCANTE) | `rescheduled` needs the new delivery window in `eta`. | no |
| [`ETA_NON_AMMESSA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ETA_NON_AMMESSA) | `eta` is not allowed with this status. | no |
| [`EXTERNAL_REF_MANCANTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/EXTERNAL_REF_MANCANTE) | The customer has no `external_ref`. | no |
| [`EXTERNAL_REF_TROPPO_LUNGO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/EXTERNAL_REF_TROPPO_LUNGO) | The `external_ref` is longer than 128 characters. | no |
| [`EXTRA_SENZA_CRITERIO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/EXTRA_SENZA_CRITERIO) | A heavy-goods extra has no criterion saying when it applies. | no |
| [`FEED_NON_CONFIGURATO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/FEED_NON_CONFIGURATO) | No catalog feed is configured for this environment. | no |
| [`FEED_URL_NON_AMMESSO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/FEED_URL_NON_AMMESSO) | The feed URL is not allowed. | no |
| [`FORMATO_NON_AMMESSO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/FORMATO_NON_AMMESSO) | The feed format is not one of those supported. | no |
| [`FRASE_NON_MODIFICABILE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/FRASE_NON_MODIFICABILE) | This phrase cannot be customised. | no |
| [`GIACENZA_NON_VALIDA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/GIACENZA_NON_VALIDA) | `stock_qty` is not a non-negative number. | no |
| [`GIORNI_NON_VALIDI`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/GIORNI_NON_VALIDI) | A number of days is outside its allowed range. | no |
| [`GRADINI_NON_IN_ORDINE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/GRADINI_NON_IN_ORDINE) | Discount tiers are not in increasing order. | no |
| [`GTIN_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/GTIN_NON_VALIDO) | The `gtin` is not a valid GTIN/GS1 barcode. | no |
| [`IBAN_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IBAN_NON_VALIDO) | The IBAN is not valid. | no |
| [`IDEMPOTENCY_KEY_MANCANTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDEMPOTENCY_KEY_MANCANTE) | This operation writes data and needs an `Idempotency-Key` header. | no |
| [`IDEMPOTENCY_KEY_RIUSATA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDEMPOTENCY_KEY_RIUSATA) | This `Idempotency-Key` was already used for a different request. | no |
| [`IDEMPOTENCY_KEY_TROPPO_LUNGA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDEMPOTENCY_KEY_TROPPO_LUNGA) | The `Idempotency-Key` is longer than 255 characters. | no |
| [`IDENTITA_DI_UN_ALTRO_AMBIENTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDENTITA_DI_UN_ALTRO_AMBIENTE) | Chat session: the identity token belongs to the other environment (test vs live). | no |
| [`IDENTITA_FUORI_DAL_NEGOZIO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDENTITA_FUORI_DAL_NEGOZIO) | Chat session: the identity token belongs to another shop. | no |
| [`IDENTITA_GIA_USATA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDENTITA_GIA_USATA) | Chat session: the identity token was already used. | no |
| [`IDENTITA_MALFORMATA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDENTITA_MALFORMATA) | Chat session: the `identity_token` is not shaped like a GroceryAI identity token. | no |
| [`IDENTITA_NON_IN_SERVIZIO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDENTITA_NON_IN_SERVIZIO) | Chat identity is not in service on this instance yet. | yes |
| [`IDENTITA_SCADUTA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDENTITA_SCADUTA) | Chat session: the identity token expired. | no |
| [`IDENTITA_SCONOSCIUTA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDENTITA_SCONOSCIUTA) | Chat session: the identity token does not exist. | no |
| [`IDENTITA_SOLO_NEGOZI_NATIVI`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDENTITA_SOLO_NEGOZI_NATIVI) | This shop does not use GroceryAI for customer identity: the website chat stays anonymous. | no |
| [`IMPORTAZIONE_SCONOSCIUTA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IMPORTAZIONE_SCONOSCIUTA) | No catalog import with this `import_id` exists for this account and environment. | no |
| [`IMPORTAZIONI_IN_CORSO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IMPORTAZIONI_IN_CORSO) | There are already 5 unfinished catalog imports in this environment. | yes |
| [`IMPORTO_INCOERENTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IMPORTO_INCOERENTE) | `delivered_amount` contradicts the status. | no |
| [`IMPORTO_MANCANTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IMPORTO_MANCANTE) | `delivered_amount` is required for this status. | no |
| [`IMPORTO_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IMPORTO_NON_VALIDO) | An amount is not a valid non-negative number. | no |
| [`INFORMAZIONI_ALIMENTARI_INCOERENTI`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/INFORMAZIONI_ALIMENTARI_INCOERENTI) | Two food-information fields of the item contradict each other. | no |
| [`IP_NON_AMMESSO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IP_NON_AMMESSO) | This key has an IP allowlist, and the request does not come from an address on it. | no |
| [`ISTANTANEA_CHIUSA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ISTANTANEA_CHIUSA) | The snapshot is already committed and accepts no more batches. | no |
| [`ISTANTANEA_SCADUTA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ISTANTANEA_SCADUTA) | The snapshot expired (snapshots live 24 hours). | no |
| [`ISTANTANEA_SCONOSCIUTA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ISTANTANEA_SCONOSCIUTA) | No snapshot with this `snapshot_id` exists for this account and environment. | no |
| [`ISTANTANEA_SOTTO_SOGLIA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ISTANTANEA_SOTTO_SOGLIA) | The batches of this snapshot cover too few of the active products: nothing was withdrawn. | no |
| [`LIMITE_RICHIESTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/LIMITE_RICHIESTE) | Too many requests for this key in the current minute. | yes |
| [`LINGUA_NON_VALIDA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/LINGUA_NON_VALIDA) | `lang` is not a language code. | no |
| [`LINK_NELLA_FRASE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/LINK_NELLA_FRASE) | The phrase contains a link. | no |
| [`LOTTO_TROPPO_GRANDE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/LOTTO_TROPPO_GRANDE) | The batch has more items than this operation accepts: 500 per call, or 50,000 for `POST /v1/catalog/imports`. | no |
| [`LOTTO_VUOTO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/LOTTO_VUOTO) | The batch list is empty. | no |
| [`METODO_DI_PAGAMENTO_NON_AMMESSO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/METODO_DI_PAGAMENTO_NON_AMMESSO) | A payment method is not one of those supported. | no |
| [`METODO_NON_AMMESSO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/METODO_NON_AMMESSO) | The path exists, but not with this HTTP method. | no |
| [`MOTIVO_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/MOTIVO_NON_VALIDO) | `reason` is not one of the allowed codes, or not allowed with this status. | no |
| [`NESSUN_CAMPO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/NESSUN_CAMPO) | The inventory item changes nothing. | no |
| [`NESSUN_METODO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/NESSUN_METODO) | No payment method is enabled. | no |
| [`NON_TROVATO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/NON_TROVATO) | The resource in the path does not exist for this account and this key's environment. | no |
| [`NOTA_TROPPO_LUNGA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/NOTA_TROPPO_LUNGA) | The note is longer than 500 characters. | no |
| [`NUMERO_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/NUMERO_NON_VALIDO) | A numeric field is not a valid number for its range. | no |
| [`NUTRIZIONE_INCOMPLETA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/NUTRIZIONE_INCOMPLETA) | Warning: the item carries part of the nutrition declaration but not all of it. | no |
| [`OFFERTA_NON_SCONTATA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/OFFERTA_NON_SCONTATA) | Warning: the offer price is not below the regular price, so it will not be shown as an offer. | no |
| [`OFFERTA_SUPERIORE_AL_PREZZO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/OFFERTA_SUPERIORE_AL_PREZZO) | The offer price is higher than the regular price. | no |
| [`ORARI_NON_VALIDI`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ORARI_NON_VALIDI) | The opening or assistant hours are not valid. | no |
| [`ORDINE_MANCANTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ORDINE_MANCANTE) | The order line has no `order_ref`. | no |
| [`ORDINE_SENZA_CLIENTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ORDINE_SENZA_CLIENTE) | The order line does not say who the customer is. | no |
| [`OUTBOX_ASSENTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/OUTBOX_ASSENTE) | The event log is not in service on this instance yet. | yes |
| [`PACCHETTO_ASSENTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/PACCHETTO_ASSENTE) | The shop has no language pack yet, so the preview cannot be rendered. | yes |
| [`PARAMETRO_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/PARAMETRO_NON_VALIDO) | A query parameter is outside its allowed values. | no |
| [`PERCENTUALE_NON_VALIDA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/PERCENTUALE_NON_VALIDA) | A percentage is outside its allowed range. | no |
| [`PERCORSO_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/PERCORSO_NON_VALIDO) | A site path is not valid. | no |
| [`PESO_MEDIO_SENZA_PESO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/PESO_MEDIO_SENZA_PESO) | Warning: an average piece weight was sent for a product not sold by weight; it is not used. | no |
| [`PREZZO_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/PREZZO_NON_VALIDO) | The price is not a non-negative number. | no |
| [`PUNTO_VENDITA_CON_ZONE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/PUNTO_VENDITA_CON_ZONE) | This store cannot be deactivated or removed while delivery zones use it. | no |
| [`PUNTO_VENDITA_SCONOSCIUTO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/PUNTO_VENDITA_SCONOSCIUTO) | No active store has this `store_code`. | no |
| [`QUANTITA_NON_VALIDA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/QUANTITA_NON_VALIDA) | `quantity` is missing or not greater than zero. | no |
| [`REGISTRO_ASSENTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/REGISTRO_ASSENTE) | The order register is not in service on this instance yet. | yes |
| [`REGOLA_SCONOSCIUTA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/REGOLA_SCONOSCIUTA) | A rule or text key is not one this API knows. | no |
| [`REGOLE_SOLO_NEGOZI_DEL_PORTALE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/REGOLE_SOLO_NEGOZI_DEL_PORTALE) | This shop does not manage its rules and texts through GroceryAI. | no |
| [`RICHIESTA_IN_CORSO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/RICHIESTA_IN_CORSO) | A request with the same `Idempotency-Key` is still being processed. | yes |
| [`RIFIUTATA_DAL_DATABASE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/RIFIUTATA_DAL_DATABASE) | The database refused this item. | no |
| [`ROTTA_SCONOSCIUTA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ROTTA_SCONOSCIUTA) | No operation exists for this method and path. | no |
| [`SEGNAPOSTO_DIVERSI`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/SEGNAPOSTO_DIVERSI) | The phrase does not keep the same placeholders as the original. | no |
| [`SKU_MANCANTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/SKU_MANCANTE) | The item has no `sku`. | no |
| [`SKU_RIPETUTO_NEL_LOTTO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/SKU_RIPETUTO_NEL_LOTTO) | The same `sku` appears twice in one batch. | no |
| [`SKU_SCONOSCIUTO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/SKU_SCONOSCIUTO) | No product with this `sku` exists for this account and environment. | no |
| [`SKU_TROPPO_LUNGO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/SKU_TROPPO_LUNGO) | The `sku` is longer than 128 characters. | no |
| [`SOGLIA_SOTTO_IL_COSTO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/SOGLIA_SOTTO_IL_COSTO) | A zone's free-delivery threshold is below its delivery fee. | no |
| [`STATO_NON_MISURABILE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/STATO_NON_MISURABILE) | The service status cannot be read right now: the status is unknown, not operational. | yes |
| [`STATO_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/STATO_NON_VALIDO) | The `status` is missing or not one of the allowed values. | no |
| [`STORICO_SOLO_NEGOZI_NATIVI`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/STORICO_SOLO_NEGOZI_NATIVI) | This shop reads its order history from its own connector, not from this route. | no |
| [`TELEFONO_NON_E164`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/TELEFONO_NON_E164) | The phone number is not in international E.164 format. | no |
| [`TENANT_NON_DELLA_CHIAMATA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/TENANT_NON_DELLA_CHIAMATA) | The body refers to a different account than the key's. | no |
| [`TENANT_SOSPESO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/TENANT_SOSPESO) | The account that owns this key is not active. | no |
| [`TERMINE_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/TERMINE_NON_VALIDO) | A term or time window is not valid. | no |
| [`TESTO_TROPPO_LUNGO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/TESTO_TROPPO_LUNGO) | A text field is longer than allowed. | no |
| [`TITLE_MANCANTE`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/TITLE_MANCANTE) | The new product has no `title`. | no |
| [`TITLE_TROPPO_LUNGO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/TITLE_TROPPO_LUNGO) | The `title` is longer than 512 characters. | no |
| [`TOTALE_NON_VALIDO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/TOTALE_NON_VALIDO) | `order_total` is not a non-negative number. | no |
| [`TRANSIZIONE_NON_AMMESSA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/TRANSIZIONE_NON_AMMESSA) | The order already has an outcome: a progress status is no longer recorded. | no |
| [`TROPPI_ELEMENTI`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/TROPPI_ELEMENTI) | A list has more items than allowed. | no |
| [`UNITA_NON_AMMESSA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/UNITA_NON_AMMESSA) | A unit field has a value that is not allowed. | no |
| [`URL_NON_AMMESSO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/URL_NON_AMMESSO) | `tracking_url` is not an `https` address on a tracking domain the shop declared. | no |
| [`VALORE_NON_AMMESSO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/VALORE_NON_AMMESSO) | A field has a value outside its allowed list. | no |
| [`VALORE_RIPETUTO`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/VALORE_RIPETUTO) | The same value appears twice where values must be unique. | no |
| [`VALUTA_DIVERSA_DAL_TENANT`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/VALUTA_DIVERSA_DAL_TENANT) | The item's currency differs from the shop currency. | no |
| [`VALUTA_NON_VALIDA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/VALUTA_NON_VALIDA) | `currency` is not an ISO 4217 code. | no |
| [`VERSIONE_CAMBIATA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/VERSIONE_CAMBIATA) | The rules changed since the version you read: nothing was saved. | yes |
| [`ZONA_NON_VALIDA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ZONA_NON_VALIDA) | A delivery zone entry is malformed. | no |
| [`ZONA_SCONOSCIUTA`](https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/ZONA_SCONOSCIUTA) | A delivery zone is not one of the shop's zones. | no |

Full catalog as JSON: `GET https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors` (no key needed).

_Generated from the OpenAPI document by `tools/genera-openapi.mjs`: do not edit by hand._

## API GroceryAI · guida per chi integra

Il riferimento completo, rotta per rotta, è il documento OpenAPI 3.1 (`openapi.json`): forme delle risposte, codici
d'errore per ogni stato (`x-error-codes`) ed eventi (`webhooks`). Questa guida spiega le regole che valgono per tutte
le rotte. Gli esempi in `examples/` sono provati a ogni giro contro il codice della piattaforma. Il documento OpenAPI è in
inglese, si scarica **senza chiave** (`GET /v1/openapi.json`, con `ETag` e `Cache-Control`) e ha un esempio di richiesta
e di risposta provato per ogni operazione. Ogni risposta d'errore porta `error.doc_url`, la pagina del suo codice (che
cosa vuol dire, come si corregge): il catalogo intero è `GET /v1/errors`, anche lui senza chiave. Per cominciare:
`quickstart.it.md`; per gli agenti di programmazione: `AGENTS.md` e il prompt pronto `agent-prompt.md`.

Indirizzo: `https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api` più il percorso (`/v1/products`…).
Ogni risposta porta `x-request-id` (lo stesso valore è `request_id` nel corpo) e `x-core-version`: se ci scrivi, mandaci
il `request_id`.

### 1. Chiavi e autenticazione

Ogni chiamata porta `Authorization: Bearer <chiave>`. La chiave si crea nel portale (Sviluppatori → Chiavi API) e si
vede **una volta sola**: copiala subito in un posto sicuro.

| | |
|---|---|
| forma | `gai_<ambiente>_<prefisso di 8>_<segreto di 32><somma di 6>`, per esempio `gai_test_ab12cd34_…`. Gli ultimi 6 caratteri sono la **somma di controllo** (CRC32 di tutto ciò che li precede, in base 62 `0-9A-Za-z`): una chiave troncata o ricopiata male si riconosce senza chiamarci, e la nostra porta la rifiuta prima di cercarla (`401 CHIAVE_SOMMA_ERRATA`). Le chiavi create prima del 5 novembre 2026 hanno 32 caratteri dopo il prefisso, senza somma, e continuano a valere: ruotale quando vuoi avere la somma |
| prefisso | `gai_test_ab12cd34` è pubblico: lo vedi nel portale e nel registro attività, da solo non apre niente |
| ambiente | `test` o `live`. Separa i **dati**, non solo l'etichetta: una chiave `test` vede solo il catalogo, i clienti e gli ordini di prova, una `live` solo quelli veri |
| permessi | `catalog:read`, `catalog:write`, `customers:read`, `customers:write`, `orders:read`, `orders:write`, `chat:write` (aprire sessioni di chat dal tuo server). Nessuno ne contiene un altro: `catalog:write` non permette di leggere il catalogo |
| chiave pubblicabile | `gai_pk_…` serve alla chat sul tuo sito, non ha permessi: su questa API riceve `403 AMBITO_MANCANTE` |
| indirizzi IP ammessi | facoltativi, per chiave (portale → la chiave → «Indirizzi IP ammessi»): reti CIDR o indirizzi singoli, al più 50. Una chiamata da fuori elenco, o di cui non conosciamo l'indirizzo, riceve `403 IP_NON_AMMESSO`. Senza elenco la chiave si usa da ovunque |
| chiave per un agente AI | facoltativa, per chiave: le operazioni che tolgono o annullano qualcosa aspettano che una persona del negozio le approvi (§11) |

Una chiave che non apre risponde `401` con un codice preciso: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`,
`CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE`. Un negozio non attivo
risponde `403 TENANT_SOSPESO`; una chiave senza il permesso della rotta `403 AMBITO_MANCANTE`; una chiave usata da un indirizzo
che la sua politica non ammette `403 IP_NON_AMMESSO`.

### 2. Errori

Un solo formato, su ogni rotta e per ogni errore, nostro o tuo:

```json
{ "error": { "type": "richiesta_non_valida", "code": "PARAMETRO_NON_VALIDO", "message": "`limit` deve essere un intero fra 1 e 200.", "param": "limit" },
  "request_id": "6f1c…" }
```

- **`code`** è ciò su cui programmi: i valori possibili di ogni rotta e stato sono in `x-error-codes` nel documento.
- **`type`** è la famiglia, e dipende solo dallo stato HTTP: 400 e 405 `richiesta_non_valida`, 401 `autenticazione`,
  403 `autorizzazione`, 404 `non_trovato`, 409 `conflitto`, 413 `troppo_grande`, 429 `limite_richieste`,
  503 `servizio_non_disponibile`, altri 5xx `errore_interno`.
- **`message`** è per chi legge e può cambiare; **`param`** c'è quando l'errore riguarda un campo o un parametro.
- Un percorso che non esiste è `404 ROTTA_SCONOSCIUTA`; un percorso che esiste con il metodo sbagliato è
  `405 METODO_NON_AMMESSO`. La chiave si controlla prima del percorso: senza una chiave valida ricevi il `401`.
- Un `5xx` non porta mai il dettaglio interno: il `request_id` basta a noi per ritrovarlo.

### 3. Idempotenza

Ogni chiamata che scrive (`PUT /v1/products`, `PUT /v1/inventory`, `PUT /v1/customers`, i `POST …/ack`) vuole
l'intestazione `Idempotency-Key`: un valore tuo, al più 255 caratteri. Senza: `400 IDEMPOTENCY_KEY_MANCANTE`.

- Stessa chiave, stesso corpo: ricevi **la stessa risposta** (stato, corpo e `request_id` della prima volta) con
  `idempotent-replayed: true`, e niente viene rieseguito. Puoi quindi ripetere senza paura una chiamata di cui non hai
  visto la risposta (rete caduta, tempo scaduto).
- Stessa chiave, corpo diverso: `409 IDEMPOTENCY_KEY_RIUSATA`.
- Stessa chiave mentre la prima chiamata è ancora in corso: `409 RICHIESTA_IN_CORSO`; riprova fra qualche secondo.
- La chiave vale **per negozio e per ambiente** (su tutte le chiavi API dello stesso ambiente): la stessa chiave usata
  prima con una chiave `test` e poi con una `live` esegue in `live`, senza rigiocare la risposta della prova. **Scade
  dopo 24 ore**: da lì la stessa chiave esegue di nuovo. Usa un valore nuovo per ogni operazione distinta (un UUID, o un
  id del tuo sistema come `ack-<event_id>`).
- Viene registrato anche l'esito di una chiamata fallita dopo essere stata accettata (un `404` sull'ack di un ordine
  che non esiste, un `5xx`): ripeterla con la stessa chiave ti ridà quell'esito, marcato `idempotent-replayed`. Per
  riprovare davvero serve una chiave nuova. Gli errori che arrivano prima (chiave API, permessi, limite, corpo non JSON
  o troppo grande, `Idempotency-Key` mancante o troppo lunga) non consumano la chiave.

### 4. Limiti

| | |
|---|---|
| richieste | per chiave API, secondo il **piano del negozio** (tabella qui sotto): un ritmo sostenuto al secondo e una raffica che il secchio assorbe. Una chiave può avere un tetto suo al minuto, più basso. Oltre: `429 LIMITE_RICHIESTE` con `Retry-After`. Ogni risposta dice quanto resta: `RateLimit` (qui sotto) |
| corpo | al più 1 MiB (16 MiB per `POST /v1/catalog/imports`): oltre, `413 CORPO_TROPPO_GRANDE` |
| lotti | al più 500 elementi per chiamata (50.000 per `POST /v1/catalog/imports`, §8-bis): oltre, `400 LOTTO_TROPPO_GRANDE`; una lista vuota è `400 LOTTO_VUOTO` |
| importazioni | al più 5 non finite per ambiente: oltre, `409 IMPORTAZIONI_IN_CORSO` |

#### I limiti per piano

| piano | chiavi `test` | chiavi `live` |
|---|---|---|
| prova (nessun piano) | 5 al secondo, raffica 120 | 5 al secondo, raffica 120 |
| `small` | 10 al secondo, raffica 120 | 25 al secondo, raffica 250 |
| `mid` | 25 al secondo, raffica 250 | 50 al secondo, raffica 500 |
| `enterprise` | 25 al secondo, raffica 250 | 100 al secondo, raffica 1000 |

Il limite si conta con un **secchio** per chiave: si riempie al ritmo del piano fino alla raffica, e ogni richiesta ne
prende un gettone. Un gestionale che manda 250 richieste di fila con una chiave `small` live le vede passare tutte, poi
prosegue a 25 al secondo; una richiesta respinta non consuma gettoni. Un contratto può fissare per il negozio un limite
diverso da quello del piano (scritto da noi, mai implicito). Una chiave coniata con `rate_limit_per_min` ha in più il suo
tetto al minuto, che vale solo se è più basso del piano; senza, segue il piano. Le chiavi `test` hanno limiti più bassi
delle `live`, come nelle sandbox dei grandi fornitori: le prove di carico non si fanno in `test`.

#### Quanto resta: `RateLimit-Policy` e `RateLimit`

Ogni risposta di una rotta con chiave porta due intestazioni nella forma della bozza IETF
`draft-ietf-httpapi-ratelimit-headers` (versione -11, 23 maggio 2026), così rallenti **prima** del `429` invece di
scoprire il tetto sbattendoci contro:

```
RateLimit-Policy: "key";q=25;w=1;burst=250
RateLimit: "key";r=249;t=1
```

- `q` è il ritmo sostenuto del piano, in richieste al secondo, `w=1` la finestra di un secondo, `burst` la raffica (le
  richieste che passano di fila a secchio pieno).
- `r` sono le richieste che puoi fare **adesso**, di fila, **già tolta questa** (i gettoni nel secchio); `t` i secondi al
  prossimo gettone. Ogni richiesta contata fa scendere `r` di uno, anche un rigioco con la stessa `Idempotency-Key`.
- Se la chiave ha un tetto suo al minuto le liste hanno un secondo elemento, `"key-minute";q=<tetto>;w=60` e
  `"key-minute";r=<restano nel minuto>;t=<secondi alla fine del minuto>`: vale il più stretto dei due.
- Con `r=0` la richiesta successiva prima di `t` secondi riceve `429`, che porta `r=0` e `Retry-After` **uguale** al `t`
  della politica che ha respinto.
- Il 401, il 403 e il 404/405 di un percorso che non esiste arrivano prima del conteggio e non le portano; nemmeno le rotte senza chiave (`/v1/openapi.json`,
  `/v1/errors`, `/v1/status`). Il limite è per chiave: due chiavi dello stesso negozio hanno due secchi.
- Un `r` positivo non è una garanzia (la bozza, §8.3): un `429` va gestito comunque.
- Gli **SDK ufficiali** lo fanno da sé: con `r=0` aspettano `t` secondi prima della richiesta successiva, e ritentano
  comunque sul `429` dopo `Retry-After` (`docs/api/sdk.it.md`; si spegne con `throttle: false`). Il **server MCP** porta
  le stesse due intestazioni, dallo stesso conteggio, a finestra di un minuto sul tetto equivalente del piano (`docs/api/mcp.md`, «I limiti»).

Un client che rallenta da sé (Node, `fetch`; l'esempio è eseguito dal nostro banco contro le intestazioni vere):

```js
// Quanto aspettare prima della prossima richiesta, letto dalla risposta precedente.
function attesaMs(risposta) {
  let attesa = 0;                                // nessun limite dichiarato (rotta senza chiave, 401, 403): avanti
  // Un elemento per politica: il secchio del piano ("key") e, se c'e', il tetto al minuto della chiave ("key-minute").
  for (const m of (risposta.headers.get('ratelimit') ?? '').matchAll(/;r=(\d+);t=(\d+)/g)) {
    const restano = Number(m[1]), secondi = Number(m[2]);
    if (restano === 0) attesa = Math.max(attesa, secondi * 1000);      // quota finita: si aspetta t
    else if (restano < 10) attesa = Math.max(attesa, Math.ceil((secondi * 1000) / restano)); // quasi finita: si distribuisce il resto
  }
  return attesa;                                 // vale la politica più stretta
}
```

Nei lotti un elemento non valido **non fa cadere** il lotto: la risposta dice quanti ne sono arrivati, quanti scritti e
quali rifiutati, con posizione e motivo.

```json
{ "received": 3, "written": 2, "rejected": 1,
  "errors": [{ "index": 1, "id": "SKU-9", "code": "GTIN_NON_VALIDO", "message": "…" }],
  "request_id": "…" }
```

`index` è la posizione nel tuo lotto (da 0); è `null` quando a rifiutare è stato il database dopo la validazione
(`RIFIUTATA_DAL_DATABASE`). Su `PUT /v1/inventory` uno SKU che non esiste è `SKU_SCONOSCIUTO`: non si crea un prodotto a
metà. I prezzi si caricano nella valuta del negozio: un'altra valuta è `VALUTA_DIVERSA_DAL_TENANT`, non si converte.

### 5. Paginazione

- **Catalogo** (`GET /v1/products`): ordinato per `sku`; `limit` da 1 a 200 (50 se manca); la pagina successiva si
  chiede con `cursor` = `next_cursor` della precedente. `next_cursor` c'è solo quando c'è davvero un'altra pagina: sull'ultima,
  anche se è piena, è `null` e il giro finisce senza chiamate in più. Filtri: `sku`, `gtin`.
- **Ordini e richieste di assistenza** (`GET /v1/orders`, `GET /v1/support_requests`): dal più vecchio, `limit` da 1 a
  200. Non c'è cursore: la coda avanza con l'**ack**. `status=new` (predefinito) dà ciò che non hai ancora confermato,
  `status=acked` ciò che hai confermato.

### 6. Eventi via webhook

Quando un cliente conferma un ordine (`order.confirmed`) o chiede una persona dello staff (`support.requested`), o quando il
negozio comunica a che punto è un ordine (`order.updated`, sezione 7-bis), la piattaforma manda una `POST` firmata a ogni
endpoint del negozio iscritto a quell'evento. Il pulsante «Manda un evento di
prova» del portale manda un `webhook.ping` (ambiente `test`) al solo endpoint provato.

Le consegne seguono **Standard Webhooks** (specifica 1.0.0, https://www.standardwebhooks.com): la libreria ufficiale della
tua lingua le verifica così come arrivano, senza niente di nostro da copiare.

Il corpo è sempre la stessa busta:

```json
{ "id": "2b1e…", "type": "order.confirmed", "environment": "live", "timestamp": "2026-10-13T09:00:00.000Z",
  "occurred_at": "2026-10-13T09:00:00.000Z", "resource_id": "ORD-1042", "attempt": 1,
  "data": { "schema_version": 2, "order": { … } } }
```

`data` cambia con il tipo; le forme esatte sono nel documento (`webhooks`, schemi `OrdineConfermato`,
`RichiestaAssistenza`, `OrdineAggiornato`, `Ping`). `environment` dice se è una prova o un fatto vero: gli endpoint sono gli stessi.
`timestamp` (il campo di Standard Webhooks) e `occurred_at` sono lo stesso istante: quando è accaduto il fatto, non quando
è partita la consegna.

#### Verificare la firma

Ogni consegna porta le tre intestazioni di Standard Webhooks:

| intestazione | |
|---|---|
| `webhook-id` | l'id del messaggio: l'`id` dell'evento, uguale a ogni tentativo e a ogni riconsegna |
| `webhook-timestamp` | i secondi Unix di questo tentativo (cambia a ogni ritento) |
| `webhook-signature` | `v1,<base64>`, l'HMAC-SHA256 di `<webhook-id>.<webhook-timestamp>.<corpo grezzo>`; due, separate da uno spazio, mentre è in corso una rotazione del segreto |

Si verifica con la libreria ufficiale (`npm install standardwebhooks`, `pip install standardwebhooks`), passando il
**corpo grezzo** (i byte esatti ricevuti: rileggere e riscrivere il JSON li cambia) e il segreto così come il portale te
l'ha mostrato, `whsec_` compreso:

```js
import { Webhook } from 'standardwebhooks';
const wh = new Webhook(process.env.GAI_WEBHOOK_SECRET);           // "whsec_..."
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
  let event;
  try { event = wh.verify(req.body.toString('utf8'), req.headers); }  // solleva se falsa, toccata o vecchia
  catch { return res.status(400).end(); }
  res.status(200).end();                                           // rispondi entro 15 secondi, lavora dopo
  // scarta i doppioni con req.headers['webhook-id'] (= event.id), poi tratta event.type
});
```

```python
from standardwebhooks.webhooks import Webhook, WebhookVerificationError
wh = Webhook(os.environ["GAI_WEBHOOK_SECRET"])                    # "whsec_..."
def webhooks():                                                   # Flask; any framework works
    try:
        event = wh.verify(request.get_data(as_text=True), dict(request.headers))
    except WebhookVerificationError:
        return "", 400
    # scarta i doppioni con request.headers["webhook-id"] (= event["id"]), poi tratta event["type"]
    return "", 200
app.add_url_rule("/webhooks", view_func=webhooks, methods=["POST"])
```

La libreria rifiuta un `webhook-timestamp` che dista più di **300 secondi** dal tuo orologio: una consegna vera
intercettata e rimandata più tardi cade lì, anche con la firma giusta. Il segreto è `whsec_` seguito dal base64 di 32
byte casuali; la chiave dell'HMAC sono i byte decodificati. Ricevitori completi e provati:
`examples/verify-standardwebhooks.mjs` e `examples/verify_standardwebhooks.py` (librerie ufficiali);
`examples/verify-signature.mjs` e `examples/verify_signature.py` fanno lo stesso senza nessuna dipendenza, per un
ambiente in cui non puoi aggiungerne.

#### Ruotare il segreto

Attraverso il portale (`POST /organizations/{org}/webhooks/{endpoint_id}/rotate-secret` con `{"overlap_hours": 0-72}`)
l'endpoint riceve un segreto nuovo, mostrato una volta. Per `overlap_hours` resta valido
anche il vecchio: ogni consegna porta **due** firme, la nuova e la vecchia, e la libreria accetta l'una o l'altra. Metti il
segreto nuovo nella tua configurazione entro quella finestra; `0` invalida subito il vecchio (per un segreto finito in
mani sbagliate).

#### Rispondere e ritentare

- Rispondi `2xx` **entro 15 secondi** e lavora dopo. Qualunque altra risposta (un redirect compreso: non si segue), o
  nessuna risposta in tempo, è un tentativo fallito.
- I tentativi sono dieci: il primo entro un minuto circa dall'evento, poi ciascuno dopo il precedente di 1 minuto,
  5 minuti, 30 minuti, 2 ore, 5 ore, 10 ore, 14 ore, 20 ore e 24 ore (poco più di tre giorni in tutto), ogni ritardo
  variato fino al 10 % perché gli endpoint caduti insieme non vengano ritentati nello stesso secondo. Un'intestazione
  `Retry-After` nella tua risposta ci fa aspettare di più (fino a un giorno per quel tentativo), mai di meno. Dopo il
  decimo la consegna è abbandonata e lo vedi nel portale (Sviluppatori → Webhook → Consegne), da dove puoi rimandarla.
- `410 Gone` vuol dire «basta»: l'endpoint si **disattiva** subito (l'elenco degli endpoint del
  portale dice perché: `disabled_reason: "http_410"`) e non riceve più niente finché
  non lo crei di nuovo. Ogni altro `4xx` si ritenta come un `5xx`: un endpoint che risponde `401` perché non ha ancora il
  segreto nuovo non perde niente.
- Ogni tentativo è firmato di nuovo, con il suo `webhook-timestamp` e il suo `attempt`; `webhook-id`, `id` e `data` non
  cambiano.
- Lo stesso evento può arrivarti più di una volta (un ritento dopo un `2xx` che non ci è arrivato, una consegna
  rimandata dal portale): scarta i doppioni con `webhook-id`.
- Il segreto si vede una volta sola, alla creazione dell'endpoint o alla rotazione. Un endpoint disattivato e poi
  riattivato riceve un segreto **nuovo**.

### 7. Ritiro in pull

Se non vuoi un endpoint in ingresso, ritiri ordini e richieste quando vuoi tu: `GET /v1/orders?status=new` (permesso
`orders:read`), salvi, e confermi con `POST /v1/orders/{order_id}/ack` (permesso `orders:write`, con
`Idempotency-Key`). Lo stesso per `GET /v1/support_requests` e `POST /v1/support_requests/{support_id}/ack`.

- Vedi solo ciò che appartiene all'ambiente della tua chiave.
- Ogni elemento porta `event_id` (lo stesso `id` del webhook), l'identificativo da passare all'ack, `payload` (lo stesso
  `data` del webhook), `occurred_at` e `created_at`, e `stato` (`in_attesa` finché non confermi, poi `consegnato` con
  `consegnato_at`).
- Confermare due volte non è un errore. Finché non confermi, l'elemento torna a ogni lettura: salva per id, in modo
  idempotente, e se cadi fra il salvataggio e la conferma lo rivedrai, senza perderlo.
- Gli ordini più vecchi dell'11/10/2026 sono nella versione 1 del contratto: niente `schema_version`, e il cliente ha il
  solo `chatId`.

Esempio completo e provato: `examples/pull-orders.mjs`.

### 7-bis. A che punto è l'ordine, e com'è andato

Dopo l'ack, il tuo sistema dice a GroceryAI che cosa succede all'ordine con **una sola chiamata**, la stessa per tutta la
sua vita: `POST /v1/orders/{order_id}/status` (permesso `orders:write`, con `Idempotency-Key`). `status` è un codice:

- **avanzamento**, prima dell'esito: `preparing` (in preparazione), `ready` (pronto, anche per il ritiro),
  `out_for_delivery` (in consegna), `delayed` (in ritardo), `rescheduled` (rinviato a una fascia nuova);
- **esito**: `delivered`, `substituted` (con sostituzioni o voci mancanti, con `delivered_amount`), `not_delivered`,
  `returned`. È l'esito che conta per la fatturazione, e vale l'ultimo comunicato; l'avanzamento non la tocca mai.

```json
{ "status": "out_for_delivery",
  "eta": { "start": "2026-11-06T17:00:00Z", "end": "2026-11-06T18:00:00Z" },
  "tracking_url": "https://tracking.example-carrier.com/t/ORD-1042" }
```

- `eta` è la finestra prevista o concordata: **obbligatoria** con `rescheduled` (`400 ETA_MANCANTE`), facoltativa con
  `out_for_delivery` e `delayed`, vietata con gli altri stati (`400 ETA_NON_AMMESSA`); la fine dopo l'inizio, al più 24 ore
  dopo, l'inizio entro 30 giorni (`400 DATA_NON_VALIDA`).
- `reason` è un codice, mai un testo: `stock`, `capacity`, `traffic`, `weather`, `customer_request`, `shop_request`,
  `failed_attempt`, `other`; solo con `delayed`, `rescheduled` e `not_delivered` (`400 MOTIVO_NON_VALIDO`). Il cliente legge
  la frase della sua lingua.
- `tracking_url` va in `https` su un dominio di tracciamento dichiarato per il negozio (`400 URL_NON_AMMESSO`); per un
  corriere nuovo chiedi al supporto di dichiararne il dominio.
- `delivered_amount` va solo con l'esito (`400 IMPORTO_INCOERENTE` con l'avanzamento).
- Dopo un esito l'avanzamento non si registra più: `409 TRANSIZIONE_NON_AMMESSA`. Un altro esito sì (vale l'ultimo).
- Fra due avanzamenti vale il più recente per `reported_at`, non quello arrivato per ultimo: uno più vecchio si conserva
  e risponde `superseded: true`, senza evento.
- Lo stesso stato ridetto (con un'altra `Idempotency-Key`) risponde `duplicate: true` e non produce un secondo evento.
- Con una chiave agente l'avanzamento non chiede l'approvazione di una persona; `not_delivered` e `returned` sì
  (sezione 11).

La risposta ridice ciò che hai mandato, più `kind` (`outcome` o `progress`). Ogni comunicazione registrata diventa
l'evento **`order.updated`** per gli endpoint iscritti (sezione 6): `resource_id` è l'identificativo della comunicazione,
l'ordine è `data.order.id`, e il corpo non porta dati del cliente né importi. `order.updated` non si ritira in pull.

### 8. Aggiornare il catalogo

Il listino cambia ogni giorno: queste sono le vie per tenerlo vero senza ricaricare tutto.

- **Merge, di serie.** `PUT /v1/products` aggiorna solo i campi che l'elemento nomina: un elemento con `sku`, `title` e
  `price` cambia il prezzo e lascia com'erano formato, pezzi, offerta, marca e reparto. Gli `attributes` si fondono con
  quelli che ci sono; per togliere un campo lo mandi a `null`. Lo stesso `sku` due volte nello stesso lotto: vale il primo.
- **I campi del contratto del catalogo** si scrivono col loro nome nell'elemento (`min_order_qty`, `min_order_unit`,
  `sold_by_weight`, `avg_piece_weight_kg`, `items_per_pack`, `pack_only`, `stock_managed`, `unit_price`,
  `gross_weight_kg`, `tare_kg`, `list_price`, `subcategory`, `description`, `vat_rate`, `diet_tags`, `offer_price`,
  `offer_start`, `offer_end`, `offer_min_qty`, `offer_label`; `is_online` è `available`) e si validano come nel file
  del portale: un valore illeggibile ferma solo il suo elemento, con un `code` per campo.
- **Le informazioni alimentari** (art. 14 del Reg. (UE) 1169/2011: per vendere a distanza un alimento preimballato vanno
  date prima dell'acquisto) sono campi facoltativi dello stesso elemento: `allergens` (i 14 dell'allegato II coi codici
  `gluten`, `crustaceans`, `eggs`, `fish`, `peanuts`, `soybeans`, `milk`, `nuts`, `celery`, `mustard`, `sesame`,
  `sulphites`, `lupin`, `molluscs`, o i codici GS1 come `AW`; `none` dichiara che non ce n'è nessuno), `may_contain`
  (le tracce), `ingredients`, `nutrition_basis` (`100g` o `100ml`) con `energy_kj`, `energy_kcal`, `fat_g`,
  `saturated_fat_g`, `carbohydrate_g`, `sugars_g`, `protein_g`, `salt_g`, `fibre_g`, e `storage_conditions`,
  `usage_instructions`, `food_business_operator`, `origin`, `alcohol_percent`, `food_info_url` (la scheda, se le
  informazioni stanno in una pagina). Un campo assente vuol dire «non dichiarato»: l'assistente lo dice al cliente e
  non indovina mai un allergene. La risposta del lotto porta
  anche `warnings`: l'elemento è scritto, ma qualcosa non si userà (un'offerta che non sconta).
- **Prezzi, giacenze e offerte, leggeri.** `PUT /v1/inventory` tocca solo ciò che l'elemento porta: `price`, `stock_qty`,
  `available`, il barrato `list_price` e l'offerta (`offer_price`, `offer_start`, `offer_end`). `price` resta il prezzo
  pieno; l'offerta vale nelle sue date, nel fuso del negozio, e finisce da sola.
- **Ritirare un prodotto.** `DELETE /v1/products/{sku}` lo spegne, non lo cancella: l'assistente non lo vende più, gli
  ordini che lo citano restano leggibili. Per rimetterlo in vendita lo rimandi con `PUT /v1/products`.
- **«Questo è il catalogo intero».** `POST /v1/products/snapshots` apre un'istantanea; mandi i lotti con `PUT
  /v1/products` e lo `snapshot_id` nel corpo; poi `POST /v1/products/snapshots/{snapshot_id}/commit` con `{"dry_run":
  true}` ti dice quanti prodotti attivi i lotti non hanno portato (`to_switch_off`) e i primi 20; lo richiami con
  `{"expected_off": n}` e quelli si ritirano. Se i lotti hanno portato meno del **90 %** dei prodotti attivi non si
  ritira niente (`409 ISTANTANEA_SOTTO_SOGLIA`) e l'istantanea resta aperta: un file troncato non svuota il catalogo. Se il
  numero è cambiato fra la prova e la conferma, `409 CONTEGGIO_CAMBIATO` e niente ritirato. L'istantanea vive 24 ore.
- **Il feed programmato.** `PUT /v1/catalog/feed` con `{"url": "https://…", "format": "google_merchant_xml"}` (o
  `google_merchant_tsv`, `csv`, `xlsx`): lo leggiamo noi ogni `every_hours` ore (di serie 24), con le stesse regole del
  file del portale. Il feed prodotti di Google Merchant o Meta Commerce va bene così com'è: `id`, `title`, `price`,
  `sale_price` con `sale_price_effective_date` (le date dell'offerta), `availability`, `gtin`, `brand`, `product_type`,
  `unit_pricing_measure`, `link`, `image_link`. Con `"mode": "snapshot"` i prodotti che il feed non porta si ritirano, col
  cancello del 90 %. `POST /v1/catalog/feed/run` lo legge subito; `GET /v1/catalog/feed` dice com'è andato l'ultimo
  giro. L'URL deve essere `https://` verso un nome pubblico.
- **La freschezza.** Dichiari ogni quante ore aggiorni (`PUT /v1/catalog/feed` con `{"declared_refresh_hours": 24}`,
  anche senza feed); `GET /v1/catalog/freshness` dice l'ultimo aggiornamento e `stale: true` quando il catalogo è fermo
  da oltre il doppio.
### 8-bis. Il catalogo intero in una volta: le importazioni asincrone

Per un listino da decine di migliaia di referenze non servono ottanta lotti in fila: una chiamata, e il lavoro lo facciamo
noi dopo, a pezzi. È il disegno delle Bulk Operations di Shopify: un'operazione con un id, lo stato da leggere, la fine
come evento.

1. **Mandi il catalogo** con `POST /v1/catalog/imports` e un `Idempotency-Key`, in uno di tre modi:
   - `{"products": [...], "mode": "delta"}`: fino a **50.000** elementi, gli stessi di `PUT /v1/products` (codici GS1
     compresi), in un corpo fino a **16 MiB**;
   - il CSV del file del portale nel corpo, con `Content-Type: text/csv` (e `?mode=snapshot` nella query se è il catalogo
     intero);
   - `{"url": "https://…", "format": "jsonl"}`: l'indirizzo di un file che leggiamo noi, con le guardie del feed (fino a
     40 MB). `format` è `json` (una lista, o `{"products": [...]}`), `jsonl` (un prodotto per riga, come i file di
     Shopify), `csv` o `xlsx` (il file del portale), `google_merchant_xml` o `google_merchant_tsv`.
2. **La risposta è subito `202`** con l'importazione (`status: queued`, `id`) e l'intestazione `Location`, l'indirizzo
   del suo stato. Parte entro un minuto.
3. **Leggi lo stato** con `GET /v1/catalog/imports/{import_id}` (una volta ogni 30 secondi basta): `running` mentre
   lavora (`chunks_done` su `chunks_total`, e `written`, `rejected`, `warnings` crescono), poi `succeeded`, `partial`
   (righe rifiutate, o il cancello dell'istantanea che non ha ritirato niente: `error` dice quale) o `failed` (`error.code`:
   l'indirizzo che non risponde, il file illeggibile, nessuna riga scritta…). `GET /v1/catalog/imports` le elenca.
4. **La fine arriva anche come evento** `catalog_import.completed` agli endpoint iscritti (§6), con gli stessi numeri.
   Come per Shopify, una consegna di webhook può mancare: lo stato resta leggibile, sempre.
5. **I rifiuti, riga per riga**: `GET /v1/catalog/imports/{import_id}/errors` (`?type=warnings` per gli avvisi), a pagine
   con `cursor`. Ogni riga dice `index` (la posizione in `products`, da 0) o `row` (la riga del file, con l'intestazione
   alla 1), lo `sku`, il `code` e il `field`. Con `complete: true` l'elenco è intero.

Le regole sono quelle che conosci: merge per `sku` come `PUT /v1/products` (o le regole del file del portale per CSV,
XLSX e feed); lo stesso `sku` due volte nella stessa importazione vale il primo (`SKU_RIPETUTO_NEL_LOTTO`); con
`"mode": "snapshot"` alla fine si ritirano le referenze attive che l'importazione non porta, col cancello del **90 %**
(con una chiave agente aspetta l'approvazione di una persona, §11). La stessa richiesta con lo stesso `Idempotency-Key`
rende la stessa importazione, anche dopo le 24 ore del registro; una richiesta diversa con una chiave usata è
`409 IDEMPOTENCY_KEY_RIUSATA`. Se un pezzo non si riesce a scrivere (il database non risponde) si riprova al minuto dopo
dal pezzo dove ci si era fermati, mai da capo; dopo cinque tentativi le sue righe tornano come `PEZZO_NON_SCRITTO` e il
resto va avanti.

### 9. La chat del sito per il tuo cliente autenticato

Sulla chat del tuo sito il cliente è anonimo: il telefono, se lo scrive, nessuno lo verifica, e per questo la chat non
apre il suo storico (mostrerebbe gli acquisti di una persona a chi digita il suo numero). Se il cliente è **entrato nel
tuo sito**, il tuo server può garantirne l'identità, e da lì la chat è la sua: lo stesso carrello e la stessa
conversazione da una visita all'altra, e il suo «solito» (lo storico di `PUT /v1/order_history` e gli ordini fatti in
chat), come su WhatsApp.

Il cliente lo carichi prima con `PUT /v1/customers` (`{"customers": [...]}`), coi nomi di `core.customers`
(`external_ref`, `display_name`, `address`, `attributes`) o con quelli del modello clienti della specifica (`customer_ref`,
`full_name`, `street`, `house_number`, `city`, `postal_code`, `floor`, `intercom`, `delivery_notes`, `language`,
`exemption`): gli indirizzi vanno in `address` col loro nome. Il telefono è internazionale (`+39…`), o la riga è rifiutata
con `TELEFONO_NON_E164`. Un campo che non è di nessuno dei due elenchi non si scrive, e la risposta lo dice in
`warnings` (`CAMPO_SCONOSCIUTO`); lo stesso dato in due posti con due valori diversi è `CAMPO_IN_DUE_POSTI`.

1. Il tuo **server** chiede un gettone per quel cliente: `POST /v1/chat_identity_tokens` con la chiave **segreta** e il
   permesso `chat:write`, corpo `{"customer_ref": "<external_ref del cliente>"}` (facoltativo `expires_in`, in
   secondi: da 30 a 600, 300 se non lo dici). Il cliente deve esserci, nello stesso ambiente della chiave
   (`PUT /v1/customers`), o la risposta è `404 CLIENTE_SCONOSCIUTO`.
2. La risposta porta `identity_token` (`gai_cid_test_…` o `gai_cid_live_…`), `expires_at` e `chat_id`. Il gettone si
   vede solo in questa risposta: per questo la rotta non usa l'`Idempotency-Key`, e una chiamata ripetuta conia un altro
   gettone senza effetti in più. `chat_id` è l'identità di chat del cliente, **sempre la stessa**: è il
   `customer.chatId` degli ordini e delle richieste di assistenza che arrivano dalla sua chat, così li ricolleghi al tuo
   cliente.
3. La **pagina** passa il gettone al widget (`data-identity-token="…"` accanto a `data-site-key`): il widget lo manda a
   `core-chat /session` come `identity_token`, con la tua chiave pubblicabile. In modalità server lo manda il tuo
   server stesso a `/session`, con la chiave segreta, e passa alla pagina il `session_token`.

Il gettone vale **una volta sola** e per pochi minuti, per il tuo negozio e per l'ambiente della chiave che l'ha coniato.
Coniane uno quando componi la pagina per quel cliente, e servi quella pagina con `Cache-Control: private, no-store`: una
pagina in cache servita a un altro visitatore porterebbe un gettone già usato, che non apre niente.

Senza gettone `/session` risponde come sempre. Con un gettone, la risposta ha in più `identity`: `{"status": "verified"}`,
oppure `{"status": "not_verified", "code": …}` e la sessione nasce **anonima**, come oggi (la chat funziona lo stesso). I
motivi: `IDENTITA_MALFORMATA` (non è un gettone), `IDENTITA_SCONOSCIUTA` (nessuno l'ha coniato, o l'ha coniato un altro
negozio), `IDENTITA_GIA_USATA`, `IDENTITA_SCADUTA`, `IDENTITA_DI_UN_ALTRO_AMBIENTE` (coniato con la chiave `test` e
usato con la `live`, o il contrario: resta buono per il suo ambiente), `CLIENTE_SCONOSCIUTO` (il cliente è stato tolto
nel frattempo), `IDENTITA_FUORI_DAL_NEGOZIO` (la chat di prova del portale non porta un cliente),
`IDENTITA_NON_IN_SERVIZIO`.

Esempi completi e provati, lato server: `examples/chat-identity.mjs` (Node) e `examples/chat_identity.py` (Python).

### 10. Versioni e deprecazione

Quello che costruisci oggi deve funzionare anche domani. Le regole:

- **La versione è nel percorso**: `/v1`. `x-core-version` nelle risposte dice quale rilascio della piattaforma ha
  risposto, non la versione del contratto: non programmarci sopra.
- **Dentro `/v1` cambiamo solo in modo compatibile**: operazioni nuove, parametri e campi facoltativi nuovi nelle
  richieste, campi nuovi nelle risposte, codici d'errore nuovi, valori nuovi di campi che sono testo libero, tipi di
  evento nuovi, l'ordine dei campi, la lunghezza degli identificativi e il testo di `error.message`. Il tuo codice deve
  **ignorare** ciò che non conosce (un campo, un tipo di evento, un codice) invece di fallire. La regola vale dal
  1° novembre 2026: prima alcune modifiche non compatibili sono entrate in `/v1`, quando l'API non aveva integratori in
  produzione, e il registro (`CHANGELOG.md`) le elenca tutte come tali.
- **Non compatibile** è tutto ciò che può rompere un'integrazione scritta bene: togliere o rinominare un'operazione, un
  campo o un valore di un elenco chiuso (`enum`), cambiare un tipo, rendere obbligatorio un campo che non lo era,
  rifiutare un valore che prima si accettava, cambiare il significato di un campo o di un codice, cambiare l'ambito che
  un'operazione chiede, cambiare la firma dei webhook. Non lo facciamo dentro `/v1`: arriva con una versione nuova del
  percorso (`/v2`), oppure deprecando un'operazione e offrendone un'altra accanto.
- **Un'operazione deprecata funziona come prima per almeno 12 mesi** dalla data di deprecazione. Lo vedi in tre posti:
  il documento OpenAPI la marca `deprecated: true` con `x-deprecation` (date e operazione sostituta); **ogni sua
  risposta**, riuscita o d'errore, porta le intestazioni

  ```
  Deprecation: @1793491200
  Sunset: Thu, 31 Dec 2099 23:59:59 GMT
  Link: <https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/openapi.json>; rel="deprecation"
  ```

  dove `Deprecation` (RFC 9745) è la data di deprecazione in secondi dall'epoca dopo `@`, `Sunset` (RFC 8594) la data
  dalla quale l'operazione può smettere di rispondere (mai prima di 12 mesi dalla prima), e `Link` la pagina che dice che
  cosa usare al suo posto. Una chiamata respinta per la chiave (`401`) non le porta: la rotta non è ancora nota.
- **Il preavviso**: il giorno della deprecazione scriviamo ai titolari del negozio (l'email dell'account nel portale) e
  pubblichiamo la voce nel **registro delle modifiche** (`CHANGELOG.md`), con la data di `Sunset` e la sostituta. Una
  versione del percorso che va in pensione (`/v1` quando arriverà `/v2`) segue le stesse regole: 12 mesi, le stesse
  intestazioni su ogni sua risposta, lo stesso preavviso.
- **Il registro delle modifiche** (`CHANGELOG.md`) elenca, giorno per giorno dal 7/9/2026, ogni cambiamento del
  contratto e se è compatibile.

Per provare il tuo codice che legge le intestazioni c'è una **rotta di prova**: `GET /v1/_deprecation_probe` con una
chiave `gai_test_…` risponde `200` con le tre intestazioni qui sopra e le stesse date nel corpo (`deprecated_at`,
`sunset_at`, `replacement`, `link`). Non è una funzione dell'API, non tocca i tuoi dati e non si ritira; con una chiave
`gai_live_…` risponde `404 ROTTA_SCONOSCIUTA`.

### 11. Chiavi per un agente AI e l'approvazione di una persona

Se dai la chiave a un agente AI (Claude Code, Codex, Cursor, un'automazione), creala nel portale con **«Chiave per un agente
AI»**. L'agente legge e scrive come con ogni chiave, ma le operazioni che **tolgono o annullano** qualcosa non si eseguono
subito:

| operazione | quando aspetta |
|---|---|
| `DELETE /v1/products/{sku}` | sempre |
| `POST /v1/products/snapshots/{snapshot_id}/commit` | senza `dry_run: true` (la prova risponde subito) |
| `POST /v1/orders/{order_id}/status` | con `status` = `not_delivered` o `returned` |

1. L'agente chiama l'operazione come sempre e riceve `202` con `data.id` (l'approvazione), `data.status = "pending"` e
   `data.next` (che cosa fare). **Niente è cambiato.** Rimandare la stessa richiesta ritrova la stessa approvazione.
2. Una persona del negozio (titolare o amministratore) la vede nel portale, **Sviluppatori → Approvazioni**, con
   l'operazione, il percorso e i dati, e la approva o la rifiuta.
3. L'agente segue lo stato con `GET /v1/approvals/{approval_id}` (una volta al minuto basta). Quando è `approved`, rimanda
   **la stessa richiesta** (stesso metodo, percorso e corpo) con l'intestazione `GroceryAI-Approval-Id: <id>`: l'operazione
   si esegue, una volta sola. Puoi riusare la stessa `Idempotency-Key` della prima richiesta.

Che cosa può andare storto: `409 APPROVAZIONE_IN_ATTESA` (nessuno ha ancora deciso), `409 APPROVAZIONE_RIFIUTATA`,
`409 APPROVAZIONE_SCADUTA` (72 ore senza uso: chiedine una nuova), `409 APPROVAZIONE_GIA_USATA`, `409 APPROVAZIONE_DIVERSA`
(la richiesta non è quella approvata), `404 APPROVAZIONE_SCONOSCIUTA` (l'id non è di questa chiave). L'approvazione vale solo
per la chiave che l'ha chiesta. Una chiave che non è «per un agente» lavora come prima, e l'intestazione non conta.

### 12. Lo stato del servizio

`GET /v1/status`, **senza chiave**, dice come sta il servizio adesso, componente per componente, e come è andato:

| componente | che cos'è |
|---|---|
| `assistant` | la conversazione che compone il carrello e l'ordine, su ogni canale |
| `web_chat` | la chat sul sito del negozio |
| `api` | questa API (`/v1`) e il feed programmato del catalogo |
| `events` | i webhook, la coda in pull e le email d'ordine |
| `portal` | il portale del negozio |
| `mcp` | il server MCP per gli agenti AI |

- `status`: `operational`; `degraded` (risponde, ma una parte del lavoro fallisce: risposte `5xx`, turni di conversazione
  con errore, consegne abbandonate o in ritardo, un lavoro programmato fermo); `outage` (non risponde come deve a due sonde
  di fila, una al minuto); `unknown` (**non misurato**: nessuna sonda, una sonda che non ha ancora completato un giro, o
  la misura è ferma). `unknown` non vuol dire attivo.
- `measured_at`: l'ultima misura (una al minuto). Più vecchia di 3 minuti vuol dire ogni componente `unknown`.
- `availability.30d` / `availability.90d`: calcolata **sui soli minuti misurati**, da `from`: ogni componente si conta da
  quando è nata la sua sonda (24 ottobre 2026; `mcp` dal 5 novembre 2026), e `complete` è `false` finché la sua storia
  non copre la finestra intera. `uptime_percent` conta i minuti `outage`;
  i minuti `degraded` si dicono a parte e non lo abbassano.
- `incidents`: gli ultimi (al più 50 in 90 giorni), con `started_at`, `last_seen_at` (l'ultimo minuto in cui il guasto è
  stato visto) e `resolved_at` (un incidente si chiude dopo 10 minuti senza il guasto).

La risposta non contiene dati di nessun negozio. Cambia al più una volta al minuto: resta in cache 30 secondi e
`If-None-Match` con l'ultimo `ETag` dà `304`. Interrogala al più una volta al minuto. Se lo stato stesso non si può leggere
la risposta è `503 STATO_NON_MISURABILE`: lo stato è sconosciuto, e non dice niente degli altri componenti.

## Riferimento delle rotte

Il riferimento è in inglese, come il documento OpenAPI di Core. I codici (`error.code`), i tipi (`error.type`) e valori come `stato` sono identificatori italiani stabili; `error.message` è in italiano e può cambiare.

The GroceryAI platform API, from your systems to ours: catalog, prices and stock, customers, order status (including what happened to an order after the shop took it: delivered, substituted, not delivered, returned).

**Authentication**: one API key per account, sent as `Authorization: Bearer gai_live_…`. Keys have an environment (`test` or `live`) that separates the data, not just the labels, and scopes (catalog:read, catalog:write, customers:read, customers:write, orders:read, orders:write, chat:write, history:write, rules:read, rules:write, texts:read, texts:write). The plain value is shown only once.

**Batches**: writes accept up to 500 items per call; each item is validated on its own and the rejected ones are listed in the response instead of failing the whole batch.

**Idempotency**: every call that writes requires `Idempotency-Key`. Replaying it with the same body returns the same response without running it again. The key is scoped to the environment (`test` and `live` never see each other) and expires after 24 hours.

**Traceability**: every response, successful or not, carries `request_id`. It is the only thing we ask for when you contact us.

**Events**: confirmed orders and customer support requests reach the shop's endpoint as webhooks signed according to Standard Webhooks (see `webhooks`; https://www.standardwebhooks.com: verify them with the official library for your language), or are pulled (`GET /v1/orders`, `GET /v1/support_requests`) and acknowledged.

**Errors**: a single format, `{"error": {"type", "code", "message", "param", "doc_url"}, "request_id"}`. Program against `code`; `doc_url` links to the code's page (what it means, how to fix it, whether retrying helps). The full catalog: `GET /v1/errors`.

**No key needed**: this document (`GET /v1/openapi.json`) and the error catalog (`GET /v1/errors`, `GET /v1/errors/{code}`) are readable without a key, with `ETag` and `Cache-Control`. Every other operation requires a key.

**Getting started**: with a `gai_test_…` key you work in the test environment, separate from real data. Every operation below has a request and a 200-response example (and every error response an example envelope): the examples are valid against the schemas and were sent to the test environment, but the data is illustrative; your test shop returns its own. Recommended first call: `GET /v1/products?limit=1`.

**Versions and deprecation**: the contract version is in the path (`/v1`). Within `/v1` we only make compatible changes (new operations, optional fields, response fields, error codes, event types): your code must ignore what it does not know. An incompatible change only comes with a new path version, or by deprecating an operation: a deprecated operation carries `deprecated: true` here and the `Deprecation` (RFC 9745), `Sunset` (RFC 8594) and `Link: rel="deprecation"` headers on every response, and stays in service for at least 12 months; notice is sent by email to the shop owners and published in the changelog. To try them: `GET /v1/_deprecation_probe` with a `gai_test_…` key.

**Language**: this document is in English; codes (`error.code`), types (`error.type`) and values such as `stato` are stable Italian identifiers, and `error.message` is in Italian and may change.

### Gli ambiti delle chiavi

Ogni operazione chiede un ambito alla chiave; una chiave senza l'ambito riceve 403 AMBITO_MANCANTE. Qui ogni ambito con le operazioni che lo chiedono.

- `catalog:write`: `PUT /v1/products`, `DELETE /v1/products/{sku}`, `POST /v1/products/snapshots`, `POST /v1/products/snapshots/{snapshot_id}/commit`, `PUT /v1/catalog/feed`, `POST /v1/catalog/feed/run`, `POST /v1/catalog/imports`, `PUT /v1/inventory`, `PUT /v1/stores`
- `catalog:read`: `GET /v1/products`, `GET /v1/catalog/freshness`, `GET /v1/catalog/feed`, `GET /v1/catalog/imports`, `GET /v1/catalog/imports/{import_id}`, `GET /v1/catalog/imports/{import_id}/errors`, `GET /v1/stores`
- `customers:write`: `PUT /v1/customers`
- `history:write`: `PUT /v1/order_history`
- `rules:read`: `GET /v1/rules`, `POST /v1/rules/preview`
- `rules:write`: `PUT /v1/rules`
- `texts:read`: `GET /v1/store_texts`
- `texts:write`: `PUT /v1/store_texts`
- `customers:read`: `GET /v1/customers/{external_ref}`
- `orders:read`: `GET /v1/orders`, `GET /v1/support_requests`
- `orders:write`: `POST /v1/orders/{order_id}/ack`, `POST /v1/orders/{order_id}/status`, `POST /v1/support_requests/{support_id}/ack`
- `chat:write`: `POST /v1/chat_identity_tokens`

### `GET /v1/openapi.json`

`operationId`: `getOpenapi`

**The OpenAPI document of this API**

Generated from the same route table that serves the calls, so it cannot drift from the behaviour. Downloadable without a key from a stable address, with `ETag` and `Cache-Control`: with `If-None-Match` equal to the `ETag` the response is `304` with no body.

Nessuna chiave: si chiama senza autenticazione.

#### Parametri

- `If-None-Match` · intestazione (string) — The `ETag` of a previous read: if the content has not changed the response is `304` with no body.

#### Esempio · Risposta 200

```json
{
  "openapi": "3.1.0",
  "info": {
    "title": "GroceryAI Platform API",
    "version": "1.0.0"
  },
  "paths": {
    "/v1/products": {
      "get": {
        "operationId": "getProducts"
      }
    }
  }
}
```

#### Risposte

- `200` The OpenAPI 3.1 document. — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`, `etag`
- `304` The document has not changed since the `ETag` sent in `If-None-Match`: no body. — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`, `etag`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`

### `GET /v1/errors`

`operationId`: `listErrorCodes`

**The error code catalog**

Every code this API can return in `error.code`, in a batch's `errors[].code` or in `warnings[].code`: what it means, how to fix it, with which statuses and in which operations it appears. No key needed.

Nessuna chiave: si chiama senza autenticazione.

#### Parametri

- `If-None-Match` · intestazione (string) — The `ETag` of a previous read: if the content has not changed the response is `304` with no body.

#### Esempio · Risposta 200

```json
{
  "data": [
    {
      "code": "IDEMPOTENCY_KEY_MANCANTE",
      "title": "This operation writes data and needs an `Idempotency-Key` header.",
      "how_to_fix": "Generate a unique value per logical operation (a UUID v4 is ideal), send it as `Idempotency-Key`, and reuse the same value only when retrying that same request.",
      "retryable": false,
      "appears_as": {
        "error": [
          {
            "status": 400,
            "type": "richiesta_non_valida",
            "operations": [
              "putProducts",
              "createProductSnapshot",
              "commitProductSnapshot",
              "putCatalogFeed",
              "runCatalogFeed",
              "createCatalogImport",
              "putInventory",
              "putCustomers",
              "putOrderHistory",
              "putStores",
              "putRules",
              "putStoreTexts",
              "ackOrder",
              "reportOrderStatus",
              "ackSupportRequest"
            ]
          }
        ],
        "batch_item_error": [],
        "batch_item_warning": [],
        "chat_session_identity": false
      },
      "doc_url": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDEMPOTENCY_KEY_MANCANTE"
    }
  ]
}
```

#### Risposte

- `200` All codes, in alphabetical order. — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`, `etag`
- `304` The catalog has not changed since the `ETag` sent in `If-None-Match`: no body. — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`, `etag`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`

### `GET /v1/errors/{code}`

`operationId`: `getErrorCode`

**The page of one error code**

The page `error.doc_url` points to: what the code means, how to fix it, the statuses and operations in which it appears. No key needed.

Nessuna chiave: si chiama senza autenticazione.

#### Parametri

- `code` · nel percorso (string) · obbligatorio — The code, as written in `error.code` (for example `IDEMPOTENCY_KEY_MANCANTE`).
- `If-None-Match` · intestazione (string) — The `ETag` of a previous read: if the content has not changed the response is `304` with no body.

#### Esempio · Risposta 200

```json
{
  "data": {
    "code": "IDEMPOTENCY_KEY_MANCANTE",
    "title": "This operation writes data and needs an `Idempotency-Key` header.",
    "how_to_fix": "Generate a unique value per logical operation (a UUID v4 is ideal), send it as `Idempotency-Key`, and reuse the same value only when retrying that same request.",
    "retryable": false,
    "appears_as": {
      "error": [
        {
          "status": 400,
          "type": "richiesta_non_valida",
          "operations": [
            "putProducts",
            "createProductSnapshot",
            "commitProductSnapshot",
            "putCatalogFeed",
            "runCatalogFeed",
            "createCatalogImport",
            "putInventory",
            "putCustomers",
            "putOrderHistory",
            "putStores",
            "putRules",
            "putStoreTexts",
            "ackOrder",
            "reportOrderStatus",
            "ackSupportRequest"
          ]
        }
      ],
      "batch_item_error": [],
      "batch_item_warning": [],
      "chat_session_identity": false
    },
    "doc_url": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDEMPOTENCY_KEY_MANCANTE"
  }
}
```

#### Risposte

- `200` The code's page. — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`, `etag`
- `304` The page has not changed since the `ETag` sent in `If-None-Match`: no body. — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`, `etag`
- `404` `CODICE_ERRORE_SCONOSCIUTO`: this API never returns that code (the full catalog is `GET /v1/errors`). — Codici d'errore: `CODICE_ERRORE_SCONOSCIUTO` — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`

### `GET /v1/status`

`operationId`: `getStatus`

**The status of the service, per component**

For each component (`assistant`, `web_chat`, `api`, `events`, `portal`, `mcp`) its status now, from the same rules as the internal alarms that measure the service every minute: `operational`, `degraded` (it answers, but part of the work fails: 5xx responses, conversation turns with errors, abandoned or late deliveries, stopped scheduled jobs), `outage` (it does not answer as it should to two probes in a row) or `unknown` (not measured: no probe, measurement stopped for more than 3 minutes or failing for more than 10). Then availability over the last 30 and 90 days, on measured minutes only (with `from` and `complete`: the history starts on 2026-10-24), and the latest incidents with start, last impact and resolution (an incident is resolved after 10 minutes without errors). No key, no data about any shop. Updated at most once a minute: `Cache-Control` of 30 seconds, `ETag` and `304`.

Nessuna chiave: si chiama senza autenticazione.

#### Parametri

- `If-None-Match` · intestazione (string) — The `ETag` of a previous read: if the content has not changed the response is `304` with no body.

#### Esempio · Risposta 200

```json
{
  "status": "operational",
  "measured_at": "2026-10-31T09:15:00.000Z",
  "measured_since": "2026-10-24T12:51:00.000Z",
  "components": [
    {
      "id": "assistant",
      "name": "Shopping assistant",
      "description": "The conversation that builds the cart and the order, on every channel.",
      "status": "operational",
      "availability": {
        "30d": {
          "window_days": 30,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 5,
          "uptime_percent": 100
        },
        "90d": {
          "window_days": 90,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 5,
          "uptime_percent": 100
        },
        "month": {
          "month": "2026-10",
          "from": "2026-10-24T12:51:00.000Z",
          "to": "2026-10-31T09:15:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 5,
          "downtime_minutes": 5,
          "availability_percent": 99.951,
          "objective_percent": 99.9,
          "objective_met": true
        },
        "previous_month": null
      }
    },
    {
      "id": "web_chat",
      "name": "Web chat",
      "description": "The chat on the shop's website.",
      "status": "operational",
      "availability": {
        "30d": {
          "window_days": 30,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 4,
          "degraded_minutes": 0,
          "uptime_percent": 99.96
        },
        "90d": {
          "window_days": 90,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 4,
          "degraded_minutes": 0,
          "uptime_percent": 99.96
        },
        "month": {
          "month": "2026-10",
          "from": "2026-10-24T12:51:00.000Z",
          "to": "2026-10-31T09:15:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 4,
          "degraded_minutes": 0,
          "downtime_minutes": 4,
          "availability_percent": 99.96,
          "objective_percent": 99.9,
          "objective_met": true
        },
        "previous_month": null
      }
    },
    {
      "id": "api",
      "name": "API",
      "description": "The REST API for catalog, customers, orders and events (`/v1`), and the scheduled catalog feed.",
      "status": "operational",
      "availability": {
        "30d": {
          "window_days": 30,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "90d": {
          "window_days": 90,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "month": {
          "month": "2026-10",
          "from": "2026-10-24T12:51:00.000Z",
          "to": "2026-10-31T09:15:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "downtime_minutes": 0,
          "availability_percent": 100,
          "objective_percent": 99.9,
          "objective_met": true
        },
        "previous_month": null
      }
    },
    {
      "id": "events",
      "name": "Webhooks and order delivery",
      "description": "Signed events to your endpoints, the pull queue and the order emails.",
      "status": "operational",
      "availability": {
        "30d": {
          "window_days": 30,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "90d": {
          "window_days": 90,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "month": {
          "month": "2026-10",
          "from": "2026-10-24T12:51:00.000Z",
          "to": "2026-10-31T09:15:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "downtime_minutes": 0,
          "availability_percent": 100,
          "objective_percent": 99.9,
          "objective_met": true
        },
        "previous_month": null
      }
    },
    {
      "id": "portal",
      "name": "Merchant portal",
      "description": "The portal where shops manage their catalog, keys and settings.",
      "status": "operational",
      "availability": {
        "30d": {
          "window_days": 30,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "90d": {
          "window_days": 90,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "month": {
          "month": "2026-10",
          "from": "2026-10-24T12:51:00.000Z",
          "to": "2026-10-31T09:15:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "downtime_minutes": 0,
          "availability_percent": 100,
          "objective_percent": 99.9,
          "objective_met": true
        },
        "previous_month": null
      }
    },
    {
      "id": "mcp",
      "name": "MCP server",
      "description": "The Model Context Protocol server for AI agents.",
      "status": "operational",
      "availability": {
        "30d": {
          "window_days": 30,
          "from": "2026-10-30T12:00:00.000Z",
          "complete": false,
          "measured_minutes": 1275,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "90d": {
          "window_days": 90,
          "from": "2026-10-30T12:00:00.000Z",
          "complete": false,
          "measured_minutes": 1275,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "month": {
          "month": "2026-10",
          "from": "2026-10-30T12:00:00.000Z",
          "to": "2026-10-31T09:15:00.000Z",
          "complete": false,
          "measured_minutes": 1275,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "downtime_minutes": 0,
          "availability_percent": 100,
          "objective_percent": 99.9,
          "objective_met": true
        },
        "previous_month": null
      }
    }
  ],
  "incidents": [
    {
      "components": [
        "web_chat"
      ],
      "severity": "outage",
      "status": "resolved",
      "started_at": "2026-10-30T07:02:00.000Z",
      "last_seen_at": "2026-10-30T07:05:00.000Z",
      "resolved_at": "2026-10-30T07:15:00.000Z"
    },
    {
      "components": [
        "assistant"
      ],
      "severity": "degraded",
      "status": "resolved",
      "started_at": "2026-10-28T10:30:00.000Z",
      "last_seen_at": "2026-10-28T10:34:00.000Z",
      "resolved_at": "2026-10-28T10:44:00.000Z"
    }
  ]
}
```

#### Risposte

- `200` The status, the availability and the incidents. — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`, `etag`
- `304` The status has not changed since the `ETag` sent in `If-None-Match`: no body. — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`, `etag`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`
- `503` `STATO_NON_MISURABILE`: the measurement cannot be read right now. The status is unknown, not operational: retry in a minute. — Codici d'errore: `STATO_NON_MISURABILE` — Intestazioni: `x-request-id`, `x-core-version`, `cache-control`, `access-control-allow-origin`, `access-control-expose-headers`

### `PUT /v1/products`

`operationId`: `putProducts`

**Create or update the catalog, in batches**

Upsert by `sku`, as a MERGE: on an existing product only the fields the item names are updated, and the ones it does not name stay as they were; `attributes` are merged, and a key set to `null` is removed. The catalog contract fields (`min_order_qty`, `min_order_unit`, `sold_by_weight`, `avg_piece_weight_kg`, `items_per_pack`, `pack_only`, `stock_managed`, `unit_price`, `gross_weight_kg`, `tare_kg`, `list_price`, `subcategory`, `description`, `vat_rate`, `diet_tags`, `offer_price`, `offer_start`, `offer_end`, `offer_min_qty`, `offer_label`; `is_online` is `available`) are written with their name on the item and validated. A withdrawn product (`DELETE` or snapshot) that is sent again goes back on sale. `gtin` is optional, but if present it must be a valid GTIN/GS1 (8, 12, 13 or 14 digits, check digit included): a wrong barcode is worse than none. With `snapshot_id` the batch is part of a snapshot (`POST /v1/products/snapshots`).

Permesso: `catalog:write`

#### Parametri

- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{
  "products": [
    {
      "sku": "EXAMPLE-SPAGHETTI-500",
      "title": "Spaghetti di semola 500 g",
      "gtin": "4006381333931",
      "brand": "Esempio",
      "category": "Pasta",
      "unit": "pz",
      "price": 1.29,
      "currency": "EUR",
      "stock_qty": 140,
      "available": true,
      "vat_rate": 4,
      "link": "https://shop.example.invalid/p/spaghetti-500",
      "image_link": "https://shop.example.invalid/img/spaghetti-500.jpg"
    },
    {
      "sku": "EXAMPLE-MILK-1L",
      "title": "Latte intero 1 l",
      "brand": "Esempio",
      "category": "Latte e derivati",
      "unit": "pz",
      "price": 1.49,
      "stock_qty": 60
    }
  ]
}
```

#### Esempio · Risposta 200

```json
{
  "received": 2,
  "written": 2,
  "rejected": 0,
  "errors": [],
  "warnings": [],
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` Batch outcome: how many received, how many written, which were rejected and why, and the warnings. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` Invalid body, or a batch over 500 items. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA`, `CORPO_NON_VALIDO`, `LOTTO_VUOTO`, `LOTTO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `404` `ISTANTANEA_SCONOSCIUTA`: the `snapshot_id` does not belong to this account and environment. — Codici d'errore: `ISTANTANEA_SCONOSCIUTA` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `409` `ISTANTANEA_CHIUSA` or `ISTANTANEA_SCADUTA`: the snapshot no longer accepts batches. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO`, `ISTANTANEA_CHIUSA`, `ISTANTANEA_SCADUTA` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/products`

`operationId`: `getProducts`

**List the catalog**

Sorted by `sku`. Cursor pagination: `cursor` is the last `sku` of the previous page.

Permesso: `catalog:read`

#### Parametri

- `sku` · nella query (string) — A single product, by SKU.
- `gtin` · nella query (string) — The products with this GTIN.
- `limit` · nella query (integer) — From 1 to 200 (default 50).
- `cursor` · nella query (string) — Last `sku` of the previous page.
- `store_code` · nella query (string) — The catalog as it is in one store (`GET /v1/stores`): price, strikethrough price, offer, stock and availability of the store where it declares them, the shop's where it does not.

#### Esempio · Risposta 200

```json
{
  "data": [
    {
      "sku": "EXAMPLE-SPAGHETTI-500",
      "gtin": "4006381333931",
      "title": "Spaghetti di semola 500 g",
      "brand": "Esempio",
      "category": "Pasta",
      "unit": "pz",
      "price": 1.29,
      "net_price": null,
      "currency": "EUR",
      "stock_qty": 140,
      "available": true,
      "link": "https://shop.example.invalid/p/spaghetti-500",
      "image_link": "https://shop.example.invalid/img/spaghetti-500.jpg",
      "attributes": {
        "vat_rate": 4
      }
    }
  ],
  "next_cursor": "EXAMPLE-SPAGHETTI-500",
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The page, with `next_cursor` when there is more. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `400` Invalid request: `code` says which field or header, `param` where. — Codici d'errore: `PARAMETRO_NON_VALIDO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `404` `PUNTO_VENDITA_SCONOSCIUTO`: no active store with that `store_code`. — Codici d'errore: `PUNTO_VENDITA_SCONOSCIUTO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `DELETE /v1/products/{sku}`

`operationId`: `deleteProduct`

**Withdraw a product from sale**

The product is switched off (`available: false`, with the withdrawal date in `attributes.withdrawn_at`), not deleted: orders and history that mention it stay readable, and the assistant stops selling it. Withdrawing the same product twice is not an error. To put it back on sale, send it again with `PUT /v1/products`. With an agent key it waits for a person's approval (`202`).

Permesso: `catalog:write`

#### Parametri

- `sku` · nel percorso (string) · obbligatorio — The product's `sku`.

#### Esempio · Risposta 200

```json
{
  "data": {
    "sku": "EXAMPLE-MILK-1L",
    "available": false,
    "withdrawn": true
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` Withdrawn. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `202` Agent key: waiting for a person's approval. Nothing has changed. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `400` Invalid request: `code` says which field or header, `param` where. — Codici d'errore: `CORPO_NON_JSON` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `404` No product with this `sku` for the account and the key's environment. — Codici d'errore: `NON_TROVATO`, `APPROVAZIONE_SCONOSCIUTA` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `409` `Idempotency-Key` already used for a different request, or a request still in progress. — Codici d'errore: `APPROVAZIONE_IN_ATTESA`, `APPROVAZIONE_RIFIUTATA`, `APPROVAZIONE_SCADUTA`, `APPROVAZIONE_GIA_USATA`, `APPROVAZIONE_DIVERSA` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE`, `APPROVAZIONI_ASSENTI` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `POST /v1/products/snapshots`

`operationId`: `createProductSnapshot`

**Open a catalog snapshot ("this is the whole catalog")**

To say the catalog you send is the WHOLE catalog: open the snapshot, send the batches with `PUT /v1/products` and the `snapshot_id`, and close it with `commit`. On commit, the active products that no batch carried are withdrawn (switched off, not deleted), but only if the batches carried at least 90% of the active products (the threshold can be declared): a truncated file does not empty the catalog. A snapshot lives 24 hours.

Permesso: `catalog:write`

#### Parametri

- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{}
```

#### Esempio · Risposta 200

```json
{
  "data": {
    "snapshot_id": "3b9f0e62-1d4a-4c8e-a7b2-5f6e9d0c1a23",
    "expires_at": "2026-11-01T09:15:00Z",
    "active_products": 1240
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The open snapshot: `snapshot_id`, expiry, products active now. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` Invalid request: `code` says which field or header, `param` where. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `409` `Idempotency-Key` already used for a different request, or a request still in progress. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `POST /v1/products/snapshots/{snapshot_id}/commit`

`operationId`: `commitProductSnapshot`

**Commit the snapshot: withdraw the products the batches did not carry**

With `dry_run: true` it only returns the numbers (active, carried, to withdraw, the share, the threshold, the first 20 skus to withdraw) and changes nothing. Without it, it requires `expected_off`, the number to withdraw read in the dry run: if it changed in the meantime nothing is withdrawn (409 `CONTEGGIO_CAMBIATO`). Below the threshold nothing is withdrawn (409 `ISTANTANEA_SOTTO_SOGLIA`) and the snapshot stays open: the missing batches can still be sent. With an agent key the real commit (without `dry_run`) waits for a person's approval (`202`).

Permesso: `catalog:write`

#### Parametri

- `snapshot_id` · nel percorso (string) · obbligatorio — The snapshot identifier.
- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{
  "dry_run": true
}
```

#### Esempio · Risposta 200

```json
{
  "data": {
    "snapshot_id": "3b9f0e62-1d4a-4c8e-a7b2-5f6e9d0c1a23",
    "active": 1240,
    "seen_active": 1228,
    "to_switch_off": 12,
    "share": 0.9903,
    "min_share": 0.9,
    "allowed": true,
    "count_changed": false,
    "dry_run": true,
    "switched_off": 0,
    "sample": [
      "EXAMPLE-OLD-001",
      "EXAMPLE-OLD-002"
    ]
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The gate numbers and, without `dry_run`, how many products were withdrawn. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `202` Agent key, without `dry_run`: waiting for a person's approval. Nothing has changed. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` Invalid body: `expected_off` is missing or not an integer. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA`, `CORPO_NON_VALIDO`, `ATTESO_NON_VALIDO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `404` `ISTANTANEA_SCONOSCIUTA`. — Codici d'errore: `ISTANTANEA_SCONOSCIUTA`, `APPROVAZIONE_SCONOSCIUTA` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `409` `ISTANTANEA_SOTTO_SOGLIA`, `CONTEGGIO_CAMBIATO`, `ISTANTANEA_CHIUSA` or `ISTANTANEA_SCADUTA`. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO`, `ISTANTANEA_SOTTO_SOGLIA`, `CONTEGGIO_CAMBIATO`, `ISTANTANEA_CHIUSA`, `ISTANTANEA_SCADUTA`, `APPROVAZIONE_IN_ATTESA`, `APPROVAZIONE_RIFIUTATA`, `APPROVAZIONE_SCADUTA`, `APPROVAZIONE_GIA_USATA`, `APPROVAZIONE_DIVERSA` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE`, `APPROVAZIONI_ASSENTI` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/catalog/freshness`

`operationId`: `getCatalogFreshness`

**How fresh the catalog is**

The last catalog update (any channel: file, API, feed), the refresh interval the shop declared, and whether the catalog has been unchanged for more than twice that interval (`stale`).

Permesso: `catalog:read`

#### Esempio · Risposta 200

```json
{
  "data": {
    "environment": "test",
    "last_update_at": "2026-10-31T09:15:00Z",
    "age_hours": 2.5,
    "declared_refresh_hours": 24,
    "stale": false,
    "products": 1240,
    "available": 1198
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The freshness. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/catalog/feed`

`operationId`: `getCatalogFeed`

**The scheduled catalog feed and its last run**

The configuration (URL, format, how many hours apart, delta or snapshot, on or off, the declared refresh interval) and the outcome of the last run. A shop that never configured it receives `data: null`.

Permesso: `catalog:read`

#### Esempio · Risposta 200

```json
{
  "data": {
    "url": "https://shop.example.invalid/feed/products.csv",
    "format": "csv",
    "every_hours": 6,
    "mode": "delta",
    "enabled": true,
    "declared_refresh_hours": 24,
    "next_run_at": "2026-10-31T15:15:00Z",
    "last_run_at": null,
    "last_run": null,
    "updated_at": "2026-10-31T09:15:00Z"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The configuration, or `null`. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `PUT /v1/catalog/feed`

`operationId`: `putCatalogFeed`

**Configure the scheduled feed and the declared refresh interval**

An `https://` URL that GroceryAI reads every `every_hours` hours (24 by default): our CSV or XLSX, or the Google Merchant / Meta Commerce product feed (XML or TSV). `mode: snapshot` withdraws the products the feed does not carry, behind the 90% gate; the default `delta` only updates. `declared_refresh_hours` is how often the shop updates prices and stock (through any channel): past twice that, the catalog is flagged as stale. The interval can be declared without a feed (`url: null`).

Permesso: `catalog:write`

#### Parametri

- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{
  "url": "https://shop.example.invalid/feed/products.csv",
  "format": "csv",
  "every_hours": 6,
  "mode": "delta",
  "enabled": true,
  "declared_refresh_hours": 24
}
```

#### Esempio · Risposta 200

```json
{
  "data": {
    "url": "https://shop.example.invalid/feed/products.csv",
    "format": "csv",
    "every_hours": 6,
    "mode": "delta",
    "enabled": true,
    "declared_refresh_hours": 24,
    "next_run_at": "2026-10-31T15:15:00Z",
    "last_run_at": null,
    "last_run": null,
    "updated_at": "2026-10-31T09:15:00Z"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The saved configuration. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` Invalid body: `code` says which field. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA`, `CORPO_NON_VALIDO`, `CAMPO_SCONOSCIUTO`, `FEED_URL_NON_AMMESSO`, `FORMATO_NON_AMMESSO`, `CADENZA_NON_VALIDA`, `VALORE_NON_AMMESSO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `409` `Idempotency-Key` already used for a different request, or a request still in progress. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `POST /v1/catalog/feed/run`

`operationId`: `runCatalogFeed`

**Run the feed now**

The same run as the scheduler, right now: reads the URL, prepares the rows with the rules of the portal file import, writes them as a merge and, in `mode: snapshot`, withdraws the missing ones behind the gate. The run is recorded even when it fails.

Permesso: `catalog:write`

#### Parametri

- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{}
```

#### Esempio · Risposta 200

```json
{
  "data": {
    "status": "ok",
    "error_code": null,
    "message": null,
    "received": 1240,
    "written": 1240,
    "rejected": 0,
    "switched_off": 0,
    "errors": [],
    "snapshot": null,
    "started_at": "2026-10-31T09:15:00Z",
    "finished_at": "2026-10-31T09:15:04Z"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The run outcome (`status`: `ok`, `partial` with rejected rows, `failed` with `error_code`). — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` Invalid request: `code` says which field or header, `param` where. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `409` `FEED_NON_CONFIGURATO`: no URL configured for this environment. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO`, `FEED_NON_CONFIGURATO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `POST /v1/catalog/imports`

`operationId`: `createCatalogImport`

**Import the whole catalog, asynchronously**

For the whole catalog in one call: up to 50,000 products in the body (`products`: the same items as `PUT /v1/products`, GS1 codes included), a CSV in the body (`Content-Type: text/csv`, the columns of the portal file; `mode` in the query), or the address of a file (`url` and `format`: `json`, `jsonl`, `csv`, `xlsx`, `google_merchant_xml`, `google_merchant_tsv`). The body can be up to 16 MiB. The answer is an IMMEDIATE `202` with the import (`status: queued`) and `Location`: the work happens afterwards, in chunks of 500 items, with the rules of `PUT /v1/products` (merge by `sku`) or of the portal file. Read the status with `GET /v1/catalog/imports/{import_id}`, the rejected rows with `.../errors`, and the end arrives as a `catalog_import.completed` event at the subscribed endpoints. The same `sku` twice in the same import: the first one wins. `mode: snapshot` withdraws, at the end, the active products the import does not carry, behind the 90 % gate (with an agent key it waits for a person's approval). At most 5 unfinished imports per environment.

Permesso: `catalog:write`

#### Parametri

- `mode` · nella query (string) — Only with a CSV body: `delta` (default) or `snapshot`. With a JSON body, `mode` goes in the body.
- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{
  "products": [
    {
      "sku": "EXAMPLE-SPAGHETTI-500",
      "gtin": "8000000000017",
      "title": "Spaghetti n.5 500 g",
      "brand": "Esempio",
      "category": "Pasta",
      "price": 1.29,
      "stock_qty": 240
    },
    {
      "sku": "EXAMPLE-MILK-1L",
      "title": "Latte intero 1 l",
      "category": "Latte e derivati",
      "price": 1.49,
      "available": true
    }
  ],
  "mode": "delta"
}
```

#### Esempio · Risposta 202

```json
{
  "data": {
    "id": "3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
    "status": "queued",
    "mode": "delta",
    "source": "body",
    "format": "json",
    "url": null,
    "received": 2,
    "written": 0,
    "rejected": 0,
    "warnings": 0,
    "switched_off": 0,
    "chunks_total": 1,
    "chunks_done": 0,
    "error": null,
    "snapshot": null,
    "created_at": "2026-10-31T09:15:00.000Z",
    "started_at": null,
    "finished_at": null,
    "links": {
      "self": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
      "errors": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81/errors"
    }
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `202` Accepted: the import is queued, with `Location` pointing to its status. With an agent key and `mode: snapshot`, the approval request. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`, `location`
- `400` Invalid body: neither `products` nor `url`, an empty list or more than 50,000 items, a format or address that is not allowed. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA`, `CORPO_NON_VALIDO`, `LOTTO_VUOTO`, `LOTTO_TROPPO_GRANDE`, `CAMPO_SCONOSCIUTO`, `VALORE_NON_AMMESSO`, `FORMATO_NON_AMMESSO`, `FEED_URL_NON_AMMESSO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `404` `APPROVAZIONE_SCONOSCIUTA`: with an agent key, the `GroceryAI-Approval-Id` header is not an approval of this key. — Codici d'errore: `APPROVAZIONE_SCONOSCIUTA` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `409` `IMPORTAZIONI_IN_CORSO`: there are already 5 unfinished imports in this environment. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO`, `IMPORTAZIONI_IN_CORSO`, `APPROVAZIONE_IN_ATTESA`, `APPROVAZIONE_RIFIUTATA`, `APPROVAZIONE_SCADUTA`, `APPROVAZIONE_GIA_USATA`, `APPROVAZIONE_DIVERSA` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE`, `APPROVAZIONI_ASSENTI` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/catalog/imports`

`operationId`: `listCatalogImports`

**The catalog imports, most recent first**

Cursor pagination: `cursor` is the `id` of the last import of the previous page.

Permesso: `catalog:read`

#### Parametri

- `limit` · nella query (integer) — From 1 to 100 (default 20).
- `cursor` · nella query (string) — The `id` of the last import of the previous page.

#### Esempio · Risposta 200

```json
{
  "data": [
    {
      "id": "3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
      "status": "partial",
      "mode": "delta",
      "source": "url",
      "format": "jsonl",
      "url": "https://shop.example.invalid/export/products.jsonl",
      "received": 38412,
      "written": 38408,
      "rejected": 4,
      "warnings": 12,
      "switched_off": 0,
      "chunks_total": 77,
      "chunks_done": 77,
      "error": null,
      "snapshot": null,
      "created_at": "2026-10-31T09:15:00.000Z",
      "started_at": "2026-10-31T09:15:41.000Z",
      "finished_at": "2026-10-31T09:19:02.000Z",
      "links": {
        "self": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
        "errors": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81/errors"
      }
    }
  ],
  "next_cursor": null,
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The page, with `next_cursor` when there is more. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `400` Invalid request: `code` says which field or header, `param` where. — Codici d'errore: `PARAMETRO_NON_VALIDO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/catalog/imports/{import_id}`

`operationId`: `getCatalogImport`

**The status of a catalog import**

`status`: `queued` (waiting: it starts within a minute), `running` (in progress: `chunks_done` out of `chunks_total`, and the counts grow), `succeeded`, `partial` (rejected rows, or the snapshot gate that withdrew nothing: `error`), `failed` (`error` says why). `received`, `written`, `rejected` and `warnings` count the items (or the rows of the file).

Permesso: `catalog:read`

#### Parametri

- `import_id` · nel percorso (string) · obbligatorio — The `id` returned by `POST /v1/catalog/imports`.

#### Esempio · Risposta 200

```json
{
  "data": {
    "id": "3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
    "status": "partial",
    "mode": "delta",
    "source": "url",
    "format": "jsonl",
    "url": "https://shop.example.invalid/export/products.jsonl",
    "received": 38412,
    "written": 38408,
    "rejected": 4,
    "warnings": 12,
    "switched_off": 0,
    "chunks_total": 77,
    "chunks_done": 77,
    "error": null,
    "snapshot": null,
    "created_at": "2026-10-31T09:15:00.000Z",
    "started_at": "2026-10-31T09:15:41.000Z",
    "finished_at": "2026-10-31T09:19:02.000Z",
    "links": {
      "self": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
      "errors": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81/errors"
    }
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The import. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `404` `IMPORTAZIONE_SCONOSCIUTA`: no import with this id for the tenant and the environment of the key. — Codici d'errore: `IMPORTAZIONE_SCONOSCIUTA` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/catalog/imports/{import_id}/errors`

`operationId`: `getCatalogImportErrors`

**The rejected rows (or the warnings) of an import, row by row**

Each row says where (`index` of the JSON item, from 0, or `row` of the file, with the header on row 1), which `sku`, the code and the field. The rows are those of the chunks already written: once the import is finished (`complete: true`) the list is whole. `type=warnings` for the warnings (rows written with something to know).

Permesso: `catalog:read`

#### Parametri

- `import_id` · nel percorso (string) · obbligatorio — The `id` of the import.
- `type` · nella query (string) — `errors` (default) or `warnings`.
- `limit` · nella query (integer) — From 1 to 1000 (default 500).
- `cursor` · nella query (string) — The `next_cursor` of the previous page.

#### Esempio · Risposta 200

```json
{
  "data": [
    {
      "index": 1204,
      "row": null,
      "id": "EXAMPLE-OLIVE-OIL-1L",
      "code": "PREZZO_NON_VALIDO",
      "field": "price",
      "message": "`price` deve essere un numero >= 0."
    },
    {
      "index": 20877,
      "row": null,
      "id": "EXAMPLE-SPAGHETTI-500",
      "code": "SKU_RIPETUTO_NEL_LOTTO",
      "field": "sku",
      "message": "Questo `sku` e' gia' in un elemento precedente della stessa importazione: vale il primo."
    },
    {
      "index": 31002,
      "row": null,
      "id": null,
      "code": "ELEMENTO_NON_JSON",
      "field": null,
      "message": "La riga non e' JSON: Unexpected end of JSON input"
    },
    {
      "index": 36511,
      "row": null,
      "id": "EXAMPLE-RICE-1KG",
      "code": "PEZZO_NON_SCRITTO",
      "field": null,
      "message": "Il pezzo non si e' potuto scrivere dopo 5 tentativi: connessione chiusa. Rimanda queste righe."
    }
  ],
  "next_cursor": null,
  "complete": true,
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The page of rows, with `next_cursor` when there is more and `complete` when the import is finished. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `400` Invalid request: `code` says which field or header, `param` where. — Codici d'errore: `PARAMETRO_NON_VALIDO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `404` `IMPORTAZIONE_SCONOSCIUTA`: no import with this id for the tenant and the environment of the key. — Codici d'errore: `IMPORTAZIONE_SCONOSCIUTA` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `PUT /v1/inventory`

`operationId`: `putInventory`

**Update prices, stock and offers, in batches**

Touches ONLY the fields present in each item (`price`, `net_price`, `stock_qty`, `available` or `is_online`, the strikethrough price `list_price` and the offer `offer_price`, `offer_start`, `offer_end`, `offer_min_qty`, `offer_label`, `null` to remove it): whatever is not named stays as it was. An SKU that does not exist is a rejected item, not a half-created product. With `store_code` the item applies to THAT store (`GET /v1/stores`) and carries only `price`, `stock_qty`, `available` or `is_online`, `list_price`, `offer_price`, `offer_start`, `offer_end` (otherwise `CAMPO_NON_PER_PUNTO_VENDITA`): the shop-wide row is not touched, and whatever the store does not declare stays the shop's. A code that is not an active store is a rejected item (`PUNTO_VENDITA_SCONOSCIUTO`).

Permesso: `catalog:write`

#### Parametri

- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{
  "inventory": [
    {
      "sku": "EXAMPLE-SPAGHETTI-500",
      "price": 1.19,
      "stock_qty": 120
    },
    {
      "sku": "EXAMPLE-MILK-1L",
      "available": false
    }
  ]
}
```

#### Esempio · Risposta 200

```json
{
  "received": 2,
  "written": 2,
  "rejected": 0,
  "errors": [],
  "warnings": [],
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` Batch outcome. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` Invalid body, or a batch over 500 items. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA`, `CORPO_NON_VALIDO`, `LOTTO_VUOTO`, `LOTTO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `409` `Idempotency-Key` already used for a different request, or a request still in progress. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `PUT /v1/customers`

`operationId`: `putCustomers`

**Sync customers, in batches**

Upsert by `external_ref`, the identifier the customer has in your system.

Permesso: `customers:write`

#### Parametri

- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{
  "customers": [
    {
      "external_ref": "example-customer-001",
      "display_name": "Giulia Esempio",
      "email": "giulia@example.invalid",
      "phone": "+390000000001",
      "street": "Via delle Prove",
      "house_number": "1",
      "city": "Olbia",
      "postal_code": "07026",
      "language": "it"
    }
  ]
}
```

#### Esempio · Risposta 200

```json
{
  "received": 1,
  "written": 1,
  "rejected": 0,
  "errors": [],
  "warnings": [],
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` Batch outcome. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` Invalid body, or a batch over 500 items. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA`, `CORPO_NON_VALIDO`, `LOTTO_VUOTO`, `LOTTO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `409` `Idempotency-Key` already used for a different request, or a request still in progress. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `PUT /v1/order_history`

`operationId`: `putOrderHistory`

**Load the shop's order history, in batches**

One row per order line, upsert by `order_ref` + `sku`: an optional field the row does not carry stays as it was. The customer is identified by E.164 phone (`phone`) or by their `customer_ref` (the `external_ref` of `PUT /v1/customers`). From this the assistant learns each customer's "usual": the products, the quantities of the last purchase, the last order. History is matched to a customer only when the channel guarantees the phone number (WhatsApp): in the web chat the customer types the number, and it opens nobody's history. Only for shops that live on GroceryAI (`409 STORICO_SOLO_NEGOZI_NATIVI` for shops that read history from their own connector).

Permesso: `history:write`

#### Parametri

- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{
  "order_history": [
    {
      "order_ref": "EXAMPLE-ORDER-0001",
      "sku": "EXAMPLE-SPAGHETTI-500",
      "title": "Spaghetti di semola 500 g",
      "quantity": 2,
      "unit_price": 1.29,
      "customer_ref": "example-customer-001",
      "order_date": "2026-10-20",
      "status": "delivered"
    },
    {
      "order_ref": "EXAMPLE-ORDER-0001",
      "sku": "EXAMPLE-MILK-1L",
      "title": "Latte intero 1 l",
      "quantity": 1,
      "unit_price": 1.49,
      "customer_ref": "example-customer-001",
      "order_date": "2026-10-20",
      "status": "delivered"
    }
  ]
}
```

#### Esempio · Risposta 200

```json
{
  "received": 2,
  "written": 2,
  "rejected": 0,
  "errors": [],
  "warnings": [],
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` Batch outcome: how many received, how many written, which were rejected and why. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` Invalid body, or a batch over 500 items. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA`, `CORPO_NON_VALIDO`, `LOTTO_VUOTO`, `LOTTO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `409` The shop does not read its history from GroceryAI. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO`, `STORICO_SOLO_NEGOZI_NATIVI` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/stores`

`operationId`: `getStores`

**Read the shop's stores**

The list of stores (`store_code`, `name`, `city`, `address`, `timezone`, `is_active`), with `principal` (the shop's own store: it serves locations no zone covers), the zones each one serves and a preview of its catalog: `products.sellable` (products sellable there), `own_price` (those with a store-specific price), `not_sold_here` (those not sold there). A shop with a single store reads zero: its store is implicit.

Permesso: `catalog:read`

#### Esempio · Risposta 200

```json
{
  "data": {
    "environment": "test",
    "catalog_products": 1240,
    "stores": [
      {
        "store_code": "OLB-01",
        "name": "Bottega Esempio Centro",
        "city": "Olbia",
        "address": "Via delle Prove 1",
        "timezone": "Europe/Rome",
        "is_active": true,
        "principal": true,
        "zones": [],
        "products": {
          "sellable": 1240,
          "own_price": 0,
          "not_sold_here": 0
        }
      }
    ]
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The stores, with a catalog preview for each. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `PUT /v1/stores`

`operationId`: `putStores`

**Write the shop's stores**

The body `{stores: [...]}` is the COMPLETE list: a store that is not named is switched off (never deleted). Each item: `store_code` (letters, digits, `_ . -`, up to 64), `name`, `city`, optional `address` and `timezone` (IANA; absent = the shop's), `is_active`. The first store is the shop's own. A store that serves an active delivery zone cannot be switched off (`409 PUNTO_VENDITA_CON_ZONE`): move the zone first. Zones choose their store in the portal (Delivery page, the zone's `store_code`); per-store prices arrive with `PUT /v1/inventory` and `store_code`.

Permesso: `catalog:write`

#### Parametri

- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{
  "stores": [
    {
      "store_code": "OLB-01",
      "name": "Bottega Esempio Centro",
      "city": "Olbia",
      "address": "Via delle Prove 1",
      "timezone": "Europe/Rome",
      "is_active": true
    }
  ]
}
```

#### Esempio · Risposta 200

```json
{
  "data": {
    "environment": "test",
    "catalog_products": 1240,
    "stores": [
      {
        "store_code": "OLB-01",
        "name": "Bottega Esempio Centro",
        "city": "Olbia",
        "address": "Via delle Prove 1",
        "timezone": "Europe/Rome",
        "is_active": true,
        "principal": true,
        "zones": [],
        "products": {
          "sellable": 1240,
          "own_price": 0,
          "not_sold_here": 0
        }
      }
    ]
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The stores written, in the shape of `GET /v1/stores`. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` A malformed field, a repeated code, a time zone that is not IANA. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA`, `CORPO_NON_VALIDO`, `CAMPO_OBBLIGATORIO`, `VALORE_NON_AMMESSO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE`, `TENANT_NON_DELLA_CHIAMATA` — Intestazioni: `x-request-id`, `x-core-version`
- `409` `PUNTO_VENDITA_CON_ZONE`. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO`, `PUNTO_VENDITA_CON_ZONE` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE`, `DIPENDENZA_NON_DISPONIBILE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/rules`

`operationId`: `getRules`

**Read the shop's rules**

The rules document the assistant applies: minimum order, payment methods, delivery fee and free-delivery threshold per zone, bank transfer details, prepayment, cash only with own delivery, discounts (welcome, welcome back, loyalty tiers, excluded on offers), friend codes, heavy-goods extras, order edit window, checkout upsell, cart reminder, delivery slot on send; plus the `version` to start from when writing it. Only for shops created in the portal (`409 REGOLE_SOLO_NEGOZI_DEL_PORTALE`).

Permesso: `rules:read`

#### Esempio · Risposta 200

```json
{
  "data": {
    "version": 4,
    "currency": "EUR",
    "min_order_amount": "25.00",
    "payment_methods": [
      "cash",
      "card_pos"
    ],
    "payment_methods_source": "shop",
    "zones": [
      {
        "zone_slug": "centro",
        "is_active": true,
        "delivery_cost": "3.90",
        "free_threshold": "60.00"
      }
    ],
    "bank_transfer": null,
    "bank_transfer_ready": false,
    "prepaid_flow": "none",
    "cash_requires_own_delivery": false,
    "discounts": null,
    "friend_codes": null,
    "heavy_extras": null,
    "order_edit_window_hours": null,
    "checkout_upsell": null,
    "cart_reminder": true,
    "slot_on_send": "propose",
    "matches_version": null,
    "updated_at": "2026-10-31T09:15:00Z",
    "updated_by": "api_key:1201"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The rules document, with `version`. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `409` `REGOLE_SOLO_NEGOZI_DEL_PORTALE`. — Codici d'errore: `REGOLE_SOLO_NEGOZI_DEL_PORTALE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `PUT /v1/rules`

`operationId`: `putRules`

**Write the shop's rules, versioned**

The whole document of `GET /v1/rules` with `based_on_version` (the version you read): `min_order_amount`, `payment_methods` and `zones` are required, the commercial rules optional (absent = they stay as they are). Every write that changes something creates a version, like the portal; an outdated `based_on_version` is `409 VERSIONE_CAMBIATA`. Field errors are all collected in `errors: [{field, code, message}]`, with the message in the `?lang=` language (it, en, es, fr, de, pt). Rules are one per shop: only a key of the environment the shop runs in can write them (`409 AMBIENTE_DEL_NEGOZIO`).

Permesso: `rules:write`

#### Parametri

- `lang` · nella query (string) — The language of error messages (it, en, es, fr, de, pt; en by default).
- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{
  "based_on_version": 3,
  "min_order_amount": "25.00",
  "payment_methods": [
    "cash",
    "card_pos"
  ],
  "zones": [
    {
      "zone_slug": "centro",
      "delivery_cost": "3.90",
      "free_threshold": "60.00"
    }
  ],
  "cart_reminder": true,
  "slot_on_send": "propose"
}
```

#### Esempio · Risposta 200

```json
{
  "data": {
    "version": 4,
    "currency": "EUR",
    "min_order_amount": "25.00",
    "payment_methods": [
      "cash",
      "card_pos"
    ],
    "payment_methods_source": "shop",
    "zones": [
      {
        "zone_slug": "centro",
        "is_active": true,
        "delivery_cost": "3.90",
        "free_threshold": "60.00"
      }
    ],
    "bank_transfer": null,
    "bank_transfer_ready": false,
    "prepaid_flow": "none",
    "cash_requires_own_delivery": false,
    "discounts": null,
    "friend_codes": null,
    "heavy_extras": null,
    "order_edit_window_hours": null,
    "checkout_upsell": null,
    "cart_reminder": true,
    "slot_on_send": "propose",
    "matches_version": null,
    "updated_at": "2026-10-31T09:15:00Z",
    "updated_by": "api_key:1201",
    "changed": true
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The rules document after the write, with `version` and `changed`. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` A field out of bounds: the first one in the envelope, all of them in `errors`. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA`, `CORPO_NON_VALIDO`, `CAMPO_OBBLIGATORIO`, `VALORE_NON_AMMESSO`, `IMPORTO_NON_VALIDO`, `METODO_DI_PAGAMENTO_NON_AMMESSO`, `NESSUN_METODO`, `ZONA_NON_VALIDA`, `ZONA_SCONOSCIUTA`, `SOGLIA_SOTTO_IL_COSTO`, `REGOLA_SCONOSCIUTA`, `TESTO_TROPPO_LUNGO`, `IBAN_NON_VALIDO`, `BIC_NON_VALIDO`, `PERCENTUALE_NON_VALIDA`, `GIORNI_NON_VALIDI`, `GRADINI_NON_IN_ORDINE`, `CODICE_AMICO_NON_VALIDO`, `VALORE_RIPETUTO`, `TROPPI_ELEMENTI`, `TERMINE_NON_VALIDO`, `EXTRA_SENZA_CRITERIO`, `NUMERO_NON_VALIDO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `409` `VERSIONE_CAMBIATA`, `AMBIENTE_DEL_NEGOZIO`, `COORDINATE_BANCARIE_ASSENTI` or `REGOLE_SOLO_NEGOZI_DEL_PORTALE`. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO`, `VERSIONE_CAMBIATA`, `AMBIENTE_DEL_NEGOZIO`, `COORDINATE_BANCARIE_ASSENTI`, `REGOLE_SOLO_NEGOZI_DEL_PORTALE` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `POST /v1/rules/preview`

`operationId`: `previewRules`

**Preview what the customer will read with these rules (writes nothing)**

The same body as `PUT /v1/rules` (`based_on_version` optional) plus `example_subtotal` and `lang`: the blocks the assistant would render (delivery per zone, totals, summary, minimum order) and `commerce` (each tier's discount, the friend code, the heavy-goods extra, the welcome discount that is not shown if the phrase states a different percentage), rendered by the assistant's renderer with the shop's language pack.

Permesso: `rules:read`

#### Esempio · Corpo della richiesta

```json
{
  "min_order_amount": "25.00",
  "payment_methods": [
    "cash",
    "card_pos"
  ],
  "zones": [
    {
      "zone_slug": "centro",
      "delivery_cost": "3.90",
      "free_threshold": "60.00"
    }
  ],
  "example_subtotal": "42.00",
  "lang": "en"
}
```

#### Esempio · Risposta 200

```json
{
  "data": {
    "zones": [
      {
        "zone_slug": "centro",
        "blocks": [
          "Delivery to centro costs €3.90, free over €60.00."
        ]
      }
    ],
    "min_order": "The minimum order is €25.00.",
    "commerce": {
      "discounts": null,
      "friend_codes": null,
      "heavy_extras": null
    },
    "missing_keys": [],
    "fallbacks": []
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The preview. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `400` A field out of bounds (as in `PUT /v1/rules`). — Codici d'errore: `CORPO_NON_JSON`, `CORPO_NON_VALIDO`, `CAMPO_OBBLIGATORIO`, `VALORE_NON_AMMESSO`, `IMPORTO_NON_VALIDO`, `METODO_DI_PAGAMENTO_NON_AMMESSO`, `NESSUN_METODO`, `ZONA_NON_VALIDA`, `ZONA_SCONOSCIUTA`, `SOGLIA_SOTTO_IL_COSTO`, `REGOLA_SCONOSCIUTA`, `TESTO_TROPPO_LUNGO`, `IBAN_NON_VALIDO`, `BIC_NON_VALIDO`, `PERCENTUALE_NON_VALIDA`, `GIORNI_NON_VALIDI`, `GRADINI_NON_IN_ORDINE`, `CODICE_AMICO_NON_VALIDO`, `VALORE_RIPETUTO`, `TROPPI_ELEMENTI`, `TERMINE_NON_VALIDO`, `EXTRA_SENZA_CRITERIO`, `NUMERO_NON_VALIDO`, `LINGUA_NON_VALIDA` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `409` `Idempotency-Key` already used for a different request, or a request still in progress. — Codici d'errore: `COORDINATE_BANCARIE_ASSENTI`, `PACCHETTO_ASSENTE`, `REGOLE_SOLO_NEGOZI_DEL_PORTALE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/store_texts`

`operationId`: `getStoreTexts`

**Read the shop's texts and site settings**

The template phrases of the language pack that the shop can rewrite (with the original phrase), the assistant's hours, the departments with their emoji, the basic weekly shopping list and, in the `site` block, the site paths (categories, FAQ, offers, delivery rates).

Permesso: `texts:read`

#### Esempio · Risposta 200

```json
{
  "data": {
    "default_lang": "it",
    "languages": [
      "it",
      "en"
    ],
    "phrases": [
      {
        "key": "greeting",
        "base": "Ciao! Sono l'assistente del negozio.",
        "lang": "it",
        "text": "Ciao! Sono l'assistente di Bottega Esempio.",
        "customized": true
      }
    ],
    "assistant_hours": null,
    "departments": [],
    "weekly_shop_base_list": [
      "latte",
      "pane",
      "uova",
      "frutta"
    ],
    "site": {
      "origin": "https://shop.example.invalid",
      "faq_path": "/faq",
      "offers_path": "/offerte",
      "category_paths": [],
      "delivery_rates_path": null
    }
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The texts and site settings. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `409` `REGOLE_SOLO_NEGOZI_DEL_PORTALE`. — Codici d'errore: `REGOLE_SOLO_NEGOZI_DEL_PORTALE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `PUT /v1/store_texts`

`operationId`: `putStoreTexts`

**Write the shop's texts and site settings**

Only the fields to change: `phrases: [{lang, key, text|null}]` (a phrase from the closed list, keeping the original phrase's placeholders and without links; `null` reverts to the original phrase), `assistant_hours`, `departments`, `weekly_shop_base_list`, `site: {category_paths, faq_path, offers_path, delivery_rates_path}`. Errors collected in `errors`, in the `?lang=` language.

Permesso: `texts:write`

#### Parametri

- `lang` · nella query (string) — The language of error messages (it, en, es, fr, de, pt; en by default).
- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{
  "weekly_shop_base_list": [
    "latte",
    "pane",
    "uova",
    "frutta"
  ]
}
```

#### Esempio · Risposta 200

```json
{
  "data": {
    "default_lang": "it",
    "languages": [
      "it",
      "en"
    ],
    "phrases": [
      {
        "key": "greeting",
        "base": "Ciao! Sono l'assistente del negozio.",
        "lang": "it",
        "text": "Ciao! Sono l'assistente di Bottega Esempio.",
        "customized": true
      }
    ],
    "assistant_hours": null,
    "departments": [],
    "weekly_shop_base_list": [
      "latte",
      "pane",
      "uova",
      "frutta"
    ],
    "site": {
      "origin": "https://shop.example.invalid",
      "faq_path": "/faq",
      "offers_path": "/offerte",
      "category_paths": [],
      "delivery_rates_path": null
    },
    "changed": true
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The texts and site settings after the write, with `changed`. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` A field out of bounds: the first one in the envelope, all of them in `errors`. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA`, `CORPO_NON_VALIDO`, `VALORE_NON_AMMESSO`, `REGOLA_SCONOSCIUTA`, `TROPPI_ELEMENTI`, `FRASE_NON_MODIFICABILE`, `SEGNAPOSTO_DIVERSI`, `LINK_NELLA_FRASE`, `TESTO_TROPPO_LUNGO`, `ORARI_NON_VALIDI`, `VALORE_RIPETUTO`, `TERMINE_NON_VALIDO`, `PERCORSO_NON_VALIDO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `409` `AMBIENTE_DEL_NEGOZIO`, `PACCHETTO_ASSENTE` or `REGOLE_SOLO_NEGOZI_DEL_PORTALE`. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO`, `AMBIENTE_DEL_NEGOZIO`, `PACCHETTO_ASSENTE`, `REGOLE_SOLO_NEGOZI_DEL_PORTALE` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/customers/{external_ref}`

`operationId`: `getCustomer`

**Read a customer**

An `external_ref` of another account answers 404, not 403: whether someone else's record exists is not information to give out.

Permesso: `customers:read`

#### Parametri

- `external_ref` · nel percorso (string) · obbligatorio — The customer's identifier in your system.

#### Esempio · Risposta 200

```json
{
  "data": {
    "external_ref": "example-customer-001",
    "display_name": "Giulia Esempio",
    "email": "giulia@example.invalid",
    "phone": "+390000000001",
    "address": {
      "street": "Via delle Prove",
      "house_number": "1",
      "city": "Olbia",
      "postal_code": "07026"
    },
    "attributes": {
      "language": "it"
    }
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The customer. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `404` Does not exist (or does not belong to this account). — Codici d'errore: `NON_TROVATO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/orders`

`operationId`: `getOrders`

**Orders to take over (pull)**

The alternative to webhooks for those who do not want an inbound endpoint: read `status=new` and confirm with the ack. Reads the platform's event log (outbox), filtered by the key's environment: a `test` key sees test orders, a `live` key the real ones.

Permesso: `orders:read`

#### Parametri

- `status` · nella query (string) — `new` (default) or `acked`.
- `limit` · nella query (integer) — From 1 to 200 (default 50).

#### Esempio · Risposta 200

```json
{
  "data": [
    {
      "event_id": "8a4e2c10-5b3f-4d9a-b1c7-0e6f2a9d3b58",
      "order_id": "ORD-20261031-0042",
      "type": "order.confirmed",
      "payload": {
        "schema_version": 2,
        "order": {
          "id": "ORD-20261031-0042",
          "status": "confirmed",
          "lines": [
            {
              "sku": "EXAMPLE-SPAGHETTI-500",
              "name": "Spaghetti di semola 500 g",
              "brand": "Esempio",
              "qty": 2,
              "unit": "pz",
              "unit_price": 1.29,
              "out_of_catalog": false
            },
            {
              "sku": null,
              "name": "Basilico fresco",
              "brand": null,
              "qty": 1,
              "unit": null,
              "unit_price": null,
              "out_of_catalog": true
            }
          ],
          "totals": {
            "subtotal": 2.58,
            "discounts": 0,
            "delivery": 3.9,
            "extras": 0,
            "total": 6.48
          },
          "delivery": {
            "startISO": "2026-11-01T08:00:00.000Z",
            "endISO": "2026-11-01T10:00:00.000Z",
            "label": "domenica 1 novembre, 9:00-11:00"
          },
          "customer": {
            "chatId": "web:7d0c2b9e",
            "channel": "web",
            "fullName": "Giulia Esempio",
            "address": "Via delle Prove 1",
            "city": "Olbia",
            "zip": "07026",
            "phone": null,
            "email": null,
            "notes": null,
            "missing_fields": [
              "phone",
              "email"
            ]
          },
          "notes": "Citofono Esempio",
          "currency": "EUR"
        }
      },
      "occurred_at": "2026-10-31T09:10:00Z",
      "created_at": "2026-10-31T09:10:01Z",
      "stato": "in_attesa",
      "consegnato_at": null
    }
  ],
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The orders, oldest first. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `400` Invalid request: `code` says which field or header, `param` where. — Codici d'errore: `PARAMETRO_NON_VALIDO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` `OUTBOX_ASSENTE`: the event log is not in service on this instance yet. — Codici d'errore: `DB_URL_ASSENTE`, `OUTBOX_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `POST /v1/orders/{order_id}/ack`

`operationId`: `ackOrder`

**Acknowledge that you took over an order**

From then on the order no longer appears in `status=new`. Acknowledging the same order twice is not an error: it returns the same response.

Permesso: `orders:write`

#### Parametri

- `order_id` · nel percorso (string) · obbligatorio — The order identifier.
- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{}
```

#### Esempio · Risposta 200

```json
{
  "data": {
    "order_id": "ORD-20261031-0042",
    "status": "acked"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` Acknowledged. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` Invalid request: `code` says which field or header, `param` where. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `404` No order with that identifier for this account. — Codici d'errore: `NON_TROVATO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `409` `Idempotency-Key` already used for a different request, or a request still in progress. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` `OUTBOX_ASSENTE`: the event log is not in service on this instance yet. — Codici d'errore: `DB_URL_ASSENTE`, `OUTBOX_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `POST /v1/orders/{order_id}/status`

`operationId`: `reportOrderStatus`

**Report where an order stands or how it went: progress and outcome**

The shop says how the order went after taking it over: `delivered` (`delivered_amount` optional; absent = in full), `substituted` (delivered with substitutions; `delivered_amount` required), `not_delivered`, `returned` (returned after delivery; `delivered_amount` = what is kept, even 0). It can be reported more than once: the last report counts, and all are recorded with who made them (the key) and when. An order with no report stays as it was sent. Before the outcome the same call reports PROGRESS, which does not count for billing: `preparing`, `ready`, `out_for_delivery` and `delayed` (with the expected window `eta`, optional), `rescheduled` (with the new window `eta`, required); `reason` (a code) with `delayed`, `rescheduled` and `not_delivered`; `tracking_url` on a declared tracking domain. After an outcome progress is no longer recorded (`409`). Every recorded report becomes the `order.updated` event; the same status reported again answers `duplicate: true` without a second event. With an agent key `not_delivered` and `returned` wait for a person's approval (`202`); progress does not.

Permesso: `orders:write`

#### Parametri

- `order_id` · nel percorso (string) · obbligatorio — The order identifier (`order.id` of the `order.confirmed` event).
- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{
  "status": "substituted",
  "delivered_amount": 5.98,
  "note": "Latte intero sostituito con latte parzialmente scremato."
}
```

#### Esempio · Risposta 200

```json
{
  "data": {
    "order_id": "ORD-20261031-0042",
    "status": "substituted",
    "delivered_amount": 5.98,
    "source": "api",
    "reported_at": "2026-10-31T09:15:00Z",
    "received_at": "2026-10-31T09:15:00Z",
    "duplicate": false,
    "kind": "outcome"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` Recorded. `duplicate` is true when the same report had already arrived. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `202` Agent key, `not_delivered` or `returned`: waiting for a person's approval. Nothing has changed. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` Invalid body: `code` says which field. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA`, `CORPO_NON_VALIDO`, `STATO_NON_VALIDO`, `IMPORTO_NON_VALIDO`, `IMPORTO_MANCANTE`, `IMPORTO_INCOERENTE`, `DATA_NON_VALIDA`, `NOTA_TROPPO_LUNGA`, `ETA_MANCANTE`, `ETA_NON_AMMESSA`, `MOTIVO_NON_VALIDO`, `URL_NON_AMMESSO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `404` No order with that identifier for this account and environment. — Codici d'errore: `NON_TROVATO`, `APPROVAZIONE_SCONOSCIUTA` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `409` `TRANSIZIONE_NON_AMMESSA`: the order already has an outcome and progress is no longer recorded. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO`, `TRANSIZIONE_NON_AMMESSA`, `APPROVAZIONE_IN_ATTESA`, `APPROVAZIONE_RIFIUTATA`, `APPROVAZIONE_SCADUTA`, `APPROVAZIONE_GIA_USATA`, `APPROVAZIONE_DIVERSA` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` `REGISTRO_ASSENTE`: the order register is not in service on this instance yet. — Codici d'errore: `DB_URL_ASSENTE`, `REGISTRO_ASSENTE`, `APPROVAZIONI_ASSENTI` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/support_requests`

`operationId`: `getSupportRequests`

**Customer support requests to take over (pull)**

A chat customer asked for a person, made a complaint or wants to change an order already sent: the request travels the same way as orders. Read `status=new` and confirm with the ack. Filtered by the key's environment, like orders.

Permesso: `orders:read`

#### Parametri

- `status` · nella query (string) — `new` (default) or `acked`.
- `limit` · nella query (integer) — From 1 to 200 (default 50).

#### Esempio · Risposta 200

```json
{
  "data": [
    {
      "support_id": "support:web:7d0c2b9e:1",
      "event_id": "0c7b3e91-2f4a-4b6d-8e15-9a3c7d2f4e60",
      "type": "support.requested",
      "payload": {
        "schema_version": 1,
        "support_request": {
          "id": "support:web:7d0c2b9e:1",
          "kind": "modify_order",
          "outcome": "nuova",
          "customer_message": "Posso aggiungere del latte all'ordine di domani?",
          "lang": "it",
          "channel": "web",
          "order_code": "ORD-20261031-0042",
          "customer": {
            "chatId": "web:7d0c2b9e",
            "channel": "web",
            "fullName": "Giulia Esempio",
            "address": "Via delle Prove 1",
            "city": "Olbia",
            "zip": "07026",
            "phone": null,
            "email": null,
            "notes": null,
            "missing_fields": [
              "phone",
              "email"
            ]
          }
        }
      },
      "occurred_at": "2026-10-31T09:12:00Z",
      "created_at": "2026-10-31T09:12:01Z",
      "stato": "in_attesa",
      "consegnato_at": null
    }
  ],
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The requests, oldest first. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `400` Invalid request: `code` says which field or header, `param` where. — Codici d'errore: `PARAMETRO_NON_VALIDO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` `OUTBOX_ASSENTE`: the event log is not in service on this instance yet. — Codici d'errore: `DB_URL_ASSENTE`, `OUTBOX_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `POST /v1/support_requests/{support_id}/ack`

`operationId`: `ackSupportRequest`

**Acknowledge that you took over a support request**

From then on the request no longer appears in `status=new`. Acknowledging the same request twice is not an error: it returns the same response.

Permesso: `orders:write`

#### Parametri

- `support_id` · nel percorso (string) · obbligatorio — The request identifier (`support_request.id`).
- `Idempotency-Key` · intestazione (string) · obbligatorio — A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

#### Esempio · Corpo della richiesta

```json
{}
```

#### Esempio · Risposta 200

```json
{
  "data": {
    "support_id": "support:web:7d0c2b9e:1",
    "status": "acked"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` Acknowledged. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `idempotent-replayed`
- `400` Invalid request: `code` says which field or header, `param` where. — Codici d'errore: `CORPO_NON_JSON`, `IDEMPOTENCY_KEY_MANCANTE`, `IDEMPOTENCY_KEY_TROPPO_LUNGA` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `404` No request with that identifier for this account. — Codici d'errore: `NON_TROVATO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `409` `Idempotency-Key` already used for a different request, or a request still in progress. — Codici d'errore: `IDEMPOTENCY_KEY_RIUSATA`, `RICHIESTA_IN_CORSO` — Intestazioni: `x-request-id`, `x-core-version`, `idempotent-replayed`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` `OUTBOX_ASSENTE`: the event log is not in service on this instance yet. — Codici d'errore: `DB_URL_ASSENTE`, `OUTBOX_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `POST /v1/chat_identity_tokens`

`operationId`: `createChatIdentityToken`

**Open the website chat for one of your signed-in customers: a short-lived, single-use token**

When the customer has signed in to your website, your server requests a token for them (`customer_ref` = their `external_ref` from `PUT /v1/customers`) and passes it to the page; the widget sends it to `core-chat /session` as `identity_token`. From then on the chat is THEIRS: the same cart and the same conversation from one visit to the next, and their history (`PUT /v1/order_history` and orders placed in chat), that is the "usual" as on WhatsApp. The token is valid for your shop and the key's environment, for at most `expires_in` seconds (300 if omitted, between 30 and 600), and ONCE only: never put it in a page a cache could serve to someone else. It is shown only in this response (our database keeps only its hash), so the route does not use `Idempotency-Key`: a repeated call mints another token, with no other effect. Without a token, or with one that does not pass, the chat stays anonymous and `/session` says why (`identity`). `chat_id` is the customer's chat identity, always the same: it is the `customer.chatId` of the orders and support requests that come from their chat. Only for shops that live on GroceryAI.

Permesso: `chat:write`

#### Esempio · Corpo della richiesta

```json
{
  "customer_ref": "example-customer-001",
  "expires_in": 300
}
```

#### Esempio · Risposta 200

```json
{
  "data": {
    "identity_token": "gai_cid_test_8Qm2ZpR4vT7xLc9NbF3kHs6WdJ1yAe5UoGi0XtKq",
    "expires_at": "2026-10-31T09:20:00Z",
    "chat_id": "cv_4f9a2c7e1b3d5f6a8c0e2b4d6f8a1c3e",
    "customer_ref": "example-customer-001"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The token, its expiry, the customer's chat identity. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `400` Invalid body: `code` says which field. — Codici d'errore: `CORPO_NON_JSON`, `CORPO_NON_VALIDO`, `CUSTOMER_REF_NON_VALIDO`, `DURATA_NON_VALIDA` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO`, `AMBITO_MANCANTE` — Intestazioni: `x-request-id`, `x-core-version`
- `404` `CLIENTE_SCONOSCIUTO`: no customer with that `customer_ref` for the shop and the key's environment. — Codici d'errore: `CLIENTE_SCONOSCIUTO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `409` The shop does not use GroceryAI for its customers' identity. — Codici d'errore: `IDENTITA_SOLO_NEGOZI_NATIVI` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `413` Body over the allowed limit (1 MiB). — Codici d'errore: `CORPO_TROPPO_GRANDE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` `IDENTITA_NON_IN_SERVIZIO`: the identity token is not in service on this instance yet. — Codici d'errore: `DB_URL_ASSENTE`, `IDENTITA_NON_IN_SERVIZIO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/approvals/{approval_id}`

`operationId`: `getApproval`

**The status of an approval requested by an agent key**

An agent key calling a destructive operation receives `202` with an approval: a person at the shop approves or rejects it in the portal. This operation says where it stands: `pending` (waiting), `approved` (send the same request again with `GroceryAI-Approval-Id`), `rejected`, `consumed` (already used) or `expired` (72 hours without use). Only the key that requested it can see it.

Permesso: basta una chiave segreta valida, senza un permesso particolare.

#### Parametri

- `approval_id` · nel percorso (string) · obbligatorio — The approval id (`data.id` of the `202` response).

#### Esempio · Risposta 200

```json
{
  "data": {
    "object": "approval",
    "id": "a0000000-0000-4000-8000-000000000001",
    "status": "pending",
    "operation_id": "deleteProduct",
    "method": "DELETE",
    "path": "/v1/products/EXAMPLE-MILK-1L",
    "environment": "test",
    "created_at": "2026-11-05T10:00:00.000Z",
    "expires_at": "2026-11-08T10:00:00.000Z",
    "decided_at": null,
    "consumed_at": null
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The approval. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO` — Intestazioni: `x-request-id`, `x-core-version`
- `404` `APPROVAZIONE_SCONOSCIUTA`: no approval with this id for this key. — Codici d'errore: `APPROVAZIONE_SCONOSCIUTA` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`
- `503` `APPROVAZIONI_ASSENTI`: approvals are not in service on this instance yet. — Codici d'errore: `DB_URL_ASSENTE`, `APPROVAZIONI_ASSENTI` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`

### `GET /v1/_deprecation_probe`

`operationId`: `getDeprecationProbe`

**Test route: the headers of a deprecated operation**

Not a feature of the API: it exists so that integrators can see, with a `gai_test_…` key, the headers they would receive from a deprecated operation (`Deprecation`, RFC 9745; `Sunset`, RFC 8594; `Link` with `rel="deprecation"`) and test their own code that reads them. It is deprecated by construction, with a distant `Sunset`, and is never retired. It does not touch the shop's data. With a `gai_live_…` key it returns `404 ROTTA_SCONOSCIUTA`.

**Deprecata** · Ritiro non prima del 2099-12-31 · Rotta di prova: deprecata per costruzione, non si ritira mai.

Permesso: basta una chiave segreta valida, senza un permesso particolare.

#### Esempio · Risposta 200

```json
{
  "data": {
    "probe": true,
    "deprecated_at": "2026-11-01T00:00:00Z",
    "sunset_at": "2099-12-31T23:59:59Z",
    "replacement": null,
    "link": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/openapi.json"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}
```

#### Risposte

- `200` The dates and the page of the test deprecation, equal to the response headers. — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `deprecation`, `sunset`, `link`
- `401` Key missing, malformed, unknown, revoked or expired. — Codici d'errore: `CHIAVE_ASSENTE`, `CHIAVE_MALFORMATA`, `CHIAVE_SOMMA_ERRATA`, `CHIAVE_SCONOSCIUTA`, `CHIAVE_REVOCATA`, `CHIAVE_SCADUTA`, `CHIAVE_INCOERENTE` — Intestazioni: `x-request-id`, `x-core-version`
- `403` The key lacks the required scope, or the account is not active. — Codici d'errore: `TENANT_SOSPESO`, `IP_NON_AMMESSO` — Intestazioni: `x-request-id`, `x-core-version`, `deprecation`, `sunset`, `link`
- `404` `ROTTA_SCONOSCIUTA`: the key belongs to the `live` environment, where the test route does not exist. — Codici d'errore: `ROTTA_SCONOSCIUTA` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `deprecation`, `sunset`, `link`
- `429` Request limit exceeded: the store plan's rate (or the key's own per-minute cap, if it has one). `Retry-After` says how many seconds to wait. — Codici d'errore: `LIMITE_RICHIESTE` — Intestazioni: `x-request-id`, `x-core-version`, `retry-after`, `ratelimit-policy`, `ratelimit`, `deprecation`, `sunset`, `link`
- `500` Internal error: the `request_id` identifies the call in our logs. — Codici d'errore: `ERRORE_INTERNO` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `deprecation`, `sunset`, `link`
- `503` Service unavailable on this instance: `code` says which part is missing. Retry later. — Codici d'errore: `DB_URL_ASSENTE` — Intestazioni: `x-request-id`, `x-core-version`, `ratelimit-policy`, `ratelimit`, `deprecation`, `sunset`, `link`

### Errori del percorso, su ogni rotta

- `404 ROTTA_SCONOSCIUTA` — No route for that method and path.
- `405 METODO_NON_AMMESSO` — The path exists, but not for that method (a 404 would send you looking for a URL that does exist).

### Intestazioni delle risposte

- `x-request-id` (string) — The identifier of THIS call: equal to `request_id` in the body, except on replay (`idempotent-replayed: true`), where the body is the original call's and carries its `request_id`.
- `x-core-version` (string) — The platform version that answered.
- `retry-after` (integer) — Seconds to wait before retrying: until the next token of the plan's bucket, or until the end of the minute if the key's own cap refused the request. Always equal to the `t` parameter of the refusing policy in the `RateLimit` header of the same response.
- `ratelimit-policy` (string) — This key's rate-limit policy, in the form of the IETF draft `draft-ietf-httpapi-ratelimit-headers` (version -11, §3). The limit comes from the store's plan and is counted with a bucket: `"key";q=<requests per second>;w=1;burst=<burst>`, where `q` is the sustained rate, `w` a one-second window and `burst` how many requests in a row pass when the bucket is full (an extra parameter the draft allows, §3.1 and appendix C). If the key has its own per-minute cap, lower than the plan, the list carries a second item `"key-minute";q=<requests>;w=60` (a calendar minute). Before per-plan limits the form was `"key";q=<requests>;w=60`. It is on every response of a keyed route except 401 and 403, which come before counting (like a 404 or 405 for a path that does not exist); unkeyed routes (`/v1/openapi.json`, `/v1/errors`, `/v1/status`) do not carry it.
- `ratelimit` (string) — What is left, in the form of the IETF draft `draft-ietf-httpapi-ratelimit-headers` (version -11, §4): `"key";r=<remaining>;t=<seconds>`. `r` is how many requests this key may make right now, in a row, this one already counted (the tokens in the bucket); `t` the seconds to the next token (1 for a rate of at least one request per second). With the key's own per-minute cap there is a second item `"key-minute";r=<left in the minute>;t=<seconds to the end of the minute>`. It comes from the same count that decides the `429`: with `r=0` the next request before `t` seconds gets `429` with `Retry-After` equal to `t`. A client that reads it slows down before getting there (for example: with a low `r`, it spreads the remaining requests over the `t` seconds). A positive `r` is not a guarantee (the draft, §8.3).
- `cache-control` (string) — How long a cache may keep the response without asking again: `public, max-age=300` for the documentation, `public, max-age=30` for the service status; `no-store` on an error.
- `etag` (string) — The content fingerprint (sha256 of the bytes served). Send it back in `If-None-Match` to get `304` if nothing changed.
- `access-control-allow-origin` (string) — Always `*`: the documentation can also be read from a browser or a tool running in a web page.
- `access-control-expose-headers` (string) — The headers a web page can read: `etag, x-request-id, x-core-version`.
- `deprecation` (string) — RFC 9745: the operation is deprecated from the given date, in seconds since the epoch after `@` (for example `@1793491200`). It keeps working as before until the `Sunset`.
- `sunset` (string) — RFC 8594: from this date (HTTP-date, for example `Sat, 01 Jan 2028 00:00:00 GMT`) the operation may stop responding. It is never earlier than 12 months after the `Deprecation` date.
- `link` (string) — RFC 9745 §3: `<address>; rel="deprecation"`, the page that says what to use instead (this document: the operation carries `x-deprecation`).
- `location` (string) — The address of the status of the accepted resource (`data.links.self`): read it with `GET` until it is finished. It is there also when the answer is replayed with the same `Idempotency-Key`.
- `idempotent-replayed` (string) — `true` when the response is the replay of a call already executed with the same `Idempotency-Key`: same status, same body, same `request_id` as the first time, and no new execution.

## Eventi dei webhook

### `order.confirmed`

A customer confirmed an order in the shop's chat. Sent once per order (`resource_id` = the order identifier) to every endpoint subscribed to `order.confirmed`; the same order can also be pulled with `GET /v1/orders`.

#### Intestazioni

- `webhook-id` · intestazione (string) · obbligatorio — The message identifier: the event `id`, the same on every attempt and on every redelivery. It is the key to drop duplicates with.
- `webhook-timestamp` · intestazione (string) · obbligatorio — Unix seconds of the instant of the ATTEMPT (not of the fact): it changes on every retry. Reject a delivery more than 300 seconds away from your own clock.
- `webhook-signature` · intestazione (string) · obbligatorio — One or two signatures separated by a space, each `v1,<base64>`: HMAC-SHA256 of `<webhook-id>.<webhook-timestamp>.<raw body>` keyed with the bytes of the endpoint's secret (`whsec_<base64>`: the base64-decoded value). During a secret rotation there are two signatures, with the new secret and with the old one: one matching is enough. Verify it with the official Standard Webhooks library.
- `user-agent` · intestazione (string) · obbligatorio — Always `GroceryAI-Core-Events/2`.

#### Corpo dell'evento

```json
{
  "id": "8a4e2c10-5b3f-4d9a-b1c7-0e6f2a9d3b58",
  "type": "order.confirmed",
  "environment": "test",
  "timestamp": "2026-10-31T09:10:00Z",
  "occurred_at": "2026-10-31T09:10:00Z",
  "resource_id": "ORD-20261031-0042",
  "attempt": 1,
  "data": {
    "schema_version": 2,
    "order": {
      "id": "ORD-20261031-0042",
      "status": "confirmed",
      "lines": [
        {
          "sku": "EXAMPLE-SPAGHETTI-500",
          "name": "Spaghetti di semola 500 g",
          "brand": "Esempio",
          "qty": 2,
          "unit": "pz",
          "unit_price": 1.29,
          "out_of_catalog": false
        },
        {
          "sku": null,
          "name": "Basilico fresco",
          "brand": null,
          "qty": 1,
          "unit": null,
          "unit_price": null,
          "out_of_catalog": true
        }
      ],
      "totals": {
        "subtotal": 2.58,
        "discounts": 0,
        "delivery": 3.9,
        "extras": 0,
        "total": 6.48
      },
      "delivery": {
        "startISO": "2026-11-01T08:00:00.000Z",
        "endISO": "2026-11-01T10:00:00.000Z",
        "label": "domenica 1 novembre, 9:00-11:00"
      },
      "customer": {
        "chatId": "web:7d0c2b9e",
        "channel": "web",
        "fullName": "Giulia Esempio",
        "address": "Via delle Prove 1",
        "city": "Olbia",
        "zip": "07026",
        "phone": null,
        "email": null,
        "notes": null,
        "missing_fields": [
          "phone",
          "email"
        ]
      },
      "notes": "Citofono Esempio",
      "currency": "EUR"
    }
  }
}
```

### `support.requested`

A chat customer asks for a person, makes a complaint or wants to change an order already sent. Sent to every endpoint subscribed to `support.requested`; the same request can also be pulled with `GET /v1/support_requests`.

#### Intestazioni

- `webhook-id` · intestazione (string) · obbligatorio — The message identifier: the event `id`, the same on every attempt and on every redelivery. It is the key to drop duplicates with.
- `webhook-timestamp` · intestazione (string) · obbligatorio — Unix seconds of the instant of the ATTEMPT (not of the fact): it changes on every retry. Reject a delivery more than 300 seconds away from your own clock.
- `webhook-signature` · intestazione (string) · obbligatorio — One or two signatures separated by a space, each `v1,<base64>`: HMAC-SHA256 of `<webhook-id>.<webhook-timestamp>.<raw body>` keyed with the bytes of the endpoint's secret (`whsec_<base64>`: the base64-decoded value). During a secret rotation there are two signatures, with the new secret and with the old one: one matching is enough. Verify it with the official Standard Webhooks library.
- `user-agent` · intestazione (string) · obbligatorio — Always `GroceryAI-Core-Events/2`.

#### Corpo dell'evento

```json
{
  "id": "0c7b3e91-2f4a-4b6d-8e15-9a3c7d2f4e60",
  "type": "support.requested",
  "environment": "test",
  "timestamp": "2026-10-31T09:12:00Z",
  "occurred_at": "2026-10-31T09:12:00Z",
  "resource_id": "support:web:7d0c2b9e:1",
  "attempt": 1,
  "data": {
    "schema_version": 1,
    "support_request": {
      "id": "support:web:7d0c2b9e:1",
      "kind": "modify_order",
      "outcome": "nuova",
      "customer_message": "Posso aggiungere del latte all'ordine di domani?",
      "lang": "it",
      "channel": "web",
      "order_code": "ORD-20261031-0042",
      "customer": {
        "chatId": "web:7d0c2b9e",
        "channel": "web",
        "fullName": "Giulia Esempio",
        "address": "Via delle Prove 1",
        "city": "Olbia",
        "zip": "07026",
        "phone": null,
        "email": null,
        "notes": null,
        "missing_fields": [
          "phone",
          "email"
        ]
      }
    }
  }
}
```

### `order.updated`

The shop reported where an order stands (`POST /v1/orders/{order_id}/status`): progress (preparing, ready, out for delivery, delayed, rescheduled) or an outcome (delivered, with substitutions, not delivered, returned). Sent once per report to every endpoint subscribed to `order.updated`; the same status reported again is not sent twice, and progress older than the last one reported is not sent. The order is `data.order.id`. Not available via pull.

#### Intestazioni

- `webhook-id` · intestazione (string) · obbligatorio — The message identifier: the event `id`, the same on every attempt and on every redelivery. It is the key to drop duplicates with.
- `webhook-timestamp` · intestazione (string) · obbligatorio — Unix seconds of the instant of the ATTEMPT (not of the fact): it changes on every retry. Reject a delivery more than 300 seconds away from your own clock.
- `webhook-signature` · intestazione (string) · obbligatorio — One or two signatures separated by a space, each `v1,<base64>`: HMAC-SHA256 of `<webhook-id>.<webhook-timestamp>.<raw body>` keyed with the bytes of the endpoint's secret (`whsec_<base64>`: the base64-decoded value). During a secret rotation there are two signatures, with the new secret and with the old one: one matching is enough. Verify it with the official Standard Webhooks library.
- `user-agent` · intestazione (string) · obbligatorio — Always `GroceryAI-Core-Events/2`.

#### Corpo dell'evento

```json
{
  "id": "5d1f3a7c-2b9e-4c6d-8a0f-1e3b5c7d9f20",
  "type": "order.updated",
  "environment": "test",
  "timestamp": "2026-10-31T16:05:00+00:00",
  "occurred_at": "2026-10-31T16:05:00+00:00",
  "resource_id": "7b2e9c41-6a3d-4f8e-9b1c-2d4e6f8a0c13",
  "attempt": 1,
  "data": {
    "schema_version": 1,
    "order": {
      "id": "ORD-20261031-0042",
      "event_id": "7b2e9c41-6a3d-4f8e-9b1c-2d4e6f8a0c13",
      "status": "out_for_delivery",
      "kind": "progress",
      "reported_at": "2026-10-31T16:05:00+00:00",
      "eta": {
        "start": "2026-10-31T17:00:00+00:00",
        "end": "2026-10-31T18:00:00+00:00"
      },
      "tracking_url": "https://tracking.example-carrier.com/t/ORD-20261031-0042"
    }
  }
}
```

### `catalog_import.completed`

A catalog import (`POST /v1/catalog/imports`) has finished, well or badly (`data.import.status`): it arrives once per import at every endpoint subscribed to `catalog_import.completed`. It is the counterpart of Shopify's `bulk_operations/finish`: as there, a webhook delivery can go missing, and the status stays readable with `GET /v1/catalog/imports/{import_id}`. It cannot be pulled.

#### Intestazioni

- `webhook-id` · intestazione (string) · obbligatorio — The message identifier: the event `id`, the same on every attempt and on every redelivery. It is the key to drop duplicates with.
- `webhook-timestamp` · intestazione (string) · obbligatorio — Unix seconds of the instant of the ATTEMPT (not of the fact): it changes on every retry. Reject a delivery more than 300 seconds away from your own clock.
- `webhook-signature` · intestazione (string) · obbligatorio — One or two signatures separated by a space, each `v1,<base64>`: HMAC-SHA256 of `<webhook-id>.<webhook-timestamp>.<raw body>` keyed with the bytes of the endpoint's secret (`whsec_<base64>`: the base64-decoded value). During a secret rotation there are two signatures, with the new secret and with the old one: one matching is enough. Verify it with the official Standard Webhooks library.
- `user-agent` · intestazione (string) · obbligatorio — Always `GroceryAI-Core-Events/2`.

#### Corpo dell'evento

```json
{
  "id": "9b2d4f60-1a3c-4e5f-8a7b-0c1d2e3f4a5b",
  "type": "catalog_import.completed",
  "environment": "test",
  "timestamp": "2026-10-31T09:19:02.000Z",
  "occurred_at": "2026-10-31T09:19:02.000Z",
  "resource_id": "3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
  "attempt": 1,
  "data": {
    "schema_version": 1,
    "import": {
      "id": "3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
      "status": "partial",
      "mode": "delta",
      "source": "url",
      "format": "jsonl",
      "received": 38412,
      "written": 38408,
      "rejected": 4,
      "warnings": 12,
      "switched_off": 0,
      "error": null,
      "finished_at": "2026-10-31T09:19:02.000Z",
      "links": {
        "self": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
        "errors": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81/errors"
      }
    }
  }
}
```

### `webhook.ping`

The test event of the portal's "send a test event" button: a single delivery to the endpoint being tested, signed like the others. Cannot be pulled.

#### Intestazioni

- `webhook-id` · intestazione (string) · obbligatorio — The message identifier: the event `id`, the same on every attempt and on every redelivery. It is the key to drop duplicates with.
- `webhook-timestamp` · intestazione (string) · obbligatorio — Unix seconds of the instant of the ATTEMPT (not of the fact): it changes on every retry. Reject a delivery more than 300 seconds away from your own clock.
- `webhook-signature` · intestazione (string) · obbligatorio — One or two signatures separated by a space, each `v1,<base64>`: HMAC-SHA256 of `<webhook-id>.<webhook-timestamp>.<raw body>` keyed with the bytes of the endpoint's secret (`whsec_<base64>`: the base64-decoded value). During a secret rotation there are two signatures, with the new secret and with the old one: one matching is enough. Verify it with the official Standard Webhooks library.
- `user-agent` · intestazione (string) · obbligatorio — Always `GroceryAI-Core-Events/2`.

#### Corpo dell'evento

```json
{
  "id": "e2d4f6a8-1b3c-4d5e-8f70-9a1b2c3d4e5f",
  "type": "webhook.ping",
  "environment": "test",
  "timestamp": "2026-10-31T09:00:00Z",
  "occurred_at": "2026-10-31T09:00:00Z",
  "resource_id": null,
  "attempt": 1,
  "data": {
    "test": true,
    "endpoint_id": 42
  }
}
```

### Consegna degli eventi

- Ritenti, in secondi dopo il tentativo precedente: 60, 300, 1800, 7200, 18000, 36000, 50400, 72000, 86400
- Tentativi al massimo: 10
- Tempo per rispondere: 15000 ms
- Firma: `v1,` + base64(HMAC-SHA256(bytes of the `whsec_<base64>` secret, `${webhook-id}.${webhook-timestamp}.${raw body}`)); two signatures separated by a space during a rotation
- Formato: [Standard Webhooks 1.0.0](https://www.standardwebhooks.com)
- Ogni attesa è variata fino al 10 %, perché gli endpoint caduti insieme non vengano ritentati nello stesso secondo.
- Rifiuta una consegna il cui `webhook-timestamp` dista più di 300 secondi dal tuo orologio.
- Una risposta `410 Gone` disattiva l'endpoint (l'elenco degli endpoint del portale dice `disabled_reason: http_410`); ogni altro `4xx` si ritenta.

Gli esempi di verifica della firma:

- Verifica della firma con la libreria ufficiale Standard Webhooks (Node) (`verify-standardwebhooks.mjs`)
- Verifica della firma con la libreria ufficiale Standard Webhooks (Python) (`verify_standardwebhooks.py`)
- Verifica della firma senza dipendenze (Node) (`verify-signature.mjs`)
- Verifica della firma senza dipendenze (Python) (`verify_signature.py`)

## Esempi provati

### Verifica della firma con la libreria ufficiale Standard Webhooks (Node) (`verify-standardwebhooks.mjs`)

```javascript
// Receive GroceryAI webhooks with the OFFICIAL Standard Webhooks library. Node 18+.
//
//   npm install standardwebhooks
//   GAI_WEBHOOK_SECRET=whsec_... node verify-standardwebhooks.mjs      # http://localhost:8080/webhooks
//
// The library checks webhook-id, webhook-timestamp (300 seconds tolerance) and webhook-signature (one or two `v1,`
// signatures: two while a secret rotation is in progress). Pass the RAW body and the secret as the portal showed it.
// Specification: https://www.standardwebhooks.com

import http from 'node:http';
import { fileURLToPath } from 'node:url';
import { Webhook } from 'standardwebhooks';

/** Verify one delivery: the parsed event, or null when it is forged, altered or stale. */
export const verifyDelivery = (rawBody, headers, secret) => {
  try { return new Webhook(secret).verify(rawBody, headers); } catch { return null; }
};

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const wh = new Webhook(process.env.GAI_WEBHOOK_SECRET);   // "whsec_..."
  const seen = new Set();   // in production: a table with a unique key on webhook-id
  http.createServer((req, res) => {
    if (req.method !== 'POST' || req.url !== '/webhooks') { res.writeHead(404).end(); return; }
    const chunks = [];
    req.on('data', (c) => chunks.push(c));
    req.on('end', () => {
      let event;
      try { event = wh.verify(Buffer.concat(chunks).toString('utf8'), req.headers); } catch { res.writeHead(400).end(); return; }
      res.writeHead(200).end('ok');   // within 15 seconds, then work
      if (seen.has(req.headers['webhook-id'])) return;
      seen.add(req.headers['webhook-id']);
      console.log(event.type, event.environment, event.resource_id);
    });
  }).listen(Number(process.env.PORT ?? 8080));
}

```

### Verifica della firma con la libreria ufficiale Standard Webhooks (Python) (`verify_standardwebhooks.py`)

```python
"""Receive GroceryAI webhooks with the OFFICIAL Standard Webhooks library. Python 3.8+.

    pip install standardwebhooks flask
    GAI_WEBHOOK_SECRET=whsec_... flask --app verify_standardwebhooks run --port 8080

The library checks webhook-id, webhook-timestamp (300 seconds tolerance) and webhook-signature (one or two `v1,`
signatures: two while a secret rotation is in progress). Pass the RAW body and the secret as the portal showed it.
Specification: https://www.standardwebhooks.com
"""

import os

from standardwebhooks.webhooks import Webhook, WebhookVerificationError

def verify_delivery(raw_body, headers, secret):
    """Return the parsed event, or None when the delivery is forged, altered or stale."""
    try:
        return Webhook(secret).verify(raw_body, dict(headers))
    except WebhookVerificationError:
        return None

try:
    from flask import Flask, request

    app = Flask(__name__)
    seen = set()  # in production: a table with a unique key on webhook-id

    @app.post("/webhooks")
    def webhooks():
        event = verify_delivery(request.get_data(as_text=True), request.headers, os.environ["GAI_WEBHOOK_SECRET"])
        if event is None:
            return "", 400
        if request.headers["webhook-id"] not in seen:
            seen.add(request.headers["webhook-id"])
            print(event["type"], event["environment"], event["resource_id"])
        return "ok", 200  # within 15 seconds, then work
except ImportError:  # the verification above works without Flask
    app = None

```

### Verifica della firma senza dipendenze (Node) (`verify-signature.mjs`)

```javascript
// Verify a GroceryAI webhook delivery (Standard Webhooks 1.0.0) with NO dependency. Node 18+.
//
//   GAI_WEBHOOK_SECRET=whsec_... node verify-signature.mjs      # a minimal receiver on http://localhost:8080/webhooks
//
// Prefer the official library (`npm install standardwebhooks`, see verify-standardwebhooks.mjs): this file does exactly
// what it does, for a runtime where you cannot add a dependency. Specification: https://www.standardwebhooks.com
//
// Every delivery is a POST with a JSON body and these headers:
//   webhook-id         the message id = the event id (the same on every attempt: use it to drop duplicates)
//   webhook-timestamp  Unix seconds of this attempt (it changes on every retry)
//   webhook-signature  "v1,<base64>" HMAC-SHA256 of `${webhook-id}.${webhook-timestamp}.${raw body}`; during a secret
//                      rotation two of them, separated by a space: one matching is enough
//
// The secret is the endpoint's signing secret exactly as the portal showed it: "whsec_" + base64. The HMAC key is the
// base64-DECODED bytes, not the string. Verify on the RAW bytes of the body: parsing and re-serialising the JSON changes them.

import crypto from 'node:crypto';
import http from 'node:http';
import { fileURLToPath } from 'node:url';

/** The tolerance of the official libraries: five minutes covers clock drift and slow networks. */
export const TOLERANCE_SECONDS = 300;

const header = (headers, name) => {
  for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === name) return Array.isArray(v) ? v[0] : v;
  return undefined;
};

/**
 * @param {Buffer|string} rawBody  the request body exactly as received
 * @param {Record<string, string|string[]|undefined>} headers  the request headers (any case)
 * @param {string} secret  the endpoint's signing secret, "whsec_..." included
 * @returns {{ ok: true } | { ok: false, reason: 'bad_secret' | 'missing_headers' | 'bad_timestamp' | 'timestamp_out_of_tolerance' | 'signature_mismatch' }}
 */
export function verifyGroceryAiSignature(rawBody, headers, secret, { toleranceSeconds = TOLERANCE_SECONDS, now = Date.now() } = {}) {
  if (typeof secret !== 'string' || !secret.startsWith('whsec_')) return { ok: false, reason: 'bad_secret' };
  const key = Buffer.from(secret.slice('whsec_'.length), 'base64');
  if (key.length === 0) return { ok: false, reason: 'bad_secret' };
  const id = header(headers, 'webhook-id');
  const timestamp = header(headers, 'webhook-timestamp');
  const signatures = header(headers, 'webhook-signature');
  if (!id || !timestamp || !signatures) return { ok: false, reason: 'missing_headers' };
  if (!/^\d+$/.test(timestamp)) return { ok: false, reason: 'bad_timestamp' };
  // The timestamp is inside the signed string: an old delivery replayed later fails here, even with a valid signature.
  if (Math.abs(Math.floor(now / 1000) - Number(timestamp)) > toleranceSeconds) return { ok: false, reason: 'timestamp_out_of_tolerance' };
  const expected = Buffer.from(crypto.createHmac('sha256', key).update(`${id}.${timestamp}.`).update(rawBody).digest('base64'));
  for (const versioned of String(signatures).split(' ')) {
    const [version, value] = versioned.split(',');
    if (version !== 'v1' || value === undefined) continue;
    const given = Buffer.from(value);
    if (given.length === expected.length && crypto.timingSafeEqual(given, expected)) return { ok: true };
  }
  return { ok: false, reason: 'signature_mismatch' };
}

// A minimal receiver: verify, drop duplicates, answer 2xx fast, work afterwards.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const secret = process.env.GAI_WEBHOOK_SECRET;
  if (!secret) { console.error('set GAI_WEBHOOK_SECRET'); process.exit(1); }
  const seen = new Set();   // in production: a table with a unique key on webhook-id
  http.createServer((req, res) => {
    if (req.method !== 'POST' || req.url !== '/webhooks') { res.writeHead(404).end(); return; }
    const chunks = [];
    req.on('data', (c) => chunks.push(c));
    req.on('end', () => {
      const raw = Buffer.concat(chunks);
      const check = verifyGroceryAiSignature(raw, req.headers, secret);
      if (!check.ok) { res.writeHead(400).end(check.reason); return; }
      const event = JSON.parse(raw.toString('utf8'));
      res.writeHead(200).end('ok');   // within 15 seconds, or the attempt counts as failed
      if (seen.has(req.headers['webhook-id'])) return;
      seen.add(req.headers['webhook-id']);
      if (event.type === 'order.confirmed') console.log('order', event.data.order.id, event.environment);
      else if (event.type === 'support.requested') console.log('support request', event.data.support_request.id, event.data.support_request.kind);
      else if (event.type === 'webhook.ping') console.log('ping for endpoint', event.data.endpoint_id);
    });
  }).listen(Number(process.env.PORT ?? 8080));
}

```

### Verifica della firma senza dipendenze (Python) (`verify_signature.py`)

```python
"""Verify a GroceryAI webhook delivery (Standard Webhooks 1.0.0) with NO dependency. Python 3.8+, standard library only.

Prefer the official library (`pip install standardwebhooks`, see verify_standardwebhooks.py): this file does exactly what
it does, for a runtime where you cannot add a dependency. Specification: https://www.standardwebhooks.com

Every delivery is a POST with a JSON body and these headers:
  webhook-id         the message id = the event id (the same on every attempt: use it to drop duplicates)
  webhook-timestamp  Unix seconds of this attempt (it changes on every retry)
  webhook-signature  "v1,<base64>" HMAC-SHA256 of f"{webhook-id}.{webhook-timestamp}.{raw body}"; during a secret
                     rotation two of them, separated by a space: one matching is enough

The secret is the endpoint's signing secret exactly as the portal showed it: "whsec_" + base64. The HMAC key is the
base64-DECODED bytes, not the string. Verify on the RAW bytes of the body: parsing and re-serialising the JSON changes them.

With Flask, for example:

    @app.post("/webhooks")
    def webhooks():
        ok, reason = verify_signature(request.get_data(), request.headers, os.environ["GAI_WEBHOOK_SECRET"])
        if not ok:
            return reason, 400
        event = request.get_json()
        # drop duplicates by request.headers["webhook-id"], answer within 15 seconds, work afterwards
        return "ok", 200
"""

import base64
import binascii
import hashlib
import hmac
import time

# The tolerance of the official libraries: five minutes covers clock drift and slow networks.
TOLERANCE_SECONDS = 300

def verify_signature(raw_body, headers, secret, tolerance_seconds=TOLERANCE_SECONDS, now=None):
    """Return (True, "ok") or (False, reason).

    reason is one of: bad_secret, missing_headers, bad_timestamp, timestamp_out_of_tolerance, signature_mismatch.
    raw_body: bytes exactly as received; headers: any mapping (any case); secret: "whsec_..." included.
    """
    if not isinstance(secret, str) or not secret.startswith("whsec_"):
        return False, "bad_secret"
    try:
        key = base64.b64decode(secret[len("whsec_"):], validate=True)
    except (binascii.Error, ValueError):
        return False, "bad_secret"
    if not key:
        return False, "bad_secret"
    lowered = {str(k).lower(): v for k, v in dict(headers).items()}
    msg_id = lowered.get("webhook-id")
    timestamp = lowered.get("webhook-timestamp")
    signatures = lowered.get("webhook-signature")
    if not msg_id or not timestamp or not signatures:
        return False, "missing_headers"
    if not str(timestamp).isdigit():
        return False, "bad_timestamp"
    current = int(time.time()) if now is None else int(now)
    # The timestamp is inside the signed string: an old delivery replayed later fails here, even with a valid signature.
    if abs(current - int(timestamp)) > tolerance_seconds:
        return False, "timestamp_out_of_tolerance"
    if isinstance(raw_body, str):
        raw_body = raw_body.encode("utf-8")
    signed = str(msg_id).encode("utf-8") + b"." + str(timestamp).encode("ascii") + b"." + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode("ascii")
    for versioned in str(signatures).split(" "):
        version, _, value = versioned.partition(",")
        if version == "v1" and hmac.compare_digest(value, expected):
            return True, "ok"
    return False, "signature_mismatch"

```

### Ritiro in pull e conferma (Node) (`pull-orders.mjs`)

```javascript
// Take orders and support requests by pull, then acknowledge them. Node 18+, no dependencies.
//
//   GAI_API_KEY=gai_test_... node pull-orders.mjs
//
// The key needs `orders:read` (to list) and `orders:write` (to acknowledge). Its environment decides what you see:
// a `test` key sees test orders only, a `live` key real ones only. An item stays in `status=new` until you acknowledge
// it, so a crash between "saved" and "acknowledged" only means you will see it again: store by id, idempotently.

import { fileURLToPath } from 'node:url';

const BASE = process.env.GAI_API_BASE ?? 'https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api';
const KEY = process.env.GAI_API_KEY;

const call = async (method, path, idempotencyKey) => {
  // `x-region` runs the platform next to its database (Frankfurt): optional, it only saves latency.
  const headers = { authorization: `Bearer ${KEY}`, 'x-region': 'eu-central-1' };
  if (idempotencyKey) headers['idempotency-key'] = idempotencyKey;
  const res = await fetch(`${BASE}${path}`, { method, headers });
  const body = await res.json();
  if (res.status === 429) {
    const wait = Number(res.headers.get('retry-after') ?? '60');
    await new Promise((r) => setTimeout(r, wait * 1000));
    return call(method, path, idempotencyKey);
  }
  if (!res.ok) throw new Error(`${method} ${path}: ${res.status} ${body.error?.code} (request_id ${body.request_id})`);
  return body;
};

/** Your side: save the item. Must be idempotent on the id (the same item can come twice). */
const save = async (kind, id, payload) => {
  console.log(`saved ${kind} ${id}`, kind === 'order' ? `${payload.order.lines.length} lines` : payload.support_request.kind);
};

export const pullOnce = async () => {
  let handled = 0;
  const done = new Set();
  for (const [kind, list, idField, ack] of [
    ['order', '/v1/orders', 'order_id', (id) => `/v1/orders/${encodeURIComponent(id)}/ack`],
    ['support request', '/v1/support_requests', 'support_id', (id) => `/v1/support_requests/${encodeURIComponent(id)}/ack`],
  ]) {
    // Oldest first, up to 200 per call; acknowledging is what moves the queue forward.
    for (;;) {
      const page = await call('GET', `${list}?status=new&limit=50`);
      if (page.data.length === 0) break;
      for (const item of page.data) {
        // An item acknowledged in this run must not come back: if it does, stop instead of looping.
        if (done.has(item.event_id)) throw new Error(`${kind} ${item[idField]} is still new after its ack`);
        done.add(item.event_id);
        await save(kind, item[idField], item.payload);
        // Acknowledging twice is not an error; the idempotency key makes a retried call harmless.
        await call('POST', ack(item[idField]), `ack-${item.event_id}`);
        handled++;
      }
    }
  }
  return handled;
};

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  if (!KEY) { console.error('set GAI_API_KEY'); process.exit(1); }
  pullOnce().then((n) => console.log(`done: ${n} acknowledged`)).catch((e) => { console.error(e.message); process.exit(1); });
}

```
