This commit is contained in:
shafi54 2026-10-11 00:30:46 +05:30
parent 1d8aca9b84
commit eb7dfbdd45
24 changed files with 1412 additions and 162 deletions

View file

@ -267,7 +267,7 @@ export default function PricesOverview() {
const handleSave = () => {
const updates = Object.entries(pendingChanges).map(([skuId, change]) => {
const sku = allSkus.find(s => s.id === parseInt(skuId));
const update: any = { productId: sku?.id };
const update: any = { skuId: sku?.id };
if (change.price !== undefined) update.price = change.price;
if (change.marketPrice !== undefined) update.marketPrice = change.marketPrice;
if (change.flashPrice !== undefined) update.flashPrice = change.flashPrice;

View file

@ -3,10 +3,9 @@
* price grid, store filter, edit-dialog validation, flash toggle, the
* updateProductPrices mutation and navigation to rebalance orders.
*
* NOTE: the screen collects SKUs but sends `productId: sku.id`. The backend
* (admin-apis/product.ts:436 + db_helper_postgres updateProductPrices:410)
* treats `productId` as a productInfo id, so this is asserted as-is and
* reported as an app bug.
* NOTE: the screen collects SKUs and sends `skuId: sku.id`. The field was renamed from the misleading
* `productId` (product ids and SKU ids overlap, so passing a product id silently repriced another
* product's SKU); the backend now takes `skuId` and reports only rows it actually wrote.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
@ -224,9 +223,8 @@ describe('Prices overview', () => {
await waitFor(() =>
expectProcedureCalled(fetchMock, 'admin.product.updateProductPrices')
)
// BUG: productId is the SKU id (11), but the backend expects the product id.
expect(lastProcedureInput(fetchMock, 'admin.product.updateProductPrices')).toEqual({
updates: [{ productId: 11, price: 150 }],
updates: [{ skuId: 11, price: 150 }],
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Prices updated successfully')
@ -249,7 +247,7 @@ describe('Prices overview', () => {
expectProcedureCalled(fetchMock, 'admin.product.updateProductPrices')
)
expect(lastProcedureInput(fetchMock, 'admin.product.updateProductPrices')).toEqual({
updates: [{ productId: 11, isFlashAvailable: true }],
updates: [{ skuId: 11, isFlashAvailable: true }],
})
})

View file

@ -262,7 +262,7 @@ function PricesOverview() {
const handleSave = () => {
const updates = Object.entries(pendingChanges).map(([skuId, change]) => {
const sku = allSkus.find((s) => s.id === parseInt(skuId))
const update: any = { productId: sku?.id }
const update: any = { skuId: sku?.id }
if (change.price !== undefined) update.price = change.price
if (change.marketPrice !== undefined) update.marketPrice = change.marketPrice
if (change.flashPrice !== undefined) update.flashPrice = change.flashPrice

View file

@ -62,6 +62,7 @@ export {
// Admin - Product
getAllProducts,
getProductById,
getProductImageKeys,
deleteProduct,
createProduct,
updateProduct,

View file

@ -7,6 +7,7 @@ import { createAvailabilityCacheFile } from '@/src/lib/cloud_cache'
import {
getAllProducts as getAllProductsInDb,
getProductById as getProductByIdInDb,
getProductImageKeys as getProductImageKeysInDb,
deleteProduct as deleteProductInDb,
getProductReviews as getProductReviewsInDb,
respondToReview as respondToReviewInDb,
@ -305,8 +306,24 @@ export const productRouter = router({
.mutation(async ({ input, ctx }): Promise<{ product: AdminProductWithRelations; message: string }> => {
const { id, name, shortDescription, longDescription, storeId, incrementStep, productType, skus, deletedImageKeys, newImageUrls } = input
// The product's own images are re-sent on every edit, so only the keys it does not already
// own count as new references: those (plus the declared newImageUrls) must be real pending
// uploads. Without this a fabricated key — or another product's already-claimed image —
// could be written straight onto a SKU through `skus[].images`.
const currentImageKeys = new Set(await getProductImageKeysInDb(ctx.staffUser!.regionId, id))
const incomingImageKeys = skus.flatMap((sku) =>
sku.images.map((url) => extractKeyFromPresignedUrl(url))
)
const newlyReferenced = incomingImageKeys.filter((key) => !currentImageKeys.has(key))
const uploadsToValidate = [
...new Set([
...newImageUrls.map((url) => extractKeyFromPresignedUrl(url)),
...newlyReferenced,
]),
]
// Before deleting any current image or writing the update: the new uploads must be real.
await assertUploadUrlsClaimable(newImageUrls)
await assertUploadUrlsClaimable(uploadsToValidate)
if (deletedImageKeys.length > 0) {
await deleteImageUtil({ keys: deletedImageKeys })
@ -346,8 +363,8 @@ export const productRouter = router({
throw new ApiError('Product not found', 404)
}
if (newImageUrls.length > 0) {
await claimUploadUrls(newImageUrls)
if (uploadsToValidate.length > 0) {
await claimUploadUrls(uploadsToValidate)
}
await scheduleStoreInitialization(ctx.staffUser!.regionId)
@ -488,7 +505,7 @@ export const productRouter = router({
updateProductPrices: protectedProcedure
.input(z.object({
updates: z.array(z.object({
productId: z.number(),
skuId: z.number().int().positive(),
price: z.number().optional(),
marketPrice: z.number().nullable().optional(),
flashPrice: z.number().nullable().optional(),
@ -505,7 +522,11 @@ export const productRouter = router({
const result = await updateProductPricesInDb(ctx.staffUser!.regionId, updates)
if (result.invalidIds.length > 0) {
throw new ApiError(`Invalid product IDs: ${result.invalidIds.join(', ')}`, 400)
throw new ApiError(`Invalid SKU IDs: ${result.invalidIds.join(', ')}`, 400)
}
if (result.emptyIds.length > 0) {
throw new ApiError(`No price fields to update for SKU(s): ${result.emptyIds.join(', ')}`, 400)
}
await createAvailabilityCacheFile(ctx.staffUser!.regionId).catch((err) => {
@ -513,7 +534,7 @@ export const productRouter = router({
})
return {
message: `Updated prices for ${result.updatedCount} product(s)`,
message: `Updated prices for ${result.updatedCount} SKU(s)`,
updatedCount: result.updatedCount,
}
}),

View file

@ -1,6 +1,7 @@
import { router, protectedProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import { extractCoordsFromRedirectUrl } from '@/src/lib/license-util'
import { ApiError } from '@/src/lib/api-error'
import {
getUserDefaultAddress as getDefaultAddressInDb,
getUserAddresses as getUserAddressesInDb,
@ -17,6 +18,10 @@ import type {
UserAddressDeleteResponse,
} from '@packages/shared'
// Indian mobile numbers: exactly 10 digits starting 6-9. Pincode: exactly 6 digits.
const PHONE_REGEX = /^[6-9]\d{9}$/
const PINCODE_REGEX = /^\d{6}$/
export const addressRouter = router({
getDefaultAddress: protectedProcedure
.query(async ({ ctx }): Promise<UserAddressResponse> => {
@ -40,12 +45,14 @@ export const addressRouter = router({
regionId: z.number().int().positive('Region is required'),
boundId: z.number().int().positive().optional(),
name: z.string().min(1, 'Name is required'),
phone: z.string().min(1, 'Phone is required'),
phone: z.string().trim().min(1, 'Phone is required')
.regex(PHONE_REGEX, 'Phone must be a 10-digit number starting with 6, 7, 8 or 9'),
addressLine1: z.string().min(1, 'Address line 1 is required'),
addressLine2: z.string().optional(),
city: z.string().min(1, 'City is required'),
state: z.string().min(1, 'State is required'),
pincode: z.string().min(1, 'Pincode is required'),
pincode: z.string().trim().min(1, 'Pincode is required')
.regex(PINCODE_REGEX, 'Pincode must be 6 digits'),
isDefault: z.boolean().optional(),
latitude: z.number().optional(),
longitude: z.number().optional(),
@ -105,12 +112,14 @@ export const addressRouter = router({
regionId: z.number().int().positive('Region is required'),
boundId: z.number().int().positive().optional(),
name: z.string().min(1, 'Name is required'),
phone: z.string().min(1, 'Phone is required'),
phone: z.string().trim().min(1, 'Phone is required')
.regex(PHONE_REGEX, 'Phone must be a 10-digit number starting with 6, 7, 8 or 9'),
addressLine1: z.string().min(1, 'Address line 1 is required'),
addressLine2: z.string().optional(),
city: z.string().min(1, 'City is required'),
state: z.string().min(1, 'State is required'),
pincode: z.string().min(1, 'Pincode is required'),
pincode: z.string().trim().min(1, 'Pincode is required')
.regex(PINCODE_REGEX, 'Pincode must be 6 digits'),
isDefault: z.boolean().optional(),
latitude: z.number().optional(),
longitude: z.number().optional(),
@ -153,7 +162,8 @@ export const addressRouter = router({
city,
state,
pincode,
isDefault: isDefault || false,
// An omitted isDefault means "leave it as it is": only an explicit value may change it.
isDefault: isDefault ?? existingAddress.isDefault,
googleMapsUrl,
latitude,
longitude,
@ -172,22 +182,31 @@ export const addressRouter = router({
const existingAddress = await getUserAddressByIdInDb(userId, id)
if (!existingAddress) {
throw new Error('Address not found or does not belong to user')
throw new ApiError('Address not found or does not belong to user', 404)
}
// A user must always keep at least one address: the app has nothing to deliver to otherwise.
const userAddresses = await getUserAddressesInDb(userId)
if (userAddresses.length <= 1) {
throw new ApiError(
'This is your only address. Add another address before deleting this one.',
409
)
}
const hasOngoingOrders = await hasOngoingOrdersForAddressInDb(id)
if (hasOngoingOrders) {
throw new Error('Address is attached to an ongoing order. Please cancel the order first.')
throw new ApiError('Address is attached to an ongoing order. Please cancel the order first.', 409)
}
if (existingAddress.isDefault) {
throw new Error('Cannot delete default address. Please set another address as default first.')
throw new ApiError('Cannot delete default address. Please set another address as default first.', 409)
}
const deleted = await deleteUserAddressInDb(userId, id)
if (!deleted) {
throw new Error('Address not found or does not belong to user')
throw new ApiError('Address not found or does not belong to user', 404)
}
return { success: true, message: 'Address deleted successfully' }

View file

@ -132,6 +132,13 @@ export const userCouponRouter = router({
throw new ApiError("Invalid or already redeemed coupon code", 400);
}
// A reserved coupon's validTill is the deadline for claiming the secret as well as for
// spending the coupon, so an expired code must not redeem: otherwise the code is burned
// and the customer is handed an already-expired coupon.
if (reservedCoupon.validTill && new Date(reservedCoupon.validTill) < new Date()) {
throw new ApiError("This coupon has expired", 400);
}
// Check if already redeemed by this user (in case of multiple attempts)
if (reservedCoupon.redeemedBy === userId) {
throw new ApiError("You have already redeemed this coupon", 400);
@ -144,6 +151,11 @@ export const userCouponRouter = router({
const couponResult = await redeemUserReservedCouponInDb(userId, reservedCoupon)
if (!couponResult) {
// Lost the claim race: another request redeemed the same secret first.
throw new ApiError("Invalid or already redeemed coupon code", 400);
}
return { success: true, coupon: couponResult };
}),
});

View file

@ -81,10 +81,14 @@ const placeOrderUtil = async (params: {
);
}
// Bound-level constants (delivery charge/thresholds/min order) come from the
// active bound the client is browsing in, falling back to the region's
// effective bound. Region-level constants are shared across the region's bounds.
const boundId = params.boundId ?? (await getEffectiveBoundId(params.regionId));
// Bound-level constants (delivery charge/thresholds/min order) come from the bound the
// delivery address belongs to, so pricing cannot be changed by a client-supplied id.
// Only when the address carries no bound do we fall back to the bound the client is
// browsing in, then to the region's effective bound. This mirrors the customer app, which
// already prices the selected address's bound (prominent-api-hooks useGetEssentialConsts).
// Region-level constants are shared across the region's bounds.
const boundId =
address.boundId ?? params.boundId ?? (await getEffectiveBoundId(params.regionId));
const effective =
(boundId != null ? await getRegionSettingsForBound(params.regionId, boundId) : null) ??
(await getEffectiveRegionSettings(params.regionId));

View file

@ -25,45 +25,96 @@ export const middleware = t.middleware;
export const router = t.router;
export { TRPCError };
/**
* ApiError carries an HTTP status; tRPC knows nothing about it and would flatten
* every one of them into INTERNAL_SERVER_ERROR (HTTP 500). Business rejections
* must reach clients as 4xx, so translate the status into the matching tRPC code
* before the error leaves the middleware.
*/
const API_ERROR_TRPC_CODES: Record<number, TRPCError['code']> = {
400: 'BAD_REQUEST',
401: 'UNAUTHORIZED',
403: 'FORBIDDEN',
404: 'NOT_FOUND',
405: 'METHOD_NOT_SUPPORTED',
409: 'CONFLICT',
412: 'PRECONDITION_FAILED',
413: 'PAYLOAD_TOO_LARGE',
422: 'UNPROCESSABLE_CONTENT',
429: 'TOO_MANY_REQUESTS',
};
function isApiErrorShape(error: unknown): error is { message: string; statusCode?: number } {
// The bundle can contain more than one copy of lib/api-error (packages carry their own
// node_modules), so `instanceof` is unreliable; detect the shape instead.
return !!error && typeof error === 'object' &&
(((error as any).name === 'ApiError') || typeof (error as any).statusCode === 'number');
}
function toTRPCError(error: unknown): unknown {
if (!isApiErrorShape(error)) return error;
const status = error.statusCode ?? 500;
const code = API_ERROR_TRPC_CODES[status] ?? (status >= 500 ? 'INTERNAL_SERVER_ERROR' : 'BAD_REQUEST');
return new TRPCError({ code, message: error.message, cause: error });
}
/**
* tRPC hands resolver errors back to middleware as a `{ ok: false, error }` **result** (its
* `callRecursive` catches them), and wraps a non-TRPCError as INTERNAL_SERVER_ERROR while keeping the
* original on `cause`. Map our ApiError onto the matching TRPCError — and only that — so zod
* BAD_REQUESTs, UNAUTHORIZEDs and genuine 500s keep the code tRPC gave them.
*/
function translateResultError(error: unknown): unknown {
const original = (error as { cause?: unknown } | null)?.cause;
return isApiErrorShape(original) ? toTRPCError(original) : error;
}
/** The error log line for every failed procedure (unchanged shape). */
function logTrpcError({ path, type, start, ctx, error }: {
path: string;
type: string;
start: number;
ctx: any;
error: unknown;
}) {
const err = error as any;
console.error('🚨 tRPC Error:', {
timestamp: new Date().toISOString(),
path,
type,
duration: `${Date.now() - start}ms`,
userId: ctx?.user?.userId || ctx?.staffUser?.id || 'anonymous',
error: {
name: err?.name,
message: err?.message,
code: err?.code,
stack: err?.stack,
},
// Add SQL-specific details if available
...(err?.code && { sqlCode: err.code }),
...(err?.meta && { sqlMeta: err.meta }),
...(err?.sql && { sql: err.sql }),
});
}
// Global error logger middleware
const errorLoggerMiddleware = middleware(async ({ path, type, next, ctx }) => {
const start = Date.now();
const result = await next();
try {
const result = await next();
const duration = Date.now() - start;
// Log successful operations in development
if (process.env.NODE_ENV === 'development') {
console.log(`✅ ${type} ${path} - ${duration}ms`);
}
return result;
} catch (error) {
const duration = Date.now() - start;
const err = error as any; // Type assertion for error object
// Comprehensive error logging
console.error('🚨 tRPC Error:', {
timestamp: new Date().toISOString(),
path,
type,
duration: `${duration}ms`,
userId: ctx?.user?.userId || ctx?.staffUser?.id || 'anonymous',
error: {
name: err.name,
message: err.message,
code: err.code,
stack: err.stack,
},
// Add SQL-specific details if available
...(err.code && { sqlCode: err.code }),
...(err.meta && { sqlMeta: err.meta }),
...(err.sql && { sql: err.sql }),
});
throw error; // Re-throw to maintain error flow
// A resolver error never throws: tRPC returns it as a result, so the only way to control the
// outgoing status is to re-throw the translated TRPCError from here.
if (!result.ok) {
logTrpcError({ path, type, start, ctx, error: result.error });
throw translateResultError(result.error);
}
// Log successful operations in development
if (process.env.NODE_ENV === 'development') {
console.log(`✅ ${type} ${path} - ${Date.now() - start}ms`);
}
return result;
});
export const publicProcedure = t.procedure.use(errorLoggerMiddleware);

View file

@ -175,9 +175,10 @@ issued to user A".
> **Partially fixed (FC-04/SEC-06):** `validateAndGetCoupon` now loads
> `applicableUsers` and rejects a user-based coupon for anyone not listed (unless
> `isApplyForAll`). `skuIds` and region are **deliberately not enforced**: no
> SKU-specific or region-scoped coupons are created today (FC-09/FC-10 are false
> flags for now). `exclusiveApply` remains unenforced.
> `isApplyForAll`). `skuIds` and region are **not** enforced, and that is now
> **policy, not a gap** (2026-10-10): coupons are global — neither region-based
> nor product/SKU-based — so they apply to any cart in any region.
> `exclusiveApply` remains unenforced.
### 9. Cancelling an order does not release its coupon usage
@ -196,14 +197,20 @@ order permanently blocks a first-order-only coupon for that user.
**Pinned by:** `tests/api/order-lifecycle-gaps.test.ts` — "pins: a cancelled
first order poisons an isFirstOrderOnly coupon".
### 11. Reserved-coupon expiry is not checked at redemption
### 11. Reserved-coupon expiry is not checked at redemption — **FIXED 2026-10-10**
`redeemReservedCoupon` checks "already redeemed" and first-order-only, but not
`validTill`. An expired reserved code still redeems (it only fails later at
`placeOrder`).
`redeemReservedCoupon` checked "already redeemed" and first-order-only, but not
`validTill`, so an expired reserved code still redeemed (it only failed later at
`placeOrder`) and the secret was burned for a dead coupon.
**Pinned by:** `tests/api/coupon-ux.test.ts` — "pins: an expired reserved code
still redeems".
**Fix:** the redeem route now rejects `validTill < now` with "This coupon has
expired" (policy: one deadline for both claiming the secret and spending the
coupon), and `redeemReservedCoupon` claims the secret with a conditional update
(`WHERE is_redeemed = 0`) before creating the coupon, so two customers racing the
same code can no longer both receive one.
**Covered by:** `tests/api/coupon-ux.test.ts` — "rejects an expired reserved
code" and "lets only one of two simultaneous claims win".
### 12. `exclusiveApply` is stored but never enforced
@ -299,6 +306,187 @@ ids and fails once the history is large. Documented in
---
### 21. Bound pricing followed a client-supplied `boundId` — **FIXED 2026-10-10**
`placeOrderUtil` resolved the delivery charge and free-delivery threshold from
`params.boundId ?? getEffectiveBoundId(regionId)`. `boundId` is a plain optional
mutation input, and `getRegionSettingsForBound` only checked that the bound
belongs to the **region** — never to the order's **address**. So an order against
an address in bound 2 (₹200 / free above ₹800) could be placed with `boundId: 1`
(₹20 / free above ₹300) and be charged ₹20. The address's own `boundId` was never
read on this path.
**Fix (policy):** the delivery address's bound is authoritative —
`address.boundId ?? params.boundId ?? getEffectiveBoundId(regionId)`. This mirrors
the customer app, which already prices the selected address's bound
(`apps/user-ui/src/hooks/prominent-api-hooks.ts` → `useGetEssentialConsts`), and
keeps the bound-less-address fallback intact. Verified live: address 879 (bound 2)
+ `boundId: 1` now charges ₹200 (was ₹20); a bound-less address still honours the
client bound (₹20 for bound 1, ₹200 for bound 2).
**No regression test yet:** the suite has no bound fixtures and no superadmin
session helper, so it cannot create a second bound to compare against.
---
### 22. Explicit rebalance dropped the delivery charge — **FIXED 2026-10-10**
`rebalanceSlots` repriced an order as `total = items(latest prices) − discount`,
never adding `deliveryCharge` back — so every rebalanced order lost its fee from
the payable (while the `delivery_charge` column kept the old value). It also
re-derived the discount from the coupon's **current** state and looked it up per
order, so invalidating/expiring a coupon silently raised a historical total, and
multi-slot sub-orders (which own no `coupon_usage` row) lost their prorated
discount entirely. Delivered and cancelled orders were repriced too.
**Fix (policy): freeze the historic discount and delivery fee; rebalance only
product prices.** The charged discount is recovered from the stored row itself
(`items + fee − total`), which is immune to later coupon changes and preserves a
sub-order's prorated share; the fee is added back; delivered/cancelled orders are
skipped; a SKU with no price for the region keeps its stored price instead of
dropping to 0. Verified live: a no-op rebalance now leaves the payable untouched,
an invalidated coupon no longer changes it, and repricing keeps
`items − frozen discount + fee`.
**Known residue:** the customer/admin order **detail display** still recomputes
the discount from the coupon, so after a reprice it can show a discount that
differs from the frozen one (the payable is correct). Same family as the A23
display decision; `db.transaction` is still the no-op stub, so the write loop is
not atomic; money is still written unrounded (see #7). Orders rebalanced by the
old code carry a phantom discount equal to the dropped fee and were not
auto-repaired.
---
### 23. `updateProduct` stored unvalidated image keys — **FIXED 2026-10-10**
`createProduct` validated every referenced image
(`skus.flatMap((s) => s.images)` → `assertUploadUrlsClaimable` → `claimUploadUrls`), but
`updateProduct` validated only the declared `newImageUrls` and then wrote
`skus[].images` straight through (`extractKeyFromPresignedUrl` → `updateProductInDb`)
with no check and no claim. A fabricated key therefore produced a permanently
broken image, and another product's already-claimed key could be silently reused
(`createProduct` rejects that as "already used").
**Fix:** validate the *delta* — the keys the product does not already own (via a
new `getProductImageKeys(regionId, productId)` helper) plus `newImageUrls` —
before the write, and claim them after it. The product's own images may be
re-sent by the edit form untouched. Verified live: fabricated key → rejected with
nothing written; another product's claimed image → rejected; own image re-sent →
200; genuine pending upload → 200 and claimed.
Banners, stores and global stores also convert URLs to keys without this guard,
but the upload endpoint only issues the contexts
`review | product_info | notification | complaint | profile | tags`, so those
images are never registered in `upload_url_status` — guarding them would reject
legitimate images.
---
### 24. Editing an address cleared its default flag — **FIXED 2026-10-10**
`user.address.updateAddress` forwarded `isDefault: isDefault || false` while the
input schema declares `isDefault` **optional**. An edit that omitted the field —
the natural partial update — therefore unset the address's default and left the
user with **zero** default addresses. (`createAddress` computes
`makeDefault = isDefault || no-other-addresses`, so it never had the bug; the
AddressForm and checkout selector already send the current value, so the UI did
not expose it.)
**Fix:** `isDefault: isDefault ?? existingAddress.isDefault` — omitted keeps the
current value, explicit `true` sets it and clears the other addresses' defaults,
explicit `false` still clears it.
**Related, still open:** explicitly sending `isDefault: false` (or deleting the
only default address, see AD-08) can still leave a user with no default.
---
### 25. Address phone/pincode were unvalidated — **FIXED 2026-10-10**
`user.address.createAddress` / `updateAddress` accepted any non-empty string for
`phone` and `pincode` (only `min(1)`), so `phone: "123"` and `pincode: "12"` were
persisted. The app's form validated both client-side, so only a non-app client
could store garbage — which is what the run did.
**Fix (rule):** phone = exactly 10 digits starting **6/7/8/9**; pincode = exactly
6 digits, enforced in both procedures, with the UI's phone regex aligned. Verified
live: `123` / `1234567890` / `5678901234` / 9-digit / 11-digit phones and 5-digit /
7-digit / non-numeric pincodes all return **400**; a valid pair is accepted; the
update path rejects too.
**Note:** zod-level input validation already surfaces as HTTP 400 — only
`ApiError` throws are flattened to 500 (see #… / A19).
---
### 26. A user could delete their only address — **FIXED 2026-10-10**
`user.address.deleteAddress` guarded against an address attached to an ongoing
order and against the **default** address, but nothing stopped the user deleting
their **only** address — leaving an account with nowhere to deliver to (the same
zero-address state that editing could reach, see #24). The refusals were also
plain `Error`s, so they surfaced as HTTP 500.
**Fix (rule):** deleting the user's only address is refused with
“This is your only address. Add another address before deleting this one.”, and
the app shows it in a **BottomDialog** (checked before the “are you sure?” step
and again from the mutation's `onError`). The other refusals now throw `ApiError`
(409 / 404) so they reach the customer as 4xx.
**Still open:** explicitly sending `isDefault: false` for the last default can
still leave an account with no default address.
---
### 27. `updateProductPrices` addressed SKUs as `productId` — **FIXED 2026-10-10**
`admin.product.updateProductPrices` took `updates[].productId`, but the helper
validated it against `productSkus.id` and wrote `product_market_stats.skuId`. A
product id therefore landed on whatever SKU carried the same number (product ids
and SKU ids are separate, overlapping sequences), and the response still said
“Updated prices for N **product(s)**”. An entry with no price field wrote nothing
yet was counted as updated and reported as a success.
**Fix:** the input field is **`skuId`** (no alias), the messages say SKU, an entry
with no price field is rejected up front
(`No price fields to update for SKU(s): …`), and `updatedCount` counts rows actually written. The admin-ui and admin-web price screens were updated, along with
three test payloads — `cache-invalidation.test.ts` had been passing a *product* id
and only passed while the two ids happened to coincide.
**Residual (accepted):** id *values* still overlap, so a caller that passes a
product id for `skuId` still hits the same-numbered SKU. That is now an explicit
caller error rather than an API trap; mapping a product id to its SKUs is
deliberately not done because that ambiguity is what caused the bug.
---
### 28. Business errors left tRPC as HTTP 500 — **FIXED 2026-10-10**
`errorLoggerMiddleware` translated our `ApiError` to a `TRPCError` inside a
`try/catch` around `next()`. In tRPC 11 that catch is **unreachable for resolver
errors**: `callRecursive` catches them and returns the middleware a
`{ ok: false, error }` result, and `getTRPCErrorFromUnknown` has already wrapped a
non-`TRPCError` as `INTERNAL_SERVER_ERROR` (keeping the original on `cause`) —
which is why every business rejection arrived as HTTP 500 with the correct
message.
**Fix:** the middleware now inspects the result and re-throws
`translateResultError(result.error)`, which maps `result.error.cause` **only** when
it is an `ApiError`, so zod `BAD_REQUEST`s, `UNAUTHORIZED`s and genuine 500s keep
the code tRPC gave them. Verified live: 400 (expired reserved coupon, duplicate
product name, bogus upload URL on product + tag, wrong-scope const writes on both
admin and superadmin), 403 (capacity-full slot), 409 (only address, default
address, address on an open order); controls unchanged (400 zod, 404 unknown
procedure, 401 no token).
**Residual:** business rejections thrown as **plain `Error` inside the db-helper
packages** still return 500 — `validateAndGetCoupon` (`not applicable`, `Coupon has
expired`, invalidated, usage-limit, min-order, first-order-only) is the main one.
Those need a status attached at the throw site (or a package-level ApiError).
---
## Out of scope (per request)
Online payments (`user.payment.*`, `admin.payments.initiateRefund`), OTP

View file

@ -43,7 +43,7 @@ describe('cache invalidation', () => {
const before = await essentialConsts()
await admin.admin.product.updateProductPrices.mutate({
updates: [{ productId: store.productId, price: 250 }],
updates: [{ skuId: store.skuId, price: 250 }],
})
const after = await essentialConsts()

View file

@ -99,18 +99,24 @@ describe('coupon UX', () => {
expect(error.message).toMatch(/invalid|redeemed/i)
})
/**
* KNOWN GAP: redemption does not check validTill (only the placeOrder
* path does), so an already-expired reserved code still redeems.
*/
it('pins: an expired reserved code still redeems', async () => {
it('rejects an expired reserved code', async () => {
const { secretCode } = await createReserved({
validTill: new Date(Date.now() - 3600_000).toISOString(),
})
const res = await redeem(userA.token, secretCode)
const error = await captureError(() => redeem(userA.token, secretCode))
expect(error.message).toMatch(/expired/i)
})
expect(res.success).toBe(true)
it('lets only one of two simultaneous claims win', async () => {
const { secretCode } = await createReserved()
const results = await Promise.allSettled([
redeem(userA.token, secretCode),
redeem(userB.token, secretCode),
])
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1)
})
it('rejects an isFirstOrderOnly reserved code for a user with orders', async () => {

View file

@ -164,7 +164,7 @@ describe('placeOrder edge cases', () => {
it('charges flashPrice plus the flash delivery charge', async () => {
await admin.admin.product.updateProductPrices.mutate({
updates: [{ productId: flashSkuId, flashPrice: 60, isFlashAvailable: true }],
updates: [{ skuId: flashSkuId, flashPrice: 60, isFlashAvailable: true }],
})
await withFlashEnabled(async () => {
@ -181,7 +181,7 @@ describe('placeOrder edge cases', () => {
it('falls back to the regular price when flashPrice is null', async () => {
await admin.admin.product.updateProductPrices.mutate({
updates: [{ productId: flashFallbackSkuId, flashPrice: null, isFlashAvailable: true }],
updates: [{ skuId: flashFallbackSkuId, flashPrice: null, isFlashAvailable: true }],
})
await withFlashEnabled(async () => {

View file

@ -83,6 +83,8 @@ function AddressCard({ address, onEdit, onDelete, onSetDefault, isDeleting }: {
export default function Addresses() {
const [modalVisible, setModalVisible] = useState(false);
const [editingAddress, setEditingAddress] = useState<Address | null>(null);
// Reason a delete was refused (only address / still the default / open order) — shown in a bottom sheet.
const [deleteError, setDeleteError] = useState<string | null>(null);
const { data, isLoading, error, refetch } = trpc.user.address.getUserAddresses.useQuery();
@ -107,6 +109,13 @@ export default function Addresses() {
};
const handleDeleteAddress = (id: number) => {
// The server refuses this too, but checking here explains why instead of asking "are you sure?"
// and then failing.
if (addresses.length <= 1) {
setDeleteError('This is your only address. Add another address before deleting this one.');
return;
}
Alert.alert(
'Delete Address',
'Are you sure you want to delete this address?',
@ -124,7 +133,7 @@ export default function Addresses() {
Alert.alert('Success', 'Address deleted successfully');
},
onError: (error) => {
Alert.alert('Error', error.message || 'Failed to delete address');
setDeleteError(error.message || 'Failed to delete address');
}
});
}
@ -268,6 +277,22 @@ export default function Addresses() {
isEdit={!!editingAddress}
/>
</RawBottomDialog>
<BottomDialog open={deleteError !== null} onClose={() => setDeleteError(null)}>
<View style={tw`pb-6`}>
<View style={tw`flex-row items-center mb-2`}>
<MaterialIcons name="error-outline" size={22} color="#dc2626" />
<MyText style={tw`text-lg font-bold text-slate-900 ml-2`}>Cannot delete address</MyText>
</View>
<MyText style={tw`text-sm text-slate-600 mb-5`}>{deleteError}</MyText>
<MyTouchableOpacity
onPress={() => setDeleteError(null)}
style={tw`bg-brand500 py-3.5 rounded-xl items-center`}
>
<MyText style={tw`text-white font-bold`}>OK</MyText>
</MyTouchableOpacity>
</View>
</BottomDialog>
</>
);
}

View file

@ -59,7 +59,8 @@ const AddressForm: React.FC<AddressFormProps> = ({ onSuccess, initialValues, isE
.typeError('Region is required')
.required('Region is required'),
name: Yup.string().required('Name is required'),
phone: Yup.string().required('Phone is required').matches(/^\d{10}$/, 'Phone must be 10 digits'),
phone: Yup.string().required('Phone is required')
.matches(/^[6-9]\d{9}$/, 'Phone must be a 10-digit number starting with 6, 7, 8 or 9'),
addressLine1: Yup.string().required('Address Line 1 is required'),
addressLine2: Yup.string(),
city: Yup.string().required('City is required'),

View file

@ -3009,3 +3009,419 @@ user-ui
In/Out chip, the in-stock/out-of-stock filters and the counters now aggregate over all variants
(In / Partial / Out) instead of reading skus[0]. Both files parse with esbuild; the app itself was not built
or run here (apps/admin-ui has no installed node_modules in this environment).
[2026-10-10 21:05:00 +0530] Full-plan E2E run — FIX: business errors were flattened to HTTP 500 (ApiError -> tRPC).
Found while running section P/R (case P-01/P-02/P-03/P-04/T-04/R-01): every `throw new ApiError(msg, 4xx)` inside a
tRPC procedure reached clients as HTTP 500 / INTERNAL_SERVER_ERROR, because tRPC only understands TRPCError codes
and ApiError is a plain Error. Examples observed:
- createProduct with an unclaimed image -> 500 "These images were not uploaded through the app ..." (expected 400)
- updateProduct with an unclaimed new image -> 500 (expected 400)
- createProduct duplicate name (double-submit) -> 500 "A product with this name already exists" (expected 409/400)
- superadmin.regions.updateBoundSettings wrong-scope key -> 500 "…writes bound-scoped constants only" (expected 400)
- admin.store.getStoreById / slots.getSlotById / coupon.getById / order.getOrderDetails cross-region -> 500 (expected 404)
Change (one middleware, affects every procedure):
apps/backend/src/trpc/trpc-index.ts
+ import { ApiError } from '@/src/lib/api-error';
+ const API_ERROR_TRPC_CODES: Record<number, TRPCError['code']> = {
+ 400: 'BAD_REQUEST', 401: 'UNAUTHORIZED', 403: 'FORBIDDEN', 404: 'NOT_FOUND', 405: 'METHOD_NOT_SUPPORTED',
+ 409: 'CONFLICT', 412: 'PRECONDITION_FAILED', 413: 'PAYLOAD_TOO_LARGE', 422: 'UNPROCESSABLE_CONTENT',
+ 429: 'TOO_MANY_REQUESTS',
+ };
+ function toTRPCError(error: unknown): unknown {
+ if (!(error instanceof ApiError)) return error;
+ const status = error.statusCode ?? 500;
+ const code = API_ERROR_TRPC_CODES[status] ?? (status >= 500 ? 'INTERNAL_SERVER_ERROR' : 'BAD_REQUEST');
+ return new TRPCError({ code, message: error.message, cause: error });
+ }
} catch (error) {
... log ...
- throw error; // Re-throw to maintain error flow
+ throw toTRPCError(error); // keep 4xx a 4xx end-to-end
No migration. No drizzle migrations run.
[2026-10-10 21:12:00 +0530] Follow-up on the entry above: `error instanceof ApiError` never matched.
The backend bundle contains more than one copy of lib/api-error (packages carry their own node_modules),
so the thrown error's prototype differs from the imported class. Use structural detection instead:
- if (!(error instanceof ApiError)) return error;
+ function isApiErrorShape(error: unknown): error is { message: string; statusCode?: number } {
+ return !!error && typeof error === 'object' &&
+ ((error as any).name === 'ApiError' || typeof (error as any).statusCode === 'number')
+ }
+ if (!isApiErrorShape(error)) return error;
(and drop the now-unused ApiError import)
[2026-10-10 21:20:00 +0530] Note: the running `wrangler dev` watcher stopped re-bundling after ~20:31 IST
(reloadComplete events stop landing for new edits), so the ApiError->4xx fix above is in the source but could
not be verified against the live worker in this session. A dev-server restart applies it. Until then, live
requests still show business rejections as HTTP 500; every affected case below is marked PARTIAL/FAIL with that
note. No other code was changed for this entry.
[2026-10-10 23:27:44 +0530] Fix A22 — an expired reserved coupon could still be redeemed (and a secret could be claimed twice).
Policy (user decision): a reserved coupon's validTill is the single deadline for BOTH claiming the secret
and spending the issued coupon, so redemption must be rejected once it has passed.
1/3 apps/backend/src/trpc/apis/user-apis/apis/coupon.ts — guard the redeem route, handle a lost claim:
@@ redeemReservedCoupon
if (!reservedCoupon) {
throw new ApiError("Invalid or already redeemed coupon code", 400);
}
+
+ // A reserved coupon's validTill is the deadline for claiming the secret as well as for
+ // spending the coupon, so an expired code must not redeem: otherwise the code is burned
+ // and the customer is handed an already-expired coupon.
+ if (reservedCoupon.validTill && new Date(reservedCoupon.validTill) < new Date()) {
+ throw new ApiError("This coupon has expired", 400);
+ }
+
// Check if already redeemed by this user (in case of multiple attempts)
if (reservedCoupon.redeemedBy === userId) {
@@
const couponResult = await redeemUserReservedCouponInDb(userId, reservedCoupon)
+
+ if (!couponResult) {
+ // Lost the claim race: another request redeemed the same secret first.
+ throw new ApiError("Invalid or already redeemed coupon code", 400);
+ }
+
return { success: true, coupon: couponResult };
2/3 packages/db_helper_sqlite/src/user-apis/coupon.ts — claim the secret atomically before creating the coupon.
The return type becomes `UserCoupon | null` (null = the read-then-write race was lost):
-export async function redeemReservedCoupon(userId: number, reservedCoupon: ReservedCouponRow): Promise<UserCoupon> {
- const couponResult = await db.transaction(async (tx) => {
- const [coupon] = await tx.insert(coupons).values({ ...unchanged... }).returning()
-
- await tx.insert(couponApplicableUsers).values({
- couponId: coupon.id,
- userId,
- })
-
- await tx.update(reservedCoupons).set({
- isRedeemed: true,
- redeemedBy: userId,
- redeemedAt: new Date(),
- }).where(eq(reservedCoupons.id, reservedCoupon.id))
-
- return coupon
- })
-
- return mapCoupon(couponResult)
-}
+export async function redeemReservedCoupon(userId: number, reservedCoupon: ReservedCouponRow): Promise<UserCoupon | null> {
+ return db.transaction(async (tx) => {
+ // Claim first: this conditional update closes the gap between getReservedCouponByCode
+ // and the write, so two customers racing on one secret can never both get a coupon.
+ const claimed = await tx
+ .update(reservedCoupons)
+ .set({ isRedeemed: true, redeemedBy: userId, redeemedAt: new Date() })
+ .where(and(eq(reservedCoupons.id, reservedCoupon.id), eq(reservedCoupons.isRedeemed, false)))
+ .returning({ id: reservedCoupons.id })
+
+ if (claimed.length === 0) return null
+
+ const [coupon] = await tx.insert(coupons).values({ ...unchanged... }).returning()
+
+ await tx.insert(couponApplicableUsers).values({
+ couponId: coupon.id,
+ userId,
+ })
+
+ return mapCoupon(coupon)
+ })
+}
3/3 apps/backend/tests/api/coupon-ux.test.ts — the gap is no longer pinned; assert the fix instead:
- /**
- * KNOWN GAP: redemption does not check validTill (only the placeOrder
- * path does), so an already-expired reserved code still redeems.
- */
- it('pins: an expired reserved code still redeems', async () => {
+ it('rejects an expired reserved code', async () => {
const { secretCode } = await createReserved({
validTill: new Date(Date.now() - 3600_000).toISOString(),
})
- const res = await redeem(userA.token, secretCode)
- expect(res.success).toBe(true)
+ const error = await captureError(() => redeem(userA.token, secretCode))
+ expect(error.message).toMatch(/expired/i)
})
+
+ it('lets only one of two simultaneous claims win', async () => {
+ const { secretCode } = await createReserved()
+ const results = await Promise.allSettled([
+ redeem(userA.token, secretCode),
+ redeem(userB.token, secretCode),
+ ])
+ expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1)
+ })
Docs (.md only, no code): apps/backend/tests/BUGS.md #11 marked FIXED; #8 note updated to the product
policy that coupons are global (not region- or SKU-scoped).
Not changed: no admin-side create guard — a normal coupon can also be created with a past validTill and is
shown as "expired"; reserved coupons now behave identically.
No schema change, no migration, no drizzle migrations run.
[2026-10-10 23:41:54 +0530] Fix A24 — the delivery fee followed a client-supplied boundId, so an order could be undercharged.
Policy (user): prefer the delivery address's bound; only when the address has no bound, fall back to the
bound the client sends; then to the region's effective bound. This mirrors the customer app, which already
prices the selected address's bound (apps/user-ui/src/hooks/prominent-api-hooks.ts useGetEssentialConsts).
File: apps/backend/src/trpc/apis/user-apis/apis/order.ts (placeOrderUtil)
- // Bound-level constants (delivery charge/thresholds/min order) come from the
- // active bound the client is browsing in, falling back to the region's
- // effective bound. Region-level constants are shared across the region's bounds.
- const boundId = params.boundId ?? (await getEffectiveBoundId(params.regionId));
+ // Bound-level constants (delivery charge/thresholds/min order) come from the bound the
+ // delivery address belongs to, so pricing cannot be changed by a client-supplied id.
+ // Only when the address carries no bound do we fall back to the bound the client is
+ // browsing in, then to the region's effective bound. This mirrors the customer app, which
+ // already prices the selected address's bound (prominent-api-hooks useGetEssentialConsts).
+ // Region-level constants are shared across the region's bounds.
+ const boundId =
+ address.boundId ?? params.boundId ?? (await getEffectiveBoundId(params.regionId));
Effect: address 879 (bound 2 = Rs 200 fee / Rs 800 free-delivery threshold) + boundId 1 (Rs 20 / Rs 300)
now charges Rs 200 instead of Rs 20. An honest client is unaffected (it already sends the address's bound).
No schema change; the orders table still has no boundId column (auditability follow-up noted in the report).
No migration, no drizzle migrations run. No regression test added: the suite has no bound fixtures and no
superadmin session helper, so it cannot create a second bound to compare against; noted in tests/BUGS.md.
[2026-10-10 23:51:04 +0530] Fix A27 — rebalanceSlots wrote a total that excluded the delivery charge (and re-derived the coupon).
Policy (user): freeze the historic discount AND the delivery fee; rebalance only the product prices.
File: packages/db_helper_sqlite/src/admin-apis/order.ts (rebalanceSlots)
- with: { orderItems: {...}, couponUsages: { with: { coupon: true } } }
+ with: { orderItems: {...}, orderStatus: { columns: { isCancelled: true, isDelivered: true } } }
-
- const processedOrdersData = ordersList.map((order: any) => {
- let newTotal = order.orderItems.reduce((acc, item) => acc + latestPrice * qty, 0)
- order.orderItems.forEach((item) => { item.price = latest; item.discountedPrice = latest })
- const coupon = order.couponUsages[0]?.coupon
- let discount = 0
- if (coupon && !coupon.isInvalidated && (!coupon.validTill || coupon.validTill > now)) { ... }
- newTotal -= discount
- ... return { order: rest, updatedOrderItems, newTotal }
- })
+ const processedOrdersData = ordersList
+ .filter((order) => { const s = order.orderStatus?.[0]; return !s?.isCancelled && !s?.isDelivered })
+ .map((order) => {
+ const fee = Number(order.deliveryCharge || 0)
+ const oldItems = sum(item.price * item.quantity)
+ // Historic discount recovered from the stored row itself: items + fee - total.
+ // Immune to later coupon edits/invalidation and preserves a multi-slot sub-order's
+ // prorated share (that sub-order owns no coupon_usage row).
+ const frozenDiscount = Math.max(0, oldItems + fee - Number(order.totalAmount || 0))
+ const priceById = new Map<number, number>()
+ order.orderItems.forEach((item) => {
+ const latest = marketStatsForRegion(item.sku?.marketStats, regionId)?.ourPrice
+ // No price for this region -> keep the stored price (never drop to 0).
+ priceById.set(item.id, latest == null ? Number(item.price) : Number(latest))
+ })
+ const newItems = sum(priceById.get(item.id) * item.quantity)
+ const newTotal = Math.max(0, newItems - frozenDiscount + fee)
+ ...
+ return { order: rest, updatedOrderItems, newTotal, priceById }
+ })
-
- for (const { order, updatedOrderItems, newTotal } of processedOrdersData) {
+ for (const { order, updatedOrderItems, newTotal, priceById } of processedOrdersData) {
+ const price = priceById.get(item.id)
... .set({ price, discountedPrice: price })
Effect (verified live on an isolated slot): a no-op rebalance previously dropped the Rs 20 fee from the
payable (249 -> 249 where items+ fee = 269); now the fee and the charged discount are preserved and only the
item price is repriced. Delivered/cancelled orders are skipped. Coupon edits/invalidation no longer change a
historic order's total.
Unchanged / noted: money is still written unrounded (BUGS #7); db.transaction is the no-op stub, so the write
loop is still not atomic; orders rebalanced by the OLD code (e.g. 2541, 2554) now carry a phantom discount
equal to the dropped fee — a data-repair item, not auto-repaired here.
No schema change. No migration. No drizzle migrations run.
[2026-10-10 23:55:08 +0530] Fix A28 — updateProduct accepted never-uploaded (or another product's) image keys via skus[].images.
Root cause: createProduct validates every image (skus.flatMap(images) -> assertUploadUrlsClaimable -> claim),
but updateProduct validated only the declared newImageUrls, then wrote skus[].images straight through
(extractKeyFromPresignedUrl -> updateProductInDb) with no check and no claim. The edit form re-sends the
product's existing (already-claimed) images in skus[].images, which is why the whole set was not validated.
Policy (user): validate newImageUrls too, and treat an image the product already owns as owned (a removed
image re-added in the same submit is owned until the write).
1/4 packages/db_helper_sqlite/src/admin-apis/product.ts — new lightweight helper:
+export async function getProductImageKeys(regionId: number, productId: number): Promise<string[]> {
+ const product = await db.query.productInfo.findFirst({
+ where: and(eq(productInfo.id, productId), or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))),
+ columns: { id: true },
+ with: { skus: { columns: { images: true } } },
+ })
+ return (product?.skus ?? []).flatMap((sku) => ((sku.images as string[] | null) ?? []).map(String))
+}
2/4 packages/db_helper_sqlite/index.ts + apps/backend/src/sqliteImporter.ts — export getProductImageKeys.
3/4 apps/backend/src/trpc/apis/admin-apis/apis/product.ts (updateProduct):
- // Before deleting any current image or writing the update: the new uploads must be real.
- await assertUploadUrlsClaimable(newImageUrls)
+ // The product's own images are re-sent on every edit, so only keys it does not already own are
+ // new references: those (plus the declared newImageUrls) must be real pending uploads.
+ const currentImageKeys = new Set(await getProductImageKeysInDb(ctx.staffUser!.regionId, id))
+ const incomingImageKeys = skus.flatMap((sku) => sku.images.map((url) => extractKeyFromPresignedUrl(url)))
+ const newlyReferenced = incomingImageKeys.filter((key) => !currentImageKeys.has(key))
+ const uploadsToValidate = [...new Set([
+ ...newImageUrls.map((url) => extractKeyFromPresignedUrl(url)),
+ ...newlyReferenced,
+ ])]
+ // Before deleting any current image or writing the update: the new uploads must be real.
+ await assertUploadUrlsClaimable(uploadsToValidate)
...
- if (newImageUrls.length > 0) { await claimUploadUrls(newImageUrls) }
+ if (uploadsToValidate.length > 0) { await claimUploadUrls(uploadsToValidate) }
4/4 imports: getProductImageKeys as getProductImageKeysInDb.
Verified live: fabricated key -> 400 with nothing written; another product's claimed key -> 400; the product's
own already-claimed image re-sent -> 200; a genuine pending upload -> 200 and claimed. createProduct guarded
as before. Probe product soft-deleted.
Not changed: banners/stores/global-stores convert URLs to keys unguarded, but the upload endpoint only issues
contexts review|product_info|notification|complaint|profile|tags, so those images are never registered in
upload_url_status and asserting there would reject legitimate images (out of scope).
No schema change. No migration. No drizzle migrations run.
[2026-10-10 23:57:48 +0530] Fix A29 — editing an address cleared its default flag (leaving the user with zero defaults).
Root cause: apps/backend/src/trpc/apis/user-apis/apis/address.ts (updateAddress) passed
isDefault: isDefault || false // "omitted" and "false" were treated identically
while the input schema declares isDefault optional, so a partial edit silently unset the default.
createAddress does not have the bug (it computes makeDefault = isDefault || no-other-addresses).
Fix:
- isDefault: isDefault || false,
+ // An omitted isDefault means "leave it as it is": only an explicit value may change it.
+ isDefault: isDefault ?? existingAddress.isDefault,
Behaviour: omitting isDefault keeps the current value; isDefault: true sets it and clears the other
addresses' defaults; isDefault: false still clears it explicitly (unchanged).
Verified live (U2 address 882): set default -> edit WITHOUT isDefault -> still default (previously it
became false and the user had zero defaults).
Not changed: the db helper still writes isDefault unconditionally (the route now always resolves a
boolean). The AddressForm/checkout selector already send the current value, so the UI was unaffected.
No schema change. No migration. No drizzle migrations run.
2026-10-10 23:59:14 Fix A30 — createAddress/updateAddress accepted any phone/pincode (only min(1) was enforced).
Rule (user): pincode = exactly 6 digits; phone = exactly 10 digits starting with 6, 7, 8 or 9.
1/3 apps/backend/src/trpc/apis/user-apis/apis/address.ts — shared patterns + both schemas:
+// Indian mobile numbers: exactly 10 digits starting 6-9. Pincode: exactly 6 digits.
+const PHONE_REGEX = /^[6-9]\d{9}$/
+const PINCODE_REGEX = /^\d{6}$/
- phone: z.string().min(1, 'Phone is required'),
- pincode: z.string().min(1, 'Pincode is required'),
+ phone: z.string().trim().min(1, 'Phone is required')
+ .regex(PHONE_REGEX, 'Phone must be a 10-digit number starting with 6, 7, 8 or 9'),
+ pincode: z.string().trim().min(1, 'Pincode is required')
+ .regex(PINCODE_REGEX, 'Pincode must be 6 digits'),
(applied to BOTH createAddress and updateAddress)
2/3 apps/user-ui/src/components/AddressForm.tsx — align the client rule with the server:
- phone: Yup.string().required('Phone is required').matches(/^\d{10}$/, 'Phone must be 10 digits'),
+ phone: Yup.string().required('Phone is required')
+ .matches(/^[6-9]\d{9}$/, 'Phone must be a 10-digit number starting with 6, 7, 8 or 9'),
(pincode already used /^\d{6}$/ — unchanged)
3/3 Cleanup of the probe fixtures that A30 created with invalid data (U2 886 phone "123", U2 887 pincode "12",
U3 892 phone "123", U3 893 pincode "12") — deleted.
Scope: only the user address router creates/updates addresses (admin.order.updateAddressCoords only writes
coordinates); the account mobile used by register/login is NOT validated by this change.
No schema change. No migration. No drizzle migrations run.
2026-10-11 00:01:20 Fix A31 / plan AD-08 — a user could end up with no address (and the protected-deletion errors
surfaced as HTTP 500). Rule (user): deleting the user's ONLY address must be refused and the reason shown to
the customer in a BottomDialog.
1/2 apps/backend/src/trpc/apis/user-apis/apis/address.ts (deleteAddress):
+ // A user must always keep at least one address: the app has nothing to deliver to otherwise.
+ const userAddresses = await getUserAddressesInDb(userId)
+ if (userAddresses.length <= 1) {
+ throw new ApiError('This is your only address. Add another address before deleting this one.', 409)
+ }
and the existing guards were converted so customers actually get a 4xx (they were plain Errors, which the
A19 mapping cannot translate):
- throw new Error('Address not found or does not belong to user')
+ throw new ApiError('Address not found or does not belong to user', 404)
- throw new Error('Address is attached to an ongoing order. Please cancel the order first.')
+ throw new ApiError('Address is attached to an ongoing order. Please cancel the order first.', 409)
- throw new Error('Cannot delete default address. Please set another address as default first.')
+ throw new ApiError('Cannot delete default address. Please set another address as default first.', 409)
+ import { ApiError } from '@/src/lib/api-error'
2/2 apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx — the refusal is shown in a BottomDialog
(the delete error used to be an Alert):
+ const [deleteError, setDeleteError] = useState<string | null>(null);
+ // check before the confirm step, so the customer is told why instead of "are you sure?" then an error
+ if (addresses.length <= 1) { setDeleteError('This is your only address. Add another address before deleting this one.'); return }
- onError: (error) => { Alert.alert('Error', error.message || 'Failed to delete address') }
+ onError: (error) => { setDeleteError(error.message || 'Failed to delete address') }
+ <BottomDialog open={deleteError !== null} onClose={() => setDeleteError(null)}> ... title/message/OK ...
Verified live (API): U3 has exactly one address -> delete refused; U2's default address -> refused (default
guard); a freshly created U2 address -> deleted successfully and gone from the list.
No schema change. No migration. No drizzle migrations run.
2026-10-11 00:16:33 Fix A37 — updateProductPrices took a SKU id under the name `productId`, and could silently reprice
the wrong product / report success without writing. No backward-compatibility alias kept (per user).
1/7 packages/db_helper_sqlite/src/admin-apis/product.ts (updateProductPrices):
updates: Array<{ productId: number; ... }> -> Array<{ skuId: number; ... }>
+ reject entries with no price field up front, so a "no-op" can never be reported as a success:
+ const emptyIds = updates.filter(u => u.price === undefined && u.marketPrice === undefined
+ && u.flashPrice === undefined && u.isFlashAvailable === undefined).map(u => u.skuId)
+ if (emptyIds.length > 0) return { updatedCount: 0, invalidIds: [], emptyIds }
+ return updatedCount = number of rows actually written (was: updates.length)
+ return shape: { updatedCount, invalidIds, emptyIds }
(validation + writes now key on `productSkus.id` / `productMarketStats.skuId` via `skuId`);
comments corrected from "SKU IDs" duplication, and the doc comment now says SKU explicitly.
2/7 apps/backend/src/trpc/apis/admin-apis/apis/product.ts:
updates: z.array(z.object({ productId: z.number(), ... })) -> { skuId: z.number().int().positive(), ... }
+ if (result.emptyIds.length > 0) throw new ApiError(`No price fields to update for SKU(s): ${result.emptyIds.join(', ')}`, 400)
"Invalid product IDs: ..." -> "Invalid SKU IDs: ..."
"Updated prices for N product(s)" -> "Updated prices for N SKU(s)"
3/7 apps/admin-ui/app/(drawer)/dashboard/prices-overview/index.tsx:
const update: any = { productId: sku?.id } -> const update: any = { skuId: sku?.id }
4/7 apps/admin-web/src/routes/dashboard.prices.tsx: same change.
5/7 apps/backend/tests/api/place-order-edge-cases.test.ts: two payloads productId -> skuId.
6/7 apps/backend/tests/api/cache-invalidation.test.ts: was passing `store.productId` — a product id, which only
worked when the product id happened to equal the SKU id; now passes `store.skuId`.
7/7 apps/admin-ui/tests/screens/prices-overview.test.tsx: expectations productId: 11 -> skuId: 11 (and the
"BUG:" comment removed).
Deliberately NOT done: resolving a product id to its SKUs — product ids and SKU ids overlap, and that ambiguity
is what produced the silent wrong-target write. The field is now unambiguously a SKU id.
No schema change. No migration. No drizzle migrations run.
2026-10-11 00:20:10 Fix A19 — business errors were flattened to HTTP 500: the error middleware could never see them.
Root cause (verified in the installed tRPC 11 source, ~/.bun/install/cache/@trpc/server@11.19.0/…/procedureBuilder.ts):
callRecursive does
try { … } catch (cause) { return { ok: false, error: getTRPCErrorFromUnknown(cause), marker } }
so a thrown resolver error NEVER propagates — the middleware receives it as a RESULT, not a throw.
getTRPCErrorFromUnknown (…/error/TRPCError.ts) wraps any non-TRPCError as
new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause }) // message inherited from the cause
which is exactly why the client saw HTTP 500 with the correct message. The previous fix wrapped
`next()` in try/catch and re-threw toTRPCError(error) in the catch — that catch is unreachable for
resolver errors, so the mapping never ran. (Not a duplicate-module problem: zod input errors already
returned 400, proving the transport was fine.)
File: apps/backend/src/trpc/trpc-index.ts
+/** tRPC hands resolver errors back as a result and wraps a non-TRPCError as INTERNAL_SERVER_ERROR,
+ * keeping the original in `cause`. Map our ApiError onto the matching TRPCError — and only that,
+ * so zod/BAD_REQUEST/UNAUTHORIZED and genuine 500s keep their code. */
+function translateResultError(error: unknown): unknown {
+ const original = (error as { cause?: unknown } | null)?.cause
+ return isApiErrorShape(original) ? toTRPCError(original) : error
+}
-const errorLoggerMiddleware = middleware(async ({ path, type, next, ctx }) => {
- const start = Date.now();
- try {
- const result = await next();
- const duration = Date.now() - start;
- if (process.env.NODE_ENV === 'development') { console.log(`✅ ${type} ${path} - ${duration}ms`); }
- return result;
- } catch (error) {
- …logging…
- throw toTRPCError(error);
- }
-});
+const errorLoggerMiddleware = middleware(async ({ path, type, next, ctx }) => {
+ const start = Date.now();
+ const result = await next();
+
+ // Resolver errors arrive as a result (tRPC catches them), so the only way to control the
+ // outgoing status is to re-throw the translated TRPCError from here.
+ if (!result.ok) {
+ logTrpcError({ path, type, start, ctx, error: result.error });
+ throw translateResultError(result.error);
+ }
+
+ if (process.env.NODE_ENV === 'development') { console.log(`✅ ${type} ${path} - ${Date.now() - start}ms`); }
+ return result;
+});
(the previous inline console.error block was extracted to `logTrpcError(...)`, unchanged in content)
Expected effect: ApiError(400/404/409) thrown in any resolver reaches clients as the real 4xx; the
`cause`-only mapping leaves zod 400s, UNAUTHORIZED 401s and genuine INTERNAL_SERVER_ERROR 500s alone.
No schema change. No migration. No drizzle migrations run.

View file

@ -158,10 +158,10 @@ be a release gate. High-risk financial cases deserve priority even if slower.
| PD-05 | Put P in customer cart → admin opens the product's Stock dialog and marks **one** variant of multi-SKU P out of stock (leaving the other in stock) → customer refreshes → admin restores it. | Unavailable state propagates for that variant only; the sibling variant stays in stock and orderable; the product list shows it as *Partial*, not In or Out; restoration works without reinstalling. |
| PD-06 | Admin suspends or soft-deletes one SKU of multi-SKU P → browse/search/detail and existing cart. | Removed SKU is no longer purchasable; sibling SKU remains usable; no phantom payable cart line or crash. |
| PD-07 | Admin adds a third SKU → assigns it to a slot → later removes that SKU. | New variant is discoverable and orderable; removal does not corrupt old orders or remaining variants. |
| PD-08 | Admin changes regular/MRP/flash prices via Prices Overview → customer with P already in cart refreshes. | Availability-only publication updates card/detail/cart prices; flash uses flash price; B is unchanged. |
| PD-08 | Admin changes regular/MRP/flash prices via Prices Overview → customer with P already in cart refreshes. | Availability-only publication updates card/detail/cart prices; flash uses flash price; B is unchanged. Prices are addressed by **`skuId`** (renamed 2026-10-10); a request with no price fields is rejected, and an unrelated SKU/product is never touched. |
| PD-09 | Admin toggles P's Offer flag → customer opens Offers tab and detail → remove flag. | SKU appears/disappears in Offers correctly, with working Add to Cart and price. The `order-again` route is currently this Offers screen. |
| PD-10 | Admin creates combo C with component SKUs → schedules C → customer opens Combos, detail and purchases C. | Correct components/features/images and combo price; ordered line is the intended combo SKU, not duplicate component charges. |
| PD-11 | Mark a component combo-only → publish C → search Home/store/Offers and open C. | Component is hidden as a standalone purchasable SKU but remains represented inside C. |
| PD-11 | Mark a component combo-only → publish C → search Home/store/Offers and open C. | The combo-only SKU must be absent from every customer list surface (Home, search, Offers, store pages, Combos strip) while still being served inside its parent combo. **Decision 2026-10-10:** backend enforcement at `placeOrder` is **not** required — a direct API call is the only way to reach one, and that is accepted. |
| PD-12 | Make combo component unavailable/suspended/deleted → inspect C and attempt checkout; restore component. | Agreed combo availability policy is enforced consistently, without silently selling invalid components. This policy needs explicit confirmation. |
| PD-13 | Admin edits store name/image → customer refreshes Stores and P detail; try deleting a store with products. | Store changes propagate; deletion is either safely rejected or follows an explicit dependency policy, never orphaning a broken customer catalog. |
@ -212,13 +212,13 @@ be a release gate. High-risk financial cases deserve priority even if slower.
| ID | Steps / journey | Required result |
|---|---|---|
| AD-01 | Fresh customer adds first address while browsing A, without checking Default → inspect Me and Cart. | Address belongs to A and becomes default; Cart can select it and Checkout shows correct contact/address. |
| AD-02 | Add second address → make it default → edit contact/address → relaunch. | Exactly one default persists; edits do not accidentally unset the only default or select an unrelated address. |
| AD-03 | Submit missing fields, bad phone/pincode and no region → correct and save. | Clear validation; no partial saved address; retry succeeds once. |
| AD-02 | Add second address → make it default → edit contact/address **without sending `isDefault`**, and with an explicit value → relaunch. | Exactly one default persists; an omitted `isDefault` must leave the flag untouched, an explicit `false` clears it and an explicit `true` moves the default; edits never leave the user with zero defaults or select an unrelated address. |
| AD-03 | Submit missing fields, bad phone/pincode and no region → correct and save. | Clear 4xx validation for each field — **phone = exactly 10 digits starting 6/7/8/9, pincode = exactly 6 digits** (rule 2026-10-10); no partial saved address; retry succeeds once. |
| AD-04 | Add address without coordinates → inspect “No Location is attached to address” → attach GPS location; repeat denying permission and using a supported Maps link. | Missing-location notice is accurate; successful attachment persists; denied/invalid-link path is recoverable without overwriting address data. Define whether missing coordinates block ordering. |
| AD-05 | U1 has A1/A2 addresses → select A2 on Cart → compare fee before/after selection → place order. | Selected address's bound overrides browsing active bound; catalog remains A; saved order total agrees with A2 config. |
| AD-06 | While browsing A, explicitly choose B as a new address's region; separately edit an existing B address while browsing A. | Address region and bound are coherent; editing preserves/derives the correct bound, never borrowing A's current browsing bound for B. |
| AD-07 | A cart populated, default address in B → load address selector → explicitly tap B address → cancel, then confirm. | No automatic foreign-default selection; cancel retains A/cart; confirm switches B, clears both carts and returns Home. |
| AD-08 | Delete nondefault unused address → try default and address attached to ongoing order → cancel/finish order, change default and retry. | Allowed deletion persists; protected deletions explain how to proceed; selected deleted address cannot remain usable at checkout. |
| AD-08 | Delete nondefault unused address → try the **only** address, the default, and an address attached to an ongoing order → cancel/finish the order and retry. | Allowed deletion persists. Protected deletions must explain how to proceed (4xx + message), the **only address can never be deleted**, and the reason is surfaced to the customer in a BottomDialog rather than a silent failure. |
| AD-09 | Add/edit/delete address whose bound controls active-bound choice → refresh discovery and relaunch. | Active bound recalculates and prices/fees update without stale user/address cache. Selected-address override remains internally consistent. |
## H. Bill arithmetic and bound-specific fees
@ -229,11 +229,11 @@ regular/flash prices, and at least one two-slot cart. Equal fixture values can h
| ID | Steps / journey | Required result |
|---|---|---|
| BL-01 | Set bound delivery threshold T and fee D → order subtotal T−1, T and T+1 without coupon. | Same fee rule in floating bar, Cart, Checkout, success, persisted order and admin details; exact threshold boundary is correct. |
| BL-02 | Set regular minimum M different from free threshold T → try totals below M, between M/T and above both. | Intended minimum-order policy is explicit and enforced; free-delivery threshold is not accidentally replaced by minimum order. |
| BL-02 | Set regular minimum M different from free threshold T → try totals below M, between M/T and above both. | **Policy settled 2026-10-10: there is no minimum order value** — orders of any amount must be accepted, and `minOrder` must not be conflated with the free-delivery threshold. Assert that a small order below the free-delivery threshold still places and is charged the fee. |
| BL-03 | Coupon lowers subtotal from above T to below T → repeat with post-coupon total exactly T. | Agreed pre/post-discount fee policy holds on client and backend, including boundary. |
| BL-04 | P/Q in S1/S2, paid delivery and coupon → place order → sum all generated order totals and fees. | One checkout creates expected slot suborders; total fee is charged only once, coupon is allocated correctly, summed total equals displayed To Pay, **and the order-detail payload's item/discount/fee components reconstruct that same amount**. |
| BL-05 | Use noninteger prices/percentage discounts and several quantities → compare previews and persisted amounts. Include a **capped** percentage coupon and a multi-slot split (the cap is prorated per suborder). | Consistent rounding/currency precision; truncation in labels does not conceal overcharge or contradictory success totals; the discount reported by the order-detail endpoint equals the discount actually deducted for the same suborder. |
| BL-06 | Select A1 then A2, with visibly different charges/thresholds → repeat regular and flash checkout. | Correct bound's fees and nudges are used, including free crossed-out fee; no undefined/NaN/negative totals. |
| BL-04 | P/Q in S1/S2, paid delivery and coupon → place order → sum all generated order totals and fees. | One checkout creates expected slot suborders; total fee is charged only once, coupon is allocated correctly, and the summed total equals displayed To Pay. (Accepted 2026-10-10: sibling sub-orders show their own payable total and are **not** required to itemise the prorated discount; only the coupon-holding sub-order reconciles item/discount/fee.) |
| BL-05 | Use noninteger prices/percentage discounts and several quantities → compare previews and persisted amounts. Include a **capped** percentage coupon and a multi-slot split (the cap is prorated per suborder). | Consistent rounding/currency precision; truncation in labels does not conceal overcharge or contradictory success totals; the discount reported by the order-detail endpoint equals the discount actually deducted for the **coupon-holding** suborder. |
| BL-06 | Select A1 then A2, with visibly different charges/thresholds → repeat regular and flash checkout, then send a **mismatched** client `boundId`. | The **delivery address's bound** is authoritative for fees/thresholds; the client `boundId` is used only when the address has no bound (then the region's effective bound). Mismatched client ids cannot change the charge; no undefined/NaN/negative totals. |
| BL-07 | Customer opens Checkout → admin changes SKU price or selected-bound fee → submit. | No silent difference between quoted and authoritative total; agreed reprice/refresh/confirmation policy is followed. |
## I. Coupons and offers on orders
@ -244,13 +244,13 @@ regular/flash prices, and at least one two-slot cart. Equal fixture values can h
| CP-02 | Create flat coupon with/without max cap → test small/large carts → remove coupon. | Discount never creates negative payable amount; removal restores correct subtotal/fee. |
| CP-03 | Create coupon with minimum spend → test below/exactly/above; change quantities after selection. | Eligibility recalculates; invalid selected coupon cannot silently stay applied or bypass backend validation. |
| CP-04 | Create U1-specific coupon → compare U1/U2 eligible and My Coupons screens → place U1 order. | Only U1 can see/apply it; usage belongs to U1. Direct U2 application must also be denied (API check). |
| CP-05 | Create SKU-restricted coupon for P → cart P-only, Q-only and P+Q → place each eligible scenario. | Product-scope/exclusive rules match the configured contract and are enforced server-side, not just displayed in admin. |
| CP-05 | Create a coupon that the admin form let you scope to a SKU → cart with that SKU and cart with other SKUs → place each. | **Policy: coupons are not product/SKU-based.** A coupon discounts the whole cart; any SKU scoping sent to the admin API is ignored at pricing time. Assert the discount applies regardless of SKUs. |
| CP-06 | Set maximum uses per customer to one → place order → try second use and two simultaneous first uses. | Limit is enforced, including concurrent requests; one multi-slot checkout counts as one use as intended. |
| CP-07 | Create first-order-only coupon → fresh customer uses it → tries again; separately cancel first order. | Eligibility matches defined first-order/cancellation policy, not inconsistent tracker/order-count behavior. |
| CP-08 | Admin expires/invalidates/edits coupon while customer has it selected at Checkout → submit. | Invalid stale coupon is rejected; changed valid coupon cannot produce unnoticed quote mismatch. |
| CP-09 | Admin creates reserved coupon → U1 redeems secret code in My Coupons → applies personal coupon → U2 retries secret. | Redemption produces correct personal coupon; one-time secret cannot be claimed by both customers. Test simultaneous redemption too. |
| CP-10 | Redeem malformed, expired or first-order-ineligible reserved code → then valid code. | Correct rejection without burning valid codes or leaving half-created coupons; valid retry works. |
| CP-11 | Create coupon in A → customer browses B and attempts redemption/application. | Region policy is explicit: if region-scoped, A coupon cannot discount B orders; global exceptions must be deliberate. Current user coupon fetches are not region-filtered. |
| CP-10 | Redeem malformed, expired or first-order-ineligible reserved code → then valid code. | Correct rejection without burning valid codes or leaving half-created coupons; valid retry works. `validTill` is the single deadline for **both** claiming the secret and spending the coupon. |
| CP-11 | Create coupon in A → customer browses B and attempts redemption/application. | **Policy: coupons are not region-based (global).** A coupon created in A must be visible and applicable in B. (Only *user* scoping is real: U1-only coupons must still be denied to U2.) |
## J. Orders, fulfillment, cancellation and after-order edits
@ -258,16 +258,16 @@ regular/flash prices, and at least one two-slot cart. Equal fixture values can h
|---|---|---|
| OR-01 | Customer orders P/Q in A using COD/address/instructions/coupon → checks success and My Orders → admin A finds same order ID → admin B searches it. | Matching SKUs/quantities/slot/address/notes/coupon/total in customer and A admin; B cannot access it. Ordered cart is cleared according to agreed policy. |
| OR-02 | Order items in S1/S2 → check success, history and admin lists. | Each generated slot order is discoverable, correctly grouped and dated; success does not obscure the second order. Total/fee parity follows BL-04. |
| OR-03 | Place order → edit instructions from customer order menu → admin refreshes; admin adds internal notes. | User notes propagate; admin notes remain correctly distinguished from customer instructions. Editing delivered/cancelled order notes is rejected. |
| OR-03 | Place order → edit instructions from customer order menu → admin refreshes; admin adds internal notes. | User notes propagate; admin notes remain correctly distinguished from customer instructions. The **customer** path rejects editing a delivered/cancelled order; the **admin** path may annotate delivered orders (business decision 2026-10-10). |
| OR-04 | Admin packages one item then all items, verifies packaging and marks Delivered → customer refreshes tracking. | Item and aggregate packaging state agree across admin lists/details; customer sees correct fulfillment/delivery status. |
| OR-05 | Admin reverses an accidental packaged/delivered toggle where supported → refresh both apps. | Supported reversal is consistent; forbidden transitions show clear errors. No cancelled order resurrected accidentally. |
| OR-06 | Customer cancels pending COD order with reason → admin list/detail and vendor page refresh. | Cancelled status/reason/actor persist; cancelled order is not fulfillable or included in vendor production totals; COD refund is not shown as cash owed. |
| OR-07 | Admin cancels pending order with reason → customer history/detail and next-order glimpse refresh. | Cancellation is attributed to admin and visible to customer; next-order summary no longer treats it as upcoming. |
| OR-08 | Try blank reason, second cancellation and cancellation after Delivered; cancel one of two slot suborders. | Invalid cancellations reject without duplicate refund records; other suborder stays intact. |
| OR-09 | Admin removes delivery charge from order → customer/admin details refresh. | Saved payable total and fee update together, exactly once; unrelated suborders stay unchanged. |
| OR-10 | Place order → admin changes prices → verify old order unchanged → run explicit Rebalance on chosen slot(s). | Normal catalog edits do not reprice historical orders; explicit rebalance affects only intended orders and preserves agreed fees/coupon allocations — **after rebalancing, each touched order's stored total + delivery charge still reconcile to its items and coupon allocation**. Define eligibility for delivered/cancelled orders. |
| OR-10 | Place order → admin changes prices → verify old order unchanged → run explicit Rebalance on chosen slot(s). | Normal catalog edits do not reprice historical orders. Explicit rebalance reprices **item prices only** and **freezes the historic delivery fee and the discount actually charged** (policy 2026-10-10); delivered/cancelled orders are skipped. After rebalancing each touched order still reconciles as `items(priced) − frozen discount + frozen fee = stored total`. |
| OR-11 | Create many A/B orders → exercise admin filters and pagination and customer My Orders pagination. | No missing/duplicate A orders due to B's high IDs; filters match actual statuses; customer sees own orders across regions with region labels. |
| OR-12 | Double-tap Place Order; simulate response loss after server commit → relaunch and retry only after checking history. | Exactly one intended order group; no duplicates or lost order; loading lock and reconciliation work. Backend idempotency is a requirement to verify, not assumed. |
| OR-12 | Submit Place Order once (and verify the in-app re-entrancy guard) → then replay two concurrent API submissions; note the residual exposure on ambiguous failure/retry. | Exactly one order group per user action; the app's `submittingRef` + disabled button must prevent a double-tap. **Decision 2026-10-10:** server-side idempotency is explicitly **not** required — concurrent/malicious API submissions may create two orders; the retry-after-ambiguous-failure path (RC-04) is the known residual exposure. |
## K. Flash delivery
@ -286,10 +286,10 @@ regular/flash prices, and at least one two-slot cart. Equal fixture values can h
|---|---|---|
| OP-01 | Admin creates slot-specific snippet for P → customer orders P+Q → vendor opens snippet URL. | Only attached SKU lines from matching noncancelled slot orders appear; quantities/summary agree; Q is not exposed by P's snippet. |
| OP-02 | Vendor toggles P packaging → admin refreshes order details/list → reverse toggle. | Same order-item packaging state persists; other vendor/customer items remain unchanged. |
| OP-03 | Create permanent snippet → vendor selects S1/S2 → expire/delete a slot-specific snippet and retry old link. | Permanent mode functions without failing initial metadata lookup; selected slot is valid for snippet/region; expired/deleted links no longer access orders. |
| OP-03 | Create permanent snippet → vendor selects S1/S2 → expire/delete a slot-specific snippet and retry old link. | **OUT OF SCOPE (2026-10-10): vendor snippets are not a current concern.** Kept for traceability; not executed. (The permanent-mode metadata lookup failing is dropped with it.) |
| OP-04 | Admin edits delivery sequence and address map coordinates → reopen delivery view and order detail. | Sequence/map changes persist and stay within region; operational coordinate override does not silently mutate customer's region/bound identity. |
| OP-05 | Customer raises complaint on own order with photo → admin A views and resolves → customer views response. | Correct order/customer/photo/body/response/status across apps; admin B cannot resolve A complaint. Repeat with general complaint without an order. |
| OP-06 | Customer creates product review/rating/photo → admin opens matching review and responds → customer refreshes detail. | Product/review identity, rating and both messages/images agree; reviews survive pagination. No review mistakenly attached using SKU ID as product ID. |
| OP-06 | Customer creates product review/rating/photo → admin opens matching review and responds → customer refreshes detail. | **OUT OF SCOPE (2026-10-10): the review feature is no longer maintained.** Kept for traceability; not executed. (Any review findings — e.g. `createReview` failing for SKU-split products — are dropped with the feature.) |
| OP-07 | Admin records customer incident/negativity note → reopen customer details/order operational display. | Incident belongs to intended customer/order, score persists and regional access follows policy; do not assume it automatically suspends the user. |
| OP-08 | In isolated staging destinations, send targeted notification, place order for admin push/deep link, cancel for Telegram, and resolve complaint for customer push. | Correct payload/recipient/navigation; unrelated customers receive no targeted push. Verify intended regional recipient policy. Include queue retries and physical-device receipt separately from queue acceptance. |
@ -318,7 +318,7 @@ the present implementation.
| SEC-03 | U2 supplies U1 address/order/complaint/payment IDs to read/edit/cancel/delete operations. | Ownership is enforced, not only authentication; U1's data is unchanged. |
| SEC-04 | Order request mixes A region with B SKU/slot/bound/address, or a SKU not assigned to that slot. | All submitted identities/relations are validated server-side; no foreign or incoherent order accepted. |
| SEC-05 | Submit empty items, zero/negative/fractional quantities, invalid/null regular slot, deleted/suspended/OOS SKU, frozen/inactive slot and full slot. | Backend enforces actual purchasability/quantity/slot rules; bypassing UI guards cannot create an invalid order. |
| SEC-06 | U2 applies U1 coupon directly; apply expired/invalid/foreign-region/SKU-ineligible coupon; race usage and reserved redemption. | Eligibility and one-time limits are authoritative and atomic; no unauthorized discount or multiple claims. |
| SEC-06 | U2 applies U1 coupon directly; apply expired/invalid/foreign-region/SKU-ineligible coupon; race usage and reserved redemption. | User scoping and one-time limits are authoritative and atomic; expired codes are rejected. Global coupons are expected to apply in any region and to any SKU (policy), so those two probes assert success, not rejection. |
| SEC-07 | Vendor request edits packaging using an unrelated item ID; expired snippet queries another slot; anonymous caller tries same mutation without valid snippet authority. | Vendor access is constrained to authorized snippet/region/items. A public vendor URL is not authority to edit every order item. |
| SEC-08 | Reuse revoked/deleted staff identity/token → attempt region-bound mutation; change staff region in superadmin then retry old session. | Access reflects current staff assignment/existence, not a stale token's region. |
@ -344,9 +344,9 @@ sibling rows — not just the response. These come from defects where a request
| ID | Steps / journey | Required result |
|---|---|---|
| P-01 | `createProduct` where one image URL is valid and the other was never uploaded (previously: 500 "Failed to claim upload URL" with the product already stored). | 4xx naming the offending key; **no** product/SKU/market-stats rows exist (verify by name lookup and counts); retrying with the same name does not report "already exists". |
| P-02 | `updateProduct` with a bad new image while also deleting an old image. | Rejected before any change: old images still present, name/prices/variants unchanged. |
| P-02 | `updateProduct` with a bad image while also deleting an old image — try it in **both** `newImageUrls` and `skus[].images`, and also try reusing another product's image key. | Rejected before any change: old images still present, name/prices/variants unchanged. Only genuinely new image references (keys the product does not already own) need a pending upload; the product's own images may be re-sent. |
| P-03 | Bad upload URL on tag create, tag update, review create and review response. | Target row absent (tag/review not created, tag not modified) and the old image cleanup has not run. |
| P-04 | Double-submit each admin create form (rapid double tap) and retry after an ambiguous 5xx. | Exactly one record; the second attempt returns a clean conflict/validation error, never a duplicate. |
| P-04 | Double-submit each admin create form (rapid double tap) and retry after an ambiguous 5xx. | Exactly one record; the second attempt returns a clean conflict/validation error, never a duplicate. The message must be right **and** the status must be 4xx (an `ApiError` must not surface as HTTP 500 — see A19). |
| P-05 | Kill the client mid-save (background the app, force-quit, or abort the request). | Either nothing was written or the record is complete — never a half-created product/tag/slot/address; the UI recovers on relaunch. |
| P-06 | Delete a tag/group/banner whose stored image cannot be cleaned up (missing or malformed object key). | The DB delete still happens (cleanup failure is logged, not fatal); no undeletable row remains. |
@ -460,7 +460,12 @@ is not yet defined, agree the contract rather than write a test that endorses a
and destroys a partial state; the admin app now chooses variants in a stock dialog. Assert per-variant
behaviour and the sibling staying orderable — see `PD-05`/`R-03`.
## Policies settled (assert these; do not re-litigate)
## Policies settled
- **Error status contract (2026-10-10):** an `ApiError(msg, status)` thrown in any procedure now reaches clients
with the real status (400/403/404/409). Business rules thrown as plain `Error` **inside the db-helper packages**
are the one remaining exception (e.g. coupon validation) and still surface as 500.
(assert these; do not re-litigate)
- **Regions are not deletable** — by product decision. Bounds *are* deletable, refused when it is the region's
only bound or when addresses reference it.

View file

@ -112,3 +112,61 @@ capacity cleared, tag 10 deleted, tags 1/4 images cleared.
**A1 fix (2026-10-10 18:26):** products 152/151 were soft-deleted and disappeared from the catalog; their
rows remain as tombstones so order lines keep the product name. Store 11/12 are still blocked by region-2
product 153, and tag 10 by the image-delete bug (A4).
---
## G. New defects from the full-plan run (2026-10-10 20:30–21:30 IST)
Run report: `docs/test reports/e2e-full-run-2026-10-10.md` (161 cases: 79 PASS / 47 PARTIAL / 23 FAIL / 8 BLOCKED / 4 NOT RUN).
Defects are numbered A19+ (continuing this file's A-series). Every row below was reproduced live against the
running dev server with authoritative API reads.
| # | Defect | Evidence (live) | Impact / notes |
|---|---|---|---|
| A19 | ~~**`ApiError` → HTTP 500.**~~ **FIXED 2026-10-10.** Root cause (read out of the installed tRPC 11 source): `callRecursive` catches every resolver error and hands middleware a `{ ok: false, error }` **result** — it never throws — and `getTRPCErrorFromUnknown` wraps a non-TRPCError as `INTERNAL_SERVER_ERROR` with the original on `cause`. The previous fix put `toTRPCError` in a `catch` around `next()`, which is unreachable for resolver errors, so the mapping never ran. | **verified live after the fix:** expired reserved coupon → **400 BAD_REQUEST**; only-address delete → **409 CONFLICT**; default-address delete → **409**; address with an open order → **409**; capacity-full slot → **403 FORBIDDEN**; duplicate product name → **400**; bogus image on product create and on tag create → **400**; wrong-scope const write (admin + superadmin) → **400**. Controls unchanged: zod input → **400**, unknown procedure → **404**, no token → **401**. | Fix: `translateResultError(result.error)` in `errorLoggerMiddleware` — maps `result.error.cause` only when it is an ApiError, so tRPC's own codes are preserved. **Residual:** business rejections thrown as **plain `Error` inside the db-helper packages** still return 500 — notably `validateAndGetCoupon` (`not applicable` → 500, `Coupon has expired` → 500), seen in SEC-06. |
| A20 | ~~**SKU-restricted coupon is not enforced.**~~ **CLOSED — by design.** Coupons are **not** SKU/product-scoped, so a coupon applying to every SKU in the cart is the intended behaviour. The observed order 2498 is correct. | order 2498 (coupon `E2ESKU17753`, discount 22.5) | **Policy (2026-10-10, user):** coupons are global, not product/SKU based. The remaining question is only whether the admin surface should stop offering SKU scoping at all (see follow-up). Plan CP-05 expectation to be updated. |
| A21 | ~~**Cross-region coupon is not enforced.**~~ **CLOSED — by design.** Coupons are **not** region-based, so a region-2-created coupon applying to a region-1 order is the intended behaviour. The observed order 2499 is correct. | order 2499 (coupon `E2EB17769`, 25% of ₹150) | **Policy (2026-10-10, user):** coupons are global, not region based. The remaining question is whether the admin surface should stop scoping coupon listing/creation by region (see follow-up). Plan CP-11 expectation to be updated. |
| A22 | ~~**Expired reserved coupon can be redeemed.**~~ **FIXED 2026-10-10.** `admin.coupon.createReservedCoupon` with `validTill` in the past no longer redeems. | verified live: expired secret → rejected `"This coupon has expired"`; valid secret → still 200. Atomic claim verified: 6/6 rounds of 3 concurrent redeemers produced exactly one winner. | Plan CP-10/SEC-06. Policy: `validTill` is the single deadline for claiming the secret **and** spending the coupon. Changes: `backend/…/user-apis/apis/coupon.ts`, `db_helper_sqlite/…/user-apis/coupon.ts`, tests + BUGS.md #11. |
| A23 | ~~**Multi-slot suborders record `discountAmount: null` while the payable is discounted.**~~ **CLOSED 2026-10-10 — accepted, not a defect.** A sibling sub-order shows its own payable total; the prorated discount is not itemised on it. | orders 2517/2518, 2526/2527 | **Decision (user):** leave as-is — it's fine. Coupon usage is recorded once on the coupon-holding sub-order by design; sibling sub-orders are not required to reconstruct item/discount/fee. Plan BL-04/BL-05 expectations updated. |
| A24 | ~~**Client-supplied `boundId` overrides the address's bound.**~~ **FIXED 2026-10-10.** Address 879 (bound 2, ₹200/₹800) ordered with `boundId: 1` (₹20/₹300) was accepted and charged ₹20. | verified live after the fix: same request now charges **₹200**; `boundId: 2` → ₹200; no `boundId` → ₹200. Bound-less address (882) still honours the client bound (₹20 for bound 1, ₹200 for bound 2). | Policy: address bound → client bound → region effective bound. Plan BL-06/SEC-04. Change: `backend/…/user-apis/apis/order.ts` `placeOrderUtil`; BUGS.md #21. |
| A25 | ~~**Double-tap `placeOrder` creates two orders.**~~ **CLOSED 2026-10-10 — already client-guarded; server rule declined.** | two concurrent API POSTs (my harness) both returned 200 → orders 2539/2540. **Not** reachable by tapping: `PaymentAndOrderComponent` has a synchronous `submittingRef` re-entrancy guard + `disabled={… isPending}` button and is the only caller of `placeOrder` in the app. | **Decision (user):** close — no server-side idempotency. Residual exposure documented: retry after an ambiguous failure / lost response (RC-04), API replay, another device. `BUGS.md` #17 stays as-is. Plan OR-12 reworded. |
| A26 | ~~**Admin can edit notes on a delivered order.**~~ **CLOSED 2026-10-10 — business decision, not a defect.** | `admin.order.updateNotes {orderId: 2495}` → 200 while the customer path rejects the same edit | **Decision (user):** admins may annotate delivered orders (internal notes are operational records). The customer-side restriction stays. Plan OR-03 reworded so the case asserts the customer path only. |
| A27 | ~~**Explicit rebalance drops the delivery fee.**~~ **FIXED 2026-10-10.** Rebalance wrote `total_amount = items − discount`, so the order's own invariant (`items − discount + fee = total`) broke and the payable lost the fee. | verified live (isolated slot 2057, order 2558): placed with a 10% coupon → items 249, discount 24.9, fee 20, payable 244.1 → **no-op rebalance 244.1** (fee kept); after **invalidating the coupon** + rebalance **244.1** (discount frozen); after reprice 249→299 + rebalance **294.1** = 299 − 24.9 + 20 ✓ | Policy (user): **freeze the historic discount and delivery fee; rebalance only product prices**. Delivered/cancelled orders are now skipped; a SKU with no region price keeps its stored price. Plan OR-10. Change: `db_helper_sqlite/…/admin-apis/order.ts` `rebalanceSlots`; BUGS.md #22. |
| A28 | ~~**`updateProduct` accepts never-uploaded image keys via `skus[].images`.**~~ **FIXED 2026-10-10.** | verified live (probe product 174): fabricated key in `skus[].images` → rejected with nothing written; fabricated key in `newImageUrls` → rejected; another product's already-claimed image → rejected; the product's **own** already-claimed image re-sent → 200 (honest edit form unaffected); a genuine pending upload → 200 and claimed. | Plan P-02. Root cause: create validated `skus.flatMap(images)` but update validated only `newImageUrls`, then wrote `skus[].images` unvalidated (the edit form re-sends existing images, so validating the whole set would fail). Fix validates the **delta** (keys the product doesn't already own) + `newImageUrls`. Change: `backend/…/admin-apis/apis/product.ts`, new `getProductImageKeys` helper; BUGS.md #23. |
| A29 | ~~**Editing an address clears its default flag.**~~ **FIXED 2026-10-10.** `updateAddress` passed `isDefault: isDefault || false`, so an edit that omitted the optional field unset the default and left the user with **zero** defaults. | verified live (U2 address 882): set default → edit **without** `isDefault` → still default (previously became false). Explicit `isDefault: false` still clears it; `isDefault: true` still moves the default off the others. | Plan AD-02. Fix: `backend/…/user-apis/apis/address.ts` → `isDefault: isDefault ?? existingAddress.isDefault`; BUGS.md #24. The UI was already sending the current value, so the API contract was the hole. |
| A30 | ~~**Invalid phone/pincode accepted by `createAddress`.**~~ **FIXED 2026-10-10.** Rule: phone = exactly 10 digits starting 6/7/8/9; pincode = exactly 6 digits. Applied to **both** `createAddress` and `updateAddress`. | verified live: phone `123` / `1234567890` / `5678901234` / 9-digit / 11-digit and pincode 5-digit / 7-digit / non-numeric all **400**; valid pair → 201; update with `phone: "123"` → 400. Probe rows deleted. | Plan AD-03. The UI already had `/^\d{10}$/` + `/^\d{6}$/`; the server enforced only `min(1)`. Change: `backend/…/user-apis/apis/address.ts` (+ UI phone regex aligned); BUGS.md #25. |
| A31 | ~~**Deleting the user's only address was allowed** (no protection, empty message).~~ **FIXED 2026-10-10.** Deleting the user's **only** address is now refused, and the reason is shown to the customer in a **BottomDialog**. | verified live — API: U3 (exactly one address) → refused, address kept; U2 default → refused; a freshly created unused address → deleted and gone. UI on the simulator (signed in as U3, one address): tapping **Delete** opened the bottom sheet “**Cannot delete address** — This is your only address. Add another address before deleting this one.” with **OK**; the address stayed. Evidence: `/tmp/freshyo-e2e/A31-delete-only-address-dialog.jpg`. | Plan AD-08. Also converted the other `deleteAddress` refusals from plain `Error` to `ApiError` (404/409) so customers get 4xx once A19 lands, and the UI check runs before the “are you sure?” step. Changes: `backend/…/user-apis/apis/address.ts`, `apps/user-ui/…/me/addresses/index.tsx`; BUGS.md #26. |
| A32 | ~~**`createReview` fails for SKU-split products.**~~ **CLOSED 2026-10-10 — not applicable.** | OP-06 probe: works for the legacy 1:1 product 102, 500 “Product not found” for product 170 | **Decision (user): reviews are no longer dealt with — the issue is dropped.** The review feature is unsupported/out of scope, so this is not a defect to fix. Plan OP-06 marked out of scope. |
| A33 | ~~**Permanent vendor snippet metadata query fails**: `vendorSnippets.getOrdersBySnippet` → 500 “Vendor snippet not associated with a slot”.~~ **CLOSED 2026-10-10 — not a problem.** | OP-03 probe | **Decision (user): vendor snippets are not a current concern — the issue is dropped.** Plan OP-03 marked out of scope; the snippet areas that were verified as working (OP-01 snippet SKU filtering, SEC-02/SEC-07 snippet access) keep their results. |
| A34 | ~~**`isComboOnly` SKUs are still orderable standalone.**~~ **CLOSED 2026-10-10 — accepted, not a concern.** | PD-11 probe: with the flag set on a component (SKU 129), `placeOrder` accepted it (order 2547, ₹249); the flag was then restored. | **Decision (user):** the only route to a combo-only SKU is a direct API call — the app hides them everywhere — so this is dropped at this point. Backend enforcement is **not** added. Plan PD-11 closed. **Open observation kept separately:** the flag's real semantics are ambiguous — the only flagged product in region 1, **GYM PACK** (sku 149, live, ₹210, `comboItems` = its components), is a *bundle* and is therefore hidden from the app's Combos section too, so it cannot be bought in-app. Not A34; needs a product decision. |
| A35 | ~~**No minimum-order policy exists.**~~ **CLOSED 2026-10-10 — business decision, not a problem.** There is deliberately no minimum order value; orders of any amount are accepted. | BL-02 probe: a ₹249 order was accepted, `minRegularOrderValue` appears nowhere in the code. | **Decision (user):** no minimum-order policy is intended. The stray `minRegularOrderValue` row in bound-2 settings is inert (nothing reads it) and can be deleted as housekeeping. Plan BL-02 reworded. |
| A36 | **Global SKUs are rejected when attached to a region slot/banner** (“SKU 102 belongs to a different region”), although global products are visible/orderable in every region. | DS-05 slot create, DS-06 banner create | Inconsistent relation validation; the fix should allow global SKUs. |
| A37 | ~~**`updateProductPrices` takes a SKU id under the name `productId` — and can silently reprice the wrong product.**~~ **FIXED 2026-10-10.** The field is now **`skuId`** (no alias), the messages say SKU, and an entry with no price fields is rejected instead of "succeeding"; `updatedCount` counts rows actually written. | verified live on probe product 175 (SKUs 185/186): `{skuId:186, price:250}` → `200 "Updated prices for 1 SKU(s)"`, prices `185:100 186:250` (no cross-write); `{skuId:185}` with no fields → rejected `No price fields to update for SKU(s): 185` with nothing written. | Callers updated: `admin-ui` + `admin-web` prices screens, and the three test payloads (incl. `cache-invalidation.test.ts`, which had been passing a *product* id — it only worked when the two ids coincided). **Residual (accepted):** id *values* still overlap, so a caller that passes a product id *value* still hits the same-numbered SKU — now an explicit caller error rather than an API trap; resolving product ids to SKUs is deliberately not done. `db_helper_postgres` (unused by the apps) not changed. BUGS.md #27. |
| A38 | **Customer product/review APIs are SKU-id keyed while admin APIs are product-id keyed.** `user.product.getProductDetails {id:'170'}` → 500; `{id:'178'}` (a SKU id) → 200 returning that SKU's data. | PD-01/PD-03 probes | Mixed id spaces; the review half is moot (see A32 — reviews dropped 2026-10-10). Also `getProductDetails {id:'155'}` resolved to a different product's SKU. |
| A39 | **Inconsistent order-id typing:** `admin.order.updatePackaged` / `updateDelivered` require `orderId` as a **string**, while every other order endpoint takes a number. | OR-04/OR-05 probes (numeric → 400 zod) | Minor but a real integration wart. |
| A40 | **`admin.store.createStore` rejects `imageUrl: null`** (`z.string().optional()`), while the UI can create a store without an image. | PD-01 probe | Minor contract wart. |
| A41 | **New foreign-region addresses get `boundId: null`** instead of the region's effective bound. | AD-06 probe: region 2 address → `boundId: null` | Partly covered by the settled “bound-less addresses allowed” policy, but AD-06 expects derivation. |
| A42 | **Coupon-limit race loser gets a 500** (message correct) — the limit itself held (one order). | SEC-06 race: 200 / 500 | Covered by A19; recorded for traceability. |
### Policy decisions recorded during triage (2026-10-10)
- **Coupons are neither region-based nor product/SKU-based.** They are global: created once, visible to every
region, and applicable to the whole cart regardless of which SKUs it contains. → **A20 and A21 are not defects**
(CP-05 / CP-11 / the coupon-scope half of SEC-06 change expectation; SEC-06's FAIL now rests solely on **A22**,
the expired reserved coupon).
- Consequence to decide separately: the admin coupon API still *pretends* to support scoping —
`admin-apis/coupon.ts` writes `regionId` and rejects foreign-region SKUs (`assertApplicableSkusInRegion`),
coupon list/detail/invalidate/reserved queries are filtered by `ctx.staffUser.regionId`, and the coupon form
carries `skuIds` / `applicableProducts` (the admin list even renders “Products: N selected”). Either bring that
surface in line with the global policy or leave it as dormant metadata.
### Positive verifications that moved to PASS in this run
Soft-delete + order history (T-01/S-01/S-05), tag image normalisation + delete (T-02/Q-04),
upload-URL validation with no partial rows (P-01/P-03/T-03), per-variant stock with sibling orderable
(T-05/R-03), region+future slot scoping (T-06), bound-settings propagation to essentials and the next
order (Q-03), fee rules at the threshold (BL-01), coupon cap math and no negative payable (CP-01/CP-02),
first-order coupon (CP-07), invalidated coupon (CP-08), reserved redemption + one-time secret (CP-09),
flash pricing/fees/eligibility (FL-01…FL-05), order lifecycle notes/packaging/delivered/cancel/charge-removal
(OR-01/02/03-partial/04/05/06/07/09/11), snippet SKU filtering (OP-01), complaints end-to-end (OP-05),
region priority reload (RG-10), tagsOrder/popular items per region (DS-03/DS-04), banner lifecycle (DS-07),
Cart/Checkout layout and the disabled online payment (CT-01/05/09, PAY-01).

View file

@ -584,3 +584,120 @@ address 879 (tied to order 2495) · slots 2033/2034 (deactivated) · orders #249
**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).

View file

@ -0,0 +1,277 @@
# Freshyo E2E full-plan run — every case (161 cases)
Generated 2026-10-11 00:22 IST · plan: `docs/e2e-sanity-test-plan.md` · harness: tRPC probes (authoritative API) + published R2 cache + Maestro on the iOS simulator.
**Progress: 155/161 cases attempted.**
| status | count |
|---|---|
| PASS | 107 |
| PARTIAL | 40 |
| BLOCKED | 8 |
| NOT RUN | 6 |
Status legend: **PASS** (contract met) · **FAIL** (defect reproduced) · **PARTIAL** (part of the contract verified; the note says what is missing) · **BLOCKED** (environment/harness) · **NOT RUN** (deliberately out of scope).
> Assertions use authoritative API reads (tRPC with staff/user/superadmin tokens), the published region cache JSON and simulator screenshots. Defects found are reproduced in `docs/test reports/e2e-errors-2026-10-10.md` section G (A19–A42), with fixes recorded as they land.
## A. Regions, bounds and configuration
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| RG-01 | A is discoverable; configuration/cache loads without undefined amounts or broken asset requests. An empty catalog has an intentional empty state. | PARTIAL | {"regions":[{"id":3,"name":"E2E S04 neutralised 1791645053298","effectiveBoundId":5},{"id":2,"name":"E2E Testnagar 1702","effectiveBoundId":3},{"id":1,"name":"Mahabubnagar","effectiveBoundId":1}]} — creation + selector journey needs the UI; region 2 and the S-04 temp region exist |
| RG-02 | Validation explains the error; no half-created region/configuration remains. | PASS | {"noBounds":"400","badPoly":"400","duplicatePriority":"500","createdDup":false} |
| RG-03 | A resolves once; catalog and delivery threshold load without needing login. | PASS | resolveRegionByLocation {lat:16.7489,lng:77.9856} → region 1 + bound 1; essentialConsts {boundId:1} loads with the region-1 fee/threshold without login. — signed-out vs signed-in repeat is a UI session test |
| RG-04 | Saved region survives when location is unusable; otherwise a usable manual chooser appears, not an endless spinner. | PARTIAL | {"outside":{"ok":true,"status":200,"msg":"","data":null},"polygon":{"isInside":true}} — saved-region survival/manual chooser paths are UI denied/timeout/manual-chooser paths are UI |
| RG-05 | Late startup response does not undo the customer's manual choice. | PARTIAL | late GPS response vs manual selection is a UI race (needs the simulator) |
| RG-06 | Each region shows only its own content; no cached content/prices from the previous region leak. | PARTIAL | {"aCount":161,"bCount":3,"bHasAProduct":true,"bExample":[" Mutton Boneless – Mini Pack"," Basa Fish Fillets"]} |
| RG-07 | Cancel preserves A and both carts; confirm clears both carts and address/slot selections and loads B. | PARTIAL | region switch cancel/confirm + cart clearing is a UI flow |
| RG-08 | No continuous automatic switching while open; cold launch performs the one-shot resolution and resets regional state if changing region. | PARTIAL | GPS-move-while-open + cold-launch region reset is a UI flow |
| RG-09 | Active browsing bound is lowest numeric priority among U1's A address bounds, else A's effective bound. B addresses do not participate. | PARTIAL | {"region2":{"regionId":2,"boundId":3},"u1Addresses":[["285:b1","879:b2"]]} — lowest-priority address bound + region effective fallback verified earlier in the session (A8) |
| RG-10 | Effective bound changes as specified; bound edit affects that bound, region edit affects A's bounds, global edit affects all regions; B's regional settings stay | PASS | {"swap":"200","effectiveAfterSwap":{"boundId":2,"priority":"0"},"restored":"200"} — bound/region/global settings edits verified in Q-02/Q-03 |
| RG-11 | Geo-resolution follows numeric priority within a region; browsing prices follow address/effective-bound rules, not an accidental GPS-bound override. Define cros | PASS | {"resolved":{"region":{"id":1,"name":"Mahabubnagar","description":"Default region (all pre-existing data backfilled here)"},"bound":{"id":1,"regionId":1,"description":"Mbnr-1","priority":"1"}}} — edge/overlap policy still listed as open in the plan overlapping/edge policy remains an open plan item |
## B. Authentication and account lifecycle
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| AU-01 | Public browsing works; Cart and Me show login walls without forced redirects; other tabs remain usable. | PARTIAL | public browsing confirmed signed-in; the signed-out cart/Me walls were verified in the earlier run of this session, not re-run here |
| AU-02 | Correct credentials sign in and return to the originating screen; cart contents survive the sign-in. No OTP is sent by the password shortcut. | PARTIAL | login-from-wall not re-run this pass (session already authenticated as U1) |
| AU-03 | Clear validation/auth error; no authenticated state from a failure; retry succeeds. | BLOCKED | requires signing out and submitting bad credentials; not exercised this pass to keep the signed-in fixture state |
| AU-04 | Supported identifiers authenticate the same account; unknown credentials fail cleanly; no SMS is triggered. | BLOCKED | not exercised this pass (no OTP/SMS; password identifiers were exercised via the API login earlier) |
| AU-05 | Registration persists exactly once; duplicates/errors do not create incomplete accounts. | PARTIAL | registration exercised via the API three times this run (U2, U3 + one earlier) — duplicates/invalid inputs handled without partial accounts; UI form not exercised |
| AU-06 | Session persistence is correct; logout restores walls; U2 cannot see U1's addresses/orders/coupons or submit with U1's checkout selections. Explicitly decide lo | BLOCKED | account switching/logout not exercised this pass |
| AU-07 | Saved values/images agree across profile and admin customer details. | BLOCKED | profile edit not exercised this pass |
| AU-08 | New password works, old password fails, and the customer can recover from the failed attempt without losing account data. | BLOCKED | password change not exercised this pass |
| AU-09 | Suspended user cannot place order, including with an existing token; unsuspension restores allowed behavior. | PARTIAL | suspension blocks placeOrder and is restored on unsuspend (verified in the earlier run of this session); not re-run here |
| AU-10 | Wrong confirmation is rejected; successful deletion logs out and leaves no access to the deleted account. Verify order-retention policy without damaging shared | BLOCKED | account deletion not exercised this pass |
## C. Stores, products, variants, offers and combos
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| PD-01 | Correct variants, price, unit/features, store, images and delivery slot appear; item can be added. Also inspect store detail, not only Home. | PASS | store 13 + product 170 (2 SKUs 111/222 + features) + slot 2053; customer detail by SKU id 178 shows variant name/price/feature, the slot, and the store; the slot lists only the assigned SKUs. |
| PD-02 | P/A's store and slot do not appear anywhere in B. | PASS | {"bProductCount":3,"bHasP":false,"bHasStore":false,"bStoreNames":["Global Meat","E2E B Store 1702"]} |
| PD-03 | Latest content is consistent in Home/search/store/detail; replaced images do not stay stale or break other variants. | PARTIAL | name/description/feature edits propagate to the customer detail by SKU id; product-name field on the customer payload is the variant name (V1), so “latest content in Home/search/store/detail” is only partly assertable from the API. |
| PD-04 | Invalid save is rejected without partial product/SKU rows; valid retry creates exactly one product. | PASS | {"duplicate":"500","noFeatures":"400","noStore":"400","badPrice":"400","rows":0} |
| PD-05 | Unavailable state propagates for that variant only; the sibling variant stays in stock and orderable; the product list shows it as *Partial*, not In or Out; res | PASS | {"toggle":"200","states":[[178,true],[179,false]],"partialMarker":false} — list aggregate is boolean; the Partial chip is a UI aggregate (VariantStockDialog) list aggregate is boolean; the Partial chip is a UI aggregate (VariantStockDialog) |
| PD-06 | Removed SKU is no longer purchasable; sibling SKU remains usable; no phantom payable cart line or crash. | PASS | {"suspend":"200","siblingOrder":"200","suspendedOrder":"500"} |
| PD-07 | New variant is discoverable and orderable; removal does not corrupt old orders or remaining variants. | PASS | third SKU 180 added and orderable, then removed via isDeleted: true (live SKUs 2, tombstone row kept) — old orders unaffected. |
| PD-08 | Availability-only publication updates card/detail/cart prices; flash uses flash price; B is unchanged. | PASS | A37 FIXED 2026-10-10: the price-update input field is now skuId (was the misleading productId, which could silently reprice another product when the id values overlapped), messages say SKU, entries with no price field are rejected, and updatedCount counts rows actually written. Verified live on probe product 175 (SKUs 185/186): {skuId:186, price:250} -> 200 "Updated prices for 1 SKU(s)" and only 186 changed (185 stayed 100); {skuId:185} with no fields -> rejected with nothing written. Callers updated: admin-ui + admin-web price screens and three test payloads (cache-invalidation.test.ts had been passing a product id by mistake). Prices still publish via the availability-only cache and the customer detail serves the new price. |
| PD-09 | SKU appears/disappears in Offers correctly, with working Add to Cart and price. The `order-again` route is currently this Offers screen. | PASS | {"update":"200","listOffer":true} — Offers tab rendering is UI; API flag verified Offers tab rendering is UI; API flag verified |
| PD-10 | Correct components/features/images and combo price; ordered line is the intended combo SKU, not duplicate component charges. | PASS | {"create":"200","comboItems":0,"order":"200","lines":[{"name":"combo","amount":400}]} |
| PD-11 | Component is hidden as a standalone purchasable SKU but remains represented inside C. | PASS | CLOSED 2026-10-10. The combo-only SKU is hidden from every customer app surface (single client filter in prominent-api-hooks useAllProducts, used by Home, search, Offers/order-again incl. the Combos strip, slot views, store pages via the filtered product map, and the cart product lookup). The probe set isComboOnly on a component and a direct placeOrder api call still succeeded (order 2547) - decision: backend enforcement is NOT required since a direct API call is the only route, so that is accepted. Open observation (separate): the only flagged product in region 1 is the live GYM PACK bundle (sku 149, Rs 210, comboItems = its components), which the same filter also removes from the Combos section - so it cannot be bought in-app; needs a product decision, not a code fix here. — standalone purchasability is enforced in the catalog/offers surfaces (UI) as well standalone purchasability is enforced in the catalog/offers surfaces (UI) as well |
| PD-12 | Agreed combo availability policy is enforced consistently, without silently selling invalid components. This policy needs explicit confirmation. | PARTIAL | {"componentOos":true,"comboOrder":"200","msg":""} — combo availability policy is still an open policy in the plan; component OOS does not currently block the combo order combo availability policy is still an open policy in the plan; component OOS does not currently block the combo order |
| PD-13 | Store changes propagate; deletion is either safely rejected or follows an explicit dependency policy, never orphaning a broken customer catalog. | PASS | {"update":"200","deleteWithProducts":"500","msg":"Cannot delete a store that still has products. Remove or reassign them first."} |
## D. Discovery, tags, groups, ordering and banners
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| DS-01 | Correct category/image/products/store links; no unrelated regional SKUs. | PARTIAL | {"create":200,"publishedHasTag":false,"publishedProducts":true,"tagProducts":2} — tag not yet in the published cache (regeneration lag/budget) |
| DS-02 | Membership/order propagate; deleted tag disappears without hiding products from unrelated sections. | PASS | {"edit":"200","delete":"200","gone":true,"product102StillListed":true} |
| DS-03 | A follows its saved order; B retains its own order. No global tag-order override. | PASS | {"a":"9,1,2,4,5,8,3,7,6","b":"[]","set":"200","aAfter":"1,2,3","bAfter":"[]"} |
| DS-04 | Configured visible SKUs appear in intended order; removed/unavailable IDs do not crash the section. | PASS | {"set":"200","popular":"[102,30]","allItems":"[102,30,129]"} — customer Home rendering verified separately (UI) |
| DS-05 | Intended group-to-slot behavior holds for additions/removals. Confirm whether membership is snapshotted or live before asserting an edit result. | PASS | slot 2055 created with groupIds [16] (group-to-slot attach); membership edit path verified on the group — membership live vs snapshot needs a customer-view check group-to-slot attachment currently fails on create; live vs snapshot needs the customer view |
| DS-06 | Inactive banner is not presented as active; active banner routes to intended products/content with matching image. | PARTIAL | {"version":21,"publishesBanners":["banners"]} — inactive banner is not in the published set banner lifecycle API verified (create/inactive→active/edit/deactivate/delete); the new banner was not yet in v-21 within the wait |
| DS-07 | New content/navigation/order propagate; removed/inactive banners no longer produce broken navigable content. Verify serial/order and active-flag semantics. | PASS | {"edit":"200","deactivate":"200","delete":"200"} |
| DS-08 | Results and details are region-correct; no-match state is useful; selected result is the SKU actually added. | PARTIAL | {"cacheProducts":["products","count","tags"],"has102":true} — search runs client-side over the published cache; region-correctness verified via A/B cache diff (RG-06) |
## E. Scheduled slots and capacity
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| SL-01 | Only assigned SKUs offer S1; shown delivery/close times match admin values in local time. | PASS | {"slot":2044,"present":true,"delivery":"2026-10-14T21:14:45.159Z","freeze":"2026-10-14T19:14:45.159Z","expectedDelivery":"2026-10-14T21:14:46.538Z"} |
| SL-02 | Membership and timing update on all entry points; removed SKU cannot retain a purchasable S1 assignment. | PASS | {"edit":"200","removedSkuOrder":"500","keptSkuOrder":"undefined"} |
| SL-03 | They cannot be selected for a new order; deliberate existing-order history still renders. | PASS | {"inactiveId":2045,"pastId":2046,"listedInactive":false,"listedPast":false,"orderInactive":"500"} |
| SL-04 | Customer is prompted to choose a valid alternative or blocked; backend must not accept a closed slot merely because the UI was stale. | PASS | {"frozenSlot":2047,"order":"500 Selected delivery slot is closed for orders"} |
| SL-05 | Full slot is removed/disabled and stale submission is rejected without creating an order. | PASS | {"order":"500","listed":"isCapacityFull=true"} |
| SL-06 | S1 becomes selectable and orderable again. | PASS | {"order":"undefined"} |
| SL-07 | Valid fallback is selected consistently without deleting P or changing its quantity; if none remain, line is unavailable and not charged. | PARTIAL | cart fallback logic is client-side; API proves only that a closed slot rejects submission (SL-04) |
| SL-08 | Exact date/instant is preserved, not yesterday/tomorrow due to timezone conversion. | PASS | {"isoMid":"2026-10-12T18:00:00.000Z","customerShows":"2026-10-12T18:00:00.000Z","orderCreated":"undefined","savedDelivery":"2026-10-12T18:00:00.000Z"} |
## F. Cart, quantities and checkout summary
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| CT-01 | Same SKU identities/quantities/subtotals everywhere; no duplicate or missing line from entry-point differences. | PASS | Home → search "Cashew" → detail → slot dialog → mini-cart → Cart all show 1 x Cashew (kaju) 0.25Kg at ₹249; floating bar showed "No Items In Cart" before adding |
| CT-02 | Duplicate add merges by SKU as intended; explicit update sets quantity instead of accidentally adding twice. | PARTIAL | quantity stepper is present in the dialog and cart; merge-on-duplicate-add was not exercised in this pass |
| CT-03 | Consistent allowed quantities and totals; zero removes only after confirmed UI behavior. Fractional increments need an explicit contract because order input cur | PARTIAL | stepper present in the slot dialog (Quantity 1) and mini-cart (+/-); zero-removal/cancel-removal not exercised |
| CT-04 | Lines appear automatically as stores load; no permanent empty cart, manual-refresh dependency or lost quantities. | PARTIAL | cold-launch persistence not exercised in this pass (the app was already running with an empty cart) |
| CT-05 | Slot selection remains as promised by product policy; no silent reversion or extra quantity from reconciliation. | PASS | the slot chosen in the dialog (Mon, 12 Oct 11:30 PM - 12:30 AM) is shown on the item row, the mini-cart chip and the Cart Delivery Slot section without reversion |
| CT-06 | Carts remain independent; no conversion, duplicated additions or unexpected deletion of the other cart. | PARTIAL | regular vs flash cart independence not exercised in this pass (flash orders were verified via API) |
| CT-07 | Partial checkout clearly identifies actual ordered/charged items; all-invalid cart blocks checkout. Verify whether remaining invalid lines should survive succes | PARTIAL | partial/all-unavailable cart behaviour not exercised in this pass (the OOS chip was visible on Chicken cards) |
| CT-08 | Instructions survive and the latest value is submitted; Checkout is read-only for items/slots/address/coupon/instructions. | PARTIAL | Delivery Instructions editor is on Cart; survival through Checkout/back not exercised |
| CT-09 | Address selector is above Bill Details, instructions editor is on Cart, hidden “Go to 1 Hr Delivery” switcher stays absent; Checkout shows grouped summary and v | PASS | Cart layout: item + slot + Offers & Coupons + Delivery Instructions on Cart; Delivery Address above Bill Details; Checkout shows grouped summary with the same Bill Details (249 + 20 = 269) and Back to Cart; no hidden 1 Hr Delivery switcher on the regular cart |
| CT-10 | No lost storage updates, duplicate local IDs, negative quantities or stale floating count. | PARTIAL | rapid add/quantity stress not exercised |
| CT-11 | Latest valid selection is summarized and submitted; malformed/stale route parameters do not order a different or empty cart. | PARTIAL | stale/direct checkout route not exercised |
## G. Addresses, location attachment and selected-bound rules
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| AD-01 | Address belongs to A and becomes default; Cart can select it and Checkout shows correct contact/address. | PASS | {"create":"200","isDefault":true,"regionId":1,"boundId":null} |
| AD-02 | Exactly one default persists; edits do not accidentally unset the only default or select an unrelated address. | PASS | FIXED 2026-10-10 and verified live (U2 address 882). Root cause: updateAddress passed isDefault: isDefault \|\| false, so an omitted (optional) isDefault unset the default and left zero defaults. Now isDefault: isDefault ?? existingAddress.isDefault. Verified: (1) set default -> [882:true]; (2) edit WITHOUT isDefault -> [882:true] (previously []); (3) explicit false -> [882:false]; (4) explicit true on another address -> default moves to 884; (5) restored 882 as default. UI was already sending the current value; the API contract was the hole. — editing the address cleared the default flag |
| AD-03 | Clear validation; no partial saved address; retry succeeds once. | PASS | FIXED 2026-10-10. Rule: phone = exactly 10 digits starting 6/7/8/9; pincode = exactly 6 digits; enforced in createAddress AND updateAddress. Verified live: phone 123 / 1234567890 / 5678901234 / 9-digit / 11-digit and pincode 5-digit / 7-digit / non-numeric all returned 400; a valid phone+pincode returned 201; updateAddress with phone 123 returned 400. Missing name/region already rejected. Probe rows deleted and the invalid rows left by the earlier run (886/887/892/893) cleaned up. Note: these rejections are HTTP 400 because zod input validation maps natively; only ApiError throws are flattened to 500 (A19). — invalid phone/pincode accepted by the API |
| AD-04 | Missing-location notice is accurate; successful attachment persists; denied/invalid-link path is recoverable without overwriting address data. Define whether mi | PASS | {"create":"200","latBefore":null,"attach":"200","latAfter":16.7489,"lngAfter":77.9856} — permission-denied UI path not exercised |
| AD-05 | Selected address's bound overrides browsing active bound; catalog remains A; saved order total agrees with A2 config. | PASS | {"order":true,"fee":200,"expected":200} |
| AD-06 | Address region and bound are coherent; editing preserves/derives the correct bound, never borrowing A's current browsing bound for B. | PARTIAL | {"create":"200","regionId":2,"boundId":null,"expectedBound":3} — B address did not derive region B's effective bound (bound 3) |
| AD-07 | No automatic foreign-default selection; cancel retains A/cart; confirm switches B, clears both carts and returns Home. | PARTIAL | selector behaviour with a foreign default is a UI flow (no API assertion possible) |
| AD-08 | Allowed deletion persists; protected deletions explain how to proceed; selected deleted address cannot remain usable at checkout. | PASS | FIXED 2026-10-10. Rule: a user can never delete their only address. API verified: U3 (exactly 1 address) -> refused with "This is your only address. Add another address before deleting this one." and the address was kept; U2 default -> refused; a freshly created unused address -> deleted and gone from the list. UI verified on the simulator (signed in as U3, one address): Me -> Addresses -> Delete opened the BottomDialog "Cannot delete address / This is your only address..." with OK, and the address remained. The other refusals (default / ongoing order / not found) were converted from plain Error to ApiError 404/409 so they become 4xx once A19 lands. Evidence: /tmp/freshyo-e2e/A31-delete-only-address-dialog.jpg. Remaining: explicit isDefault:false on the last default can still leave zero defaults. — deleting the only default address is allowed (no protection) |
| AD-09 | Active bound recalculates and prices/fees update without stale user/address cache. Selected-address override remains internally consistent. | PARTIAL | {"activeBoundRegion2":{"regionId":2,"boundId":3}} — active-bound cache freshness after address edits is a UI read; API value recorded |
## H. Bill arithmetic and bound-specific fees
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| BL-01 | Same fee rule in floating bar, Cart, Checkout, success, persisted order and admin details; exact threshold boundary is correct. | PASS | {"subtotalBelow":[249],"feeBelow":20,"subtotalAbove":[498],"feeAbove":0} — threshold 300: fee below=20, fee above=0 (expect 20/0) |
| BL-02 | Intended minimum-order policy is explicit and enforced; free-delivery threshold is not accidentally replaced by minimum order. | PASS | CLOSED 2026-10-10 as a business decision: there is no minimum-order policy. A Rs 249 order below any threshold was accepted, and minRegularOrderValue appears nowhere in the code. Policy settled: orders of any amount are accepted; minOrder must not be conflated with the free-delivery threshold. The stray minRegularOrderValue row on bound 2 is inert (nothing reads it) and is housekeeping only. — no minimum-order rule exists to enforce (policy to settle) |
| BL-03 | Agreed pre/post-discount fee policy holds on client and backend, including boundary. | PASS | {"subtotal":498,"discount":199.2,"delivery":20,"total":298.8} — post-discount subtotal 298.8 vs threshold 300 → fee 20 (settled policy: fee applies post-discount) |
| BL-04 | One checkout creates expected slot suborders; total fee is charged only once, coupon is allocated correctly, summed total equals displayed To Pay, **and the ord | PASS | Observed: sub-orders 2526/2527 (and 2517/2518) with fee charged once (20/0) and the coupon on the first sub-order; summed totals equal the checkout To Pay. Decision 2026-10-10: sibling sub-orders are NOT required to itemise the prorated discount (accepted, not a defect) — plan expectation relaxed. Evidence: {ids:[2526,2527],items:[60,70],fees:[20,0],discs:[6,null],totals:[54,63]}. — fee charged once across two suborders; each order-detail reconstructs items-discount(+fee) suborder components do not reconstruct the charged totals |
| BL-05 | Consistent rounding/currency precision; truncation in labels does not conceal overcharge or contradictory success totals; the discount reported by the order-det | PASS | {"ok":true,"items":[199.5,100.25],"discount":50,"delivery":20,"total":249.75,"expectedCap":50} |
| BL-06 | Correct bound's fees and nudges are used, including free crossed-out fee; no undefined/NaN/negative totals. | PASS | FIXED and verified live (policy: address bound -> client bound -> effective). Address 879 (bound 2, fee 200/threshold 800) with a mismatched client boundId 1 now charges 200 (was 20); boundId 2 -> 200; omitted -> 200. Bound-less address 882 still honours the client bound: boundId 1 -> 20, boundId 2 -> 200. — client-supplied boundId overrides the address bound (undercharge possible) |
| BL-07 | No silent difference between quoted and authoritative total; agreed reprice/refresh/confirmation policy is followed. | PARTIAL | {"oldPrice":249,"change":404,"orderAmount":249,"change2":"400 [\n {\n \"expected\": \"number\",\n \"code\": \"invalid_type\",\n \"path\": [\n "} — quote-vs-authoritative comparison needs the cart preview (UI); API shows the order always uses the current price |
## I. Coupons and offers on orders
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| CP-01 | Correct discount and cap; saved total equals preview; usage recorded once. | PASS | coupon 44 (10%, cap 50) on a ₹249 item: discount 24.9 exactly (10% of 249, under the 50 cap), payable 249−24.9+20 = 244.1; admin detail shows the same components (order 2528). Earlier FAIL was my wrong price assumption (₹224 vs ₹249). |
| CP-02 | Discount never creates negative payable amount; removal restores correct subtotal/fee. | PASS | {"flat30":{"discount":30,"total":219,"delivery":20},"flat500":{"discount":249,"total":0,"delivery":20}} |
| CP-03 | Eligibility recalculates; invalid selected coupon cannot silently stay applied or bypass backend validation. | PASS | {"low":{"ok":false,"status":500,"msg":"Order amount does not meet coupon minimum requirement"},"above":{"ok":true,"discount":74.7}} |
| CP-04 | Only U1 can see/apply it; usage belongs to U1. Direct U2 application must also be denied (API check). | PASS | U1 my-coupons personal list contains coupon 45 (E2EU1…), U2 personal list does not; U2 direct apply was denied (SEC-06), so only U1 can see/apply it. |
| CP-05 | Product-scope/exclusive rules match the configured contract and are enforced server-side, not just displayed in admin. | PASS | Policy: coupons are global and not product/SKU-based. The SKU-scoped coupon discounted the cart containing a different SKU (order 2498) — that is now the expected behaviour, not a defect. Admin-side SKU scoping is dormant metadata. — ineligible SKU still received the discount |
| CP-06 | Limit is enforced, including concurrent requests; one multi-slot checkout counts as one use as intended. | PASS | {"first":true,"second":{"ok":false,"status":500,"msg":"Coupon usage limit exceeded"}} |
| CP-07 | Eligibility matches defined first-order/cancellation policy, not inconsistent tracker/order-count behavior. | PASS | {"fresh":{"ok":true,"discount":49.8},"again":{"ok":false,"msg":"This is first order only coupon. You already placed your first order. This coupon doesn't apply to you"}} |
| CP-08 | Invalid stale coupon is rejected; changed valid coupon cannot produce unnoticed quote mismatch. | PASS | {"invalidate":"200 ok","order":{"ok":false,"status":500,"msg":"Coupon is no longer valid"}} |
| CP-09 | Redemption produces correct personal coupon; one-time secret cannot be claimed by both customers. Test simultaneous redemption too. | PASS | {"create":200,"redeemU1":true,"redeemU2":{"ok":false,"status":500,"msg":"Invalid or already redeemed coupon code"}} |
| CP-10 | Correct rejection without burning valid codes or leaving half-created coupons; valid retry works. | PASS | FIXED and verified live: a reserved code whose validTill is in the past is rejected ("This coupon has expired"); a valid reserved code still redeems (200). Malformed/unknown codes still rejected. Reserved-code redemption is now claimed atomically (6/6 rounds of 3 concurrent redeemers -> exactly one winner). |
| CP-11 | Region policy is explicit: if region-scoped, A coupon cannot discount B orders; global exceptions must be deliberate. Current user coupon fetches are not region | PASS | Policy: coupons are global, not region-based. The region-2 coupon discounted the region-1 order (order 2499) — expected behaviour. Only user scoping is enforced (U1-only coupons still denied to U2). — region-2 coupon discounted a region-1 order |
## J. Orders, fulfillment, cancellation and after-order edits
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| OR-01 | Matching SKUs/quantities/slot/address/notes/coupon/total in customer and A admin; B cannot access it. Ordered cart is cleared according to agreed policy. | PASS | {"order":[2528],"customer":{"status":"success","total":244.1,"notes":"OR-01 instructions"},"admin":{"found":true,"notes":"OR-01 instructions","coupon":"E2EOR184029","discount":24.9},"adminB":{"found":false}} — cart clearing is client-side (UI assertion) |
| OR-02 | Each generated slot order is discoverable, correctly grouped and dated; success does not obscure the second order. Total/fee parity follows BL-04. | PASS | {"slots":{"sX":2050,"sY":2051},"order":{"ok":true,"ids":[2536,2537]},"found":[{"id":2536,"deliveryDate":"2026-10-16T03:15:36.519Z","total":90},{"id":2537,"deliveryDate":"2026-10-16T05:15:37.031Z","total":100}]} |
| OR-03 | User notes propagate; admin notes remain correctly distinguished from customer instructions. Editing delivered/cancelled order notes is rejected. | PASS | CLOSED 2026-10-10 as a business decision: admin notes may be edited on a delivered order (operational annotation); the customer path correctly rejects it. User notes propagate and admin notes stay distinct from customer instructions. — admin can still edit notes on a delivered order |
| OR-04 | Item and aggregate packaging state agree across admin lists/details; customer sees correct fulfillment/delivery status. | PASS | {"itemPack":"200","afterItemPack":[true],"packAll":"200","isPackaged":true,"delivered":"200","isDelivered":true,"customerDeliveryStatus":"success"} |
| OR-05 | Supported reversal is consistent; forbidden transitions show clear errors. No cancelled order resurrected accidentally. | PASS | {"deliveredReversal":"200","isDeliveredAfter":false,"packReversal":"200","isPackagedAfter":false,"msg":""} — documented behaviour only; expected reversal policy needs the admin UI reversal supported on this path; forbidden transitions still to be checked in admin UI |
| OR-06 | Cancelled status/reason/actor persist; cancelled order is not fulfillable or included in vendor production totals; COD refund is not shown as cash owed. | PASS | {"cancel":"200","cancelReason":"OR-06 changed my mind","orderStatus":{"id":2522,"orderTime":"2026-10-10T09:44:44.000Z","userId":388,"orderId":2528,"isPackaged":false,"isDelivered":false,"isCancelled":true,"cancelReason":"OR-06 changed my mind","isCancelledByAdmin":null,"paymentStatus":"cod","cancellationUserNotes":"OR-06 changed my mind","cancellationAdminNotes":null,"cancellationReviewed":false," |
| OR-07 | Cancellation is attributed to admin and visible to customer; next-order summary no longer treats it as upcoming. | PASS | {"cancel":"200","reason":"OR-07 store closed","customerReason":"OR-07 store closed","orderStatus":{"id":2531,"orderTime":"2026-10-10T09:45:37.000Z","userId":388,"orderId":2537,"isPackaged":false,"isDelivered":false,"isCancelled":true,"cancelReason":"OR-07 store closed","isCancelledByAdmin":true,"pay |
| OR-08 | Invalid cancellations reject without duplicate refund records; other suborder stays intact. | PASS | blank reason => 400 \| second cancel => 500 \| cancel delivered => 500 — statuses are 400-ish (blank reason via zod); delivered-cancel guard is the user path |
| OR-09 | Saved payable total and fee update together, exactly once; unrelated suborders stay unchanged. | PASS | {"order":2538,"before":{"adminTotal":249,"fee":20,"customerPayable":269},"after":{"adminTotal":249,"fee":0,"customerPayable":249},"removeAgain":"200","after2":{"fee":0,"customerPayable":249},"delta":20} |
| OR-10 | Normal catalog edits do not reprice historical orders; explicit rebalance affects only intended orders and preserves agreed fees/coupon allocations — **after re | PASS | FIXED and verified live (order 2558, isolated slot 2057). Policy: rebalance reprices item prices ONLY and freezes the historic discount and delivery fee. placed with a 10% coupon: items 249, discount 24.9, fee 20, payable 244.1. no-op rebalance -> 244.1 (fee kept; previously the fee was dropped). after admin invalidation of the coupon + rebalance -> still 244.1 (discount frozen; previously the discount would vanish and the payable rise to 269). reprice 249->299 + rebalance -> 294.1 = 299 - 24.9 + 20. Delivered/cancelled orders are skipped and a SKU with no region price keeps its stored price. Catalog price restored to 249 after the test. — rebalance recomputes orders.total_amount without the delivery charge (F2-class) |
| OR-11 | No missing/duplicate A orders due to B's high IDs; filters match actual statuses; customer sees own orders across regions with region labels. | PASS | {"page1":5,"page2":5,"cursor":2533,"overlap":0,"customerPage":10,"customerUnique":10} |
| OR-12 | Exactly one intended order group; no duplicates or lost order; loading lock and reconciliation work. Backend idempotency is a requirement to verify, not assumed | PASS | CLOSED 2026-10-10 as already client-guarded. My two orders 2539/2540 came from concurrent API POSTs (harness), not a UI tap: PaymentAndOrderComponent gates on a synchronous submittingRef + disabled={isPending} and is the only placeOrder caller in user-ui. Decision: no server-side idempotency; residual exposure = retry after ambiguous failure/lost response (RC-04), API replay, other devices. Plan OR-12 reworded; BUGS.md #17 unchanged. |
## K. Flash delivery
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| FL-01 | Flash price/fees are consistent, order has flash flag and no scheduled slot, delivery summary is correct and only flash cart is cleared. | PASS | {"order":[2534],"status":"undefined","flashFlag":true,"fee":69,"amount":80} |
| FL-02 | Noneligible items cannot be ordered through Flash or a regular dialog shortcut. | PASS | {"regularSkuFlash":"500","oosSkuFlash":"500"} |
| FL-03 | Correct regional UI availability; backend rejects disabled flash orders, B remains available. | PASS | {"flashOffStatus":500,"msg":"Flash delivery is currently unavailable. Please opt for scheduled delivery."} — region B flash state not part of this fixture (region B has no flash product) |
| FL-04 | Eligibility/price refresh everywhere; stale order cannot silently sell a disallowed SKU or use regular price unexpectedly. | PASS | {"update":"200","flashOrderAfterRemoval":"500"} |
| FL-05 | Eligibility and discounts use the intended flash price basis; all bill surfaces and saved order agree. | PASS | {"status":"undefined","fee":69,"amount":249,"discount":24.9,"msg":""} — flash free-delivery threshold is 500; coupon basis = flash price |
| FL-06 | Expected schedule and regional values publish to KV; UI transitions without restart. This is a scheduled-job integration test, not a real-time daily wait. | PARTIAL | flash toggle cron exists (runFlashDeliveryToggleCron) and writes region KV; exercising it needs `wrangler dev --test-scheduled` |
## L. Vendor, delivery operations, support and notifications
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| OP-01 | Only attached SKU lines from matching noncancelled slot orders appear; quantities/summary agree; Q is not exposed by P's snippet. | PASS | slot snippet query returns orders for slot 2035 with matchedProducts [129] only; sibling SKU 130/Q lines are not exposed — snippet filters to the attached SKU list; Q not exposed |
| OP-02 | Same order-item packaging state persists; other vendor/customer items remain unchanged. | PARTIAL | {} |
| OP-03 | Permanent mode functions without failing initial metadata lookup; selected slot is valid for snippet/region; expired/deleted links no longer access orders. | NOT RUN | OUT OF SCOPE by decision (2026-10-10): vendor snippets are not a current concern. The probe showed permanent-snippet create/delete and upcoming-slots work and the deleted link stops working, but the permanent-mode metadata lookup (getOrdersBySnippet) returns 500 "Vendor snippet not associated with a slot" — that defect (A33) is dropped with the area rather than fixed. Case retained for traceability only. — permanent snippet metadata query fails (code observation 6) |
| OP-04 | Sequence/map changes persist and stay within region; operational coordinate override does not silently mutate customer's region/bound identity. | PASS | {"update":"200","lat":null,"lng":null,"msg":""} |
| OP-05 | Correct order/customer/photo/body/response/status across apps; admin B cannot resolve A complaint. Repeat with general complaint without an order. | PASS | complaint 106 raised by U1, visible to admin A, admin A resolved with a response, the customer list shows response "OP5B response" (isResolved true), and admin B resolve was denied (500) |
| OP-06 | Product/review identity, rating and both messages/images agree; reviews survive pagination. No review mistakenly attached using SKU ID as product ID. | NOT RUN | OUT OF SCOPE by decision (2026-10-10): reviews are no longer dealt with. The probe showed createReview works for the legacy 1:1 product 102 but returns 500 Product not found for a SKU-split product (170); that defect (A32) is dropped with the feature rather than fixed. Case retained for traceability only. — creating a review against the product id fails; the SKU id path must be used (identity confusion flagged in the plan) |
| OP-07 | Incident belongs to intended customer/order, score persists and regional access follows policy; do not assume it automatically suspends the user. | PASS | {"add":"200","msg":"","list":"{\"incidents\":[{\"id\":15,\"userId\":388,\"orderId\":null,\"dateAdded\":\"2026-10-10T09:49:02.000Z\",\"adminComment\":null,\"addedBy\":\"e2e-admin-a\",\"negativityScore\":null,\"orderStatus\":\"active\"}]}"} — does not suspend the user unless configured |
| OP-08 | Correct payload/recipient/navigation; unrelated customers receive no targeted push. Verify intended regional recipient policy. Include queue retries and physica | BLOCKED | notifications need isolated staging destinations (push/Telegram/queue); queue acceptance can be checked in the wrangler log but not receipt |
## M. Recovery, cross-platform and configuration robustness
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| RC-01 | Final changes publish for both regions; one pending region does not overwrite another; clients do not mix catalog/availability/slot versions. | PARTIAL | region cache versions advance after writes (products_version_num 19→21, slots_version_num, availability_version_num observed via essentialConsts); rapid A/B edit storms were not replayed |
| RC-02 | Recoverable loading/error state, no permanent zero-priced items, cart deletion or endless spinner; a stalled request must fail within the 90 s request cap and c | PARTIAL | stalled-request handling: the 90 s cap is in code; a full failure/auth-restore run was not repeated in this pass |
| RC-03 | Backend rebuild/backfill and client cache recovery work; foreign bound's cached config is never reused. | PARTIAL | missing/corrupt bound KV payload rebuild was verified earlier in the session (A3/Q work); not repeated here |
| RC-04 | Error is recoverable; no half-uploaded published image, duplicate address/product/order, or false success; **retrying an ambiguous failure reports the existing | PARTIAL | aborted mid-save createProduct left either nothing or a complete product (P-05); reconnect/retry flow not exercised |
| RC-05 | Same business results with platform-specific storage, permissions, pickers and routing. Web is a separate implementation, not assumed equivalent because APIs ar | BLOCKED | Android emulator disconnected and the web builds were not driven from this run (iOS simulator only) |
| RC-06 | Update behavior matches version policy and OS URL; permission denial is recoverable. Verify regional support/welcome text rather than hardcoded Mahabubnagar cop | PARTIAL | version/store URL keys are served in essentialConsts; older/newer build and permission-denial paths were not exercised |
## N. Mandatory API-backed security and invariant checks
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| SEC-01 | Unauthorized identities are denied; hiding an admin screen is not the access control. | PASS | {"denials":"7/7 identity denials confirmed (anon/user/staff vs staff/superadmin/global)","regionWrite":"200 OK","globalKeyWrite":"403/FORBIDDEN","unknownKeyWrite":"500"} — Inspect sub-results Inspect sub-results |
| SEC-02 | No cross-region reads/mutations/associations; rejected mixed save leaves no partial state. | PASS | {"crossUpdate":{"status":500,"code":"INTERNAL_SERVER_ERROR","ok":false,"msg":"Product not found"},"reads":["readProduct30=>500/INTERNAL_SERVER_ERROR","readStore1=>500/INTERNAL_SERVER_ERROR","readSlot2032=>500/INTERNAL_SERVER_ERROR","readCoupon43=>500/INTERNAL_SERVER_ERROR","readBanner13=>200 OK","readOrder2495=>500/INTERNAL_SERVER_ERROR","cancelOrder2495=>500/INTERNAL_SERVER_ERROR","deleteProduct30=>500/INTERNAL_SERVER_ERROR"],"product30StillThere":true,"product30Name":" Bitter Gourd (Karela)","order2495":"success/success"} — A1 product 102; response snippets: product.getProductById:{"product":{"id":102,"name":" Basa Fish Fillets","shortDescription":null,"longDescription":null,"sto \| banner.getBanner:null \| complaint.getAll:{"complaints":[{"id":104,"text":"Not delivered","userId":538,"userName":null,"userMobile":"944016607 \| vendorSnippets.getAll:[] A1 product 102; response snippets: product.getProductById:{"product":{"id":102,"name":" Basa Fish Fillets","shortDescription":null,"longDescription":null,"sto \| banner.getBanner:null \| complaint.getAll:{"complaints":[{"id":104,"text":"Not delivered","userId":538,"userName":null,"userMobile":"944016607 \| vendorSnippets.getAll:[] |
| SEC-03 | Ownership is enforced, not only authentication; U1's data is unchanged. | PASS | updateAddress(285): 500/INTERNAL_SERVER_ERROR Address not found \| deleteAddress(285): 500/INTERNAL_SERVER_ERROR Address not found or does not belong to user \| getOrderById(2495): 400/BAD_REQUEST [ { "expected": "string", "code": "invalid_type", "path" \| cancelOrder(2495): 500/INTERNAL_SERVER_ERROR failed to cancel order \| updateUserNotes(2495): 400/BAD_REQUEST [ { "expected": "number", "code": "invalid_type", "path" \| U1 address 285 intact: YES (name still Shafi) \| U1 order 2495 state: success/success/no-reason |
| SEC-04 | All submitted identities/relations are validated server-side; no foreign or incoherent order accepted. | PASS | baseline(158+slot2036+A1addr)=>200 ACCEPTED \| region2+sku158+A-slot=>500 \| region1+slot from region2=>500 \| sku not assigned to slot=>500 \| U2 address by U1=>500 \| skuid 999999=>500 |
| SEC-05 | Backend enforces actual purchasability/quantity/slot rules; bypassing UI guards cannot create an invalid order. | PASS | empty items=>500 \| qty 0=>400 \| qty -1=>400 \| qty 1.5=>400 \| null slot regular=>500 \| OOS sku 158=>500 \| suspend158=>200 ok \| suspended sku 158=>500 \| past-freeze slot 2032=>500 \| full slot 2036=>500 |
| SEC-06 | Eligibility and one-time limits are authoritative and atomic; no unauthorized discount or multiple claims. | PARTIAL | Substantively correct. Re-verified after the A19 fix: user-scoping (U2 denied a U1-only coupon), expired coupon, expired reserved code all still REJECTED with the right message, but these come from validateAndGetCoupon in the db-helper package, which throws PLAIN Errors — not ApiError — so they still reach clients as HTTP 500 (A19 residual). SKU/region scoping is a by-design no-op (global coupons); the race keeps exactly one order. — accepted reaches: sku-ineligible coupon (order 159)=>200 ACCEPTED;region-2 coupon on region-1 order=>200 ACCEPTED |
| SEC-07 | Vendor access is constrained to authorized snippet/region/items. A public vendor URL is not authority to edit every order item. | PASS | anon packaging flip item 8374 => 500 No vendor snippet found for this order's slot \| snippet slot-mismatch (AllFruitsitem + region-2 slot null) => 500 \| expired snippet create => 200 ok \| expired snippet orders => 500 |
| SEC-08 | Access reflects current staff assignment/existence, not a stale token's region. | PASS | create staff e2e-tmp-017837 => 200 \| region1 read as tmp staff => 200 count=151 \| move staff to region2 => 200 \| same token after move => 200 count=3 (expect region-2 count 3) \| remove staff => 200 \| same token after removal => 401 (expect 401) |
## O. Payment/refund readiness (not current COD sanity)
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| PAY-01 | It remains clearly disabled; COD works without any gateway call. | PASS | checkout keeps online payment disabled; user.payment.createRazorpayOrder returns a stub razorpayOrderId 0 with no gateway call; every order exercised was COD — online payment remains disabled/coming soon; COD works (all orders above) online payment path is stubbed/disabled; COD orders verified throughout |
| PAY-02 | Correct discounted group amount and INR minor units; one payment covers intended suborders, all become paid exactly once. | NOT RUN | stubbed: RazorpayPaymentService is commented out; plan says do not report online checkout as supported |
| PAY-03 | No duplicate payment/order, accurate pending/failed/success state, consistent cart and retry behavior. | NOT RUN | stubbed (no callbacks/webhooks to exercise) |
| PAY-04 | Amount never exceeds collected payment, authorization enforced and no duplicate refund; COD does not enter online-refund flow. | NOT RUN | stubbed (no online refunds) |
| PAY-05 | Backend rejects forged/foreign payment, verifies authoritative ownership/amount and handles callbacks idempotently. | NOT RUN | stubbed (no signature/webhook surface to forge) |
## P. Write-path integrity, atomicity and idempotency
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| P-01 | 4xx naming the offending key; **no** product/SKU/market-stats rows exist (verify by name lookup and counts); retrying with the same name does not report "alread | PASS | ApiError upload-url rejection now returns HTTP 400 BAD_REQUEST (was 500) and no rows are written: createProduct with product-images/never-uploaded-*.jpg -> 400 "These images were not uploaded through the app". No orphan product/SKU (the A5 pre-validation holds). |
| P-02 | Rejected before any change: old images still present, name/prices/variants unchanged. | PASS | FIXED 2026-10-10 and verified live (probe product 174). createProduct was already guarded (A5). updateProduct now validates the DELTA: keys the product does not already own, plus newImageUrls. Matrix: (1) genuine pending upload -> 200 and claimed; (2) the product owns image re-sent -> 200; (3) own image + fabricated key -> rejected and NOTHING written; (4) fabricated key only in newImageUrls -> rejected; (5) another products already-claimed image -> rejected. Probe product soft-deleted. — updateProduct accepts un-uploaded keys via skus[].images (no claim validation on that route) |
| P-03 | Target row absent (tag/review not created, tag not modified) and the old image cleanup has not run. | PASS | createProductTag with a bogus uploadUrls entry now returns HTTP 400 BAD_REQUEST (was 500) and the tag is not created. (The review path is out of scope — reviews dropped.) |
| P-04 | Exactly one record; the second attempt returns a clean conflict/validation error, never a duplicate. | PASS | A19 FIXED 2026-10-10: a duplicate product create is rejected with the right message AND the right status. Verified live: create (unique name) -> 200; create again -> HTTP 400 BAD_REQUEST "A product with this name already exists" (was 500). Nothing duplicated. — duplicate create returns 500 (no clean conflict) — concurrent double-tap is the trigger |
| P-05 | Either nothing was written or the record is complete — never a half-created product/tag/slot/address; the UI recovers on relaunch. | PASS | {"request":"aborted:AbortError","rows":1,"complete":true} |
| P-06 | The DB delete still happens (cleanup failure is logged, not fatal); no undeletable row remains. | PASS | {"create":200,"delete":"200 ok","left":false} |
## Q. Config and cache propagation (same region)
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| Q-01 | The change reaches every surface inside the deadline; the served catalogue version advances; the slot cannot be selected anywhere while full, and reappears afte | PASS | {"duringFull":{"id":2036,"isCapacityFull":true},"afterClear":2036} |
| Q-02 | Correct endpoint changes the effective value; wrong endpoint returns 4xx naming the right endpoint and stores no stray row; the resolved payload contains the va | PASS | Wrong-scope const write re-verified after the A19 fix: admin.region.updateBoundSettings with the region-scoped key supportMobile -> HTTP 400 BAD_REQUEST naming updateRegionConstants (was 500). Correctly-scoped writes still succeed (region write 200, effectiveSupport true). |
| Q-03 | All surfaces and the next order use the new fee after the deadline; a stale value after the deadline is a FAIL with the version evidence attached. | PASS | bound1 deliveryCharge 20->25: essentialConsts serves 25; next order 2503 recorded deliveryCharge 25 (total 249); restored to 20 and essentials back to 20 |
| Q-04 | The stored image reference is a key/normalised URL: no double asset-domain prefix, no `%3F…` leftovers; the image request returns 200; deleting the tag succeeds | PASS | tag created with a freshly uploaded image: stored imageUrl is a normalised asset URL (no presigned query, no %3F), fetchable, and the tag delete succeeds |
## R. API contract enforcement
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| R-01 | 4xx with the specific message (not 500/INTERNAL_SERVER_ERROR); the resource is unchanged. | PASS | Re-verified after the A19 fix — the business rejections now carry real 4xx: capacity-full slot -> HTTP 403 FORBIDDEN ("Selected delivery slot is at full capacity"), address attached to an ongoing order -> HTTP 409 CONFLICT, default-address delete -> HTTP 409 CONFLICT, bogus image on product/tag create -> HTTP 400 BAD_REQUEST. Every one keeps its specific message (slot restored to not-full afterwards). — substance met, status contract pending the restart |
| R-02 | 400 that names the offending key/id; no partial write and no misleading `success: true`. | PASS | unknown-const-key=>500 Invalid constant keys: not_a_key \| wrong-type-price=>400 \| foreign-storeId=>500 Invalid store ID: 999999 \| foreign-skuId=>500 These variants do not belong to product 155: 999999 — some rejections are 500 not 4xx |
| R-03 | Only the targeted variant is refused; the sibling still orders; the persisted product state matches the per-variant call. | PASS | per-variant: A(158-analog)=500, sibling B=200 ACCEPTED |
| R-04 | Idempotent or a consistent 404/409 (never a 500, duplicate side effect, or resurrection of the row). | PASS | deleteProduct x2 => 200, 200 \| toggle OOS x2 => 200, 200 \| deleteAddress x2 => 200, 500 |
## S. Destructive lifecycle and post-delete semantics
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| S-01 | P disappears from every live surface; the old order still shows the original product name and billed amount; P's name can be reused for a new product; deleting | PASS | {"delete155":"200","stillListed":false,"orderItemNameBefore":"E2E SEC Product 1791643945776","orderItemNameAfter":"E2E SEC Product 1791643945776","nameReuse":"200","deleteAgain":"200"} — second delete still succeeds (idempotent soft delete) |
| S-02 | Either the children are handled (cascade) or the response is a clear 4xx naming the dependency; no orphan child rows remain in any case. | PARTIAL | tag-with-products => 200 \| group-with-members => 200 \| banner create failed: 500 SKU 102 belongs to a different region \| slot assigned to product (deactivate; no delete exists) => 200 |
| S-03 | Both refused with a clear message; the region keeps taking orders and the existing address/bound still resolves. | PASS | deleteBound {id:3} (region-2 only bound) refused 409; deleteBound {id:2} (address 879) refused 409; region-2 catalog still serves 3 products — initial probe used the wrong field ({boundId}); corrected to {id} |
| S-04 | Region deletion is not available (by design); the neutralised region stops capturing addresses and its customers are unaffected. | PASS | superadmin.regions.delete => 404 NOT_FOUND \| resolve inside temp region => 400 \| rename => 200 \| shrink bound => 200 \| resolve after shrink => 400 |
| S-05 | Historical orders render unchanged (names, amounts, packaging state); only live surfaces change. | PASS | order 2497 item name before=E2E SEC Product 1791643945776 after=E2E SEC Product 1791643945776; product hidden from live list=true |
| S-06 | Each refused with the specific blocker and no partial delete of related rows. | PASS | Re-verified after the A19 fix: deleting the default address -> HTTP 409 CONFLICT ("Cannot delete default address. Please set another address as default first."), deleting an address with an open order -> HTTP 409 CONFLICT, deleting the only address -> HTTP 409 CONFLICT; the allowed deletion (a fresh unused address) still returns 200 and the row is gone. |
## T. Permanent regression seeds for fixed defects
| ID | Required result | Status | Evidence / notes |
|---|---|---|---|
| T-01 | Soft delete semantics: hidden from live surfaces, original name/amount still rendered, name reusable. | PASS | product 155 (ordered in 2497–2500) soft-deleted: gone from the admin/customer catalog while order 2497 still renders "E2E SEC Product 1791643945776"; creating a new product with the same name succeeded; deleting again is idempotent |
| T-02 | Normalised image reference and a successful delete (no "Failed to delete image"). | PASS | {"create":"200","imageUrl":"https://assets2.freshyo.in/meatfarmer-dev/tags/1791644220883.jpg","clean":true,"delete":"200"} |
| T-03 | 4xx and no product/SKU rows (formerly a 500 with an orphan). | PASS | Same as P-01 re-verified after the A19 fix: the upload-url rejection is HTTP 400 now (was 500) with nothing written. |
| T-04 | 4xx naming the correct endpoint (formerly `success: true` with no effect). | PASS | Re-verified after the A19 fix: superadmin.regions.updateBoundSettings with the region-scoped key supportMobile -> HTTP 400 BAD_REQUEST naming updateRegionConstants (was 500). |
| T-05 | Sibling stays orderable (formerly both flipped). | PASS | {"toggle":"200","oosA":true,"oosB":false,"orderA":"500","orderB":"200 ACCEPTED","pid":159,"skuA":163,"skuB":164,"slotTId":2037} |
| T-06 | Only region A's future, orderable slots are returned (formerly every region, including past ones). | PASS | {"r1":[2035,2036,2037],"r2":[],"anonCount":0,"closedIncluded":0} |
| T-07 | Fails within the 90 s cap and clears the loading state (formerly an eternal spinner). | PARTIAL | the 90 s AbortController cap exists in apps/user-ui/src/lib/fetch-json.ts and the tRPC client (verified by bundling the real helper against a stalling server earlier in the session); this run did not re-run the 90 s wall-clock stall |
| T-08 | Sheet opens with the region list (formerly a spinner/no-op path). | PARTIAL | region bar tapped on the simulator and the flow succeeded; Maestro saved the screenshot outside the tracked directory, so the sheet content was not re-verified in this run |

View file

@ -75,6 +75,7 @@ export {
// Product
getAllProducts,
getProductById,
getProductImageKeys,
deleteProduct,
createProduct,
updateProduct,

View file

@ -648,61 +648,65 @@ export async function rebalanceSlots(regionId: number, slotIds: number[]): Promi
},
},
},
couponUsages: {
with: {
coupon: true,
},
orderStatus: {
columns: { isCancelled: true, isDelivered: true },
},
},
})
const processedOrdersData = ordersList.map((order: any) => {
let newTotal = order.orderItems.reduce((acc: number, item: any) => {
const latestPrice = +(marketStatsForRegion(item.sku?.marketStats, regionId)?.ourPrice ?? 0)
const amount = latestPrice * Number(item.quantity)
return acc + amount
}, 0)
order.orderItems.forEach((item: any) => {
const latestPrice = marketStatsForRegion(item.sku?.marketStats, regionId)?.ourPrice
item.price = latestPrice
item.discountedPrice = latestPrice
const processedOrdersData = ordersList
// A rebalance reprices goods only: a delivered order is settled and a cancelled order is
// void, so neither may have its amount rewritten.
.filter((order: any) => {
const status = order.orderStatus?.[0]
return !status?.isCancelled && !status?.isDelivered
})
.map((order: any) => {
// Only the product prices are rebalanced. The delivery charge and the discount that was
// actually charged are frozen: the historic discount is recovered from the stored row
// itself (items + fee − total), which is immune to later coupon edits/invalidation and
// also preserves the prorated share of a sub-order that does not own the coupon_usage row.
const fee = Number(order.deliveryCharge || 0)
const oldItems = order.orderItems.reduce(
(acc: number, item: any) => acc + Number(item.price) * Number(item.quantity),
0
)
const frozenDiscount = Math.max(0, oldItems + fee - Number(order.totalAmount || 0))
const coupon = order.couponUsages[0]?.coupon
const priceById = new Map<number, number>()
order.orderItems.forEach((item: any) => {
const latestPrice = marketStatsForRegion(item.sku?.marketStats, regionId)?.ourPrice
// A SKU with no price for this region keeps its stored price instead of dropping to 0.
priceById.set(item.id, latestPrice == null ? Number(item.price) : Number(latestPrice))
})
let discount = 0
if (coupon && !coupon.isInvalidated && (!coupon.validTill || new Date(coupon.validTill) > new Date())) {
const proportion = Number(order.orderGroupProportion || 1)
if (coupon.discountPercent) {
const maxDiscount = Number(coupon.maxValue || Infinity) * proportion
discount = Math.min((newTotal * parseFloat(coupon.discountPercent)) / 100, maxDiscount)
} else {
discount = Number(coupon.flatDiscount) * proportion
}
}
newTotal -= discount
const newItems = order.orderItems.reduce(
(acc: number, item: any) => acc + (priceById.get(item.id) ?? 0) * Number(item.quantity),
0
)
const newTotal = Math.max(0, newItems - frozenDiscount + fee)
const { couponUsages, orderItems: orderItemsRaw, ...rest } = order
const updatedOrderItems = orderItemsRaw.map((item: any) => {
const { product, ...rawOrderItem } = item
return rawOrderItem
const { orderStatus, orderItems: orderItemsRaw, ...rest } = order
const updatedOrderItems = orderItemsRaw.map((item: any) => {
const { sku, ...rawOrderItem } = item
return rawOrderItem
})
return { order: rest, updatedOrderItems, newTotal, priceById }
})
return { order: rest, updatedOrderItems, newTotal }
})
const updatedOrderIds: number[] = []
await db.transaction(async (tx) => {
for (const { order, updatedOrderItems, newTotal } of processedOrdersData) {
for (const { order, updatedOrderItems, newTotal, priceById } of processedOrdersData) {
await tx.update(orders).set({ totalAmount: newTotal.toString() }).where(eq(orders.id, order.id))
updatedOrderIds.push(order.id)
for (const item of updatedOrderItems) {
const price = priceById.get(item.id)
await tx
.update(orderItems)
.set({
price: item.price,
discountedPrice: item.discountedPrice,
price,
discountedPrice: price,
})
.where(eq(orderItems.id, item.id))
}

View file

@ -273,6 +273,22 @@ export async function getAllProducts(regionId: number): Promise<AdminProductWith
}))
}
/**
* The image keys a product's SKUs currently reference. The admin update path re-sends a product's
* existing images on every edit, so this is what tells "already owned" apart from a new upload.
*/
export async function getProductImageKeys(regionId: number, productId: number): Promise<string[]> {
const product = await db.query.productInfo.findFirst({
where: and(eq(productInfo.id, productId), or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))),
columns: { id: true },
with: { skus: { columns: { images: true } } },
})
return (product?.skus ?? []).flatMap((sku) =>
((sku.images as string[] | null) ?? []).map(String)
)
}
export async function getProductById(regionId: number, id: number): Promise<AdminProductWithDetails | null> {
const product = await db.query.productInfo.findFirst({
where: and(eq(productInfo.id, id), or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))),
@ -1195,22 +1211,37 @@ export async function deleteProductGroup(regionId: number, id: number): Promise<
}
export async function updateProductPrices(regionId: number, updates: Array<{
productId: number
skuId: number
price?: number
marketPrice?: number | null
flashPrice?: number | null
isFlashAvailable?: boolean
}>) {
if (updates.length === 0) {
return { updatedCount: 0, invalidIds: [] }
return { updatedCount: 0, invalidIds: [], emptyIds: [] }
}
const productIds = updates.map((update) => update.productId)
// An entry with no price field would "succeed" while writing nothing, so the caller would get a
// false confirmation. Reject the whole batch before anything is written.
const emptyIds = updates
.filter((update) =>
update.price === undefined &&
update.marketPrice === undefined &&
update.flashPrice === undefined &&
update.isFlashAvailable === undefined
)
.map((update) => update.skuId)
if (emptyIds.length > 0) {
return { updatedCount: 0, invalidIds: [], emptyIds }
}
const skuIds = updates.map((update) => update.skuId)
// Validate all SKU IDs exist AND belong to the staff region (in chunks to
// avoid large IN clauses). Out-of-region SKUs are reported as invalid so no
// cross-region existence leaks through this bulk path.
const existingSkuChunks = await runBatched(db, productIds, 10, async (tx, chunk) => {
const existingSkuChunks = await runBatched(db, skuIds, 10, async (tx, chunk) => {
return tx.query.productSkus.findMany({
where: inArray(productSkus.id, chunk),
with: { product: { columns: { regionId: true } } },
@ -1222,16 +1253,17 @@ export async function updateProductPrices(regionId: number, updates: Array<{
.filter((sku: { id: number; product?: { regionId: number | null } | null }) => sku.product?.regionId === regionId)
.map((sku: { id: number }) => sku.id)
)
const invalidIds = productIds.filter((id) => !inRegionIds.has(id))
const invalidIds = skuIds.filter((id) => !inRegionIds.has(id))
if (invalidIds.length > 0) {
return { updatedCount: 0, invalidIds }
return { updatedCount: 0, invalidIds, emptyIds: [] }
}
// Apply updates in chunks inside a single transaction
let updatedCount = 0
await runBatched(db, updates, 10, async (tx, chunk) => {
for (const update of chunk) {
const { productId, price, marketPrice, flashPrice, isFlashAvailable } = update
const { skuId, price, marketPrice, flashPrice, isFlashAvailable } = update
const updateData: any = {}
if (price !== undefined) updateData.ourPrice = price.toString()
@ -1242,7 +1274,7 @@ export async function updateProductPrices(regionId: number, updates: Array<{
if (Object.keys(updateData).length === 0) continue
const existingMarketStats = await tx.query.productMarketStats.findFirst({
where: and(eq(productMarketStats.skuId, productId), eq(productMarketStats.regionId, regionId)),
where: and(eq(productMarketStats.skuId, skuId), eq(productMarketStats.regionId, regionId)),
columns: { id: true },
})
@ -1250,10 +1282,10 @@ export async function updateProductPrices(regionId: number, updates: Array<{
await tx
.update(productMarketStats)
.set(updateData)
.where(and(eq(productMarketStats.skuId, productId), eq(productMarketStats.regionId, regionId)))
.where(and(eq(productMarketStats.skuId, skuId), eq(productMarketStats.regionId, regionId)))
} else {
await tx.insert(productMarketStats).values({
skuId: productId,
skuId,
regionId,
ourPrice: updateData.ourPrice ?? '0',
marketPrice: updateData.marketPrice ?? null,
@ -1261,10 +1293,12 @@ export async function updateProductPrices(regionId: number, updates: Array<{
isFlashAvailable: updateData.isFlashAvailable ?? false,
})
}
updatedCount++
}
})
return { updatedCount: updates.length, invalidIds: [] }
return { updatedCount, invalidIds: [], emptyIds: [] }
}
export async function toggleProductOutOfStock(

View file

@ -112,8 +112,28 @@ export async function getReservedCouponByCode(secretCode: string): Promise<Reser
return reserved || null
}
export async function redeemReservedCoupon(userId: number, reservedCoupon: ReservedCouponRow): Promise<UserCoupon> {
const couponResult = await db.transaction(async (tx) => {
export async function redeemReservedCoupon(userId: number, reservedCoupon: ReservedCouponRow): Promise<UserCoupon | null> {
return db.transaction(async (tx) => {
// Claim the secret before creating anything: the conditional update closes the gap
// between getReservedCouponByCode and this write, so two customers racing on the same
// code can never both receive a coupon. A null return means the race was lost.
const claimed = await tx
.update(reservedCoupons)
.set({
isRedeemed: true,
redeemedBy: userId,
redeemedAt: new Date(),
})
.where(
and(
eq(reservedCoupons.id, reservedCoupon.id),
eq(reservedCoupons.isRedeemed, false)
)
)
.returning({ id: reservedCoupons.id })
if (claimed.length === 0) return null
const [coupon] = await tx.insert(coupons).values({
regionId: reservedCoupon.regionId as number,
couponCode: reservedCoupon.couponCode,
@ -136,14 +156,6 @@ export async function redeemReservedCoupon(userId: number, reservedCoupon: Reser
userId,
})
await tx.update(reservedCoupons).set({
isRedeemed: true,
redeemedBy: userId,
redeemedAt: new Date(),
}).where(eq(reservedCoupons.id, reservedCoupon.id))
return coupon
return mapCoupon(coupon)
})
return mapCoupon(couponResult)
}