# backend — API test case info HTTP/API tests that drive a **running** backend (not unit tests): they log in with real credentials, create data through the API, and pull the generated static JSON cache the apps consume. - **Runner**: jest + ts-jest, node environment, serial (`--runInBand`) - **Total**: **22 suites / 107 tests** — all green (`bun run test:api`, ~2.5 min) - Tests live in `apps/backend/tests/`; they do not import server runtime code beyond the `AppRouter` type. ## Run ```bash # 1. start the backend (wrangler dev, port 8787) cd apps/backend && bun run dev # 2. fill in credentials (git-ignored) cp apps/backend/tests/.env.example apps/backend/tests/.env # then edit # 3. run cd apps/backend && bun run test:api bun run test:api:typecheck # tsc over tests/ ``` `API_BASE_URL` defaults to `http://localhost:8787`; override it in `tests/.env`. ## Environment notes - **Auth**: `admin.staffUser.login` (staff) and `user.auth.login` (user). Login, not OTP — OTP requires a real SMS. The user must exist in the **local** D1. - **Preconditions are not seeded** (only config/constants are): the suites create a store, a one-SKU product and a future slot through the **admin** API, plus an address for the user. Data is **left behind**; names carry a unique suffix so reruns stay valid. - **Cache files** are written through the R2 S3 API to the real dev bucket and read back from the **assets domain** (`assetsDomain` from `common.essentialConsts`, e.g. `https://assets2.freshyo.in`). The machine therefore needs network access to both. - **Trigger timing** decides the suite layout: `slots.json` and `availability.json` are regenerated **synchronously** inside their mutations; `products.json` / `stores/.json` are rebuilt ~30 s later by the `CACHE_CREATOR` Durable Object → those tests poll. - Test slots must be in the **future** and not at capacity — the public slots payload filters to future, non-full slots. ## Findings from the first green run - **`availability.json` is keyed by SKU id**, not product id (`id: stat.skuId`), and its `isOutOfStock` comes from `product_market_stats`. `admin.product.toggleOutOfStock` takes a **product** id and flips `product_market_stats` for all of that product's SKUs, so it *is* app-visible — but look the entry up by `skuId`. - **The cache rebuild writes files in parallel (non-atomic).** After `cacheVersion` advances, `products.json` can be readable while `stores/.json` is still uploading (observed: 404 at the new version, 200 moments later). The tests therefore poll for each individual file. - **`placeOrder` accepts a non-existent `slotId`.** It only checks slot *capacity*; there is no FK/validity check, so a bogus id is stored verbatim. Case 17 documents this gap — it will need updating if the backend adds validation. - **Admin *reads* are not staff-guarded.** `protectedProcedure` only requires *some* identity, so a plain user token can call `admin.product.getProducts` (documented by the authorization suite). Staff-guarded writes (e.g. `admin.slots.createSlot`) do check `ctx.staffUser`. - **`availability.json` and `slots.json` can lead `products.json`.** Both are bumped synchronously (stock toggle / slot mutation) while `products.json` only rebuilds ~30 s later, so for a window the cache references product ids that the product file doesn't have yet. The consistency checks poll for convergence and assert the stable parts. - **`essential-consts.json` embeds a version snapshot** taken when it was written, so its `slotsVersionNum`/`availabilityVersionNum` can lag the live values (slots bump independently). Consumers get versions from `common.essentialConsts` (tRPC), not from this file. - **`updateProduct` requires a SKU feature literally named `quantity`** ("Every SKU must have a quantity feature") — the same rule as the create path. - **`admin.order.updateAddressCoords` succeeds but is not visible to the user.** The user-facing `address.getUserAddresses` still returns `latitude` null/0, so the admin write and the user read disagree. The test asserts the mutation contract only. - **`admin.order.cancelOrder` refuses an already-delivered order**; the test cancels a freshly placed one instead. - **`admin.order.*` id types are inconsistent**: `getOrderDetails` / `updateNotes` / `removeDeliveryCharge` / `cancelOrder` take a **number**; `updatePackaged` / `updateDelivered` / `getSlotOrders` take a **string**. - **`admin.coupon.create` returns an array** (`Coupon[]`) — take `[0].id`. `update` takes `{ id, updates }` and merges partially (fields present win). `delete` **soft-invalidates** ("Coupon invalidated successfully"): `getById` still returns the row, but it vanishes from `coupon.getEligible` and `placeOrder` rejects it. Creating with **both** `discountPercent` and `flatDiscount` is rejected. - **`admin.user.getUserDetails` breaks once a user has a long order history.** It builds an unchunked `select … from order_status where order_id in (…)` over every order the user ever placed; at ~110 orders the query fails outright (`Failed query`). Reproduction: call it for the shared test account after a few runs. The suite now exercises it against a fresh user. Same unchunked pattern is used for the order stats in `admin.user.getAllUsers`. - **`admin.product.deleteProduct` fails for a product that has SKUs.** It issues a hard `delete from product_info … returning …`, which trips the FK from the product's SKUs / market stats; the API returns a raw "Failed query" instead of a 404/409. There is no soft-delete path reachable through this procedure. The test asserts the rejection. - **`admin.store.deleteStore` takes `{ storeId }`**, unlike its siblings (`product.deleteProduct`, `banner.deleteBanner`, `product.deleteProductTag`) which take `{ id }`. Mismatched shape → zod `invalid_type` on `storeId`. - **`admin.slots.getAll` returns at most 20 slots** (hard-coded limit) and keeps returning them as runs accumulate data, so a freshly created slot is not guaranteed to be inside that window. The membership assertion moved to the unbounded public `user.slots.getSlots`; the cap itself is now asserted. - **`vendorSnippets.getOrdersBySnippet` requires the snippet to be linked to a slot** — otherwise it throws "Vendor snippet not associated with a slot", because it resolves orders through the slot. `snippetCode` is also **required** on create. - **`admin.banner.createBanner` needs a URL-shaped `imageUrl`** (`z.string().url()`) and extracts an object key from it; a plausible assets-domain URL is accepted without any upload. - **Suspension is a live precondition for ordering.** `placeOrder` rejects a suspended user ("Unable to place order"), so the admin-ops suite unsuspends the shared test user in `beforeAll` and the suspension test restores the flag in a `finally`. - **`stores/.json` can land in a *later* cache version than the one captured after a write.** `cacheVersion` advances on every admin write while the ~30 s rebuild writes the per-store files separately, so the store-detail test resolves the current version on each poll attempt instead of pinning it. - **A presigned upload URL is usable by any client, with no R2 credentials.** The signature travels in the query string and `Content-Type` is deliberately left unsigned (see the comment in `generateUploadUrl`), so the test process can PUT bytes straight to R2 and read the object back from the public assets domain. `X-Amz-Expires` is 180 s. - **The object key is `${folder}/${Date.now()}${extension}`** (`common.generateUploadUrls`), with the folder chosen from `contextString` (product-images, tags, store-images, review-images, review-response-images, complaint-images, profile-images) and the extension from the mime type (jpg/png/gif, jpg fallback). Two files with the *same* mime type in one call share a millisecond and therefore a key — one pending-status row, two URLs, one object. Deliberately not covered here. - **Every presign writes a `pending` status row** (`createUploadUrlStatus`), and `claimUploadUrl` flips it to claimed — throwing `Failed to claim upload URL` when the row is absent or already claimed. The admin create paths that accept `uploadUrls` (product SKU images, tag image, review response) depend on it. Not covered here: claim/re-claim, and `deleteImageUtil` on image replacement (store update, tag update/delete, product update). ## Suites ### `api/health.test.ts` — 3 (no auth) | # | Test | Request → assert | | --- | --- | --- | | 1 | GET /api/health responds 200 | `GET /api/health` → 200 + ok | | 2 | common.healthCheck resolves over tRPC | `common.healthCheck` → truthy | | 3 | common.essentialConsts returns the runtime config | numeric `freeDeliveryThreshold`, string `assetsDomain`/`apiCacheKey`, numeric `cacheVersion`/`slotsVersionNum` | ### `api/auth.test.ts` — 3 | # | Test | Request → assert | | --- | --- | --- | | 4 | staff login returns a token and staff id | `admin.staffUser.login` → token, `staff.id > 0` | | 5 | user login returns a token and user id | `user.auth.login` → token, `user.id > 0` | | 6 | each token authenticates its own protected procedures | staff → `admin.product.getProducts`; user → `user.address.getUserAddresses` | ### `api/admin.test.ts` — 2 | # | Test | Request → assert | | --- | --- | --- | | 7 | admin.product.getProducts includes the created SKU | created product found with the created sku id | | 8 | admin.slots.getAll includes the created slot | created slot id present | ### `api/order-flow.test.ts` — 5 (the requested flow) | # | Test | Request → assert | | --- | --- | --- | | 9 | lists the created slot via user.slots.getSlots | created slot id present | | 10 | places a COD order and echoes the total | `user.order.placeOrder` (cod) → one order, id/total > 0 | | 11 | returns the new order from user.order.getOrders | order id present, `deliveryStatus: 'pending'`, 1 item, `pagination.totalCount > 0` | | 12 | returns the same order from user.order.getOrderById | id/amount match, 1 item | | 13 | places an online order with a pending payment | `paymentMethod:'online'` → `paymentMode: 'Online'`, `paymentStatus: 'pending'` | ### `api/order-edge-cases.test.ts` — 4 | # | Test | Request → assert | | --- | --- | --- | | 14 | rejects an unauthenticated request | no token → UNAUTHORIZED | | 15 | rejects an address that is not the user's | bogus addressId → "Invalid address" | | 16 | rejects an unknown skuId | bogus skuId → "not found" | | 17 | accepts a non-existent slotId (known gap) | bogus slotId → order is created and `slotId` stored verbatim (no validity/FK check) — documents the gap | ### `api/cache-slots.test.ts` — 3 (synchronous cache) | # | Test | Request → assert | | --- | --- | --- | | 18 | exposes a numeric slotsVersionNum | `common.essentialConsts` → number > 0 | | 19 | contains a newly created slot | create slot → GET `slots/v-/slots.json` → slot id present, deliveryTime matches | | 20 | bumps the version and rewrites the file for a second slot | `slotsVersionNum` increases; the new file contains the second slot | ### `api/cache-availability.test.ts` — 2 (synchronous cache) | # | Test | Request → assert | | --- | --- | --- | | 21 | reflects an out-of-stock toggle for the new SKU | `admin.product.toggleOutOfStock({id})` → `isOutOfStock: true` in the response, `availabilityVersionNum` increases → GET `av-/availability.json` → entry (keyed by **skuId**) `isOutOfStock: true` | | 22 | has a count matching the number of entries | `count === availability.length` | ### `api/cache-products.test.ts` — 2 (eventual cache, polls ~30–120 s) | # | Test | Request → assert | | --- | --- | --- | | 23 | lists the new product in products.json | poll `cacheVersion` past the baseline → GET `/v-/products.json` → new product id present | | 24 | writes stores/<id>.json for the new store | GET `/v-/stores/.json` → `store.id` matches | ### `api/authorization.test.ts` — 5 | # | Test | Request → assert | | --- | --- | --- | | 25 | rejects anonymous requests | no token → UNAUTHORIZED | | 26 | a staff token cannot act as a user (no ctx.user) | staff token → `user.order.getOrders` rejects | | 27 | a user token cannot use staff-guarded admin writes | user token → `admin.slots.createSlot` rejected | | 28 | DOCUMENTS: a user token CAN read `admin.product.getProducts` | no staff guard on admin reads — documents the gap | | 29 | one user cannot see another user's addresses | registered user B's list excludes user A's address | ### `api/order-rules.test.ts` — 6 Uses a tiny-priced SKU (5) so one unit is below `minRegularOrderValue`. | # | Test | Request → assert | | --- | --- | --- | | 30 | adds the configured delivery charge below the minimum order value | qty 1 → `deliveryCharge === deliveryCharge` const | | 31 | waives the delivery charge at or above the minimum order value | qty to exceed min → `deliveryCharge === '0'` | | 32 | groups items from different slots into one order per slot, charging once | 2 slots → 2 orders, exactly 1 charged | | 33 | rejects an order for a full slot | `updateSlotCapacity(true)` → 403 "capacity"; capacity restored | | 34 | rejects flash delivery while it is disabled | `isFlashDeliveryEnabled` forced off → 403 "flash"; restored | | 35 | rejects an invalid quantity | `quantity: 0` → zod rejection | ### `api/order-lifecycle.test.ts` — 5 | # | Test | Request → assert | | --- | --- | --- | | 36 | persists special instructions | `updateUserNotes` → `getOrderById.userNotes` | | 37 | cancels the order with a reason and reflects it in the list | `cancelOrder` → `cancelReason` + cancelled status in `getOrders` | | 38 | rejects a cancellation without a reason | empty reason → zod rejection | | 39 | rejects a readable order id ("ORD<id>") | numeric-string contract | | 40 | paginates orders and rejects an oversized page size | page 1 vs 2 differ; `pageSize: 51` → rejection | ### `api/user-surface.test.ts` — 7 | # | Test | Request → assert | | --- | --- | --- | | 41 | returns the product detail for a product id | `product.getProductDetails` | | 42 | creates a review and returns it from getProductReviews | `createReview` → listed | | 43 | returns presigned upload URLs | `common.generateUploadUrls` → 1 URL | | 44 | exposes eligible and owned coupons | `coupon.getEligible` + `getMyCoupons` arrays | | 45 | rejects redeeming an unknown coupon code | bogus `secretCode` → 400 | | 46 | returns the signed-in user profile | `user.user.getSelfData.data.user.id` | | 47 | raises a complaint that staff can resolve | `complaint.raise` → `getAll` → admin `complaint.resolve` → `isResolved` | ### `api/cache-consistency.test.ts` — 5 (cross-file invariants) | # | Test | Request → assert | | --- | --- | --- | | 48 | every availability entry maps to a product in products.json | 0 orphan ids (polls — availability can lead) | | 49 | availability count matches the number of entries | `count === availability.length` | | 50 | every product referenced by slots.json exists in products.json | 0 orphans (polls) | | 51 | essential-consts.json is self-consistent with the version in its path | file's `cacheVersion` == path; other versions numeric | | 52 | stores.json productCount matches each store detail file | `productCount === detail.products.length` | ### `api/admin-catalog.test.ts` — 9 | # | Test | Request → assert | | --- | --- | --- | | 53 | getStoreById returns the created store | `{ id }` → store.id | | 54 | updateStore renames the store | update → getStoreById reflects the new name | | 55 | getProductById returns the product with its SKU | product id + sku id present | | 56 | updateProduct renames the product | update (sku feature `quantity`) → getProducts reflects the new name | | 57 | getGroups lists product groups | `groups` array | | 58 | createGroup adds a group that getGroups returns | group name present | | 59 | coupon.getAll returns a coupons array | `coupons` array | | 60 | vendorSnippets.getAll returns an array | array | | 61 | complaint.getAll returns a complaints array | `complaints` array | ### `api/admin-orders.test.ts` — 10 | # | Test | Request → assert | | --- | --- | --- | | 62 | getAll returns recent orders | `{ limit: 5 }` → `orders` array | | 63 | getOrderDetails returns the order | `{ orderId: number }` → id matches | | 64 | getSlotOrders lists the orders for a slot (string slotId) | `{ slotId: string }` → truthy | | 65 | updateNotes stores admin notes on the order | `{ orderId, adminNotes }` → details reflect | | 66 | marks the order packaged | `{ orderId: string, isPackaged: true }` → success | | 67 | marks the order delivered and the user sees "success" | user's `getOrderById.deliveryStatus === 'success'` | | 68 | removes the delivery charge | user's `deliveryCharge === 0` | | 69 | updates the address coordinates | mutation succeeds (coords not exposed to the user read — documented) | | 70 | cancels a fresh order as staff and the user sees it cancelled | new order → `cancelOrder` → status cancelled | | 71 | rebalances the orders for a slot | `{ slotIds: [id] }` → truthy | ### `api/coupons.test.ts` — 7 (admin CRUD → user applies it) | # | Test | Request → assert | | --- | --- | --- | | 72 | creates the coupon and getById returns it | `coupon.create` (flat 2, minOrder 1, apply-for-all) → `[0].id`; getById code + discount | | 73 | updates the coupon | `coupon.update({ id, updates })` → getById reflects | | 74 | is eligible for the user | `user.coupon.getEligible` contains the coupon | | 75 | reduces the order amount when the user applies it | `placeOrder({ couponId })` → `getOrderById.couponCode` + `discountAmount === 2` | | 76 | deleting the coupon invalidates it for the user | `coupon.delete` → no longer in `getEligible` | | 77 | rejects applying the invalidated coupon to an order | `placeOrder({ couponId })` → invalid/expired error | | 78 | rejects a coupon with both discount types | `coupon.create({ discountPercent, flatDiscount })` → rejected | ### `api/admin-users.test.ts` — 8 (admin user surface) | # | Test | Request → assert | | --- | --- | --- | | 79 | getEssentials returns the dashboard counters | `user.getEssentials` → numeric `unresolvedComplaints` | | 80 | getAllUsers returns users | `user.getAllUsers({ limit: 5 })` → `users` array | | 81 | getUserDetails returns the user | `user.getUserDetails({ userId })` → id matches a fresh user | | 82 | getStaff lists the staff | `staffUser.getStaff` → includes the logged-in staff id | | 83 | adds a user incident that getUserIncidents returns | `addUserIncident({ userId, adminComment })` → the comment comes back | | 84 | getUsersForNotification returns a users array | `{ search: '' }` → array | | 85 | suspends and unsuspends the user | `updateUserSuspension(true/false)` → `getUserDetails` reflects each | | 86 | sendNotification tolerates a recipient with no push token | `{ userIds: [fresh] }` → resolves (nothing delivered) | ### `api/admin-banners.test.ts` — 4 | # | Test | Request → assert | | --- | --- | --- | | 87 | getBanners returns a banners array | `banner.getBanners` → array | | 88 | createBanner creates a banner that getBanner returns | `createBanner({ name, imageUrl })` → `getBanner({ id }).name` | | 89 | updateBanner renames the banner | `updateBanner({ id, name })` → `getBanner` reflects | | 90 | deleteBanner removes it | `deleteBanner({ id })` → `getBanner` is null | ### `api/admin-tags.test.ts` — 4 | # | Test | Request → assert | | --- | --- | --- | | 91 | creates a tag that getProductTags returns | `createProductTag({ tagName, isDashboardTag })` → new id in `getProductTags` | | 92 | getProductTagById returns the tag | `getProductTagById({ id })` → tagName matches | | 93 | updateProductTag renames the tag | `updateProductTag({ id, tagName })` → reflected | | 94 | deleteProductTag removes it | `deleteProductTag({ id })` → gone from `getProductTags` | ### `api/admin-vendor-snippets.test.ts` — 4 | # | Test | Request → assert | | --- | --- | --- | | 95 | creates a snippet that getAll returns | `vendorSnippets.create({ snippetCode, slotId, skuIds, isPermanent })` → id in `getAll` | | 96 | updates the snippet | `update({ id, updates: { validTill } })` → still listed | | 97 | returns the orders for the snippet code | `getOrdersBySnippet({ snippetCode })` → resolves (needs a slot) | | 98 | deletes the snippet | `delete({ id })` → gone from `getAll` | ### `api/admin-ops.test.ts` — 5 (config, lifecycle, concurrency) | # | Test | Request → assert | | --- | --- | --- | | 99 | round-trips a constant through updateConstants | `updateConstants(minOrderAmountForCoupon = 123)` → `getConstants` shows 123 → restored | | 100 | updates and deletes a product group | `createGroup` → `updateGroup({ id, group_name })` visible in `getGroups` → `deleteGroup({ id })` removes it | | 101 | deleteProduct rejects for a product that still has SKUs | `deleteProduct({ id })` → rejected (FK on the hard delete) | | 102 | deletes a store | `store.createStore` → `deleteStore({ storeId })` → `getStoreById` no longer resolves | | 103 | places two concurrent orders for different slots | two `placeOrder` calls in parallel → two distinct, persisted order ids | ### `api/uploads.test.ts` — 4 (image upload round trip) The presigned PUT is self-signed, so these cases upload real bytes without any R2 credentials and read them back from the public assets domain (`common.essentialConsts.assetsDomain`, the same source the app renders from). Objects stay in the dev bucket. | # | Test | Request → assert | | --- | --- | --- | | 104 | stores exactly the bytes that were uploaded | `common.generateUploadUrls({contextString:'product_info'})` → PUT a 1×1 PNG → GET `/` → same length, byte-equal, same sha256 | | 105 | keeps two uploads distinct — each URL serves its own object | presign in two folders (product-images, tags) → different keys → each serves its own PNG, shas differ | | 106 | gives every mime type in one call a usable URL | one call with `['image/png','image/jpeg']` → 2 distinct keys → both objects hold their own bytes | | 107 | returns 404 for an object that was never uploaded | guards the read-back: a passing comparison must mean the object really exists | ## Harness reference | Path | Purpose | | --- | --- | | `tests/jest.config.js` | jest project (ts-jest, node env, `runInBand`, clearMocks) | | `tests/tsconfig.json` | typecheck scope for tests (`bun run test:api:typecheck`) | | `tests/setup.ts` | loads `tests/.env` before the suites | | `tests/.env.example` | credentials template (copy to `tests/.env`, git-ignored) | | `tests/helpers/env.ts` | `API_BASE_URL` + credentials with actionable errors | | `tests/helpers/api.ts` | tRPC client (`httpBatchLink`) + bearer token, `health()`, `assertServerUp()`, `uniqueSuffix()` | | `tests/helpers/sessions.ts` | staff/user login with cached tokens | | `tests/helpers/fixtures.ts` | `createStoreWithSku` (optional price), `createFutureSlot`, `ensureUserAddress`, `registerThrowawayUser` | | `tests/helpers/consts.ts` | `getConstants` (normalised), `setConst` (used to flip the flash gate, always restored), `asNumber` | | `tests/helpers/cache.ts` | `essentialConsts`, versioned cache URLs (products/stores/slots/availability/essential-consts), `fetchCacheJson`, `pollUntil` |