# Yeneb Backend — API Error Surface Reference

Generated from a full read-through of `app/api/v1/endpoints/`, `app/api/v1/deps.py`, and `app/services/rate_limit.py` as of 2026-07-28. This documents actual `raise HTTPException(...)` calls and dependency-driven auth behavior in the code — not assumed conventions. Re-generate/review after any endpoint change that adds, removes, or changes an error condition.

See also: `openapi.json` (or `make export-openapi` to regenerate it) for the full request/response schema of every endpoint — this document is the error/auth reference to read alongside that schema, not a replacement for it.

## Cross-Cutting Behavior

These apply across (almost) every endpoint and are documented once here rather than repeated per domain.

**Global per-IP rate limit (429)**
- `app/services/rate_limit.py`'s `rate_limit_global` is wired in as a router-level dependency in `app/main.py`: `app.include_router(api_router, prefix="/api/v1", dependencies=[Depends(rate_limit_global)])`. It applies to every route under `/api/v1` **except** paths starting with `/api/v1/health` (`_EXEMPT_PATH_PREFIXES`), which are polled frequently by load balancers/uptime monitors.
- It's a fixed-window counter keyed `ratelimit:global:ip:{ip}`, capped at `settings.global_rate_limit_max_requests` per `settings.global_rate_limit_window_seconds`. On breach: `429`, `detail: "Too many requests. Try again later."`, with a `Retry-After` header (seconds until the window resets).
- The WebSocket tracking route (`GET /orders/{order_id}/tracking/ws` in `tracking.py`) is mounted on a **separate router** in `app.main` without this dependency (a `Request`-typed dependency can't attach to a websocket ASGI scope) — it is the one route in the API not covered by this limiter. Its REST companion, the ws-ticket mint endpoint, is still covered.
- Several `auth.py` endpoints additionally apply a **tighter, action-scoped** limiter (`rate_limit_by_ip_and_phone`, same `429`/`Retry-After` shape, keyed by both IP and phone/email) on top of this global one — see the Auth section.

**Standard 401/403 shape for auth failures** — from `app/api/v1/deps.py`:
- `HTTPBearer(auto_error=True)` runs first as a FastAPI dependency. As of the current FastAPI/Starlette versions (upgraded 2026-07-25 — this is a real behavior change from older versions, verified against this codebase's own test suite, not assumed), a **missing `Authorization` header entirely** now raises **401**, not 403 — the older FastAPI default of 403 for "no credentials at all" no longer applies here.
- If a bearer token **is** supplied but fails to decode/verify (expired, malformed, wrong signature), or decodes to a user id that doesn't exist or belongs to a deactivated (`is_active=False`) user, `get_current_user` raises **401**: `detail: "Could not validate credentials."`, header `WWW-Authenticate: Bearer`.
- In short: essentially **every** "you're not properly authenticated" case is 401 now, whether the header is missing or invalid. **403** is reserved specifically for `require_role(*roles)` (also in `deps.py`) — a caller who **is** validly authenticated but whose role isn't one of the allowed roles: `detail: "You don't have permission to do this."`. This is the generic role-gate error referenced throughout the domain tables below as "role-gate 403."

**422 on malformed input** — every endpoint with a Pydantic request-body model implicitly returns FastAPI's standard `422` validation-error response for malformed/missing fields; this is not repeated per-endpoint below. Only **manually raised** `422`s (business-logic rejections, not schema validation) are called out per domain, since those are backend-specific behavior a client needs to know about.

**Request body size cap (413)** — `RequestBodySizeLimitMiddleware` (`app/core/middleware.py`) runs ahead of the app for every HTTP request and rejects (before any endpoint code runs) with a raw `413` (`{"detail": "Request body too large."}`, not a normal `HTTPException`/Pydantic-error payload) if the declared `Content-Length` header exceeds `settings.max_request_body_bytes`. This is separate from `uploads.py`'s own byte-count-based 413 (see Uploads section), which checks actual bytes read rather than the declared header.

**Unhandled exceptions (500)** — a catch-all handler in `app/main.py` converts any exception that isn't already an `HTTPException` into `500` with `{"detail": "Internal server error.", "request_id": "..."}` (and an `X-Request-ID` header), logging the real exception server-side and reporting to Sentry if configured. The client never sees a stack trace.

---

## admin.py — `/admin`

Admin-console operations: inviting couriers/suppliers/admins, managing courier profiles and earnings, the user roster, account activation status, and platform analytics.

| Method | Path | Purpose | Auth |
|---|---|---|---|
| POST | `/admin/couriers` | Invite a new courier account (SMS-activated) | `require_role(ADMIN, SUPERADMIN)` |
| PATCH | `/admin/couriers/{courier_id}` | Update a courier's shift hours / online switch | `require_role(ADMIN, SUPERADMIN)` |
| GET | `/admin/couriers/{courier_id}/earnings` | Courier's lifetime earnings summary | `require_role(ADMIN, SUPERADMIN)` |
| POST | `/admin/suppliers` | Invite a new supplier account | `require_role(ADMIN, SUPERADMIN)` |
| POST | `/admin/admins` | Invite a new admin account | `require_role(SUPERADMIN)` only |
| GET | `/admin/users` | List all users, filterable by role/is_active | `require_role(ADMIN, SUPERADMIN)` |
| PATCH | `/admin/users/{user_id}/status` | Activate/deactivate a user | `require_role(ADMIN, SUPERADMIN)` |
| GET | `/admin/analytics` | Platform analytics snapshot (order volume, top merchants/branches, revenue) | `require_role(ADMIN, SUPERADMIN)` (`revenue` field is `null` unless caller is SUPERADMIN — not an error) |

Error codes:

| Code | Trigger |
|---|---|
| 403 | Role-gate 403 (all endpoints, non-admin/superadmin caller). Additionally, `update_user_status` raises `"Only a superadmin can change another admin's status."` when a regular admin tries to change another admin's or superadmin's status. |
| 404 | `"Courier not found."` — `update_courier_profile`, `get_courier_earnings` (id doesn't exist or isn't a COURIER). `"User not found."` — `update_user_status`. |
| 409 | Shared constants `_ACCOUNT_EXISTS` (`"An account with this phone number already exists."`) and `_EMAIL_EXISTS` (`"An account with this email already exists."`), raised by `invite_courier`/`invite_supplier`/`invite_admin` (via shared `_invite_user`). |

---

## auth.py — `/auth`

Customer self-signup (phone-or-email + OTP + PIN), login, Google Sign-In, PIN reset/change, invited-account activation, and add-phone/add-email verification flows.

| Method | Path | Purpose | Auth |
|---|---|---|---|
| POST | `/auth/signup/start` | Step 1 of customer signup — send OTP to phone or email | None (public) |
| POST | `/auth/signup/verify-otp` | Step 2 — verify OTP, get a verification token | None |
| POST | `/auth/signup/complete` | Step 3 — set PIN, create account, log in | None |
| POST | `/auth/google` | Sign up or log in via Google ID token | None |
| POST | `/auth/google/connect` | Link Google identity to the logged-in account (PIN-confirmed) | `Depends(get_current_user)` |
| POST | `/auth/login` | Phone/email + PIN login | None |
| POST | `/auth/refresh` | Rotate a refresh token for a new access token | None |
| POST | `/auth/logout` | Revoke a refresh token | None |
| POST | `/auth/forgot-pin/start` | Send OTP to reset PIN | None |
| POST | `/auth/forgot-pin/verify-otp` | Verify OTP, get a verification token | None |
| POST | `/auth/forgot-pin/reset` | Set new PIN using verification token | None |
| POST | `/auth/activate/verify-otp` | First step activating an admin-invited account | None |
| POST | `/auth/activate/complete` | Set PIN on an invited account, log in | None |
| POST | `/auth/phone/start` | Start adding/replacing a verified phone | `Depends(get_current_user)` |
| POST | `/auth/phone/verify-otp` | Verify OTP for add-phone | `Depends(get_current_user)` |
| POST | `/auth/phone/complete` | Attach the verified phone to the account | `Depends(get_current_user)` |
| POST | `/auth/email/start` | Start adding/replacing a verified email | `Depends(get_current_user)` |
| POST | `/auth/email/verify-otp` | Verify OTP for add-email | `Depends(get_current_user)` |
| POST | `/auth/email/complete` | Attach the verified email to the account | `Depends(get_current_user)` |
| PATCH | `/auth/me/marketing-consent` | Opt in/out of marketing emails | `Depends(get_current_user)` |
| PATCH | `/auth/me/pin` | Change PIN (requires current PIN) | `Depends(get_current_user)` |
| GET | `/auth/me` | Get the logged-in user's profile | `Depends(get_current_user)` |

Error codes:

| Code | Trigger |
|---|---|
| 400 | `OTPError` (dynamic `detail`, e.g. invalid/expired code) — raised in every OTP-verify and verification-token-consume step: `signup_verify_otp`, `signup_complete`, `forgot_pin_verify_otp`, `forgot_pin_reset`, `activate_verify_otp`, `activate_complete`, `phone/verify-otp`, `phone/complete`, `email/verify-otp`, `email/complete`. Also `forgot_pin_reset` → `"Verify your phone number or email again."` if the verified identifier no longer resolves to a user; `activate_complete` → `"Account not found. Ask an admin to invite you again."` if the invited row is gone. |
| 401 | Shared constant `_INCORRECT_LOGIN` (`"Incorrect phone number, email, or PIN."`) in `login`. `google_signin`/`google_connect` → `GoogleTokenError` message (str) on bad ID token. `google_connect` and `change_pin` → `"Incorrect PIN."` when the current PIN check fails. `refresh` → `RefreshTokenError` message (str) on an invalid/expired/reused refresh token. |
| 403 | `login` → `"Activate your account first — check your SMS for a verification code."` (either a pending/never-activated account, or one whose `pin_hash` is still null). `google_signin` → `"This account has been disabled."` for a deactivated account. |
| 409 | `_ACCOUNT_EXISTS`/`_EMAIL_EXISTS` (phone/email already verified-and-owned) in `signup_start`, `signup_complete`, `add_phone_start`, `add_phone_complete`, `add_email_start`, `add_email_complete`. `google_signin` → `"An account with this email already exists. Log in, then connect Google from your account."` on an email collision with a non-Google account. `google_connect` → `"This Google account is already linked to a different account."` `activate_complete` → `"This account has already been activated. Log in instead."` |
| 423 | `login` → `"Too many failed attempts. Try again in a few minutes, or reset your PIN."` when `locked_until` is still in the future (lockout after `max_pin_attempts` failed PIN attempts). |
| 429 | `rate_limit_by_ip_and_phone` (tighter than the global limiter, keyed by IP **and** the specific phone/email, scoped per action) on: `signup_start`, `signup_verify_otp`, `login`, `forgot_pin_start`, `forgot_pin_verify_otp`, `activate_verify_otp`, `add_phone_start`, `add_phone_verify_otp`, `add_email_start`, `add_email_verify_otp`. |

Also note (not an error, but relevant to client-side validation): `PinSetRequest.pin` (signup/forgot-pin-reset/activation) and `ChangePinRequest.new_pin` reject a blocklist of predictable 6-digit PINs (`000000`–`999999` repeats, `123456`, etc.) with a `422`. `LoginRequest.pin`/`ChangePinRequest.current_pin` do not — proving you know an existing (possibly old, weak) PIN is always allowed.

---

## branches.py — `/branches`

Public branch browse/search, branch settings, full menu management (categories → items → option groups → options), manager invites, branch reviews, favoriting.

| Method | Path | Purpose | Auth |
|---|---|---|---|
| GET | `/branches` | Marketplace-wide search of approved+active branches | `Depends(get_current_user)` |
| GET | `/branches/{branch_id}` | Branch detail + full menu | `Depends(get_current_user)` |
| PATCH | `/branches/{branch_id}` | Update branch fields (e.g. `is_active`) | `get_current_user` + must be branch staff (admin, merchant owner, or assigned manager) |
| PATCH | `/branches/{branch_id}/approve` | Admin approve/reject a branch | `require_role(ADMIN, SUPERADMIN)` |
| PATCH | `/branches/{branch_id}/hours` | Set opening hours | `get_current_user` + branch staff |
| PATCH | `/branches/{branch_id}/minimum-order` | Set minimum order amount | `get_current_user` + branch staff |
| POST | `/branches/{branch_id}/categories` | Create a menu category | `get_current_user` + branch staff |
| PATCH | `/branches/{branch_id}/categories/{category_id}` | Update a menu category | `get_current_user` + branch staff |
| DELETE | `/branches/{branch_id}/categories/{category_id}` | Delete a menu category (204) | `get_current_user` + branch staff |
| POST | `/branches/{branch_id}/categories/{category_id}/items` | Create a menu item | `get_current_user` + branch staff |
| PATCH | `/branches/{branch_id}/items/{item_id}` | Update a menu item | `get_current_user` + branch staff |
| DELETE | `/branches/{branch_id}/items/{item_id}` | Soft-delete a menu item (204) | `get_current_user` + branch staff |
| POST | `/branches/{branch_id}/items/{item_id}/option-groups` | Create an option group | `get_current_user` + branch staff |
| PATCH | `/branches/{branch_id}/items/{item_id}/option-groups/{group_id}` | Update an option group | `get_current_user` + branch staff |
| DELETE | `/branches/{branch_id}/items/{item_id}/option-groups/{group_id}` | Delete an option group (204) | `get_current_user` + branch staff |
| POST | `/branches/{branch_id}/items/{item_id}/option-groups/{group_id}/options` | Create an option | `get_current_user` + branch staff |
| PATCH | `.../option-groups/{group_id}/options/{option_id}` | Update an option | `get_current_user` + branch staff |
| DELETE | `.../option-groups/{group_id}/options/{option_id}` | Delete an option (204) | `get_current_user` + branch staff |
| POST | `/branches/{branch_id}/managers` | Invite a branch manager | `get_current_user` + must be merchant owner or admin |
| GET | `/branches/{branch_id}/reviews` | List branch reviews | `Depends(get_current_user)` |
| POST | `/branches/{branch_id}/favorite` | Favorite a branch (204) | `require_role(CUSTOMER)` |
| DELETE | `/branches/{branch_id}/favorite` | Unfavorite a branch (204) | `require_role(CUSTOMER)` |

Error codes:

| Code | Trigger |
|---|---|
| 403 | `"You don't manage this branch."` (`_require_branch_staff`, all menu-mutation/hours/minimum-order/branch-update endpoints for a non-staff caller). `"Only the merchant owner or an admin can invite managers."` (`invite_manager`). |
| 404 | Shared `_NOT_FOUND` (`"Branch not found."`) — used both for a genuinely missing branch **and** for a branch that exists but isn't visible to this caller (`_get_visible_branch` deliberately 404s rather than 403s, so existence/status isn't leaked). Also `"Menu category not found."`, `"Menu item not found."`, `"Option group not found."`, `"Option not found."` from their respective `_get_..._or_404` helpers. |
| 409 | `_ACCOUNT_EXISTS`/`_EMAIL_EXISTS` in `invite_manager`. `"This category still has items — move or delete them first."` (`delete_menu_category`, refuses to orphan items). |

---

## cart.py — `/cart`

The logged-in customer's single shopping cart: add/update/remove line items with full menu-option validation.

| Method | Path | Purpose | Auth |
|---|---|---|---|
| GET | `/cart` | Get the current cart | `require_role(CUSTOMER)` |
| POST | `/cart/items` | Add an item (merges into an existing matching line) | `require_role(CUSTOMER)` |
| PATCH | `/cart/items/{item_id}` | Update a line item's quantity | `require_role(CUSTOMER)` |
| DELETE | `/cart/items/{item_id}` | Remove a line item | `require_role(CUSTOMER)` |
| DELETE | `/cart` | Clear the entire cart | `require_role(CUSTOMER)` |

Error codes:

| Code | Trigger |
|---|---|
| 404 | `"Menu item not found."` (`add_item`). `"One or more selected options were not found."` (`_validate_options`). Shared `_ITEM_NOT_FOUND` (`"Cart item not found."`) — `update_item`, `remove_item`. |
| 409 | `"This item isn't available right now."` (`add_item`, `is_available=false`). `"This branch is currently closed."` (`add_item`). `"One or more selected options don't belong to this item."` / `'"{option}" is not available right now.'` / `'Only one option can be selected from "{group}".'` (all `_validate_options`). `"Your cart has items from a different merchant. Clear it first to order from here."` (`add_item`, mixed-branch cart). |
| 422 (manual) | `"Quantity must be a whole number for this item."` (`_require_whole_number_if_no_unit` — non-weight/volume items can't have a fractional quantity; hit by `add_item` and `update_item`). `'Please select an option for "{group}".'` (`_validate_options` — a required option group has no selection; `add_item` only). |

---

## courier.py — `/courier`

Courier-side delivery workflow: profile view, live location posting, offer accept/reject, pickup/delivery confirmation, delivery history and earnings.

| Method | Path | Purpose | Auth |
|---|---|---|---|
| GET | `/courier/profile` | Read-only view of admin-configured shift/online status | `require_role(COURIER)` |
| POST | `/courier/location` | Post current GPS location (broadcast if on an active delivery) | `require_role(COURIER)` |
| GET | `/courier/offers/current` | Get the currently pending delivery offer, if any | `require_role(COURIER)` |
| POST | `/courier/offers/{assignment_id}/accept` | Accept a pending offer | `require_role(COURIER)` |
| POST | `/courier/offers/{assignment_id}/reject` | Reject a pending offer | `require_role(COURIER)` |
| POST | `/courier/deliveries/{assignment_id}/picked-up` | Mark an accepted delivery as picked up | `require_role(COURIER)` |
| POST | `/courier/deliveries/{assignment_id}/delivered` | Mark a picked-up delivery as delivered (completes the order) | `require_role(COURIER)` |
| GET | `/courier/deliveries` | Full delivery-assignment history | `require_role(COURIER)` |
| GET | `/courier/earnings/summary` | Total earnings + delivery count | `require_role(COURIER)` |
| GET | `/courier/earnings` | Itemized earnings list | `require_role(COURIER)` |

Error codes:

| Code | Trigger |
|---|---|
| 404 | Shared `_ASSIGNMENT_NOT_FOUND` (`"Delivery assignment not found."`) — `_get_own_assignment`, used by accept/reject/picked-up/delivered when the assignment id doesn't belong to this courier. `"No pending offer."` (`get_current_offer`, no `OFFERED` assignment exists). |
| 409 | `"This offer is no longer pending."` (`accept_offer`, `reject_offer` — status isn't `OFFERED`). `"This delivery hasn't been accepted yet."` (`mark_picked_up` — status isn't `ACCEPTED`). `"This delivery hasn't been picked up yet."` (`mark_delivered` — status isn't `PICKED_UP`). |

---

## customer.py — `/customer`

Customer-only self-service: favorited branches list, optional profile details (skippable).

| Method | Path | Purpose | Auth |
|---|---|---|---|
| GET | `/customer/favorites` | List favorited branches, most-recent first | `require_role(CUSTOMER)` |
| GET | `/customer/profile` | Get optional profile fields | `require_role(CUSTOMER)` |
| PATCH | `/customer/profile` | Partially update profile fields | `require_role(CUSTOMER)` |

Error codes: none raised in this file — no `HTTPException` calls beyond the role-gate 403 and standard 401/422 covered in the cross-cutting section.

---

## health.py — `/health` (no router prefix)

Liveness/readiness checks for load balancers and uptime monitors.

| Method | Path | Purpose | Auth |
|---|---|---|---|
| GET | `/health` | Basic liveness (no dependencies checked) | None |
| GET | `/health/db` | Executes `SELECT 1` to confirm DB connectivity | None |
| GET | `/health/redis` | Pings Redis to confirm connectivity | None |

Error codes: no `HTTPException` is raised in this file. `/health/db` and `/health/redis` have no try/except around the DB/Redis call — if the dependency is actually down, the call throws and falls through to the global unhandled-exception handler (**500**), not a custom status. This entire path prefix (`/api/v1/health`) is also the one exemption from the global rate limiter (see Cross-Cutting).

---

## merchants.py — `/merchants`

Merchant (business/brand) CRUD, per-merchant branch listing/creation, and public/cached merchant discovery.

| Method | Path | Purpose | Auth |
|---|---|---|---|
| POST | `/merchants` | Create a merchant (supplier for self, or admin on behalf of a supplier via `owner_id`) | `require_role(SUPPLIER, ADMIN, SUPERADMIN)` |
| GET | `/merchants` | List merchants (cached "public" list for customers) | `Depends(get_current_user)` |
| GET | `/merchants/{merchant_id}` | Get a single merchant (cached) | `Depends(get_current_user)` |
| PATCH | `/merchants/{merchant_id}` | Partially update a merchant | `get_current_user` + must own merchant or be admin |
| POST | `/merchants/{merchant_id}/branches` | Create a branch under a merchant | `get_current_user` + must own merchant or be admin |
| GET | `/merchants/{merchant_id}/branches` | List a merchant's own branches | `Depends(get_current_user)` |

Error codes:

| Code | Trigger |
|---|---|
| 403 | `"You don't own this merchant."` (`_require_merchant_manager`, `update_merchant`/`create_branch` for a non-owner, non-admin caller). |
| 404 | Shared `_NOT_FOUND` (`"Merchant not found."`) — `_get_merchant_or_404`. `"No supplier account found for that owner_id."` (`create_merchant`, admin-supplied `owner_id` doesn't resolve to a SUPPLIER account). |
| 422 (manual) | `"owner_id is required when an admin creates a merchant."` (`create_merchant`, admin path omits `owner_id`). |

---

## notifications.py — `/notifications`

Push-notification device token registration/removal, usable by any authenticated role.

| Method | Path | Purpose | Auth |
|---|---|---|---|
| POST | `/notifications/device-tokens` | Register a device token (204) | `Depends(get_current_user)` |
| DELETE | `/notifications/device-tokens/{token}` | Unregister a device token (204) | `Depends(get_current_user)` |

Error codes: none raised in this file. Unregistering a token that isn't the caller's own is a silent no-op, not an error.

---

## orders.py — `/orders`

Checkout (cart → order), order lifecycle transitions, self-cancellation, admin refund confirmation, reorder, and post-completion reviews.

| Method | Path | Purpose | Auth |
|---|---|---|---|
| POST | `/orders/checkout` | Place an order from the current cart, start Chapa payment if non-cash | `require_role(CUSTOMER)` |
| GET | `/orders` | List orders (role-scoped: own orders / own branches' orders / all) | `Depends(get_current_user)` |
| GET | `/orders/{order_id}` | Get one order with items | `get_current_user` + must be the customer or branch staff |
| PATCH | `/orders/{order_id}/status` | Advance order status (branch-staff-driven) | `get_current_user` + must be branch staff |
| POST | `/orders/{order_id}/cancel` | Customer self-cancel (only while `PENDING_PAYMENT`/`CONFIRMED`) | `require_role(CUSTOMER)` |
| POST | `/orders/{order_id}/mark-refunded` | Confirm an out-of-band refund was completed | `require_role(ADMIN, SUPERADMIN)` |
| POST | `/orders/{order_id}/reorder` | Re-add a past order's items to the current cart | `require_role(CUSTOMER)` |
| POST | `/orders/{order_id}/review` | Leave a review on a completed order | `require_role(CUSTOMER)` |

Error codes:

| Code | Trigger |
|---|---|
| 400 | `"Your cart is empty."` (`checkout`, no cart or no cart items). |
| 403 | `"You don't manage this branch."` (`update_order_status`, caller isn't staff for the order's branch). |
| 404 | Shared `_NOT_FOUND` (`"Order not found."`) — `get_order` (missing or caller has no access — hides existence rather than 403ing), `update_order_status` (order missing), `cancel_order`/`reorder_order`/`create_review` (order missing or not owned by this customer). |
| 409 | `"An item in your cart is no longer available. Update your cart and try again."` / `'"{item}" is no longer available...'` / `'"{option}" is no longer available...'` (`checkout`, stale cart contents). `"This branch is currently closed."` (`checkout`, `reorder_order`). `"This order hasn't been paid for yet."` (`update_order_status`, still `PENDING_PAYMENT`). `"Delivery orders are completed by the courier, not this endpoint."` (`update_order_status`). `"Can't move an order from {X} to {Y}."` (`update_order_status`, invalid state transition). `"This order has already been picked up for delivery — contact support to cancel it."` (`_cancel_order`, shared by both cancel paths). `"This order can no longer be self-cancelled — contact the merchant."` (`cancel_order`). `"This order doesn't have a refund pending."` (`mark_order_refunded`). `"This branch no longer exists."` (`reorder_order`). `"Your cart has items from a different merchant. Clear it first to reorder from here."` (`reorder_order`). `"None of the items in this order are still available."` (`reorder_order`, everything skipped). `"Only a completed order can be reviewed."` / `"This order has already been reviewed."` (`create_review`). |
| 422 (manual) | `"Delivery address is required for delivery orders."` / `"Delivery location is required for delivery orders."` (`checkout`, delivery mode missing required fields). `"Minimum order amount for this branch is {X} ETB."` (`checkout`, subtotal below branch minimum). Promo code rejection — `promo_service.PromoCodeError` surfaced with its own dynamic message (`checkout`, e.g. an ineligible/expired/exhausted promo code). "Order for a Friend" validation (`recipient_name`/`recipient_phone` must both be set or neither; `delivery_mode` must be `"delivery"`; the recipient's address must fall within Ethiopia) — enforced in `CheckoutRequest` itself, so these surface as standard Pydantic `422`s, not manually-raised ones. |

---

## payments.py — `/webhooks` (file is `payments.py`, router prefix is `/webhooks`)

Chapa payment-gateway webhook receiver. Not called by the Flutter app directly — included here since it's in the endpoints directory and is part of the order-payment flow the client observes indirectly (order moving from `PENDING_PAYMENT` to `CONFIRMED`).

| Method | Path | Purpose | Auth |
|---|---|---|---|
| POST | `/webhooks/chapa` | Chapa payment-status callback | None (Bearer) — authenticated via `x-chapa-signature` HMAC header instead |

Error codes:

| Code | Trigger |
|---|---|
| 400 | `"Missing tx_ref."` (payload has no `tx_ref`). |
| 401 | `"Invalid signature."` (`x-chapa-signature` header missing or doesn't verify) — a domain-specific 401, distinct from the standard bearer-token 401 shape. |

Note: for a known-but-unactionable case (unknown `tx_ref`, or an already-processed payment) the endpoint deliberately returns **200** (`{"status": "ignored"}` / `{"status": "already processed"}`) rather than an error, so Chapa's webhook retry loop doesn't keep hammering something that will never resolve.

---

## promo_codes.py — `/promo-codes`

Promo code CRUD — admins manage any code (including platform-wide ones); suppliers manage only codes scoped to a merchant they own.

| Method | Path | Purpose | Auth |
|---|---|---|---|
| POST | `/promo-codes` | Create a promo code | `require_role(SUPPLIER, ADMIN, SUPERADMIN)` |
| GET | `/promo-codes` | List promo codes (role-scoped) | `require_role(SUPPLIER, ADMIN, SUPERADMIN)` |
| PATCH | `/promo-codes/{promo_id}` | Update a promo code | `require_role(SUPPLIER, ADMIN, SUPERADMIN)` |

Error codes:

| Code | Trigger |
|---|---|
| 403 | `"You don't own this merchant."` (`_require_owns_merchant`, `create_promo_code` when a supplier's `merchant_id` isn't theirs). `"You don't manage this promo code."` (`_require_promo_manager`, `update_promo_code` when a supplier targets a platform-wide code). |
| 404 | Shared `_NOT_FOUND` (`"Promo code not found."`) — `_get_promo_or_404`, `update_promo_code`. |
| 409 | Shared `_CODE_EXISTS` (`"A promo code with this code already exists."`) — `create_promo_code`. |
| 422 (manual) | `"merchant_id is required."` (`create_promo_code`, non-admin omits `merchant_id`). `"branch_id must belong to merchant_id."` (`create_promo_code`, mismatched branch/merchant). |

---

## reviews.py — `/reviews`

Editing, staff replies, and admin moderation for reviews (reviews are created via `orders.py`'s `create_review`).

| Method | Path | Purpose | Auth |
|---|---|---|---|
| PATCH | `/reviews/{review_id}` | Customer edits their own review | `require_role(CUSTOMER)` + must be the review's author |
| POST | `/reviews/{review_id}/reply` | Branch staff post/overwrite a reply | `get_current_user` + must be branch staff |
| PATCH | `/reviews/{review_id}/visibility` | Admin hide/unhide a review | `require_role(ADMIN, SUPERADMIN)` |

Error codes:

| Code | Trigger |
|---|---|
| 403 | `"You don't manage this branch."` (`reply_to_review`, caller isn't staff for the review's branch). |
| 404 | Shared `_NOT_FOUND` (`"Review not found."`) — `_get_review_or_404`. `update_review` also returns this same 404 (not 403) when the review exists but belongs to a different customer, deliberately hiding ownership rather than exposing it. |

---

## tracking.py — `/orders` (REST) + separate `ws_router` on `/orders` (WebSocket)

Order delivery tracking: REST snapshot, a short-lived WS-ticket mint, and a live WebSocket feed of courier location/status.

| Method | Path | Purpose | Auth |
|---|---|---|---|
| GET | `/orders/{order_id}/tracking` | REST snapshot of current assignment/courier location | `Depends(get_current_user)` |
| POST | `/orders/{order_id}/tracking/ws-ticket` | Mint a short-lived, single-use WS ticket | `Depends(get_current_user)` |
| WS | `/orders/{order_id}/tracking/ws` | Live push of location/status updates | `ticket` query param (see below), not a Bearer token |

Error codes:

| Code | Trigger |
|---|---|
| 404 | Shared `_ORDER_NOT_FOUND` (`"Order not found."`) — `get_tracking`, `create_tracking_ws_ticket` (order missing, or caller is neither the customer nor branch staff for it). |

**WebSocket route is not HTTP-status-based.** It authenticates via a `?ticket=` query param (minted by the REST ws-ticket endpoint above, TTL `tracking_service.WS_TICKET_TTL_SECONDS`, single-use) instead of an `Authorization` header, since browsers/clients can't set custom headers on a WS handshake. On failure it closes the socket with an app-defined close code rather than returning an HTTP error:
- **4401** — ticket missing/invalid/expired/already-redeemed, or the resolved user is missing/inactive.
- **4404** — order doesn't exist, or the ticket's user isn't the customer or branch staff for it.

This route is also the one endpoint not covered by the global `429` rate limiter (see Cross-Cutting) — only its REST ws-ticket-mint companion is.

---

## uploads.py — `/uploads`

Generic image upload (courier/merchant photos, etc.), validated by both declared content-type and actual decoded image format.

| Method | Path | Purpose | Auth |
|---|---|---|---|
| POST | `/uploads/image` | Upload a JPEG/PNG/WebP image, get back a URL | `Depends(get_current_user)` |

Error codes:

| Code | Trigger |
|---|---|
| 400 | Shared `_INVALID_IMAGE` (`"Only JPEG, PNG, or WebP images are accepted."`) — raised for: a disallowed `Content-Type` header; Pillow failing to decode/verify the bytes as an image at all; or a successfully-decoded image whose actual format isn't JPEG/PNG/WebP (catches a relabeled/renamed non-image file even if the `Content-Type` header lied). |
| 413 | `"Images can't be larger than {max_mb}MB."` — endpoint-level check based on actually-read bytes (reads up to `settings.max_upload_size_bytes + 1` bytes), so it also catches an oversized body that never declared (or lied about) a `Content-Length` header. Distinct from the global `Content-Length`-based `413` middleware described in Cross-Cutting. |
