freshyo/docs/test reports/e2e-findings-2026-10-10.md
2026-10-11 00:48:38 +05:30

54 KiB
Raw Blame History

Freshyo E2E — defects & problems found (run 2026-10-10 16:30)

Source: docs/test reports/e2e-sanity-test-results-2026-10-10-1650.md (20-case daily subset + incidental checks). Every entry lists the exact request or flow used, so each one can be re-run. Screenshots: /tmp/freshyo-e2e/*.jpg. Backend: local wrangler dev @ :8787, D1.

Severity is my judgement, not a formal triage.

# Area Problem Severity Confidence
F1 Products API admin.product.deleteProduct always fails on D1 High Confirmed · FIXED 2026-10-10 18:26 (soft delete)
F2 Coupons / money Order detail reports a discount computed on the paid total (₹47.36 vs ₹30.4 charged) High Confirmed · FIXED 2026-10-10 18:47
F3 Slots / UI A full-capacity slot is still offered and addable in the app High Confirmed · root cause refined (stale slot cache pointer + no client-side capacity check)
F4 Tags Tag images: stored as a URL, scaffolded as a key at read, deleted as a key → broken image + undeletable tag High Confirmed · FIXED 2026-10-10 20:00
F5 Products API createProduct (and 5 more write paths) commit the row, then fail on the upload-URL claim Medium Confirmed · FIXED 2026-10-10 20:35
F6 Region config API Both superadmin const endpoints accept out-of-scope keys and report success while changing nothing Medium Confirmed · FIXED 2026-10-10 21:10
F7 Regions API Region deletion is intentionally unsupported, so region fixtures are permanent and customer-visible — Not a defect (by design) — plan guidance is the thing to change. Bounds are deletable: deleteBound added with last-bound + address guards (2026-10-10 22:15)
F8 Addresses Bound-less addresses inherit an active bound rather than a per-address bound — Not a defect (by design) — policy: an address may exist without a bound; the active bound applies
F9 Customer UI Home pull-to-refresh spinner can stick forever; region gate can strand with no escape Medium Diagnosis corrected from screenshots · spinner fix DONE 2026-10-10 22:50 (90 s abort cap); gate dead end open
F10 Admin UI (iOS) Typing during automation landed in the first field — Not an app defect (harness flow) — the repo flow hides the keyboard and scrolls per field; minor gap: no keyboard avoidance/auto-scroll in the form
F11 Products / admin OOS toggle was product-wide only and collapsed partial state Low Confirmed · FIXED 2026-10-10 23:20 (per-variant API + BottomDialog picker)
F12 Orders API Business rejections surface as HTTP 500 / INTERNAL_SERVER_ERROR Low Confirmed
F13 Customer UI Order list shows shipping status success (not Delivered) for a delivered order Low Confirmed
F14 Customer UI One address-selection switch rendered an empty cart before restoring it Low Unconfirmed (single occurrence)
— Orders API flashDeliveryFilter returns nothing — Retracted — my input error (see below)

F1 — admin.product.deleteProduct always fails (High)

Request

POST /api/trpc/admin.product.deleteProduct  {"id":152}   (also tried {"id":151})

Observed

{"error":{"message":"Failed query: delete from \"product_info\" where (\"product_info\".\"id\" = ? and
\"product_info\".\"region_id\" = ?) returning \"id\", \"region_id\", \"name\", \"short_description\",
\"long_description\", \"store_id\", \"increment_step\", \"created_at\", \"product_type\"\nparams: 152,1",
"code":-32603,"httpStatus":500}}

Reproduced for the fixture product (2 SKUs) and for an orphan product with no slot association, so it is not limited to products referenced by slots. The message exposes the SQL but not the underlying cause (no D1/driver error text), which is itself worth fixing for diagnosability.

Impact — no product can be removed through the admin API/UI. Cleanup of bad or test data is impossible; PD-13-class deletion flows cannot pass. Workaround used in this run: updateProduct with isSuspended: true on every SKU plus a rename.

Where — apps/backend/src/trpc/apis/admin-apis/apis/product.ts (deleteProduct) → deleteProductInDb.

Suggested fix — surface the driver error (cause), then resolve the FK/returning issue (delete or cascade the child rows: SKU/features, slot associations, market stats, reviews) and return a proper 4xx with a dependency reason instead of a 500.

FIXED (2026-10-10 18:26) — deleteProduct/deleteGlobalProduct are now a soft delete (packages/db_helper_sqlite/src/admin-apis/product.ts): product + SKU rows stay so order_items.sku_id and order-history name rendering keep working (product_skus.is_deleted = true, sku_features kept); market stats, cart items, coupon applicability, tags, group membership, combos and special deals are removed in one atomic db.batch. The admin product list hides products whose SKUs are all deleted, and checkProductExistsByName ignores tombstones so names can be reused. Verified by deleting fixtures 151/152 (both returned success where they previously 500'd); a deleted-SKU detail lookup returns "Product not found". Root cause of the old 500: the single DELETE FROM product_info … RETURNING hit D1's FK enforcement (product_skus.product_id is NOT NULL, ON DELETE no action).


F2 — Coupon discount is reported on a different basis than it is charged (High)

Evidence (order #2495) — cart/checkout preview and the success screen: item total ₹304, coupon E2E10PCT 10% (max ₹50), delivery fee ₹200, To Pay ₹473.6. Stored row: total_amount = 473.6 (the final payable), delivery_charge = 200. Both order-detail APIs report discountAmount: 47.36 (customer user.order.getOrderById, admin admin.order.getOrderDetails — the latter verified live):

47.36 = 10% × 473.6 (the payable, which already includes the ₹200 fee and the ₹30.4 discount), while the amount actually deducted was 30.4 = 10% × 304 (items only). The reported components therefore do not reconstruct the paid total: 304 − 47.36 + 200 = 456.64 ≠ 473.6.

Where — the discount is recomputed at read time (it is not stored anywhere): both read paths use order.totalAmount as the base — apps/backend/src/trpc/apis/user-apis/apis/order.ts getOrderById (~line 547-577) and packages/db_helper_sqlite/src/admin-apis/order.ts getOrderDetails (~line 171-197). The write path is correct and uses the items subtotal — apps/backend/src/trpc/apis/user-apis/apis/order.ts (~line 213-231) and the app's checkout (apps/user-ui/components/checkout-page.tsx ~line 205-215) both compute 10% × 304 = 30.4, which matches the charge. The cap (₹50) is above the inflated figure, so it never clamped and never exposed the error.

FIXED (2026-10-10 18:47) — both order-detail paths now compute the discount from the order's item subtotal (Σ price × quantity) with the cap prorated by orders.order_group_proportion, reusing applyDiscountToOrder() (packages/db_helper_sqlite/src/user-apis/order.ts:158, parameter narrowed to CouponDiscountFields, now also returns discountAmount so callers do not re-subtract and hit float noise). Order #2495 now reports 30.4 on both the admin and customer detail endpoints and reconciles: 304 − 30.4 + 200 = 473.6. No-coupon orders still return null (verified on #2496). Numerical check: the read-path formula equals the write-path formula for percentage and flat coupons across single- and multi-slot splits.

Still open in the same area: rebalanceSlots (packages/db_helper_sqlite/src/admin-apis/order.ts ~line 684) recomputes orders.total_amount as latest-prices − discount without adding the delivery charge, so a slot rebalance overwrites the paid total and would make the detail endpoints disagree again.

Impact — refunds, coupon accounting, admin totals and any downstream reporting will disagree with what the customer paid; the plan's own "money parity is a high-risk gap" note (BL-03/BL-04/BL-05) is confirmed with a live order.

Suggested fix — compute the discount once, in the same function used for the quote, and persist that value; add an invariant check (items − discount + fees == payable) in the order write path.


F3 — Full-capacity slot still offered and addable in the app (High)

Steps — updateSlotCapacity {slotId: 2033, isCapacityFull: true} → in the app: product → ADD TO CART → the dialog still lists “Sun, 11 Oct • 7-8 PM” with an enabled checkbox; selecting it and pressing Add to Cart succeeded (floating bar ₹199 • 1 Item).

Backend is correct: a direct placeOrder with that slot returned Selected delivery slot is at full capacity. Please choose another slot. (403).

Impact — the customer is allowed to build a cart that cannot be ordered; the failure only appears at submission (SL-05 requires the option to be removed/disabled). Evidence: SL-05-full-slot-dialog.jpg, SL-05-full-slot-accepted-into-cart.jpg.

Root cause refined 2026-10-10 19:0x (live re-test): it is not that the list query forgets to filter — three different slot sources disagree:

source used by capacity-aware?
slots.json CDN cache at regions/<r>/slots/v-<slots_version_num>/slots.json, version from common.essentialConsts (which reads the KV blob, readEssentialConstsFromKv) AddToCartDialog (useSlots() in apps/user-ui/src/hooks/prominent-api-hooks.ts) filtered when generated, but the app keeps reading the stale version
user.slots.getSlots checkout page (apps/user-ui/components/checkout-page.tsx:38) Fixed 2026-10-10 19:20 — was unfiltered and multi-region (thousands of ids incl. past/full slots); now scoped to the caller's region and filtered to future, orderable slots
user.cart.getCartSlots → getMultipleProductsSlots (live DB) cart page Yes — returned {"148": []} while the slot was full

The app also never reads the flag at all: isCapacityFull appears nowhere under apps/user-ui, and AddToCartDialog filters only freezeTime > now (availableSlots ~line 106-109), so a slot reported as full is still selectable.

Live evidence of the stale pointer (slot 2032, the only future-active slot; capacity was flipped and reverted during the test):

  • DB after revert: isActive: true, isCapacityFull: false.
  • Files produced by createSlotsCacheFile: v-13 contains [2032]; v-14…v-17 do not contain 2032.
  • common.essentialConsts {boundId:1} still advertises slots_version_num: 13 → the app keeps fetching the old file that still lists the slot, while the new files are never requested.
  • updateSlotCapacity regenerates only the slots file (createSlotsCacheFile) — the products cache (products.json, which carries each product's nextDeliveryDate computed with the capacity filter, and whose products_version_num also stayed at 7) is not regenerated at all.
  • Secondary inconsistency: slots.json content churns across versions (v-13: [2032], v-14: [2012,2014], v-15: [2012,2014,2016]) although only capacity changed — the generated slot set does not match the future-active slots the admin API reports ([2032]).

Suggested fix — (1) make the capacity flip reach the app: ensure the version pointer is refreshed (refreshGenKvForRegion → KV putBound appears not to take effect) and regenerate the products cache too; (2) have AddToCartDialog/checkout use the capacity-aware live source (getCartSlots) or re-validate at submit; (3) honour the flag in the UI (disable/label Full); (4) fix user.slots.getSlots to be region-scoped and capacity/freeze filtered; and (5) keep the server-side rejection (already correct) as the backstop, ideally with a message that tells the user the slot just filled.

Partially fixed (2026-10-10 19:20) — user.slots.getSlots is now region-scoped and future-only (apps/backend/src/trpc/apis/user-apis/apis/slots.ts): optional regionId input falling back to the caller's staff region, filtering deliveryTime/freezeTime against now. Verified: region 1 → 1 slot, region 2 → 0, staff without input → own region 1, anonymous without input → 0; a passed freeze time or an inactive slot is excluded. The checkout page passes useRegion().regionId — the same region the order is placed with. Capacity filtering is deliberately not included yet (that is the hide-vs-show decision), and the stale slots.json pointer that AddToCartDialog reads is still open.

Closed by decision (2026-10-10) — the stale slots_version_num pointer is treated as a KV propagation/cache delay and left as-is; not investigated further. If it ever outlives a refresh cycle (i.e. still stale minutes later), the next suspects are the refreshGenKvForRegion write path and the app's react-query cache of essentialConsts.


F4 — Tag images: written as a URL, read as a key, deleted as a key (High)

Steps — presigned upload (user.fileUpload.generateUploadUrls {contextString:'tags'}) → PUT 200 → admin.product.createProductTag {…, imageUrl, uploadUrls:[url]} → 201.

Observed — admin.product.getProductTags / getProductTagById return "imageUrl": "https://assets2.freshyo.in/https://da9b1aa7c1951c23e2c0c3246ba68a58.r2.cloudflarestorage.com/meatfarmer-dev/tags/1791632636038.png?X-Amz-Expires=180&X-Amz-Signature=…" and admin.product.deleteProductTag {id:10} fails with Failed to delete image (500) while tag 10 keeps existing (both re-verified 2026-10-10 ~19:35).

Root cause — three inconsistent conventions for the same field:

  1. Write stores whatever it is given. createProductTag (packages/db_helper_sqlite/src/admin-apis/product.ts:849) — and updateProductTag at :905 — insert imageUrl verbatim, with no key normalisation, unlike banners (admin-apis/banner.ts:97), stores and products which call extractKeyFromPresignedUrl(). So API-created tag 10 stored a presigned URL (expiring signature) while seeded tags 2/5/8 store plain object keys (tags/<key>.png).
  2. Read scaffolds unconditionally. Both tag endpoints run scaffoldAssetUrl(stored) (admin-apis/product.ts:475 and :494), and scaffoldAssetUrl merely strips leading slashes and prefixes ASSETS_DOMAIN (lib/s3-client.ts:96-107) — it does not detect an absolute URL. A URL therefore becomes https://assets2.freshyo.in/https://…?X-Amz-… (broken image). The customer cache path scaffolds the same way (apps/backend/src/stores/product-tag-store.ts), and products.json already contains the same class of corruption in production data: tags 1 and 4 carry …/tags/<key>.jpeg%3FX-Amz-Algorithm… (an encoded presigned query baked into the object key), while 2/5/8/9 are clean.
  3. Delete treats the stored value as an object key. deleteProductTag (admin-apis/apis/product.ts:619-621) calls deleteImageUtil({ keys: [tag.imageUrl] }); deleteImageUtil builds buildObjectUrl(bucket, key) and DELETEs it (lib/s3-client.ts:65-87). For a URL the path is nonsense → S3 responds non-2xx → it throws Failed to delete image → the mutation 500s before deleteProductTagInDb, so the row is never removed: any tag whose image is not a clean key is undeletable.

Impact — tag images are broken on the customer home for every API-created tag (plus legacy 1 and 4), and the tag cannot be deleted afterwards, which also blocks store/region cleanup (tag 10 is stuck).

Suggested fix — (1) normalise on write: imageUrl: extractKeyFromPresignedUrl(imageUrl) in createProductTag/updateProductTag (and for the uploadUrls claim, store the derived key); (2) make the asset helper defensive — detect absolute/protocol-relative URLs and strip ?X-Amz-… instead of blind prefixing (used by tags, products, banners, stores); (3) make cleanup non-fatal: normalise each key in deleteImageUtil, treat a missing object as success, and delete the tag row even if image cleanup fails; (4) repair data: re-upload or null the images for tags 10 (and legacy 1/4).

FIXED (2026-10-10 20:00) — (1) normalizeAssetRef() added to apps/backend/src/lib/s3-client.ts (trims, drops a real or %3F-encoded query, and for absolute URLs keeps the path minus host/bucket); scaffoldAssetUrl now uses it, so scaffolding is idempotent; deleteImageUtil normalises every key first. (2) createProductTag/updateProductTag store normalizeAssetRef(imageUrl). (3) Image cleanup in both the delete and update tag procedures is wrapped in try/catch and can no longer block the DB write. Verified: tag 10 read → https://assets2.freshyo.in/tags/1791632636038.png (was the double prefix); deleteProductTag {id:10} → "Tag deleted successfully" (was 500) and the tag is gone; a tag created with a presigned URL stores the key; product images still render normally; tags 2/5/8 unchanged. Data repair: tags 1 "Chicken" and 4 "Fish" had their imageUrl cleared — their objects return 404 at the clean key (the upload never landed there), so they need a fresh image from the admin UI. Tag 10 was an E2E fixture and is now deleted.


F5 — Write-then-claim: the request fails after the row is committed (Medium)

Steps — createProduct with an image URL that was never uploaded returned HTTP 500 (Failed to claim upload URL), but product 151 and its two SKUs existed afterwards, including the bogus image path (re-confirmed by reading the current code, 2026-10-10).

Root cause — the order of operations in the createProduct procedure (apps/backend/src/trpc/apis/admin-apis/apis/product.ts:204) is:

  1. createProductInDb(...) — inserts product + SKUs (+ per-region market stats) inside a db.transaction;
  2. await Promise.all(allUploadUrls.map((url) => claimUploadUrl(url))) — after the transaction;
  3. scheduleStoreInitialization(...).

claimUploadUrl (apps/backend/src/lib/s3-client.ts:264-276) calls claimUploadUrlStatus, which only updates a row whose status = 'pending' (packages/db_helper_sqlite/src/helper_methods/upload-url.ts:12-20), and throws when nothing was updated. The claim is outside the insert transaction and unguarded, so any non-pending/unknown key aborts the request with the product already committed. Partial failure is also possible: Promise.all may claim some keys before a sibling throws.

Scope — six call sites share the pattern: createProduct:204, updateProduct:298, respondToReview:356, createProductTag:534, updateProductTag:600 (all apps/backend/src/trpc/apis/admin-apis/apis/product.ts) and createReview (apps/backend/src/trpc/apis/user-apis/apis/product.ts:120).

What upload_url_status actually means — verified repo-wide: the table is written when a presigned upload URL is generated (createUploadUrlStatus) and flipped here; nothing reads it (no render-time validation, no cleanup job) and no migration adds a reader. So a failed claim does not break the uploaded image — the object is in R2 regardless. The real damage is the orphaned record, a misleading 500, a ledger row that stays pending although the upload was used, and an awkward retry (the product now exists, so the next attempt hits "A product with this name already exists", or the now-claimed URL gives "already claimed").

Impact — silent data pollution across six write paths; the E2E left policy-owner debris behind this way. Since F1 was fixed (deleteProduct is now a soft delete), such debris is at least removable again.

Suggested fix — pre-validate before writing: one query for every key (they must exist and be pending), throw a 400 listing the offending keys before the insert, then insert, then treat the claim as best-effort (log instead of failing the request) — or claim inside the insert transaction (needs claimUploadUrlStatus to accept a tx). That removes the orphan window for the common case (bad, foreign or reused upload URL, which is exactly what produced product 151) without consuming claims for writes that fail.

FIXED (2026-10-10 20:35) — option 1, applied at all six sites. New helpers in apps/backend/src/lib/s3-client.ts: findUnclaimableUploadUrls(), assertUploadUrlsClaimable() (throws ApiError 400 naming the keys) and claimUploadUrls() (Promise.allSettled, logs failures instead of aborting), backed by getPendingUploadUrlKeys() in packages/db_helper_sqlite/src/helper_methods/upload-url.ts. Each write now validates first and claims afterwards; in updateProduct and updateProductTag the check runs before any image is deleted. Verified: the original repro returns 400 with nothing written (product count unchanged, retry no longer hits "name already exists"); a legitimately generated upload URL still creates the record (tag 12, image normalised) and reusing it is rejected with 400 and no row. createReview keeps its deliberate leniency: unclaimable URLs are logged, not rejected.


F6 — Both superadmin const endpoints accept out-of-scope keys and silently no-op (Medium)

POST superadmin.regions.updateBoundSettings {"boundId":1,"settings":[{"key":"isFlashDeliveryEnabled","value":"true"}]}
→ {"success":true,"updatedCount":1}
GET  common.essentialConsts?boundId=1  → "isFlashDeliveryEnabled": false      # unchanged
POST superadmin.regions.updateRegionConstants {"regionId":1,"constants":[{"key":"isFlashDeliveryEnabled","value":"true"}]}
→ essentialConsts "isFlashDeliveryEnabled": true                              # works

Re-verified live (2026-10-10 ~19:50, with the flash state restored afterwards):

  • superadmin.regions.boundSettings {boundId:1} returns a stray isFlashDeliveryEnabled: "true" — the row my E2E run wrote through the bound endpoint.
  • common.essentialConsts {boundId:1} reports isFlashDeliveryEnabled: false (the region_consts value), so the stored bound row is ignored.
  • Writing it again returns {success:true,updatedCount:1} and the effective value stays false.
  • A genuine bound key still works: flashFreeDeliveryThreshold 500 → 501 → essentialConsts 501 → restored 500.

Root cause — the resolved payload takes each key from its own table: scaffoldEssentialConsts (apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts:47-135) reads isFlashDeliveryEnabled from getRegionConstValues(), bound keys from getBoundConstValues(), and never spreads bound rows wholesale. apps/backend/src/lib/const-keys.ts already owns the mapping (CONST_SCOPE, built from GLOBAL/REGION/BOUND/LEGACY_CONST_KEYS) and admin.const.updateConstants enforces it — but updateBoundSettings (superadmin-apis/apis/regions.ts:166-183) and updateRegionConstants (:192-216) validate nothing (the latter only filters version keys) and their helpers (upsertBoundSettings / upsertRegionConstants, packages/db_helper_sqlite/src/superadmin-apis/regions.ts:276-324) upsert any key into their own table.

Blast radius — the superadmin UI is scope-correct (it keeps BOUND_SETTING_KEYS and REGION_SETTING_KEYS apart and calls the matching mutation in apps/superadmin-ui/src/routes/regions.tsx), so this is an API-contract trap for scripts, agents and testers — the plan's own guidelines tell testers to use updateRegionConstants, and the false success cost me a debugging cycle plus one stray row. The mirror case is equally possible: updateRegionConstants would happily write a bound/global key into region_consts (none present today — checked). Stray rows are inert but cannot be removed: the endpoints are upsert-only.

Suggested fix — validate against CONST_SCOPE in both endpoints and reject mismatches with a 400 that names the correct endpoint (optionally also accept any key and route it to the right table, and/or allow value: null to delete a row so existing strays can be cleaned).

FIXED (2026-10-10 21:10) — assertConstantKeysInScope(keys, expected, endpoint) added to apps/backend/src/lib/const-keys.ts (uses CONST_SCOPE, also rejects version counters on region writes) and called first by all four endpoints — the superadmin pair and the staff pair in admin-apis/apis/region.ts. value: null now deletes the row instead of storing NULL (upsertBoundSettings/upsertRegionConstants return { updated, deleted }, and the endpoints return deletedCount); null is allowed even for a wrong-scope key so old mistakes can be removed while writes stay validated. Verified: wrong scope → 400 naming the target endpoint, version keys → 400, unknown keys → 400, legit writes unchanged, and the leftover bound-1 isFlashDeliveryEnabled row was deleted (deletedCount: 1, idempotent afterwards) with essentialConsts unaffected. One fix during verification: the delete branch's .returning({ id }) failed because these tables have no id column.


F7 — Region deletion is intentionally not supported (not a defect)

Verdict (confirmed by the product owner, 2026-10-10): deleting a region is not an allowed action. So this is not a bug — but it does make one instruction in the test plan unactionable and leaves permanent fixtures.

Observed behaviour (kept as context, re-verified live 2026-10-10 ~20:15):

  • superadmin.regions.delete → No procedure found on path "superadmin.regions.delete" (404); there is no deleteBound either.
  • regions has only id, name, description, createdAt — no isActive/isDeleted — and updateRegion changes name/description only, so a region cannot be disabled.
  • The superadmin UI offers no delete affordance for regions (the only removeBound is client-side draft editing in the create form).
  • common.listRegions returns every region, including fixtures (region 2 E2E Testnagar 1702), and bound polygons participate in address resolution (addresses.boundId → region_bounds.regionId).

Residual (process) issues, not bugs:

  1. The plan's RG-01 cleanup step ("delete the extra regions you created") cannot be followed. It should say to reuse one long-lived test region instead of creating new ones.
  2. A created region is permanent and customer-visible. The sanctioned ways to neutralise one are update (rename it clearly, e.g. ZZ DO NOT USE) and updateBound (shrink/move its geojson so its polygon cannot capture addresses).
  3. Content inside another region can only be cleaned with a temporary staff user for that region (superadmin.staff.create → use the admin.* endpoints → superadmin.staff.remove), because staffProcedure requires ctx.staffUser and a superadmin token cannot call admin.*.

The RG-01 fixture (region 2, bound 3) therefore stays, by design, along with anything created inside it.

Bounds, by contrast, are deletable (2026-10-10 22:15) — superadmin.regions.deleteBound was added with two guards: it refuses when the bound is the region's only bound (409: "A region needs at least one bound so it can take orders") and when any address still points at it (409, with the address count); the package helper deleteRegionBound removes the bound's region_bound_consts rows and the row itself, then the router re-mirrors the region's remaining bounds and drops the removed bound's essentialConsts_<id> KV blob. The superadmin UI gets a Delete bound button that is disabled (with the same hint) when canDeleteBound(bounds.length) is false — the rule lives in apps/superadmin-ui/src/lib/bound-rules.ts with a vitest test (bound-rules.test.ts, 6 cases, npm test) so the UI cannot offer the last-bound delete and the server cannot be bypassed by a script.


F8 — Bound-less addresses (by design, closed)

Business policy (confirmed 2026-10-10): an address may exist without a bound; such an address is served by an active bound rather than one tied to the address. Verdict: not a defect — the report below is kept as behavioural reference, not as work.

How it actually resolves (for future reference):

  • common.activeBound (apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts:247-265) returns the least-priority bound among the user's addresses in the region, and the region's effective (least-priority) bound when they have none. Verified live: with the user's only bounded address on bound 2, it returns boundId: 2 while region 1's least-priority bound is 1. (Address 285 was moved to bound 2 for the test and restored; state confirmed back to 285→1, 879→2.)
  • The app uses that value whenever the selected address has no bound (useGetEssentialConsts, prominent-api-hooks.ts:32-36; useRegion.ts:96-113).
  • placeOrder prices with params.boundId ?? getEffectiveBoundId(regionId) and verifies via getRegionSettingsForBound that the bound belongs to the region (otherwise it falls back to the region's effective settings), so no cross-region pricing is possible.
  • Coordinates are irrelevant to this policy: + Attach Current Location stores lat/lng and leaving boundId null is expected; the "No Location is attached" banner is an address-quality nudge.

Two notes kept for the record (no action requested): the client's params.boundId is what decides the charge for a bound-less address, and orders has no boundId column, so the applied bound is not stored on the order.


F9 — Home pull-to-refresh spinner can stick forever (corrected; the "region sheet hang" was a misread) (Medium)

What the evidence actually shows. All three E2E captures (RG-06-region-sheet.jpg, RG-06-region-sheet2.jpg, RG-06-region-sheet3.jpg, 5:02–5:03) are the home screen with the catalogue and cart fully rendered and a small centred spinner above the DELIVER TO bar — no sheet and no dark backdrop, which a presented BottomDialog (its backdrop is rgba(0,0,0,0.3)) would show. So the sheet was never open in those minutes and my original note ("the sheet never renders the region list") was a misreading of the harness screen; the taps just did not open it. The spinner itself is the home list's RefreshControl (apps/user-ui/app/(drawer)/(tabs)/home/index.tsx:758-764), which renders exactly there because LocationBar is the ListHeaderComponent.

Why it can never clear. isRefreshing is a local useState (home/index.tsx:504) reset only in handleRefresh's finally (:603-621), after await Promise.all([refetchProducts?, refetchSlots, refetchStores, refetchConsts]). Those refetches hit the versioned CDN JSON (products.json, stores.json, slots.json) through plain axios.get(cacheUrl) with no timeout (prominent-api-hooks.ts:160-171) and a global query client with retry: 3 and no fetch timeout (utils/queryClient.ts). A request that fails eventually rejects and clears the spinner; a request that hangs never settles, so finally never runs and the indicator spins until the app is relaunched — matching the captures, which are a minute apart with the spinner still going. handleRefresh is also invoked without a pull, via useManualRefresh/useMarkDataFetchers (:623-629), so it can start on its own after other screens refresh (e.g. the region switch clearing the central stores and invalidating every query — region-switch.ts).

Separate confirmed issue in the same area (region gate dead end). Independent of the sheet: isResolvingRegion = regionId == null && !startupResolved (useRegion.ts:191), and the 8 s safety net that unsticks the first-run spinner is armed only when shouldResolve is true, which requires coords != null (useRegion.ts:180-189). With location denied/off, locationStore keeps coords: null (status: 'denied' | 'unavailable'), so the timer never arms and startupResolved never flips → LoadingScreen("Finding your region...") forever, with the manual chooser unreachable because it is rendered after that branch. The only resets are a reload or refreshLocation(), and no component calls refreshLocation (checked repo-wide).

Suggested fix — (1) give the catalogue fetches a timeout/AbortController and derive the home refreshing state from real query state (or force-reset after a bounded time) so a stalled request cannot pin the UI; (2) gate: arm the timeout even without coords, route denied/unavailable straight to the manual chooser, and wire an escape (refreshLocation / "Choose region manually"); (3) don't await a global invalidateQueries() inside the region switch.

FIXED (item 1) 2026-10-10 22:50 — every catalogue/CDN request is now bounded by an AbortController with a 90 s cap: new apps/user-ui/src/lib/fetch-json.ts (JSON_FETCH_TIMEOUT_MS, fetchJson<T>(), isAbortError()), used by all five fetches in prominent-api-hooks.ts (products, availability, stores, slots, store-with-products); the shared tRPC fetch gets the same guard (covers refetchConsts, the other leg of handleRefresh); and the query client no longer retries aborted requests (retry: (n, e) => !isAbortError(e) && n < 3) so a timeout surfaces instead of repeating 3×90 s. Verified with the real helper bundled for node against a server with one instant route and one that never answers: 90000 constant, fast route resolves, stalled route rejects after the injected cap as CanceledError with isAbortError true, and a plain error is not treated as an abort (still retried). Items (2) and (3) are still open.

Suggested fix — (1) gate: arm the timeout even without coords (or route denied/unavailable straight to the manual chooser) and wire an escape (refreshLocation / "Choose region manually") — removes a hard dead end; (2) sheet: keep listRegions warm (prefetch) and show a retry instead of an endless spinner when data is absent; (3) switch: don't await a global invalidateQueries(), and dismiss Alert/modal before mounting the next one; (4) validation: only clearRegion() when a non-empty list genuinely lacks the id.


F10 — Admin form typing: harness/flow issue, not a focus bug (reclassified)

What happened: filling the Add-Product form by tapping testIDs and calling inputText left the Product Name as E2E Sanity 1655n500 g199249 1 kg — every later value was appended to the name field while the variant fields stayed empty.

Why, from the code:

  • MyTextInput is a thin passthrough to react-native-paper's TextInput (packages/ui/src/components/textinput.tsx): it spreads {...props} (so testID reaches the real input and became its accessibilityLabel) and adds no focus logic. There is no wrapper that could swallow a tap.
  • ProductForm is a bare ScrollView with keyboardShouldPersistTaps="handled" (apps/admin-ui/src/components/ProductForm.tsx:256) and KeyboardAvoidingView appears nowhere in admin-ui (grepped). Once the keyboard is up after focusing Product Name, the variant/price fields sit behind it; a coordinate tap lands on the keyboard, focus never moves, and Maestro's inputText (which types into the focused element) keeps appending to the name.
  • The repo's own flow shows the intended pattern: tests/e2e/add-product.yaml does inputText → hideKeyboard → scrollUntilVisible → tap, per field. My exploratory flow skipped the hide/scroll because hideKeyboard fails on this build (noted in the guidelines).

Verdict — primarily a harness/flow problem (the sanctioned flow exists in-repo), with a genuine but minor ergonomics gap: the long form has no keyboard avoidance or auto-scroll-to-focused-field, so on iOS a human must scroll manually and automation is fragile. Not a functional defect.


F11 — Out-of-stock can only be set for a whole product through the toggle (Low)

admin.product.toggleOutOfStock {id: 152} reports {"productId":152,…} and marks all SKUs unavailable; placeOrder then rejects both SKUs ("Product 153 is unavailable", "Product 154 is unavailable").

Where the state lives and what the endpoint does:

  • Stock is per SKU per region: product_market_stats.is_out_of_stock (packages/db_helper_sqlite/src/db/schema.ts:216).
  • toggleProductOutOfStock(regionId, productId) (packages/db_helper_sqlite/src/admin-apis/product.ts:1270-1302) loads every SKU of the product, computes nextIsOutOfStock = !skus.some(sku => marketStats.isOutOfStock) ("out if any variant is out") and writes that single value to all of the product's market-stats rows for the region. The input has no skuId.

Consequences:

  1. The endpoint cannot express PD-06 (one variant out of a multi-SKU product). Per-SKU control exists only in the full updateProduct/createProduct payloads (per-SKU isOutOfStock) and, for global products, in GlobalProductForm's per-variant "Out of stock" checkbox.
  2. It destroys partial state: with one SKU out and one in (set via updateProduct), some(...) is true, so one press sets everything back in stock and the next press takes everything out — a partial state can never survive the toggle.
  3. The admin product list switch (apps/admin-ui/app/(drawer)/dashboard/products/index.tsx:148,57) renders from the default SKU's flag, so a partially-out product can display as "in stock".

Suggested fix — give the toggle an optional skuIds (or add setVariantOutOfStock) that writes only those market-stats rows, keep the product-level action as an explicit "all variants" operation, and show a partial state in the list. No migration: the data model already supports it.

FIXED (2026-10-10 23:20) — toggleOutOfStock now takes optional skuIds + isOutOfStock (apps/backend/src/trpc/apis/admin-apis/apis/product.ts), backed by a new setProductSkusOutOfStock(regionId, productId, skuIds, isOutOfStock) (packages/db_helper_sqlite/src/admin-apis/product.ts) that writes exactly those product_market_stats rows, rejects ids that are not the product's variants (400) and requires the target state (400). The all-variants path is untouched (400/{id} only). The admin app gets a new VariantStockDialog (apps/admin-ui/src/components/VariantStockDialog.tsx) built on BottomDialog: the row's Stock button opens it, each variant has a checkbox (default all selected, with Select all / Clear), current state is shown per row (In/Out), a banner appears when the product is partially out, and two actions apply "Mark out of stock" / "Mark in stock" to the selection. The row chip and the in-stock/out-of-stock filters/counters now aggregate over all variants (In / Partial / Out) instead of reading skus[0]. Verified live: with a temp 2-SKU product, marking one variant out left the sibling in stock ((156:true, 157:false)), targeting the sibling was a no-op, a foreign id returned 400, a missing target returned 400, and the legacy {id} toggle still flipped all variants both ways. UI files parse with esbuild; the admin app was not built or run here (no installed node_modules in this environment).


F12 — Rejections are 500s (Low)

Correct business rejections come back as INTERNAL_SERVER_ERROR / HTTP 500, e.g. out-of-stock (Product 153 is unavailable), full slot, Cannot delete a store that still has products, Address is attached to an ongoing order. Please cancel the order first., Cannot delete default address…, Failed to delete image. Consistent with the already-known "ApiError statuses are flattened" quirk, but it makes monitoring and client error handling harder (the client has to parse messages).


F13 — Delivered orders still show success (Low)

In My Orders the delivered order #2495 renders SHIPPING STATUS: success; the order detail screen shows the DELIVERED badge and all three stepper nodes. The list label reads like an internal status string rather than a customer-facing state.


F14 — One empty-cart flap when selecting an address (Low, unconfirmed)

Selecting the A2 address on the cart once rendered "Your cart is empty / Start Shopping" with the A2 address checked (AD-05-bill-with-A2.jpg captured just after). Selecting it again showed the cart intact with the A2 fee (₹200) and both lines. Single occurrence; recorded so it can be watched during CT-04/AD-09-class work.


Retracted — not a defect

  • admin.order.getAll {flashDeliveryFilter: true} returning an empty list. The schema expects the enum "all" | "flash" | "regular" (apps/backend/src/trpc/apis/admin-apis/apis/order.ts:67-87). With {"flashDeliveryFilter":"flash"} the endpoint correctly returned the flash orders (2496, 2474, 2473); with a boolean it returns a zod invalid_value error, which my filter had silently rendered as []. No bug.

Harness problems also worth fixing (they cost most of the run's time)

  1. launchApp: {clearState: true} does not sign the iOS app out — every "signed-out" case needs a manual logout path.
  2. MCP request ceiling of 60 s kills long chained flows mid-way, leaving the app in an arbitrary state.
  3. Maestro percentage coordinates go stale as soon as a screen grows (the coupon row moved 51 % → 61 % when the cart gained a line). The repo's tests/e2e flows correctly use id:; the exploratory flows this run mostly could not, because the customer app exposes few testIDs outside login/search/cart.
  4. hideKeyboard fails on this build, so numeric inputs need a neutral tap that often does not dismiss the keyboard either (F10).
  5. No SQLite/D1 file is reachable from the workspace (apps/backend/.wrangler/ is empty and dumps/latest.sqlite has no regions table), so the plan's "authoritative DB read" layer was unavailable and every money/usage claim had to be made through the API.

Suggested fix order

  1. F1 (no product deletion) and F4 (tags: broken image + undeletable) — both block cleaning up the data this and the previous run created.
  2. F2 (discount basis) — money correctness, affects refunds and reporting.
  3. F3 (full slot selectable) — customers can build unplaceable carts.
  4. F6 + F7 (silent no-op config write, no region delete) — they make staging cleanup and config tests unreliable.
  5. F5, then F9/F10 (app behaviour that also blocks automation), then the Low items.

Data left behind because of F4/F7 (F1 removed)

Region 2 + bound 3 (F7: no region delete API) · stores 11 and 12 (guard: products exist) · tag 10 (F4) · region-2 product 153 (needs a region-2 staff token) · customer 9000011715 + default address 880 · address 879 (tied to order 2495) · slots 2033/2034 (deactivated) · orders #2495 (delivered) and #2496 (flash, pending).

Cleared by the F1 fix (2026-10-10 18:26): products 152 and 151 are gone from the catalog; their rows remain only as tombstones (product_skus.is_deleted = true) so order history keeps its names. Store 11/12 deletion is still blocked by region-2 product 153, not by F1.


Full-plan run addendum (2026-10-10 20:30–21:30 IST)

A fresh run of all 161 plan cases produced docs/test reports/e2e-full-run-2026-10-10.md (79 PASS / 47 PARTIAL / 23 FAIL / 8 BLOCKED / 4 NOT RUN) and 24 new defect rows A19–A42 in docs/test reports/e2e-errors-2026-10-10.md section G. Highest-impact new items: A19 (ApiError→500 mapping; fix in source, needs dev-server restart), A20/A21 (coupon SKU/region scope not enforced), A23 (multi-slot suborder discount not recorded), A24 (client boundId overrides the address bound), A25 (double-tap creates two orders), A27 (explicit rebalance drops the delivery fee), A32 (reviews fail for SKU-split products), A34 (isComboOnly not enforced).

Policy triage — coupons are global (2026-10-10)

Decision (user): coupons are neither region-based nor product/SKU-based. They apply to the whole cart in any region. Therefore A20 (SKU-scoped coupon applied to another SKU) and A21 (region-2 coupon applied to a region-1 order) are closed as by design, not defects. SEC-06's failure now rests only on A22 (expired reserved coupon still redeemable). Open follow-up: the admin coupon surface still offers/accepts region and SKU scoping (assertApplicableSkusInRegion, region-filtered coupon queries, skuIds/applicableProducts fields) — align or leave dormant, per product decision.

Fixes landed after the run (2026-10-10)

  • A22 — expired reserved coupon redeemable → FIXED (23:27). Policy: validTill is the single deadline for both claiming the secret and spending the coupon. The redeem route now rejects validTill < now ("This coupon has expired"), and redeemReservedCoupon claims the secret with a conditional update (WHERE is_redeemed = 0) before creating the coupon. Verified live: expired → rejected, valid → 200, and 6/6 rounds of 3 concurrent redeemers produced exactly one winner. Test coupon-ux.test.ts updated from "pins: an expired reserved code still redeems" to assert the rejection + the race; BUGS.md #11 marked FIXED.
  • A20 / A21 — closed as by design (coupons are global: not region-based, not product/SKU-based). Plan expectations updated for CP-05, CP-11 and SEC-06.
  • A23 — multi-slot sibling sub-order shows no discount line → CLOSED as accepted (2026-10-10). Decision: leave as-is. A sibling sub-order displays its own payable total; the prorated discount is not itemised on it. Plan BL-04/BL-05 expectations were relaxed accordingly (only the coupon-holding sub-order reconciles item/discount/fee).
  • A24 — client-supplied boundId overrode the address's bound → FIXED (2026-10-10). Policy: the delivery address's bound is authoritative; fall back to the client bound only when the address has none, then to the region's effective bound. One-line change in placeOrderUtil; matches the customer app's existing precedence. Verified live: address 879 (bound 2) + boundId: 1 → ₹200 (was ₹20); bound-less address 882 still honours the client bound (₹20 / ₹200). Recorded in tests/BUGS.md #21.
  • A25 — double-tap creates two orders → CLOSED (2026-10-10), already client-guarded. The app's Place Order handler has a synchronous submittingRef re-entrancy guard plus a disabled button (and it is the only caller of placeOrder), so a real double-tap cannot submit twice. The duplicates in the run came from concurrent API POSTs from the harness, not from the UI. Decision: no server-side idempotency; plan OR-12 corrected. Residual exposure kept on record: retry after an ambiguous failure / lost response (RC-04), API replay, other devices. tests/BUGS.md #17 unchanged.
  • A26 — admin can edit notes on a delivered order → CLOSED (2026-10-10), business decision. Admins may annotate delivered orders; the customer-side restriction stands. Plan OR-03 reworded to assert the customer path only.
  • A27 — explicit rebalance dropped the delivery fee → FIXED (2026-10-10). Policy: freeze the historic discount and delivery fee; rebalance only product prices. rebalanceSlots now recovers the charged discount from the stored row (items + fee − total) instead of re-deriving it from the coupon, adds the fee back, skips delivered/cancelled orders, and keeps a SKU's stored price when it has no price for the region. Verified live (order 2558): no-op rebalance keeps the payable; an invalidated coupon no longer raises it; repricing 249→299 yields 299 − 24.9 + 20 = 294.1. Plan OR-10 reworded; tests/BUGS.md #22 added.
  • A28 — updateProduct accepted never-uploaded (or another product's) image keys → FIXED (2026-10-10). createProduct validated every image, but updateProduct validated only newImageUrls and wrote skus[].images unchecked. Now the delta is validated (keys the product does not already own) plus newImageUrls, then claimed after the write. Verified live: fabricated key → rejected with nothing written; another product's claimed image → rejected; the product's own image re-sent → 200; a genuine pending upload → 200. tests/BUGS.md #23 added; plan P-02 rewritten.
  • A29 — editing an address cleared its default flag → FIXED (2026-10-10). updateAddress treated an omitted isDefault as false (isDefault || false), so a partial edit left the user with zero default addresses. Now isDefault: isDefault ?? existingAddress.isDefault — omitted keeps the current value, explicit true moves the default, explicit false still clears it. Verified live on U2 address 882. tests/BUGS.md #24 added; plan AD-02 reworded.
  • A30 — invalid phone/pincode accepted by the address API → FIXED (2026-10-10). Rule: phone = exactly 10 digits starting 6/7/8/9; pincode = exactly 6 digits. Enforced in createAddress and updateAddress; the UI's phone regex was aligned (its pincode rule already matched). Verified live: 8 invalid shapes → 400, valid → 201, and the update path rejects too. Probe rows deleted; the invalid rows the earlier run left behind (886/887/892/893) were cleaned up. tests/BUGS.md #25 added; plan AD-03 reworded.
  • A31 — a user could delete their only address → FIXED (2026-10-10). deleteAddress now refuses when the user has a single address ("This is your only address…"), and the customer sees that reason in a BottomDialog (checked before the confirm step, and also from the mutation's onError). The other refusals (default address, address on an ongoing order, not-found) were converted from plain Error to ApiError 409/404 so they become real 4xx once A19 lands. Verified live by API (only-address refused, default refused, unused address deleted) and in the app: signed in as U3 (one address) → My Addresses → Delete opened the "Cannot delete address" sheet. Evidence: /tmp/freshyo-e2e/A31-delete-only-address-dialog.jpg. tests/BUGS.md #26 added; plan AD-08 reworded.
  • A32 — createReview fails for SKU-split products → CLOSED (2026-10-10), not applicable. Decision: reviews are no longer dealt with, so the review feature (and its defects) is out of scope. Plan OP-06 marked out of scope; the review half of A38 is moot; P-03's review upload path no longer matters (its tag path is already fixed).
  • A33 — permanent vendor-snippet metadata query fails → CLOSED (2026-10-10), not a problem. Decision: vendor snippets are not a current concern, so this is dropped rather than fixed. Plan OP-03 marked out of scope; the snippet checks that did pass (OP-01 SKU filtering, SEC-02 cross-region, SEC-07 vendor authority) keep their results.
  • A34 — combo-only SKUs orderable standalone → CLOSED (2026-10-10), accepted. A combo-only SKU is reachable only by a direct API call: the single client filter (prominent-api-hooks.ts useAllProducts) keeps them out of Home, search, Offers/order-again (incl. the Combos strip), slot views, store pages and the cart's product lookup. Backend enforcement at placeOrder was declined. Plan PD-11 closed.
  • Open observation (not a defect, needs a product decision): the flag's semantics are contradictory. In production the flag sits on the bundle: the only isComboOnly product in region 1 is GYM PACK (sku 149 — live, not out of stock, ₹210, with comboItems = its components). Because the client filter removes it from every list including the Combos section, GYM PACK cannot be bought in the app at all, while the API would sell it. The other 7 combos (isComboOnly: false) show normally. Decide: is the flag “hide this product from the app” (then GYM PACK is intentionally unbuyable) or “only sell this inside a combo” (then it should be orderable as the combo and the app should show it)?
  • A35 — no minimum-order policy exists → CLOSED (2026-10-10), business decision. Policy settled: there is no minimum order value, so an order of any amount is accepted. The minRegularOrderValue row left on bound 2 is inert (no code reads it) and is housekeeping only. Plan BL-02 reworded to assert "no minimum order".
  • A37 — updateProductPrices took a SKU id named productId and could silently reprice/report falsely → FIXED (2026-10-10). The input field is now skuId (no back-compat alias), the messages say SKU, entries with no price field are rejected (No price fields to update for SKU(s): …), and updatedCount counts rows actually written. Callers updated: the admin-ui and admin-web price screens, plus three test payloads — including cache-invalidation.test.ts, which had been passing a product id and only worked when both ids coincided. Verified live (probe product 175, SKUs 185/186): updating skuId 186 changed only 186; the no-field entry was rejected with nothing written. Residual accepted: id values still overlap, so passing a product-id value still hits the same-numbered SKU — an explicit caller error now, not an API trap.
  • A19 — ApiError → HTTP 500 → FIXED (2026-10-10). Root cause read out of the installed tRPC 11 source (procedureBuilder.ts): callRecursive catches every resolver error and returns middleware a { ok: false, error } result — it never throws — and getTRPCErrorFromUnknown wraps a non-TRPCError as INTERNAL_SERVER_ERROR with the original kept on cause. The earlier attempt put the translation in a catch around next(), which is unreachable for resolver errors, so it never ran. Fixed by translating result.error.cause in errorLoggerMiddleware (only when it is an ApiError, so tRPC's own codes survive). Verified live: 400 for expired reserved coupon / duplicate product name / bogus image (product + tag) / wrong-scope const writes (admin + superadmin); 403 for a capacity-full slot; 409 for only-address, default-address and address-on-open-order; controls unchanged (400 zod, 404 unknown procedure, 401 no token). This closed the last FAIL (P-04) and lifted P-01/P-03/Q-02/T-03/T-04/R-01/S-06 to PASS. Residual: business rejections thrown as plain Error inside the db-helper packages still return 500 — validateAndGetCoupon (not-applicable / expired / invalidated / usage-limit / min-order / first-order-only) is the main one (SEC-06).
  • A36 / SEC-04 — global products were visible but unusable → FIXED (2026-10-10). Rule (user): admins may add global products to slots; scheduled deliveries keep the slot-SKU verification; a SKU is acceptable when its product's region is null (global) or the target region. placeOrderUtil SEC-04 now treats regionId === null as global (it previously said "a product with no region is treated as not available anywhere"), and the assertSkuIdsInRegion copies in slots.ts, banner.ts and coupon.ts accept globals. Verified live: global SKU 102 attached to a region-1 slot → 200; a scheduled order for it → 200 @ ₹498 with the slot check still applied; a genuine region-2 SKU is still rejected in a region-1 slot and at order time (409). vendor-snippets.ts (deprecated) untouched; product.ts already allowed globals.