# Yatoon Booking System — REST API

Namespace: `yatoon/v1`
Base URL: `https://example.com/wp-json/yatoon/v1`

Everything in this document is implemented in 4.7.6. Nothing here is planned
or partial.

## Authentication

Two mechanisms are accepted.

**1. A logged-in WordPress user.** Normal cookie + nonce authentication, used
by the plugin's own admin screens.

**2. A Yatoon API key**, for automation. Create one under
*Yatoon → Settings → API keys*. The secret is shown once, is prefixed `ytk_`,
and is stored only as a SHA-256 hash. New keys expire after 90 days by default
(choose 30, 180, or 365 days) and carry only the selected permissions, limited
further by the creating WordPress user's capabilities.

Send it either way:

```
X-Yatoon-Api-Key: ytk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Authorization: Bearer ytk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

An API key authenticates **as the WordPress user it was created for**, with an
additional permission ceiling selected when the key is created. The user's
WordPress capabilities still apply; a key cannot grant permissions its owner
does not have. Existing keys created before this 4.7.7 model-refresh build keep
their prior route access for a 90-day rotation window beginning the first time
this build loads. Replace them with scoped keys and revoke the old keys before
that window ends.

* HTTPS is required. A key presented over plain HTTP is refused with
  `yatoon_api_key_insecure` (401) rather than accepted.
* After 20 failed key attempts in 10 minutes the endpoint answers
  `yatoon_api_key_throttled` (429).
* A site may hold at most 20 keys.

### Capabilities per route

| Route group | Required capability |
|---|---|
| `/bookings*` | `yatoon_manage_bookings` (or `manage_options`) |
| `/availability` | `yatoon_manage_bookings`, `yatoon_manage_services` or `yatoon_manage_staff` |
| `/orders/{id}/refunds` | `yatoon_manage_commerce` (or `manage_options`) |
| `/services`, `/staff`, `/locations` | read: any of the directory capabilities; write: the matching manage capability |
| `/customers` | `yatoon_manage_bookings` (or `manage_options`) |
| `/me`, `/events`, `/subscriptions*`, `/triggers/{event}/sample` | automation capability |

Each key also needs the matching permission selected in its settings. Available
permissions include `bookings_read`, `bookings_write`, `availability_read`,
`services_read/write`, `staff_read/write`, `locations_read/write`,
`customers_read/write`, `commerce_refund`, and `automation`. Unknown Yatoon
routes are denied to scoped keys. `sensitive_data` is a separate permission.

## Endpoints

### Bookings

```
GET    /bookings                 list (paginated)
POST   /bookings                 create
GET    /bookings/{id}            read
POST   /bookings/{id}            update   (also PUT/PATCH)
DELETE /bookings/{id}            cancel   (sets status=cancelled)
```

List responses carry `X-Yatoon-Page` and standard total headers.

#### Create

```bash
curl -X POST https://example.com/wp-json/yatoon/v1/bookings \
  -H "X-Yatoon-Api-Key: ytk_..." \
  -H "Content-Type: application/json" \
  -d '{
        "customer_name":  "Ada Lovelace",
        "customer_email": "ada@example.com",
        "customer_phone": "+1 317 555 0142",
        "service_id":     12,
        "staff_id":       3,
        "location_id":    1,
        "start_time":     "2026-10-02 14:00:00",
        "duration_minutes": 60
      }'
```

`start_time` is interpreted in the location's timezone (the site timezone when
no location is given).

#### Update, and concurrent writes

`POST /bookings/{id}` accepts any subset of the create fields plus `status`
(`pending`, `confirmed`, `completed`, `no_show`, `cancelled`).

The server takes a booking-level lock, then re-reads the row, then validates
against that fresh read, so two simultaneous API writes cannot both decide
against the same stale snapshot.

That does not help when *your* client composed its request from a copy it read
minutes ago and something else changed the booking in between. For that, send
back the `updated_at` you last read:

```json
{ "status": "confirmed", "expected_updated_at": "2026-09-30 11:04:22" }
```

If the stored `updated_at` no longer matches, the request is refused:

```json
{
  "code": "yatoon_booking_stale",
  "message": "This booking changed after it was loaded. Reload it and retry.",
  "data": {
    "status": 409,
    "expected_updated_at": "2026-09-30 11:04:22",
    "current_updated_at":  "2026-09-30 11:09:57"
  }
}
```

`expected_updated_at` is **optional**. Omit it and the previous
last-write-wins behaviour applies, so existing integrations are unaffected.

#### Fields returned

Booking and customer responses omit customer names and contact details,
internal notes, consent/policy snapshots, design references, and payment
identifiers by default. To request them, select `sensitive_data` on the key
and add `include_sensitive=1` to the read request. The user's WordPress
capabilities must also permit customer-data access. Do not enable this for a
connection that does not need personal data.

### Availability

```
GET /availability?date=2026-10-02&service_id=12[&staff_id=3][&location_id=1][&days=7][&duration=90]
```

* `date` — `Y-m-d`, validated with `checkdate()`; `2026-02-31` is a 400, not a
  silent roll-forward.
* `service_id` — required.
* `staff_id` — omit or `0` for any qualified staff member.
* `days` — 1–31, default 1.
* `duration` — override the service duration, in minutes.

Availability honours business hours, buffers, staff time off, external busy
calendars, resources and staff/location rules.

### Refunds

```
POST /orders/{id}/refunds   { "amount": 25.00, "provider": "square", "reason": "..." }
```

Returns 201 on success. Requires the commerce module; otherwise
`yatoon_commerce_missing` (503).

### Directory entities

```
GET|POST        /services  /staff  /locations  /customers
GET|POST|DELETE /services/{id}  /staff/{id}  /locations/{id}  /customers/{id}
```

Creating or activating a staff member on the Free plan is refused with
`yatoon_staff_limit_reached` once the active-staff limit is reached.

## Error responses

Standard WordPress REST error shape:

```json
{ "code": "yatoon_booking_conflict",
  "message": "The staff member is already booked during this interval.",
  "data": { "status": 409 } }
```

| Code | HTTP | Meaning |
|---|---|---|
| `yatoon_not_found` | 404 | No such booking or resource |
| `yatoon_invalid_status` | 400 | Status outside the allowed set |
| `yatoon_invalid_duration` | 400 | Duration not a whole number of minutes within a year |
| `yatoon_assignment_missing` | 400 | Service or staff member is not active |
| `yatoon_location_not_found` | 404 | Location is not active |
| `yatoon_booking_conflict` | 409 | Staff member already booked |
| `yatoon_booking_stale` | 409 | `expected_updated_at` no longer matches |
| `yatoon_booking_busy` | 409 | Another write holds the lock; retry shortly |
| `yatoon_booking_locks_unavailable` | 503 | This database cannot grant advisory locks — see Tools → Site Health |
| `yatoon_external_booking` | 409 | Use the Square/Vagaro workflow for an externally owned booking |
| `yatoon_priced_service_change` | 409 | Booking has options, credit or recorded payment; use the service-change workflow |
| `yatoon_resource_unavailable` | 409 | A required resource is not free |
| `yatoon_closed` / `yatoon_unavailable` | 409 | Outside business hours or staff availability |
| `yatoon_booking_window` | 409 | Outside the online booking horizon |
| `yatoon_staff_limit_reached` | 403 | Free plan active-staff limit |
| `yatoon_update_failed` | 500 | The write itself failed |

## Rate limits

There is **no general rate limit on authenticated REST traffic.** The limits
that exist are specific:

* failed API-key authentication: 20 per 10 minutes, then 429;
* public (unauthenticated) booking-form endpoints, which are not part of this
  API, carry their own per-IP limits.

## Privacy-sensitive fields

`customer_name`, `customer_email`, `customer_phone`, `notes`,
`consent_signature`, `consent_text_snapshot`, `policy_text_snapshot`,
`design_image_url` and the payment identifiers are personal or commercially
sensitive. Do not forward them to systems that do not need them.
