# Spoonity Offers API

Spoonity Offers is the promotions engine. A kiosk, POS, ordering app or
partner sends it a cart; it decides which promotions and loyalty rewards
apply, how they combine, and exactly how much comes off which line. The
caller displays what it is given and submits it as-is. It never computes a
discount itself.

Two kinds of offer are evaluated together, in one pass:

- **Merchant promotions**: promo codes, automatic deals, spend tiers, combos,
  happy hours. They cost no points and are usually open to guests. They live
  in the engine's own catalog and are managed with the
  [admin catalog API](#admin-catalog-api) below (Prism's Promotions section
  uses the same API).
- **Loyalty rewards**: point-cost rewards defined in the Spoonity loyalty
  program. The engine reads them from the loyalty platform; they are
  read-only here.

**Base URL:** `https://offers.spoonity.com`

Machine-readable spec: [openapi/offers.yaml](openapi/offers.yaml)
(OpenAPI 3.1).

## How the engine decides

The same input always produces the same output. These rules hold on every
surface on this page.

- **Integer cents.** Every amount in a request and a response is an integer
  number of cents (`1149` is $11.49). A decimal is a `400`. The one exception
  is `order_payload` in the evaluate response, which is in decimal dollars
  because it is built for the loyalty platform's order endpoint.
- **Pre-tax.** Every subtotal, discount and total is before tax. Tax is
  applied downstream by the POS or loyalty platform.
- **Deterministic.** The engine takes the clock as an input and never reads
  it mid-evaluation. Ties are broken by explicit rules (price, then cart
  position, then offer id), not by iteration order.
- **One discount per unit.** A cart line with `quantity: 3` is three units.
  Each unit can carry at most one item-level discount. Item-level offers are
  applied first; order-level offers then apply to what is left.
- **Allocation that adds up.** An order-level discount is spread across the
  lines with a largest-remainder method, so the per-line `allocations` always
  sum to the discount.
- **Stacking.** Arbitration order is: offers the guest selected or unlocked
  with a code, then higher `stacking.priority`, then the higher standalone
  value for this cart, then offer id. Three controls limit combination:
  - `stacking.exclusive: true`: once an exclusive offer applies, every other
    requested offer is skipped with `EXCLUSIVE_CONFLICT`.
  - `stacking.group`: one applied offer per group; the rest are skipped with
    `GROUP_CONFLICT`.
  - The vendor's [promotion policy](#the-promotion-policy): a cap on applied
    offers (`MAX_OFFERS_REACHED`), a cap on the order discount as a percent
    (`ORDER_CAP_REACHED`), and whether order-level percentages cascade or add.
- **Reason codes.** Every offer in a response has exactly one status:
  `applied`, `applicable` (would apply if selected), `inapplicable` (failed
  an eligibility check) or `skipped` (lost arbitration). An offer that did not
  apply carries `reason: { code, message, ... }`. `code` is stable and
  machine-readable; `message` is display text for a guest or cashier. See
  [Reason codes](#reason-codes).
- **Discounts the POS already applied.** A line may carry `discounts` the
  register applied itself (employee, manager, senior). Order-level discounts
  are always computed on the total after them, and by default the engine does
  not add an item-level discount to such a line (`LOCALLY_DISCOUNTED`).

## Surfaces

| Surface | Paths | Who calls it | Credential |
|---|---|---|---|
| Evaluate and lifecycle | `/v1/evaluate`, `/v1/offers`, `/v1/redemptions/*`, `/v1/locks/*` | A kiosk, ordering app or channel backend that builds the cart itself | Vendor API key |
| Admin catalog | `/v1/admin/*` | A merchant's back office, or Prism | Vendor API key, or OIDC service identity |
| POS check | `/partners/pos/*` | A POS that sends the whole check at pay time | `X-Spoonity-POS-Key` |
| Health | `/readyz` | Monitoring | None |

## Authentication

Offers accepts three credentials. Which one applies depends on the path.
[Authentication](authentication.md#offers) covers them alongside the other
services.

### Vendor API key (`/v1/*`)

Send the key in either header:

```
X-API-Key: YOUR_OFFERS_API_KEY
```

```
Authorization: Bearer YOUR_OFFERS_API_KEY
```

`X-API-Key` is checked first. The key determines the vendor; no request
carries a vendor id. Keys are issued by Spoonity. There is no self-service
key page for Offers in Prism.

The key must be in a header. On `offers.spoonity.com` a request with
`?api_key=` in the URL is refused with `401 UNAUTHORIZED` even when the key
is correct, because URLs are written to request logs.

An API key has no role, so it can call every `/v1/*` route, including admin
writes.

### POS key (`/partners/pos/*`)

```
X-Spoonity-POS-Key: YOUR_POS_KEY
```

One key per merchant. The key alone determines the merchant; a vendor id in
the body is never read. A missing or unknown key is `401 UNAUTHORIZED`. The
`/v1` credentials are not accepted on `/partners/pos`, and a POS key is not
accepted on `/v1`.

### OIDC service identity (trusted Spoonity services)

Trusted Spoonity services such as Prism's BFF call `/v1/*` with a
Google-signed ID token instead of a key. This path is not available to
external integrators; it is listed so the headers you see Prism send make
sense.

| Header | Required | Meaning |
|---|---|---|
| `Authorization: Bearer <Google ID token>` | Yes | Token for an allow-listed service account, with this service as the audience |
| `X-Spoonity-Vendor` | Yes, `^[A-Za-z0-9_-]{1,64}$` | The vendor the call acts for. Missing or malformed is `401` |
| `X-Spoonity-User` | No, 1 to 256 printable characters | The person acting; stamped on `created_by` / `updated_by` |
| `X-Spoonity-Role` | No | Exactly `admin`, `editor` or `viewer`. Absent, or any other value, is treated as `viewer` |

A `viewer` gets `403 FORBIDDEN` on every non-GET `/v1/admin/*` route except
`POST /v1/admin/promotions/simulate`, which has no side effects.

## Conventions

- **Errors** use one envelope everywhere on this service:

  ```json
  { "error": { "code": "INVALID_REQUEST", "message": "Promotion validation failed",
      "issues": [ { "path": "discount_amount", "message": "percent discounts must be between 0 and 100" } ] } }
  ```

  `code` is the stable part. `issues[]` appears on validation errors, one
  entry per field. Some codes add fields (`version`, `conflict_offer_ids`,
  `state`); each endpoint lists them. This differs from CMS and Links, whose
  `error` is a string; see [Conventions](conventions.md#error-envelope).
- **Unknown fields.** Admin and POS request bodies reject unknown fields with
  `400`, so a typo cannot silently change a promotion. `POST /v1/evaluate`
  ignores fields it does not know.
- **Limits.** 200 lines per cart, 1 to 1000 units per line, 2000 units per
  cart, amounts 0 to 100,000,000 cents, at most 50 entries in `codes`,
  `selected`, `categories` and `modifiers`. Over any limit is a `400`.
- **Identifiers.** `evaluation_id`, promotion `identifier`, `requires_code`
  and `stacking.group` are 1 to 128 characters from `A-Z a-z 0-9 _ . : -`.
  SKUs, category ids and other ids you own are 1 to 128 characters of
  anything.
- **Timestamps.** Promotion, policy and redemption records use epoch
  milliseconds (`created_at`, `updated_at`, `committed_at`). Lock and hold
  expiries are ISO 8601 strings. Usage days are `YYYY-MM-DD` UTC dates.
- **Versioning.** The version is in the path (`/v1`). There is no version
  header.
- **Request ids.** Every response carries `X-Request-Id`. Send your own
  `X-Request-Id` to have it echoed and logged; quote it when reporting a
  problem.
- **Fail open.** A `503 OFFERS_UNAVAILABLE` means the engine could not read
  what it needs (catalog, policy, database). It is retryable. A checkout that
  receives it should proceed at full price rather than block the guest.

## Evaluate and lifecycle

A device that builds its own cart uses this surface. The loop:

1. **Evaluate on every change.** Call `POST /v1/evaluate` whenever the cart
   or the guest's selection changes. Reuse one `evaluation_id` for the whole
   checkout attempt; each call replaces the previous result for that id.
   Always send the full current cart and selection.
2. **Lock before payment.** Call it once more with `lock: { ttl_seconds }`.
   This reserves single-use offers so a concurrent order cannot take them,
   and records a `pending` redemption. The response carries `redemption_id`
   and `lock`.
3. **Submit the order.** Send `order_payload` to the loyalty platform
   unchanged. Its `receipt_number` is the `evaluation_id`.
4. **Commit is event-driven.** When the order lands, an `order.submitted`
   event posted to [`/webhooks/events`](#post-webhooksevents) turns the
   pending redemption into `committed`. A device never calls a commit
   endpoint. A pending redemption that is never committed expires when its
   hold lapses, and an expired one does not count against single-use offers
   or usage limits.
5. **Undo when needed.** Release an abandoned lock with
   `DELETE /v1/locks/{key}`, or roll back, cancel or partially return a
   redemption with the `/v1/redemptions/{id}` routes.

Redemption states:

```
pending --commit--> committed --return--> partially_returned
   |                    |                        |
   |                    +--------rollback--------+--> rolled_back
   +--cancel / void--> cancelled
   +--hold lapses----> expired
```

`rolled_back`, `cancelled` and `expired` are terminal. A commit that arrives
after the hold expired is refused and the record expires, so a lapsed hold
can never commit. Usage limits and budgets are computed from committed
records, so a rollback restores both the use and the budget. A partial return
restores neither.

### POST /v1/evaluate

Price a cart against the vendor's promotions and loyalty rewards.

**Auth:** Vendor API key, or OIDC service identity.

#### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `evaluation_id` | string | Yes | Your id for this checkout attempt. Reuse it on every call for the attempt. Becomes `order_payload.receipt_number` |
| `cart.line_items[]` | array | Yes | 1 to 200 lines, see below |
| `customer.identifier` | string | | Loyalty customer identifier. Resolves tier, segments, balances and pre-selected rewards when the vendor's loyalty program is connected to Offers; otherwise the cart is priced for a guest |
| `customer.pos_session_hash` | string | | Alternative identifier from a POS session |
| `customer.order_count` | integer | | Orders the customer has placed, if you know it. A value the loyalty platform resolves wins |
| `customer.tags` | string[] | | Customer tags, if you know them. A resolved list wins |
| `codes` | string[] | | Promo codes the guest entered |
| `selected` | string[] | | Offer ids the guest chose (typically point-cost rewards) |
| `selection_mode` | string | | `manual` (default): only selected, code-unlocked and auto-apply offers apply. `automatic`: every eligible offer is treated as requested. `list`: nothing applies; eligible offers come back `applicable`, for a picker UI |
| `store_id` | string | | Store, for store-restricted offers |
| `channel` | string | | Channel, for example `kiosk`, `web`, `pos` |
| `lock.ttl_seconds` | integer | | 1 to 3600. Marks this as the final evaluate before payment: reserves single-use offers and records a pending redemption |

A line is `{ line_id, id, name?, categories?, price, quantity, modifiers?, discounts? }`:

| Field | Type | Description |
|---|---|---|
| `line_id` | string | Unique within the cart |
| `id` | string | Your SKU or PLU. Promotions target it through `products` |
| `categories[]` | `{ id, name? }` | Promotions target these through `categories` |
| `price` | integer cents | Unit price excluding modifiers |
| `quantity` | integer | 1 to 1000 |
| `modifiers[]` | `{ id, name?, price, quantity }` | Unit price and quantity per modifier |
| `discounts[]` | `{ id, name?, amount, source? }` | Discounts the POS already applied to the whole line, cents. At most 10. `source` is `pos` (default) or `external` |

#### Example request

```bash
curl -X POST https://offers.spoonity.com/v1/evaluate \
  -H "X-API-Key: YOUR_OFFERS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "evaluation_id": "K12-000482",
    "channel": "kiosk",
    "store_id": "store_12",
    "customer": { "identifier": "cust_1001" },
    "codes": ["WELCOME3"],
    "selected": ["reward_free_cookie"],
    "cart": {
      "line_items": [
        { "line_id": "1", "id": "cola", "name": "Cola", "categories": [{ "id": "drinks" }], "price": 279, "quantity": 2 },
        { "line_id": "2", "id": "cookie", "name": "Cookie", "categories": [{ "id": "desserts" }], "price": 199, "quantity": 1 }
      ]
    }
  }'
```

#### Example response

`200`. The free cookie (a 150-point loyalty reward the guest selected) and a
$3 code both applied. "20% off drinks" and the combo are `applicable`: they
would apply if requested (the combo still needs a main and a side). The spend
tier is not reached.

```json
{
  "evaluation_id": "K12-000482",
  "offers": [
    {
      "offer_id": "reward_free_cookie",
      "name": "Free Cookie (150 pts)",
      "status": "applied",
      "source": { "type": "redemption", "vendor_perk_redemption_id": 501 },
      "pos_reference": "discount_free_cookie",
      "cost_points": 150,
      "discount_total": 199
    },
    {
      "offer_id": "promo_WELCOME3",
      "name": "$3 Off with Code WELCOME3",
      "status": "applied",
      "source": { "type": "promotion_code", "code": "WELCOME3" },
      "pos_reference": "discount_promo_WELCOME3",
      "funding": "restaurant",
      "discount_total": 300
    },
    {
      "offer_id": "promo_DRINKS20",
      "name": "20% off drinks",
      "status": "applicable",
      "source": { "type": "promotion_code" },
      "pos_reference": "discount_promo_DRINKS20",
      "discount_total": 112
    },
    {
      "offer_id": "promo_SPEND20",
      "name": "Spend more, save more",
      "status": "inapplicable",
      "source": { "type": "promotion_code" },
      "pos_reference": "discount_promo_SPEND20",
      "reason": {
        "code": "TIER_NOT_REACHED",
        "message": "Spend $20.00 to unlock",
        "next_min_spend": 2000,
        "shortfall": 1243
      }
    },
    {
      "offer_id": "promo_LUNCHCOMBO",
      "name": "Lunch combo $10.99",
      "status": "applicable",
      "source": { "type": "promotion_code" },
      "pos_reference": "discount_promo_LUNCHCOMBO",
      "reason": {
        "code": "BUNDLE_INCOMPLETE",
        "message": "Add the remaining items to complete this combo",
        "missing": [
          { "component": 0, "required": 1, "available": 0 },
          { "component": 1, "required": 1, "available": 0 }
        ]
      }
    }
  ],
  "cart": {
    "line_items": [
      {
        "line_id": "1", "id": "cola", "name": "Cola", "categories": [{ "id": "drinks" }],
        "price": 279, "quantity": 2, "discounts": []
      },
      {
        "line_id": "2", "id": "cookie", "name": "Cookie", "categories": [{ "id": "desserts" }],
        "price": 199, "quantity": 1,
        "discounts": [
          { "id": "discount_free_cookie", "name": "Free Cookie (150 pts)", "amount": 199,
            "offer_id": "reward_free_cookie", "unit_index": 0, "quantity": 1 }
        ]
      }
    ],
    "discounts": [
      { "id": "discount_promo_WELCOME3", "name": "$3 Off with Code WELCOME3", "amount": 300, "offer_id": "promo_WELCOME3" }
    ],
    "allocations": [
      { "line_id": "1", "offer_id": "promo_WELCOME3", "amount": 300 }
    ],
    "subtotal": 757,
    "discount_total": 499,
    "total": 258
  },
  "effects": [
    {
      "type": "order_discount",
      "offer_id": "promo_WELCOME3",
      "amount": 300,
      "pos_reference": "discount_promo_WELCOME3",
      "allocations": [{ "line_id": "1", "offer_id": "promo_WELCOME3", "amount": 300 }],
      "funding": "restaurant"
    },
    {
      "type": "item_discount",
      "offer_id": "reward_free_cookie",
      "line_id": "2",
      "unit_index": 0,
      "quantity": 1,
      "amount": 199,
      "pos_reference": "discount_free_cookie"
    }
  ],
  "receipt_lines": [
    "Free Cookie (150 pts) applied \u2014 you saved $1.99",
    "$3 Off with Code WELCOME3 applied \u2014 you saved $3.00"
  ],
  "lock": null,
  "redemption_id": null,
  "accrual_preview": null,
  "order_payload": {
    "receipt_number": "K12-000482",
    "subtotal": 7.57,
    "total": 2.58,
    "line_items": [
      { "id": "cola", "name": "Cola", "categories": [{ "id": "drinks" }], "price": 2.79, "quantity": 2, "discounts": [] },
      { "id": "cookie", "name": "Cookie", "categories": [{ "id": "desserts" }], "price": 1.99, "quantity": 1,
        "discounts": [{ "id": "discount_free_cookie", "name": "Free Cookie (150 pts)", "amount": 1.99 }] }
    ],
    "discounts": [
      { "id": "discount_promo_WELCOME3", "name": "$3 Off with Code WELCOME3", "amount": 3 }
    ]
  }
}
```

The same request with `"lock": { "ttl_seconds": 300 }` returns the same
body with these three fields filled in:

```json
{
  "evaluation_id": "K12-000482",
  "lock": { "key": "lock_73effdbf-a2b9-463c-b462-0a2a03032669", "expires_at": "2026-09-30T10:35:19.390Z" },
  "redemption_id": "ored_24b5aabb-89dc-4684-85c7-0fa6b84937b0"
}
```

Reading the response:

- `offers[]`: every candidate offer with its status. Code-gated offers whose
  code was not entered are left out entirely.
- `cart`: the repriced cart. Item discounts are on `line_items[].discounts`
  (`id` is the `pos_reference`), order discounts on `cart.discounts`, and
  `allocations` spreads each order discount across lines for refunds.
  `total` is `subtotal` minus `external_discount_total` (present only when
  lines carried POS discounts) minus `discount_total`.
- `effects[]`: the same result as instructions for a POS:
  `item_discount` (line, first unit, unit count, amount), `order_discount`
  (amount plus allocations) and `add_item_hint` (a free item offer whose SKU
  is not in the cart; also shown as `add_item_hint: { sku }` on the offer).
  `funding` is `restaurant`, `channel`, `shared` or `loyalty`; absent means
  `restaurant`. It is attribution only and never changes the amounts.
- `receipt_lines`: printable lines. Treat them as display text; the wording
  can change. The engine separates the two halves with a dash character,
  shown escaped above.
- `lock` and `redemption_id`: `null` unless `lock` was requested and the
  result has something to record.
- `accrual_preview`: an estimate of points earned, when the loyalty source
  provides an earn rate; otherwise `null`. The loyalty platform is
  authoritative.
- `order_payload`: decimal dollars, for the loyalty platform's order
  endpoint. Submit it verbatim.

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | Body failed validation; `issues[]` says where |
| 401 | `UNAUTHORIZED` | Missing or invalid credential, or `?api_key=` in production |
| 409 | `OFFERS_RESERVED` | With `lock`: another in-flight order holds one of the single-use offers. Carries `conflict_offer_ids`. Evaluate again; the next result prices without that offer |
| 409 | `EVALUATION_TERMINAL` | With `lock`: this `evaluation_id` is already `committed`, `cancelled`, `rolled_back` or `expired`. Carries `state`. Start a new `evaluation_id` |
| 503 | `OFFERS_UNAVAILABLE` | The catalog or the vendor's policy could not be read. Retryable; proceed without discounts |

### GET /v1/offers

List the vendor's offers without pricing a cart, for a rewards screen.

**Auth:** Vendor API key, or OIDC service identity.

#### Query parameters

| Name | Type | Description |
|---|---|---|
| `customer` | string | Loyalty customer identifier |
| `store_id` | string | Store |
| `channel` | string | Channel |

Code-gated offers are never listed. There is no status or reason here; call
`POST /v1/evaluate` with `selection_mode: "list"` for that.

#### Example request

```bash
curl "https://offers.spoonity.com/v1/offers?customer=cust_1001&channel=kiosk" \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

```json
{
  "offers": [
    { "offer_id": "reward_free_cookie", "name": "Free Cookie (150 pts)", "cost_points": 150,
      "pos_reference": "discount_free_cookie", "effect_type": "free_item", "requires_code": false },
    { "offer_id": "promo_DRINKS20", "name": "20% off drinks",
      "pos_reference": "discount_promo_DRINKS20", "effect_type": "percent_off", "requires_code": false },
    { "offer_id": "promo_SPEND20", "name": "Spend more, save more",
      "pos_reference": "discount_promo_SPEND20", "effect_type": "tiered", "requires_code": false },
    { "offer_id": "promo_LUNCHCOMBO", "name": "Lunch combo $10.99",
      "pos_reference": "discount_promo_LUNCHCOMBO", "effect_type": "bundle", "requires_code": false }
  ]
}
```

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | Invalid query parameter |
| 401 | `UNAUTHORIZED` | Missing or invalid credential |

### GET /v1/redemptions/{id}

Read one redemption record.

**Auth:** Vendor API key, or OIDC service identity. A redemption that
belongs to another vendor is a `404`, the same as one that does not exist.

#### Path parameters

| Name | Description |
|---|---|
| `id` | `redemption_id` from a locked evaluate (`ored_...`) |

#### Example request

```bash
curl https://offers.spoonity.com/v1/redemptions/ored_24b5aabb-89dc-4684-85c7-0fa6b84937b0 \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

The redemption from the locked evaluate above, after the order was
submitted:

```json
{
  "redemption": {
    "redemption_id": "ored_24b5aabb-89dc-4684-85c7-0fa6b84937b0",
    "vendor_id": "dev-vendor",
    "evaluation_id": "K12-000482",
    "state": "committed",
    "offers": [
      {
        "offer_id": "reward_free_cookie",
        "version": 3,
        "pos_reference": "discount_free_cookie",
        "discount_total": 199,
        "single_use": false,
        "line_discounts": [
          { "id": "discount_free_cookie", "name": "Free Cookie (150 pts)", "amount": 199,
            "offer_id": "reward_free_cookie", "unit_index": 0, "quantity": 1, "line_id": "2" }
        ]
      },
      {
        "offer_id": "promo_WELCOME3",
        "version": 1,
        "pos_reference": "discount_promo_WELCOME3",
        "discount_total": 300,
        "single_use": false,
        "allocations": [{ "line_id": "1", "offer_id": "promo_WELCOME3", "amount": 300 }]
      }
    ],
    "cart_snapshot": {
      "line_items": [
        { "line_id": "1", "id": "cola", "name": "Cola", "categories": [{ "id": "drinks" }],
          "price": 279, "quantity": 2, "discounts": [] },
        { "line_id": "2", "id": "cookie", "name": "Cookie", "categories": [{ "id": "desserts" }],
          "price": 199, "quantity": 1,
          "discounts": [{ "id": "discount_free_cookie", "name": "Free Cookie (150 pts)", "amount": 199,
                          "offer_id": "reward_free_cookie", "unit_index": 0, "quantity": 1 }] }
      ],
      "discounts": [{ "id": "discount_promo_WELCOME3", "name": "$3 Off with Code WELCOME3", "amount": 300, "offer_id": "promo_WELCOME3" }],
      "allocations": [{ "line_id": "1", "offer_id": "promo_WELCOME3", "amount": 300 }],
      "subtotal": 757,
      "discount_total": 499,
      "total": 258
    },
    "customer_id": "cust_1001",
    "created_at": 1790764219390,
    "expires_at": 1790764519390,
    "revision": 3,
    "lock_key": "lock_73effdbf-a2b9-463c-b462-0a2a03032669",
    "committed_at": 1790764226347,
    "order_reference": "ord_88213"
  }
}
```

`vendor_id` is the vendor the key belongs to. `mismatch` appears when the
submitted order's discount ids differed from what was evaluated; the record
still commits. `rolled_back_at`, `cancelled_at` and `returned_line_ids`
appear once set.

#### Errors

| Status | Code | When |
|---|---|---|
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 404 | `NOT_FOUND` | No such redemption for this vendor |

### POST /v1/redemptions/{id}/rollback

Void a redemption: the order was refunded or voided. Single-use offers,
usage counts and budget come back.

**Auth:** Vendor API key, or OIDC service identity.

A committed or partially returned record becomes `rolled_back`; a pending
one becomes `cancelled`. Calling it again is safe. A state that does not
allow the transition is returned unchanged.

#### Example request

```bash
curl -X POST https://offers.spoonity.com/v1/redemptions/ored_24b5aabb-89dc-4684-85c7-0fa6b84937b0/rollback \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

```json
{ "redemption": { "redemption_id": "ored_24b5aabb-89dc-4684-85c7-0fa6b84937b0", "state": "rolled_back" } }
```

#### Errors

| Status | Code | When |
|---|---|---|
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 404 | `NOT_FOUND` | No such redemption for this vendor |

### POST /v1/redemptions/{id}/cancel

Cancel a pending redemption and release its hold: the guest abandoned the
order. A cancelled record can never commit.

**Auth:** Vendor API key, or OIDC service identity.

Only a `pending` record changes; any other state is returned unchanged.

#### Example request

```bash
curl -X POST https://offers.spoonity.com/v1/redemptions/ored_bbfb7ca3-21c8-48aa-9dc3-137047d550fe/cancel \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

```json
{ "redemption": { "redemption_id": "ored_bbfb7ca3-21c8-48aa-9dc3-137047d550fe", "state": "cancelled" } }
```

#### Errors

| Status | Code | When |
|---|---|---|
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 404 | `NOT_FOUND` | No such redemption for this vendor |

### POST /v1/redemptions/{id}/returns

Record a partial return by line. Reports the discount that was on each
returned line, for a refund clawback.

**Auth:** Vendor API key, or OIDC service identity.

#### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `line_ids` | string[] | Yes | 1 to 200 `line_id` values from the evaluated cart. A line already returned contributes nothing the second time |

The record becomes `partially_returned`. Single-use offers are not restored
and the budget is not refunded: that money left the business on a paid
order. Use rollback for a full void.

#### Example request

```bash
curl -X POST https://offers.spoonity.com/v1/redemptions/ored_24b5aabb-89dc-4684-85c7-0fa6b84937b0/returns \
  -H "X-API-Key: YOUR_OFFERS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "line_ids": ["2"] }'
```

#### Example response

```json
{
  "redemption": { "redemption_id": "ored_24b5aabb-89dc-4684-85c7-0fa6b84937b0", "state": "partially_returned" },
  "returned": [{ "line_id": "2", "offer_id": "reward_free_cookie", "discount_amount": 199 }]
}
```

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | `line_ids` missing or empty |
| 400 | `UNKNOWN_LINES` | Some ids are not in this redemption. Carries `unknown_line_ids` |
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 404 | `NOT_FOUND` | No such redemption for this vendor |
| 409 | `INVALID_STATE` | The record is not `committed` or `partially_returned` |

### DELETE /v1/locks/{key}

Release a lock and cancel its redemption: the guest cancelled before paying.

**Auth:** Vendor API key, or OIDC service identity.

#### Path parameters

| Name | Description |
|---|---|
| `key` | `lock.key` from a locked evaluate (`lock_...`) |

#### Example request

```bash
curl -X DELETE https://offers.spoonity.com/v1/locks/lock_2cbb388d-4c86-490e-b9a0-7c71aea9154d \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

```json
{ "released": true, "redemption": { "redemption_id": "ored_e7bf6215-68bd-470f-bf19-f63baa7e2c35", "state": "cancelled" } }
```

#### Errors

| Status | Code | When |
|---|---|---|
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 404 | `NOT_FOUND` | Unknown, already released or expired lock, or another vendor's |

### POST /webhooks/events

How a pending redemption commits or voids: `order.submitted` after an order
carrying the `order_payload` lands, and `order.voided` when it is voided. It
is correlated on `receipt_number == evaluation_id`.

**Auth:** A shared secret in `x-webhook-secret`, held by Spoonity. Not the
`/v1` credentials. This route is listed so the lifecycle is complete; an
integrator does not call it directly. Before relying on single-use offers or
usage limits through `/v1/evaluate`, confirm with Spoonity that these events
are being sent for your vendor. The POS check surface does not depend on
them: `close` commits directly.

| Field | Type | Description |
|---|---|---|
| `type` | string | `order.submitted` or `order.voided` |
| `vendor_id` | string | Vendor |
| `receipt_number` | string | The `evaluation_id` |
| `discount_ids` | string[] | `order.submitted` only: the discount ids on the order, compared with what was evaluated |
| `order_reference` | string | `order.submitted` only: the order id, stored on the record |
| `event_id` | string | De-duplication key; a repeated event is a no-op |

The answer is always `200` for a valid event, including one whose receipt
has no redemption (orders without offers are normal):

```json
{ "processed": true, "redemption": { "redemption_id": "ored_24b5aabb-89dc-4684-85c7-0fa6b84937b0", "state": "committed", "mismatch": null } }
```

A bad secret is `401 UNAUTHORIZED`. An invalid payload is
`400 INVALID_REQUEST`, and on this route `issues[]` is a list of strings
rather than `{ path, message }` objects.

## Admin catalog API

Manage merchant promotions, the vendor's promotion policy, and read-only
loyalty rewards. Prism's Promotions section is built on these routes.

Every route is scoped to the calling vendor. A promotion id that belongs to
another vendor answers `404`, exactly like one that does not exist. Every
non-GET route answers `403 FORBIDDEN` to an OIDC caller with the `viewer`
role, except simulate.

A promotion is evaluated as the offer `promo_<promotion_id>`, and lands on
the POS as `pos_reference` (default `discount_promo_<promotion_id>`).

**Statuses:** `draft` (never evaluated), `active` (live, subject to its own
schedule), `paused` (withdrawn, definition kept), `archived` (retired and
read-only; never deleted, because redemptions reference its versions).
Every write, including a status change, bumps `version` and appends a
history entry. There is no delete.

**Caching:** evaluation reads the catalog through a cache of up to 5 seconds,
so an edit can take that long to affect `POST /v1/evaluate` and the POS
check. Admin reads and simulate see it at once.

### The promotion object

Request and response bodies use the same field names, so a GET body minus
the read-only fields (`promotion_id`, `vendor_id`, `status`, `version`,
`created_at`, `updated_at`, `created_by`, `updated_by`) is a valid PUT body.
Money is integer cents wherever a field is not a percent.

#### Identity and lifecycle

| Field | Type | Description |
|---|---|---|
| `identifier` | string | Optional on create: your id for the promotion. Minted when omitted. `new`, `simulate`, `policy`, `loyalty-rewards`, `history`, `usage`, `.` and `..` are reserved (any case) |
| `name` | string | Guest-facing name, 1 to 256 characters. Required |
| `notes` | string | Operator note, up to 2000 characters |
| `status` | string | On create only: `draft`, `active` or `paused`. Use the lifecycle routes afterwards |
| `expected_version` | integer | Required on PUT. Refused on create |
| `pos_reference` | string | POS discount identifier. Default `discount_promo_<promotion_id>` |

#### Effect: `discount_type`

Each type accepts only its own fields; a field that belongs to another type
is a `400`.

| `discount_type` | Fields | Effect |
|---|---|---|
| `PERCENT` | `discount_amount` (0 to 100), `scope`, `amount_limit`, `max_quantity`, `min_quantity`, `modifier_policy` | Percent off the targeted items (`scope: "item"`) or the order (`scope: "order"`). `amount_limit` caps the total discount in cents |
| `AMOUNT` | `discount_amount` (cents), `scope`, `max_quantity`, `min_quantity`, `modifier_policy` | Cents off each targeted unit (`item`) or off the order (`order`) |
| `FIXED_PRICE` | `discount_amount` (cents), `max_quantity`, `include_modifiers` | Targeted units sell at this price. By default the price replaces the item price and modifiers are charged on top; `include_modifiers: true` makes it cover item and modifiers |
| `FREE_ITEM` | `free_item_sku`, `max_quantity` | Zeroes that SKU when it is in the cart. When it is not, the offer is `applicable` with an `add_item_hint` |
| `BUY_X_GET_Y` | `bogo` | Buy the trigger set, get the reward set free or at `percent` off. See below |
| `TIERED` | `spend_tiers` | Order-level discount by spend threshold. See below |
| `BUNDLE` | `bundle` | Combo price for one complete set of components. See below |

Item-scope knobs on `PERCENT` and `AMOUNT`:

- `scope`: `item` or `order`. When omitted, `products` or `categories`
  implies `item`, otherwise `order`.
- `max_quantity`: at most this many units discounted per application.
- `min_quantity`: apply only with at least this many eligible units, else
  `MIN_QUANTITY_NOT_MET`.
- `modifier_policy`: `include` (default) computes on item plus modifiers;
  `exclude` on the item price alone.

These three are refused on an order-scope effect.

`bogo`:

```json
{
  "trigger": { "categories": ["drinks"], "quantity": 1 },
  "reward":  { "categories": ["drinks"], "quantity": 1, "percent": 100 },
  "selection": "cheapest",
  "max_applications": 2
}
```

`trigger` and `reward` take `products`, `categories`, `exclude_products`,
`exclude_categories` and `quantity` (1 to 1000). `reward.percent` defaults
to 100. `selection` is `cheapest` (default) or `most_expensive`.
`max_applications` is 1 to 100.

`spend_tiers` (1 to 20 tiers, distinct `min_spend`):

```json
[
  { "min_spend": 2000, "amount": 300 },
  { "min_spend": 4000, "percent": 15, "amount_limit": 1000 }
]
```

Each tier has exactly one of `percent` or `amount`; `amount_limit` caps a
percent tier only. The highest tier reached applies. None reached is
`TIER_NOT_REACHED` with `next_min_spend` and `shortfall`. A tiered promotion
always discounts the order, so it takes no `scope` and no top-level
`products` or `categories`. The field is `spend_tiers`, not `tiers`, because
`tiers` is the loyalty-tier restriction below.

`bundle`:

```json
{
  "components": [
    { "categories": ["mains"], "quantity": 1 },
    { "categories": ["sides"], "quantity": 1 },
    { "categories": ["drinks"], "quantity": 1 }
  ],
  "price": 1099,
  "max_applications": 1,
  "selection": "most_expensive"
}
```

1 to 10 components, each with the same item filters as a `bogo` side plus
`quantity`. `price` is the combo price in cents. `selection` picks which
units fill each component: `cheapest` (default) or `most_expensive`. With
`cheapest`, sets are taken until one would not be discounted, so a combo
whose cheapest set already costs less than `price` gives nothing even when
pricier units are in the cart; choose `most_expensive` if the combo should
always apply when the cart is worth more. An incomplete set is
`BUNDLE_INCOMPLETE` with `missing[]`. Item filters go on the components;
top-level `products` or `categories` are refused.

#### Targeting

| Field | Type | Description |
|---|---|---|
| `products` | string[] | SKUs (cart line `id`) that can receive the discount |
| `categories` | string[] | Category ids that can receive the discount |
| `exclude_products` | string[] | SKUs that never receive it |
| `exclude_categories` | string[] | Categories that never receive it |

Exclusions win over inclusions. Up to 50 entries each.

#### Conditions

| Field | Type | Description |
|---|---|---|
| `min_spend` | integer cents | Minimum subtotal, else `MIN_SPEND_NOT_MET` with `shortfall`. The vendor policy's `min_spend_basis` decides which subtotal |
| `tiers` | string[] | Loyalty tier ids allowed, else `TIER_NOT_ELIGIBLE` |
| `segments` | string[] | Customer segments allowed, else `CONDITION_NOT_MET` |
| `first_order_only` | boolean | Only for a customer with no previous orders. Fails closed when the order count is unknown |
| `customer_tags` | string[] | The customer carries at least one of these tags (1 to 50, up to 64 characters each) |
| `requires_customer` | boolean | Refuse unidentified guests with `CUSTOMER_REQUIRED`. Default false: promotions are open to guests |

#### Schedule and placement

| Field | Type | Description |
|---|---|---|
| `active` | `{ start?, end? }` | ISO 8601 instants with offset. Outside it: `OUTSIDE_ACTIVE_WINDOW` |
| `dayparts` | array | `[{ days?, start?, end? }]`. `days` 0 (Sunday) to 6; `start` inclusive and `end` exclusive, `HH:MM` 24-hour. Outside every daypart: `OUTSIDE_DAYPART` |
| `stores` | string[] | Store ids allowed, else `STORE_NOT_ELIGIBLE` |
| `channels` | string[] | Channels allowed, else `CHANNEL_NOT_ELIGIBLE` |

An active promotion outside its daypart, store or channel is still
evaluated and reported with the reason, so a screen can say "available from
3pm" rather than hiding it.

#### Stacking, redemption and limits

| Field | Type | Description |
|---|---|---|
| `stacking.exclusive` | boolean | Nothing else applies once this does |
| `stacking.priority` | integer | -1000 to 1000, default 0. Higher goes first |
| `stacking.group` | string | One applied promotion per group |
| `requires_code` | string | The code that unlocks it. Without the code the offer is not shown at all |
| `auto_apply` | boolean | Applies without being selected in `manual` mode |
| `single_use` | boolean | One use per customer. Implies `requires_customer` |
| `usage_limits.max_total` | integer | Committed uses across all customers, else `USAGE_LIMIT_REACHED` |
| `usage_limits.max_per_customer` | integer | Committed uses per customer. Implies `requires_customer` |
| `usage_limits.max_per_day` | integer | Committed uses per UTC day |
| `usage_limits.budget_cents` | integer | Total discount this promotion may ever give, else `BUDGET_EXHAUSTED` |
| `funding` | string | Who pays: `restaurant` (default), `channel`, `shared`, `loyalty`. Attribution only |
| `funding_split.restaurant_bps` | integer | Required when `funding` is `shared`, refused otherwise. Restaurant share, 0 to 10000 basis points |

Usage limits and budgets are computed from committed redemptions, so a
rollback restores them.

#### Response envelope

Single-promotion routes answer `{ "promotion": {...}, "offer": {...} }`:
the promotion in the wire vocabulary above, and the `offer` the engine
actually evaluates. When a promotion does not apply as expected, compare the
two.

### GET /v1/admin/promotions

List the vendor's promotions.

**Auth:** Vendor API key, or OIDC service identity (any role).

#### Query parameters

| Name | Type | Description |
|---|---|---|
| `status` | string | `draft`, `active`, `paused` or `archived` |
| `limit` | integer | 1 to 500 |

#### Example request

```bash
curl "https://offers.spoonity.com/v1/admin/promotions?status=active&limit=50" \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

Each entry is the promotion only, without the `offer` projection:

```json
{
  "promotions": [
    {
      "identifier": "SPEND20",
      "promotion_id": "SPEND20",
      "vendor_id": "dev-vendor",
      "name": "Spend more, save more",
      "status": "active",
      "version": 1,
      "pos_reference": "discount_promo_SPEND20",
      "discount_type": "TIERED",
      "spend_tiers": [
        { "min_spend": 2000, "amount": 300 },
        { "min_spend": 4000, "percent": 15, "amount_limit": 1000 }
      ],
      "created_at": 1790764191204,
      "updated_at": 1790764191204
    }
  ]
}
```

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | Invalid `status` or `limit` |
| 401 | `UNAUTHORIZED` | Missing or invalid credential |

### POST /v1/admin/promotions

Create a promotion.

**Auth:** Vendor API key, or OIDC service identity with `admin` or `editor`.

#### Request body

[The promotion object](#the-promotion-object), without `expected_version`.

#### Example request

```bash
curl -X POST https://offers.spoonity.com/v1/admin/promotions \
  -H "X-API-Key: YOUR_OFFERS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "identifier": "DRINKS20",
    "name": "20% off drinks",
    "discount_type": "PERCENT",
    "discount_amount": 20,
    "scope": "item",
    "categories": ["drinks"],
    "max_quantity": 2,
    "stacking": { "group": "drinks", "priority": 10 },
    "status": "active"
  }'
```

#### Example response

`201`:

```json
{
  "promotion": {
    "identifier": "DRINKS20",
    "promotion_id": "DRINKS20",
    "vendor_id": "dev-vendor",
    "name": "20% off drinks",
    "status": "active",
    "version": 1,
    "pos_reference": "discount_promo_DRINKS20",
    "discount_type": "PERCENT",
    "discount_amount": 20,
    "scope": "item",
    "max_quantity": 2,
    "categories": ["drinks"],
    "stacking": { "priority": 10, "group": "drinks" },
    "created_at": 1790764191191,
    "updated_at": 1790764191191
  },
  "offer": {
    "effect": { "type": "percent_off", "scope": "item", "percent": 20, "max_quantity": 2 },
    "targeting": { "categories": ["drinks"] },
    "stacking": { "priority": 10, "group": "drinks" },
    "offer_id": "promo_DRINKS20",
    "version": 1,
    "name": "20% off drinks",
    "source": { "type": "promotion_code" },
    "pos_reference": "discount_promo_DRINKS20"
  }
}
```

A combo, created as a draft so it can be simulated before it goes live:

```bash
curl -X POST https://offers.spoonity.com/v1/admin/promotions \
  -H "X-API-Key: YOUR_OFFERS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "identifier": "LUNCHCOMBO",
    "name": "Lunch combo $10.99",
    "discount_type": "BUNDLE",
    "bundle": {
      "components": [
        { "categories": ["mains"], "quantity": 1 },
        { "categories": ["sides"], "quantity": 1 },
        { "categories": ["drinks"], "quantity": 1 }
      ],
      "price": 1099,
      "max_applications": 1,
      "selection": "most_expensive"
    },
    "channels": ["kiosk", "pos"],
    "status": "draft"
  }'
```

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | Validation failed (see below), `expected_version` sent, or a reserved `identifier` |
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 403 | `FORBIDDEN` | OIDC caller with the `viewer` role |
| 409 | `PROMOTION_EXISTS` | The `identifier` is taken. Carries `identifier`. Ids are unique across all vendors, and the message does not say who holds it |

A validation failure lists every problem:

```json
{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "Promotion validation failed",
    "issues": [
      { "path": "discount_amount", "message": "percent discounts must be between 0 and 100" },
      { "path": "min_quantity", "message": "min_quantity applies to item-scoped effects only" }
    ]
  }
}
```

### GET /v1/admin/promotions/{id}

Read one promotion.

**Auth:** Vendor API key, or OIDC service identity (any role).

#### Path parameters

| Name | Description |
|---|---|
| `id` | The `promotion_id` |

#### Example request

```bash
curl https://offers.spoonity.com/v1/admin/promotions/DRINKS20 \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

`{ "promotion": {...}, "offer": {...} }`, the same shape as the create
response.

#### Errors

| Status | Code | When |
|---|---|---|
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 404 | `NOT_FOUND` | No such promotion for this vendor |

### PUT /v1/admin/promotions/{id}

Replace a promotion. Omitted fields are removed, so send the whole
definition: read it, change it, send it back with `expected_version` set to
the `version` you read.

**Auth:** Vendor API key, or OIDC service identity with `admin` or `editor`.

#### Request body

[The promotion object](#the-promotion-object) with `expected_version`.
`identifier` and `status` are ignored.

#### Example request

```bash
curl -X PUT https://offers.spoonity.com/v1/admin/promotions/DRINKS20 \
  -H "X-API-Key: YOUR_OFFERS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "25% off drinks",
    "discount_type": "PERCENT",
    "discount_amount": 25,
    "scope": "item",
    "categories": ["drinks"],
    "max_quantity": 2,
    "stacking": { "group": "drinks", "priority": 10 },
    "expected_version": 1
  }'
```

#### Example response

```json
{
  "promotion": {
    "identifier": "DRINKS20",
    "promotion_id": "DRINKS20",
    "vendor_id": "dev-vendor",
    "name": "25% off drinks",
    "status": "active",
    "version": 2,
    "pos_reference": "discount_promo_DRINKS20",
    "discount_type": "PERCENT",
    "discount_amount": 25,
    "scope": "item",
    "max_quantity": 2,
    "categories": ["drinks"],
    "stacking": { "priority": 10, "group": "drinks" },
    "created_at": 1790764191191,
    "updated_at": 1790764267091
  },
  "offer": {
    "effect": { "type": "percent_off", "scope": "item", "percent": 25, "max_quantity": 2 },
    "targeting": { "categories": ["drinks"] },
    "stacking": { "priority": 10, "group": "drinks" },
    "offer_id": "promo_DRINKS20",
    "version": 2,
    "name": "25% off drinks",
    "source": { "type": "promotion_code" },
    "pos_reference": "discount_promo_DRINKS20"
  }
}
```

A stale `expected_version` carries the current version and the stored
promotion, so a UI can show what changed:

```json
{
  "error": {
    "code": "VERSION_CONFLICT",
    "message": "This promotion changed since you read it; re-read and retry",
    "version": 2,
    "promotion": {
      "identifier": "DRINKS20", "promotion_id": "DRINKS20", "vendor_id": "dev-vendor",
      "name": "25% off drinks", "status": "active", "version": 2,
      "pos_reference": "discount_promo_DRINKS20", "discount_type": "PERCENT", "discount_amount": 25,
      "scope": "item", "max_quantity": 2, "categories": ["drinks"],
      "stacking": { "priority": 10, "group": "drinks" },
      "created_at": 1790764191191, "updated_at": 1790764267091
    }
  }
}
```

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | Validation failed |
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 403 | `FORBIDDEN` | OIDC caller with the `viewer` role |
| 404 | `NOT_FOUND` | No such promotion for this vendor |
| 409 | `VERSION_REQUIRED` | `expected_version` missing. Carries `version`. A missing version is never treated as "overwrite" |
| 409 | `VERSION_CONFLICT` | `expected_version` is stale. Carries `version` and `promotion` |
| 409 | `PROMOTION_ARCHIVED` | Archived promotions are read-only. Carries `version`. Pause it first to edit it |

### POST /v1/admin/promotions/{id}/activate

Set the status to `active`.

**Auth:** Vendor API key, or OIDC service identity with `admin` or `editor`.

#### Request body

Optional: `{ "expected_version": <integer> }`. When sent, a stale version is
`409 VERSION_CONFLICT`.

#### Example request

```bash
curl -X POST https://offers.spoonity.com/v1/admin/promotions/LUNCHCOMBO/activate \
  -H "X-API-Key: YOUR_OFFERS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "expected_version": 1 }'
```

#### Example response

```json
{
  "promotion": {
    "identifier": "LUNCHCOMBO",
    "promotion_id": "LUNCHCOMBO",
    "vendor_id": "dev-vendor",
    "name": "Lunch combo $10.99",
    "status": "active",
    "version": 2,
    "pos_reference": "discount_promo_LUNCHCOMBO",
    "discount_type": "BUNDLE",
    "bundle": {
      "components": [
        { "categories": ["mains"], "quantity": 1 },
        { "categories": ["sides"], "quantity": 1 },
        { "categories": ["drinks"], "quantity": 1 }
      ],
      "price": 1099,
      "max_applications": 1,
      "selection": "most_expensive"
    },
    "channels": ["kiosk", "pos"],
    "created_at": 1790764191216,
    "updated_at": 1790764208496
  },
  "offer": {
    "effect": {
      "type": "bundle",
      "components": [
        { "filter": { "categories": ["mains"] }, "quantity": 1 },
        { "filter": { "categories": ["sides"] }, "quantity": 1 },
        { "filter": { "categories": ["drinks"] }, "quantity": 1 }
      ],
      "price": 1099,
      "max_applications": 1,
      "selection": "most_expensive"
    },
    "channels": ["kiosk", "pos"],
    "offer_id": "promo_LUNCHCOMBO",
    "version": 2,
    "name": "Lunch combo $10.99",
    "source": { "type": "promotion_code" },
    "pos_reference": "discount_promo_LUNCHCOMBO"
  }
}
```

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | `expected_version` is not an integer |
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 403 | `FORBIDDEN` | OIDC caller with the `viewer` role |
| 404 | `NOT_FOUND` | No such promotion for this vendor |
| 409 | `VERSION_CONFLICT` | `expected_version` is stale |

### POST /v1/admin/promotions/{id}/pause

Set the status to `paused`. Also the way to un-archive a promotion.

**Auth:** Vendor API key, or OIDC service identity with `admin` or `editor`.

Same body, response and errors as
[activate](#post-v1adminpromotionsidactivate).

#### Example request

```bash
curl -X POST https://offers.spoonity.com/v1/admin/promotions/DRINKS20/pause \
  -H "X-API-Key: YOUR_OFFERS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "expected_version": 2 }'
```

#### Example response

`{ "promotion": {...}, "offer": {...} }` with `"status": "paused"` and
`"version": 3`.

#### Errors

As for [activate](#post-v1adminpromotionsidactivate).

### POST /v1/admin/promotions/{id}/archive

Set the status to `archived`. An archived promotion is read-only and never
evaluated. It is kept, not deleted, so a disputed redemption can be replayed
against the exact rule version that paid out.

**Auth:** Vendor API key, or OIDC service identity with `admin` or `editor`.

Same body, response and errors as
[activate](#post-v1adminpromotionsidactivate).

#### Example request

```bash
curl -X POST https://offers.spoonity.com/v1/admin/promotions/DRINKS20/archive \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

`{ "promotion": {...}, "offer": {...} }` with `"status": "archived"`. A
later PUT answers:

```json
{ "error": { "code": "PROMOTION_ARCHIVED", "message": "Archived promotions are read-only; restore it with /pause first", "version": 4 } }
```

#### Errors

As for [activate](#post-v1adminpromotionsidactivate).

### GET /v1/admin/promotions/{id}/history

Every version of a promotion, newest first, each with a full snapshot.

**Auth:** Vendor API key, or OIDC service identity (any role).

#### Example request

```bash
curl https://offers.spoonity.com/v1/admin/promotions/DRINKS20/history \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

Abridged to the two oldest entries; each `promotion` is the full snapshot in
the wire vocabulary.

```json
{
  "history": [
    {
      "version": 2,
      "status": "active",
      "change": "updated",
      "at": 1790764267091,
      "promotion": { "identifier": "DRINKS20", "promotion_id": "DRINKS20", "name": "25% off drinks", "version": 2, "discount_amount": 25 }
    },
    {
      "version": 1,
      "status": "active",
      "change": "created",
      "at": 1790764191191,
      "promotion": { "identifier": "DRINKS20", "promotion_id": "DRINKS20", "name": "20% off drinks", "version": 1, "discount_amount": 20 }
    }
  ]
}
```

`change` is `created`, `updated` or `status_changed`. `by` appears when the
change was made by a named person (an OIDC call with `X-Spoonity-User`); an
API key leaves it out.

#### Errors

| Status | Code | When |
|---|---|---|
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 404 | `NOT_FOUND` | No such promotion for this vendor |

### POST /v1/admin/promotions/simulate

Evaluate any cart against the vendor's promotions with no side effects:
nothing is reserved or recorded. Use it to check a draft before activating
it.

**Auth:** Vendor API key, or OIDC service identity (any role, including
`viewer`).

#### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `cart` | object | Yes | Same as `POST /v1/evaluate` |
| `customer` | object | | What-if customer: `customer_id`, `tier_id`, `segments`, `order_count`, `tags`, `balances: [{ currency_id, balance }]`, and `identifier` to resolve a real customer first. The what-if fields win over what the real customer has |
| `codes`, `selected`, `selection_mode`, `channel`, `store_id` | | | Same as `POST /v1/evaluate` |
| `now` | ISO 8601 | | Evaluate as of this instant (dayparts, active windows). Default now |
| `include_drafts` | boolean | | Add the vendor's `draft` promotions to the candidates |
| `promotion_ids` | string[] | | Evaluate exactly these promotions, whatever their status, and no loyalty rewards |
| `evaluation_id` | string | | Echoed back. Default `sim_<uuid>` |

The vendor's saved policy and the usage limits apply, read-only.

#### Example request

```bash
curl -X POST https://offers.spoonity.com/v1/admin/promotions/simulate \
  -H "X-API-Key: YOUR_OFFERS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "cart": {
      "line_items": [
        { "line_id": "1", "id": "burger", "name": "Classic Burger", "categories": [{ "id": "mains" }], "price": 899, "quantity": 1 },
        { "line_id": "2", "id": "fries", "name": "Fries", "categories": [{ "id": "sides" }], "price": 349, "quantity": 1 },
        { "line_id": "3", "id": "cola", "name": "Cola", "categories": [{ "id": "drinks" }], "price": 279, "quantity": 2 },
        { "line_id": "4", "id": "cookie", "name": "Cookie", "categories": [{ "id": "desserts" }], "price": 199, "quantity": 1 }
      ]
    },
    "channel": "kiosk",
    "include_drafts": true,
    "now": "2026-10-02T17:00:00Z"
  }'
```

#### Example response

The response is the evaluate result (`evaluation_id`, `offers`, `cart`,
`effects`, `receipt_lines`) plus `explain` and `simulation`. Here nothing is
selected in `manual` mode, so every eligible promotion is `applicable` with
its standalone value. Abridged: `cart.line_items` is omitted and `explain`
shows three of its five entries.

```json
{
  "evaluation_id": "sim_33bf90b3-5021-4b35-b76f-56f2029a5803",
  "offers": [
    { "offer_id": "reward_free_cookie", "name": "Free Cookie (150 pts)", "status": "inapplicable",
      "source": { "type": "redemption", "vendor_perk_redemption_id": 501 },
      "pos_reference": "discount_free_cookie", "cost_points": 150,
      "reason": { "code": "INSUFFICIENT_BALANCE", "message": "Not enough points for this reward", "required": 150, "balance": 0 } },
    { "offer_id": "promo_DRINKS20", "name": "20% off drinks", "status": "applicable",
      "source": { "type": "promotion_code" }, "pos_reference": "discount_promo_DRINKS20", "discount_total": 112 },
    { "offer_id": "promo_SPEND20", "name": "Spend more, save more", "status": "applicable",
      "source": { "type": "promotion_code" }, "pos_reference": "discount_promo_SPEND20", "discount_total": 300 },
    { "offer_id": "promo_LUNCHCOMBO", "name": "Lunch combo $10.99", "status": "applicable",
      "source": { "type": "promotion_code" }, "pos_reference": "discount_promo_LUNCHCOMBO", "discount_total": 428 }
  ],
  "cart": { "discounts": [], "allocations": [], "subtotal": 2005, "discount_total": 0, "total": 2005 },
  "effects": [],
  "receipt_lines": [],
  "explain": [
    { "offer_id": "promo_WELCOME3", "name": "$3 Off with Code WELCOME3", "status": "inapplicable",
      "reason": { "code": "CODE_REQUIRED", "message": "Enter the promotion code to see this offer" },
      "promotion_id": "WELCOME3", "promotion_status": "active" },
    { "offer_id": "promo_DRINKS20", "name": "20% off drinks", "status": "applicable",
      "discount_total": 112, "promotion_id": "DRINKS20", "promotion_status": "active" },
    { "offer_id": "promo_LUNCHCOMBO", "name": "Lunch combo $10.99", "status": "applicable",
      "discount_total": 428, "promotion_id": "LUNCHCOMBO", "promotion_status": "draft" }
  ],
  "simulation": { "now": "2026-10-02T17:00:00.000Z", "include_drafts": true, "policy_version": null }
}
```

`explain` has one entry per candidate. It includes code-gated promotions
whose code was not entered (as `CODE_REQUIRED`), which `offers` leaves out.
`arbitration_rank` (1-based) appears on offers arbitration tried to apply
(`applied` or `skipped`). `policy_version` is `null` when the vendor has no
saved policy.

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | Validation failed, or a `promotion_ids` entry is unknown or another vendor's (listed in `unknown_promotion_ids`) |
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 503 | `OFFERS_UNAVAILABLE` | The catalog or policy could not be read |

### GET /v1/admin/promotions/{id}/usage

Uses and discount given for one promotion, from the redemption ledger.

**Auth:** Vendor API key, or OIDC service identity (any role).

#### Query parameters

| Name | Type | Description |
|---|---|---|
| `days` | integer | 1 to 90, default 30. Length of the `per_day` series |

`uses` and `discount_cents` are all-time and count `committed` and
`partially_returned` records, the same way the usage limits do. `per_day` is
zero-filled, oldest first, in UTC days. `limits` echoes `usage_limits` (or
`null`); `budget` is `null` without a `budget_cents`.

#### Example request

```bash
curl "https://offers.spoonity.com/v1/admin/promotions/WELCOME3/usage?days=3" \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

```json
{
  "promotion_id": "WELCOME3",
  "offer_id": "promo_WELCOME3",
  "uses": 2,
  "discount_cents": 600,
  "per_day": [
    { "day": "2026-09-28", "uses": 0, "discount_cents": 0 },
    { "day": "2026-09-29", "uses": 0, "discount_cents": 0 },
    { "day": "2026-09-30", "uses": 2, "discount_cents": 600 }
  ],
  "window": { "days": 3, "since": "2026-09-28", "until": "2026-09-30" },
  "limits": { "max_per_day": 100, "budget_cents": 50000 },
  "budget": { "budget_cents": 50000, "spent_cents": 600, "remaining_cents": 49400 }
}
```

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | `days` out of range |
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 404 | `NOT_FOUND` | No such promotion for this vendor |
| 503 | `OFFERS_UNAVAILABLE` | The redemption ledger is not available |

### GET /v1/admin/promotions/{id}/redemptions

Recent redemption records holding this promotion, in every state, newest
first.

**Auth:** Vendor API key, or OIDC service identity (any role).

#### Query parameters

| Name | Type | Description |
|---|---|---|
| `limit` | integer | 1 to 200, default 50 |
| `before` | string | The previous page's `next_before`, or an epoch-millisecond instant |

`next_before` is `null` on the last page. `customer_id`, `order_reference`,
`committed_at`, `rolled_back_at`, `cancelled_at`, `mismatch` and
`returned_line_ids` appear only when set.

#### Example request

```bash
curl "https://offers.spoonity.com/v1/admin/promotions/WELCOME3/redemptions?limit=1" \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

```json
{
  "redemptions": [
    {
      "redemption_id": "ored_cc3e0ab9-63f8-4697-8b06-544bb832b6d7",
      "evaluation_id": "K12-000491",
      "state": "committed",
      "order_reference": "ord_88491",
      "discount_cents": 300,
      "offer_version": 1,
      "pos_reference": "discount_promo_WELCOME3",
      "cart": { "subtotal": 757, "discount_total": 300, "total": 457 },
      "created_at": 1790764254348,
      "expires_at": 1790764554348,
      "committed_at": 1790764254365
    }
  ],
  "next_before": "1790764254348:ored_cc3e0ab9-63f8-4697-8b06-544bb832b6d7"
}
```

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | Invalid `limit` or `before` |
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 404 | `NOT_FOUND` | No such promotion for this vendor |
| 503 | `OFFERS_UNAVAILABLE` | The redemption ledger is not available |

### The promotion policy

One policy per vendor sets the stacking and safety rules for every
evaluation of that vendor's carts: `POST /v1/evaluate`, the POS check and
simulate. A vendor that never saved one gets the defaults at `version: 0`.

| Setting | Values | Default | Effect |
|---|---|---|---|
| `max_applied_offers` | 1 to 50 | 5 | Most offers applied to one order. Beyond it: `MAX_OFFERS_REACHED` |
| `order_percent_mode` | `cascade`, `additive` | `cascade` | `cascade`: each order-level percent applies to what the previous ones left. `additive`: each applies to the same post-item-discount base |
| `max_order_discount_percent` | 0 to 100 | none | Ceiling on the order's total discount as a percent of subtotal. Order-level discounts are trimmed, last applied first (`ORDER_CAP_REACHED`); item discounts are never trimmed |
| `excluded` | `{ products?, categories?, exclude_products?, exclude_categories? }` | none | Items no promotion may touch (gift cards, alcohol, deposits): never discounted, never counted in an order-level base |
| `min_spend_basis` | `subtotal`, `eligible` | `subtotal` | What `min_spend` and spend tiers compare against. `eligible` is the subtotal minus excluded items and POS discounts |
| `local_discount_policy` | `respect`, `ignore` | `respect` | `respect`: a line carrying a POS discount gets no item-level offer (`LOCALLY_DISCOUNTED`). `ignore`: it stays discountable, capped at what the POS left |

A PUT replaces the whole policy; a setting left out goes back to its
default. A GET body minus `vendor_id`, `version`, `updated_at` and
`updated_by` is a valid PUT body.

### GET /v1/admin/promotion-policy

Read the vendor's policy.

**Auth:** Vendor API key, or OIDC service identity (any role).

#### Example request

```bash
curl https://offers.spoonity.com/v1/admin/promotion-policy \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

Before any save:

```json
{
  "policy": {
    "vendor_id": "dev-vendor",
    "version": 0,
    "updated_at": 0,
    "max_applied_offers": 5,
    "order_percent_mode": "cascade",
    "min_spend_basis": "subtotal",
    "local_discount_policy": "respect"
  },
  "saved": false
}
```

#### Errors

| Status | Code | When |
|---|---|---|
| 401 | `UNAUTHORIZED` | Missing or invalid credential |

### PUT /v1/admin/promotion-policy

Replace the vendor's policy.

**Auth:** Vendor API key, or OIDC service identity with `admin` or `editor`.

#### Request body

The settings in the table above, plus `expected_version`: `0` for the first
save, otherwise the `version` you read. Unknown keys, including the
read-only record fields, are a `400`.

#### Example request

```bash
curl -X PUT https://offers.spoonity.com/v1/admin/promotion-policy \
  -H "X-API-Key: YOUR_OFFERS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "expected_version": 0,
    "max_applied_offers": 3,
    "order_percent_mode": "additive",
    "max_order_discount_percent": 50,
    "excluded": { "categories": ["gift_cards", "alcohol"] },
    "min_spend_basis": "eligible",
    "local_discount_policy": "respect"
  }'
```

#### Example response

```json
{
  "policy": {
    "vendor_id": "dev-vendor",
    "version": 1,
    "updated_at": 1790764275951,
    "max_applied_offers": 3,
    "order_percent_mode": "additive",
    "min_spend_basis": "eligible",
    "local_discount_policy": "respect",
    "max_order_discount_percent": 50,
    "excluded": { "categories": ["gift_cards", "alcohol"] }
  },
  "saved": true
}
```

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | Validation failed |
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 403 | `FORBIDDEN` | OIDC caller with the `viewer` role |
| 409 | `VERSION_REQUIRED` | `expected_version` missing. Carries the current `version` |
| 409 | `VERSION_CONFLICT` | `expected_version` is stale. Carries `version` and the stored `policy` |

### GET /v1/admin/promotion-policy/history

Every saved version of the policy, newest first.

**Auth:** Vendor API key, or OIDC service identity (any role).

#### Example request

```bash
curl https://offers.spoonity.com/v1/admin/promotion-policy/history \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

```json
{
  "history": [
    {
      "version": 1,
      "at": 1790764275951,
      "policy": {
        "vendor_id": "dev-vendor",
        "version": 1,
        "updated_at": 1790764275951,
        "max_applied_offers": 3,
        "order_percent_mode": "additive",
        "min_spend_basis": "eligible",
        "local_discount_policy": "respect",
        "max_order_discount_percent": 50,
        "excluded": { "categories": ["gift_cards", "alcohol"] }
      }
    }
  ]
}
```

`by` appears on an entry saved by a named person.

#### Errors

| Status | Code | When |
|---|---|---|
| 401 | `UNAUTHORIZED` | Missing or invalid credential |

### GET /v1/admin/loyalty-rewards

The vendor's loyalty rewards, read-only, so they can be shown beside the
promotions they stack with. They are edited in the loyalty program, not
here.

**Auth:** Vendor API key, or OIDC service identity (any role).

The response has three parts:

- `rewards`: the rewards the engine prices, in the engine's offer shape.
  These are exactly what arbitration sees. A loyalty reward's discount
  applies to one line: a percent or amount reward is item-scoped with
  `max_quantity: 1`.
- `unpriced`: active loyalty rewards the engine cannot price. They never
  enter arbitration, and are listed so they are not silently missing. Each
  has a `reason`:
  - `POS_PRICED`: no discount definition, and a catalog identifier starting
    with `discount_` or `clover_`. The POS prices it by catalog code (Clover,
    for example, rings it as 100% off the line the cashier picks), which the
    engine cannot do because it cannot pick the line.
  - `NO_DISCOUNT_DEFINITION`: no discount definition and any other
    identifier.
  - `UNSUPPORTED_DISCOUNT`: a discount definition this service cannot read.
- `loyalty.connected`: whether this vendor's loyalty program is connected to
  Offers. A vendor without a connection gets `200` with empty lists and
  `connected: false`; that is not an error.

Inactive rewards, Loyalty Pay (a tender, not a discount) and information-only
rows appear in neither list.

`unpriced` entries:

| Field | Type | Description |
|---|---|---|
| `vendor_perk_redemption_id` | integer | The reward's id in the loyalty program |
| `name` | string | Reward name |
| `catalog_identifier` | string | The loyalty catalog identifier (the POS code), when the reward has one |
| `pos_reference` | string | `discount_<identifier>`, with the identifier exactly as the loyalty program sends it, and not doubled when it already starts with `discount_` |
| `cost_points` | integer | Point cost, when the reward has one |
| `pos_ids` | string[] | POS ids, ascending, when the reward's data is keyed by point of sale |
| `reason` | string | `POS_PRICED`, `NO_DISCOUNT_DEFINITION` or `UNSUPPORTED_DISCOUNT` |

#### Example request

```bash
curl https://offers.spoonity.com/v1/admin/loyalty-rewards \
  -H "X-API-Key: YOUR_OFFERS_API_KEY"
```

#### Example response

A connected vendor with one priced reward and two the engine cannot price:

```json
{
  "rewards": [
    {
      "offer_id": "off_r12617",
      "version": 1,
      "name": "New Member Half Off",
      "source": { "type": "redemption", "vendor_perk_redemption_id": 12617 },
      "pos_reference": "discount_16ozHalfOffEspresso",
      "effect": { "type": "percent_off", "scope": "item", "percent": 50, "max_quantity": 1 },
      "stacking": { "exclusive": false, "priority": 0 },
      "cost_points": 100
    }
  ],
  "unpriced": [
    {
      "vendor_perk_redemption_id": 1644,
      "name": "Welcome Reward",
      "catalog_identifier": "discount_reward300",
      "pos_reference": "discount_reward300",
      "cost_points": 30000,
      "reason": "POS_PRICED"
    },
    {
      "vendor_perk_redemption_id": 8346,
      "name": "Drip Tea",
      "catalog_identifier": "DripTea",
      "pos_reference": "discount_DripTea",
      "cost_points": 5000,
      "reason": "NO_DISCOUNT_DEFINITION"
    }
  ],
  "loyalty": { "connected": true }
}
```

Not connected:

```json
{ "rewards": [], "unpriced": [], "loyalty": { "connected": false } }
```

#### Errors

| Status | Code | When |
|---|---|---|
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 503 | `OFFERS_UNAVAILABLE` | Connected, but the loyalty platform failed (error or timeout). Retryable |

## POS check API

For a POS that sends the whole check at pay time and wants the discount
back. The customer's app QR, a customer id or phone number, or a coupon code
can go on the check. Spoonity reprices it with the vendor's promotions,
rewards and policy, holds single-use rewards for 15 minutes, and returns one
subtotal discount plus the per-line detail. The POS applies it, takes
payment, and posts `close`.

1. **Pay pressed:** `POST /partners/pos/check` with the full check. Send it
   again if the cart changes; each call replaces the hold.
2. **Apply** `subtotal_discount` as one subtotal discount, or each
   `discounts[]` entry on its line. Take payment.
3. **Check closed:** `POST /partners/pos/close`, always, even when `check`
   failed or timed out.
4. **Refund or void:** `POST /partners/pos/void`.

Optionally, `GET /partners/pos/offers` fills a cashier prompt after a scan.

**Base path:** `https://offers.spoonity.com/partners/pos`

### Evaluation ids

The engine keys a check as `"<store_id>:<check_id>"`, for example
`S12:1042`. That is why neither id may contain a colon. You never send it
back; it is returned for support and logs.

If a check's hold expires, or it is voided while still open, a later `check`
reserves under a new id with a generation suffix: `S12:1042:2`, then
`S12:1042:3`. Every later call on that check finds the current one. A check
has 10 ids in total. Each expiry, open void and lost race for a single-use
reward uses one; after that `check` answers `409 CHECK_REOPEN_LIMIT`.

### Idempotency

- `check` is safe to repeat: the same `store_id` + `check_id` always refers
  to the same hold, replaced with the new cart's result. A re-check that no
  longer qualifies releases the held reward.
- `close` is idempotent on `pos_transaction_id` within a check: a retry
  returns the same answer and never commits twice. Transaction ids only need
  to be unique per check.
- `void` is idempotent on `pos_transaction_id`, tracked separately from
  `close`, so a void may reuse the close's transaction id.
- A closed check cannot be checked again (`409 CHECK_CLOSED`); a new sale
  needs a new `check_id`.

### Timeouts and retries

- Time out `check` at 800 ms. On a timeout, a `5xx` or a network error,
  close the check without a Spoonity discount. Do not block the cashier.
- Retry `close` and `void` on `5xx` or network errors, with backoff. They are
  idempotent.
- Do not retry a `4xx`. The one exception is `409 OFFERS_RESERVED`: another
  check won the race for the same single-use reward three times inside this
  one request. Re-send `check` once within the 800 ms budget, and if it fails
  again, proceed without a discount.
- `503 CUSTOMER_LOOKUP_UNAVAILABLE` means a `qr_token` was sent but could not
  be verified (the lookup failed, took longer than 400 ms, or token lookup is
  not available for this merchant). Spoonity will not price a scanned
  customer as a guest. Proceed without a discount, or re-send without the
  token to get guest promotions and codes only. Always `close`.

Token lookup for rotating app QR codes is not available yet: every
`qr_token` currently answers `503 CUSTOMER_LOOKUP_UNAVAILABLE`. Guest checks
and codes work. `customer_id` and `phone` resolve a customer only for a
vendor whose loyalty program is connected to Offers; otherwise the check is
priced as a guest (`customer: null`).

### POST /partners/pos/check

Reprice a check and hold its single-use rewards.

**Auth:** `X-Spoonity-POS-Key`.

#### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `check_id` | string | Yes | Your check number. `A-Z a-z 0-9 _ . -`, at most 60 characters, no colon. Must stay unique per store for as long as the check can be refunded; prefix a daily-reset number with the business date |
| `store_id` | string | Yes | Same rules as `check_id` |
| `lines` | array | Yes | Up to 200 lines, see below |
| `customer` | object | | Exactly one of `qr_token` (1 to 512 characters), `customer_id`, `phone` (3 to 32). Omit for a guest |
| `codes` | string[] | | Coupon or promo codes |
| `selected_offer_ids` | string[] | | Rewards the cashier selected from `GET /offers` |
| `channel` | string | | Default `pos` |
| `terminal_id` | string | | Logged only |
| `pos_transaction_id` | string | | Logged only on `check` |

A line is `{ line_id, sku, name?, price, quantity, categories?, modifiers?, discounts? }`.
`price` is the unit price excluding modifiers, in cents. `discounts` are
discounts the POS already applied: `{ id, name?, amount, source? }`,
whole-line cents. Up to 50 categories, modifiers and discounts per line.
Unknown fields anywhere are a `400`.

#### Example request

A customer identified by id, a coupon code, and a cookie the register has
already discounted:

```bash
curl -X POST https://offers.spoonity.com/partners/pos/check \
  -H "X-Spoonity-POS-Key: YOUR_POS_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "check_id": "1042",
    "store_id": "S12",
    "terminal_id": "T1",
    "customer": { "customer_id": "cust_1001" },
    "codes": ["WELCOME3"],
    "selected_offer_ids": ["reward_free_cookie"],
    "lines": [
      { "line_id": "1", "sku": "burger", "name": "Classic Burger", "price": 899, "quantity": 1,
        "categories": [{ "id": "mains" }] },
      { "line_id": "2", "sku": "cola", "name": "Cola", "price": 279, "quantity": 1,
        "categories": [{ "id": "drinks" }],
        "modifiers": [{ "id": "large", "name": "Large", "price": 50, "quantity": 1 }] },
      { "line_id": "3", "sku": "cookie", "name": "Cookie", "price": 199, "quantity": 1,
        "categories": [{ "id": "desserts" }],
        "discounts": [{ "id": "emp", "name": "Employee 50%", "amount": 100 }] }
    ]
  }'
```

#### Example response

`200`. The code applied. The cookie reward was skipped because the register
had already discounted that line (`LOCALLY_DISCOUNTED`).

```json
{
  "evaluation_id": "S12:1042",
  "check_id": "1042",
  "customer": {
    "customer_id": "cust_1001",
    "balances": [{ "currency_id": "points", "balance": 420 }]
  },
  "subtotal": 1427,
  "subtotal_discount": 300,
  "external_discount_total": 100,
  "total": 1027,
  "discounts": [
    { "pos_reference": "discount_promo_WELCOME3", "offer_id": "promo_WELCOME3",
      "name": "$3 Off with Code WELCOME3", "amount": 300, "scope": "order" }
  ],
  "offers": [
    { "offer_id": "reward_free_cookie", "name": "Free Cookie (150 pts)", "status": "skipped",
      "source": { "type": "redemption", "vendor_perk_redemption_id": 501 },
      "pos_reference": "discount_free_cookie", "cost_points": 150,
      "reason": { "code": "LOCALLY_DISCOUNTED", "message": "Eligible items already carry a discount from the register" } },
    { "offer_id": "promo_WELCOME3", "name": "$3 Off with Code WELCOME3", "status": "applied",
      "source": { "type": "promotion_code", "code": "WELCOME3" },
      "pos_reference": "discount_promo_WELCOME3", "funding": "restaurant", "discount_total": 300 },
    { "offer_id": "promo_SPEND20", "name": "Spend more, save more", "status": "inapplicable",
      "source": { "type": "promotion_code" }, "pos_reference": "discount_promo_SPEND20",
      "reason": { "code": "TIER_NOT_REACHED", "message": "Spend $20.00 to unlock", "next_min_spend": 2000, "shortfall": 673 } },
    { "offer_id": "promo_LUNCHCOMBO", "name": "Lunch combo $10.99", "status": "applicable",
      "source": { "type": "promotion_code" }, "pos_reference": "discount_promo_LUNCHCOMBO",
      "reason": { "code": "BUNDLE_INCOMPLETE", "message": "Add the remaining items to complete this combo",
                  "missing": [{ "component": 1, "required": 1, "available": 0 }] } }
  ],
  "receipt_lines": ["$3 Off with Code WELCOME3 applied \u2014 you saved $3.00"],
  "redemption_id": "ored_d768ed3c-503c-453f-a03c-70ae6538695c",
  "hold_expires_at": "2026-09-30T10:46:31.864Z"
}
```

- `subtotal_discount` is the whole Spoonity discount, item and order
  combined. A POS that takes one number applies it as a subtotal discount.
- `discounts[]` sums to `subtotal_discount`. `scope: "item"` entries carry
  `line_id` (and `unit_index`, `quantity`); `scope: "order"` entries go on
  the subtotal. Echo the ones you applied on `close`.
- `total` is `subtotal` minus `external_discount_total` minus
  `subtotal_discount`, pre-tax. `external_discount_total` appears only when
  lines carried POS discounts.
- `customer` is `null` for a guest, and for a `qr_token` that is unknown or
  expired (the check is then priced as a guest). `display_name` appears when
  the lookup provides one.
- `hold_expires_at`: single-use rewards are held until then. A `close` after
  it does not commit (`EVALUATION_EXPIRED`); send `check` again first if a
  check sits that long.

#### Errors

| Status | Code | When | POS action |
|---|---|---|---|
| 400 | `INVALID_REQUEST` | Validation failed: decimals, duplicate `line_id`, unknown fields, a colon in an id, two customer identifiers, any limit | Fix the integration; do not retry |
| 401 | `UNAUTHORIZED` | Missing or unknown `X-Spoonity-POS-Key` | Proceed without discount |
| 409 | `CHECK_CLOSED` | The check already closed or was refunded. Carries `state` and `evaluation_id` | New sale, new `check_id` |
| 409 | `CHECK_REOPEN_LIMIT` | All 10 evaluation ids used | New `check_id` |
| 409 | `OFFERS_RESERVED` | Lost the race for a single-use reward three times | Re-send once, else proceed without discount |
| 503 | `CUSTOMER_LOOKUP_UNAVAILABLE` | A `qr_token` could not be verified | Proceed without discount, or re-send without the token |
| 503 | `OFFERS_UNAVAILABLE` | Promotions, policy or database could not be read | Proceed without discount; always `close` |
| 500 | `INTERNAL` | A bug on Spoonity's side | As for 503 |

```json
{ "error": { "code": "CHECK_CLOSED", "message": "This check is already closed; a new sale needs a new check_id", "state": "committed", "evaluation_id": "S12:1042" } }
```

```json
{ "error": { "code": "CUSTOMER_LOOKUP_UNAVAILABLE", "message": "The customer QR could not be verified; retry, or close the check without a discount" } }
```

### POST /partners/pos/close

Commit a closed check. Send it once the check is paid, always.

**Auth:** `X-Spoonity-POS-Key`.

#### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `check_id`, `store_id` | string | Yes | As on `check` |
| `pos_transaction_id` | string | Yes | Your id for this closed transaction. The idempotency key |
| `receipt.discounts` | array | Yes | The Spoonity discounts you actually applied, echoed from `check`: `{ pos_reference, amount, name?, line_id? }`. Empty if none. Up to 200 |
| `receipt.lines` | array | Yes | The final lines, same shape as on `check`. Validated; reserved for reconciliation |
| `receipt.total` | integer cents | Yes | The receipt total. Validated; reserved for reconciliation |
| `terminal_id` | string | | Logged only |
| `closed_at` | ISO 8601 with offset | | Logged only. The commit time is Spoonity's clock |

Spoonity commits what the last `check` evaluated; it does not reprice at
close. The references and the sum of `receipt.discounts[].amount` are
compared with that result.

#### Example request

```bash
curl -X POST https://offers.spoonity.com/partners/pos/close \
  -H "X-Spoonity-POS-Key: YOUR_POS_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "check_id": "1042",
    "store_id": "S12",
    "pos_transaction_id": "TXN-S12-1042",
    "terminal_id": "T1",
    "closed_at": "2026-09-30T12:31:05-04:00",
    "receipt": {
      "lines": [
        { "line_id": "1", "sku": "burger", "name": "Classic Burger", "price": 899, "quantity": 1,
          "categories": [{ "id": "mains" }] },
        { "line_id": "2", "sku": "cola", "name": "Cola", "price": 279, "quantity": 1,
          "categories": [{ "id": "drinks" }],
          "modifiers": [{ "id": "large", "name": "Large", "price": 50, "quantity": 1 }] },
        { "line_id": "3", "sku": "cookie", "name": "Cookie", "price": 199, "quantity": 1,
          "categories": [{ "id": "desserts" }],
          "discounts": [{ "id": "emp", "name": "Employee 50%", "amount": 100 }] }
      ],
      "discounts": [{ "pos_reference": "discount_promo_WELCOME3", "amount": 300 }],
      "total": 1027
    }
  }'
```

#### Example response

```json
{ "committed": true, "redemption_id": "ored_d768ed3c-503c-453f-a03c-70ae6538695c", "evaluation_id": "S12:1042" }
```

If what you applied differs from what `check` returned, Spoonity still
commits (the money has left the till) and reports the difference:

```json
{
  "committed": true,
  "redemption_id": "ored_dbde8782-27cb-42ed-b2be-42b2d90f12ef",
  "evaluation_id": "S12:1043",
  "mismatch": {
    "expected_pos_references": ["discount_promo_WELCOME3"],
    "received_pos_references": ["discount_promo_WELCOME3"],
    "expected_discount_total": 300,
    "received_discount_total": 250
  }
}
```

`committed: false` is still a `200`, so the POS never retries it forever.
`reason` says why:

| `reason` | Meaning |
|---|---|
| `NO_PENDING_EVALUATION` | Spoonity never saw a `check` for this check. Nothing to commit. Body: `{ "committed": false, "redemption_id": null, "reason": "NO_PENDING_EVALUATION" }` |
| `EVALUATION_EXPIRED` | The 15-minute hold had lapsed. The reward was not consumed |
| `EVALUATION_CANCELLED` | The check was voided while open, or the last `check` answered `409 OFFERS_RESERVED` |
| `EVALUATION_ROLLED_BACK` | The transaction was already voided |

Apart from `NO_PENDING_EVALUATION`, the body also carries `redemption_id`,
`evaluation_id` and `state`.

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | Validation failed |
| 401 | `UNAUTHORIZED` | Missing or unknown `X-Spoonity-POS-Key` |
| 503 | `OFFERS_UNAVAILABLE` | The database could not be reached. Retry with backoff |

### POST /partners/pos/void

Void or refund a closed check, or cancel an open one. Restores single-use
rewards, usage counts and budget.

**Auth:** `X-Spoonity-POS-Key`.

#### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `check_id`, `store_id` | string | Yes | As on `check` |
| `pos_transaction_id` | string | Yes | Idempotency key for the void |
| `terminal_id` | string | | Logged only |

Partial refunds are not supported on this surface.

#### Example request

```bash
curl -X POST https://offers.spoonity.com/partners/pos/void \
  -H "X-Spoonity-POS-Key: YOUR_POS_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "check_id": "1042", "store_id": "S12", "pos_transaction_id": "TXN-S12-1042" }'
```

#### Example response

```json
{ "voided": true, "redemption_id": "ored_d768ed3c-503c-453f-a03c-70ae6538695c", "evaluation_id": "S12:1042", "state": "rolled_back" }
```

`voided: true` means nothing is held or consumed for the check any more.
`state` is `rolled_back` (it had closed), `cancelled` (it was open) or
`expired` (its hold had already lapsed). An unknown check answers
`{ "voided": false, "redemption_id": null, "reason": "NO_PENDING_EVALUATION" }`.

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | Validation failed |
| 401 | `UNAUTHORIZED` | Missing or unknown `X-Spoonity-POS-Key` |
| 503 | `OFFERS_UNAVAILABLE` | The database could not be reached. Retry with backoff |

### GET /partners/pos/offers

What to show on a cashier prompt after a scan, before the cart is final.
Nothing is applied or held.

**Auth:** `X-Spoonity-POS-Key`.

#### Query parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `store_id` | string | Yes | Store |
| `customer` | string | | The scanned `qr_token`. Omit for a guest |
| `channel` | string | | Default `pos` |

Any other query parameter is a `400`. Code-gated offers are never listed.
Offers this customer cannot have at all (wrong tier, not enough points,
already used, outside its schedule, not in its segment) are left out. An
offer whose cart condition is not met yet carries `needs`, a reason with the
shortfall. `pre_selected: true` marks a reward the customer chose in the app.

#### Example request

```bash
curl "https://offers.spoonity.com/partners/pos/offers?store_id=S12" \
  -H "X-Spoonity-POS-Key: YOUR_POS_KEY"
```

#### Example response

A guest, with an empty cart:

```json
{
  "customer": null,
  "offers": [
    {
      "offer_id": "promo_SPEND20",
      "name": "Spend more, save more",
      "pos_reference": "discount_promo_SPEND20",
      "effect_type": "tiered",
      "auto_apply": false,
      "pre_selected": false,
      "needs": { "code": "TIER_NOT_REACHED", "message": "Spend $20.00 to unlock", "next_min_spend": 2000, "shortfall": 2000 }
    },
    {
      "offer_id": "promo_LUNCHCOMBO",
      "name": "Lunch combo $10.99",
      "pos_reference": "discount_promo_LUNCHCOMBO",
      "effect_type": "bundle",
      "auto_apply": false,
      "pre_selected": false,
      "needs": {
        "code": "BUNDLE_INCOMPLETE",
        "message": "Add the remaining items to complete this combo",
        "missing": [
          { "component": 0, "required": 1, "available": 0 },
          { "component": 1, "required": 1, "available": 0 },
          { "component": 2, "required": 1, "available": 0 }
        ]
      }
    }
  ]
}
```

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `INVALID_REQUEST` | `store_id` missing, or an unknown parameter |
| 401 | `UNAUTHORIZED` | Missing or unknown `X-Spoonity-POS-Key` |
| 503 | `CUSTOMER_LOOKUP_UNAVAILABLE` | The `customer` token could not be verified |
| 503 | `OFFERS_UNAVAILABLE` | Promotions or policy could not be read |

## Reason codes

`reason.code` on an offer result (`needs.code` on the POS cashier prompt).
The status column is where the code is normally seen. Extra fields are
machine-readable context next to `code` and `message`.

| Code | Status | Meaning | Extra fields |
|---|---|---|---|
| `MIN_SPEND_NOT_MET` | inapplicable | Subtotal below `min_spend` | `shortfall` (cents); `basis: "eligible"` when the policy uses the eligible subtotal |
| `NO_ELIGIBLE_ITEMS` | applicable | A free item offer whose SKU is not in the cart. The offer also carries `add_item_hint: { sku }` | |
| `OUTSIDE_ACTIVE_WINDOW` | inapplicable | Before `active.start` or after `active.end` | |
| `OUTSIDE_DAYPART` | inapplicable | Outside every daypart | |
| `TIER_NOT_ELIGIBLE` | inapplicable | The customer's loyalty tier is not in `tiers` | |
| `INSUFFICIENT_BALANCE` | inapplicable | Not enough points for a point-cost reward (a guest has 0) | `required`, `balance` |
| `CODE_REQUIRED` | inapplicable | Simulate `explain` only: a code-gated offer whose code was not entered. Evaluate leaves such offers out | |
| `CONDITION_NOT_MET` | inapplicable | Another condition failed (segment, tag, first order, order count, store, channel condition) | `attribute` |
| `STORE_NOT_ELIGIBLE` | inapplicable | `store_id` not in `stores` | |
| `CHANNEL_NOT_ELIGIBLE` | inapplicable | `channel` not in `channels` | |
| `EXCLUSIVE_CONFLICT` | skipped | An exclusive offer applied, or this exclusive offer could not apply alongside those already applied | |
| `LOWER_VALUE_THAN_APPLIED` | | Reserved. Not emitted today | |
| `UNIT_CONFLICT` | skipped | The units it needs already carry another offer's discount | |
| `MAX_OFFERS_REACHED` | skipped | The policy's `max_applied_offers` was reached | |
| `ZERO_DISCOUNT` | skipped | It would not reduce the total (for example, the order is already fully discounted) | |
| `ALREADY_USED` | inapplicable | A single-use offer this customer already redeemed | |
| `RESERVED` | inapplicable | A single-use offer held by another order in progress | |
| `CUSTOMER_REQUIRED` | inapplicable | The offer needs an identified customer | `because: "single_use"` when implied by single use or a per-customer cap |
| `USAGE_LIMIT_REACHED` | inapplicable | A usage limit was reached | `scope` (`total`, `per_customer`, `per_day`), `limit`, `used` |
| `BUDGET_EXHAUSTED` | inapplicable | `budget_cents` is spent | `budget_cents`, `spent_cents` |
| `GROUP_CONFLICT` | skipped | Another offer in the same `stacking.group` applied | `group`, `applied_offer_id` |
| `LOCALLY_DISCOUNTED` | skipped | The units it needs carry a POS discount and the policy is `respect` | |
| `ORDER_CAP_REACHED` | skipped | Trimmed to nothing by `max_order_discount_percent` | `cap` |
| `MIN_QUANTITY_NOT_MET` | inapplicable | Fewer eligible units than `min_quantity` | `required`, `eligible` |
| `TIER_NOT_REACHED` | inapplicable | No spend tier reached | `next_min_spend`, `shortfall` |
| `BUNDLE_INCOMPLETE` | applicable | The cart does not hold a complete combo set | `missing: [{ component, required, available }]` |

## Error codes

Every error on this service, by code. Each endpoint above lists the ones it
returns.

| Status | Code | Meaning |
|---|---|---|
| 400 | `INVALID_REQUEST` | Validation failed. `issues[]` lists `{ path, message }` |
| 400 | `UNKNOWN_LINES` | Partial return named lines that are not in the redemption |
| 401 | `UNAUTHORIZED` | Missing or invalid credential |
| 403 | `FORBIDDEN` | Read-only role attempted a write |
| 404 | `NOT_FOUND` | Unknown route, or a resource that does not exist for this vendor |
| 409 | `OFFERS_RESERVED` | A single-use offer is held by another order |
| 409 | `EVALUATION_TERMINAL` | The `evaluation_id` is already finished |
| 409 | `VERSION_REQUIRED` | An update without `expected_version` |
| 409 | `VERSION_CONFLICT` | An update with a stale `expected_version` |
| 409 | `PROMOTION_ARCHIVED` | An edit to an archived promotion |
| 409 | `PROMOTION_EXISTS` | Create with an identifier that is taken |
| 409 | `INVALID_STATE` | A redemption in the wrong state for the action |
| 409 | `CHECK_CLOSED` | POS: the check already closed |
| 409 | `CHECK_REOPEN_LIMIT` | POS: the check has no evaluation ids left |
| 500 | `INTERNAL` | Unexpected server error |
| 503 | `OFFERS_UNAVAILABLE` | Catalog, policy, loyalty source or database unavailable. Retryable |
| 503 | `CUSTOMER_LOOKUP_UNAVAILABLE` | POS: a scanned QR token could not be verified |

## Health

### GET /readyz

Readiness. No credential.

#### Example request

```bash
curl https://offers.spoonity.com/readyz
```

#### Example response

```json
{ "ready": true, "db": "ok" }
```

`503 { "ready": false, "db": "connecting" }` (or `"unavailable"`) while the
database is not answering.

`GET /healthz` exists in the service but is not usable on
`offers.spoonity.com`: the hosting frontend answers that path itself with a
404. Use `/readyz`.

## Not on this page

- **Partner protocol layers.** The service also has translators for specific
  partner promotion protocols (Olo, Toast, NCR PES, the Deliverect loyalty
  partner and Deliverect Commerce). They are not enabled on
  `offers.spoonity.com` today. Some of their routes appear in the
  [OpenAPI spec](openapi/offers.yaml) because the spec is shared with the
  service repository.
- **Tax, offline mode and points accrual.** The engine is pre-tax, needs a
  live connection, and does not post points; the loyalty platform does.

## See also

- [Authentication](authentication.md) · [Conventions](conventions.md)
- [OpenAPI spec](openapi/offers.yaml)
