From 854fac7f2e0cc00272f4c24698f449ad28dc2200 Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:09:13 +0530 Subject: [PATCH] enh --- .../dashboard/customize-app/index.tsx | 4 +- .../src/routes/dashboard.customize-app.tsx | 4 +- apps/backend/src/lib/const-keys.ts | 6 +- .../apis/common-apis/common-trpc-index.ts | 1 - .../src/trpc/apis/user-apis/apis/auth.ts | 19 +- .../src/trpc/apis/user-apis/apis/order.ts | 47 +- apps/backend/src/trpc/trpc-index.ts | 4 +- apps/backend/tests/BUGS.md | 31 +- apps/backend/tests/api/admin-ops.test.ts | 15 + apps/backend/tests/api/admin-tags.test.ts | 17 + apps/backend/tests/api/coupon-math.test.ts | 43 +- apps/backend/tests/api/coupon-ux.test.ts | 23 +- .../backend/tests/api/misc-procedures.test.ts | 43 +- apps/backend/tests/api/order-rules.test.ts | 24 +- apps/superadmin-ui/src/routes/regions.tsx | 2 - .../components/PaymentAndOrderComponent.tsx | 15 +- apps/user-ui/components/registration-form.tsx | 7 +- apps/user-ui/tests/KNOWN-GAPS.md | 32 +- .../components/payment-and-order.test.tsx | 26 + apps/web-ui/src/hooks/prominent-api-hooks.ts | 1 - change-log.txt | 874 ++++++++++++++++++ packages/db_helper_postgres/src/db/seed.ts | 1 - ...ser_creds_unique_and_min_order_cleanup.sql | 26 + .../src/admin-apis/product.ts | 20 +- .../db_helper_sqlite/src/admin-apis/store.ts | 33 +- packages/db_helper_sqlite/src/db/schema.ts | 4 +- packages/db_helper_sqlite/src/db/seed.sql | 1 - .../db_helper_sqlite/src/lib/const-keys.ts | 7 +- .../src/superadmin-apis/regions.ts | 55 +- .../db_helper_sqlite/src/user-apis/auth.ts | 33 +- .../db_helper_sqlite/src/user-apis/order.ts | 12 + 31 files changed, 1233 insertions(+), 197 deletions(-) create mode 100644 packages/db_helper_sqlite/drizzle/0008_user_creds_unique_and_min_order_cleanup.sql diff --git a/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx b/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx index d66a039..23c585d 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx @@ -18,12 +18,11 @@ const REGION_KEYS = [ 'supportMobile', 'supportEmail', 'welcomeMessage', ] const BOUND_KEYS = [ - 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge', + 'freeDeliveryThreshold', 'deliveryCharge', 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', ] const CONST_LABELS: Record = { - minRegularOrderValue: 'Minimum Regular Order Value', freeDeliveryThreshold: 'Free Delivery Threshold', deliveryCharge: 'Delivery Charge', flashFreeDeliveryThreshold: 'Flash Free Delivery Threshold', @@ -51,7 +50,6 @@ const CONST_LABELS: Record = { type ConstValueType = 'number' | 'boolean' | 'array' | 'string' const KEY_TYPES: Record = { - minRegularOrderValue: 'number', freeDeliveryThreshold: 'number', deliveryCharge: 'number', flashFreeDeliveryThreshold: 'number', diff --git a/apps/admin-web/src/routes/dashboard.customize-app.tsx b/apps/admin-web/src/routes/dashboard.customize-app.tsx index 53e1a0f..04308f1 100644 --- a/apps/admin-web/src/routes/dashboard.customize-app.tsx +++ b/apps/admin-web/src/routes/dashboard.customize-app.tsx @@ -21,12 +21,11 @@ const REGION_KEYS = [ 'supportMobile', 'supportEmail', 'welcomeMessage', ] const BOUND_KEYS = [ - 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge', + 'freeDeliveryThreshold', 'deliveryCharge', 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', ] const CONST_LABELS: Record = { - minRegularOrderValue: 'Minimum Regular Order Value', freeDeliveryThreshold: 'Free Delivery Threshold', deliveryCharge: 'Delivery Charge', flashFreeDeliveryThreshold: 'Flash Free Delivery Threshold', @@ -54,7 +53,6 @@ const CONST_LABELS: Record = { type ConstValueType = 'number' | 'boolean' | 'array' | 'string' const KEY_TYPES: Record = { - minRegularOrderValue: 'number', freeDeliveryThreshold: 'number', deliveryCharge: 'number', flashFreeDeliveryThreshold: 'number', diff --git a/apps/backend/src/lib/const-keys.ts b/apps/backend/src/lib/const-keys.ts index fa0121a..5790e66 100644 --- a/apps/backend/src/lib/const-keys.ts +++ b/apps/backend/src/lib/const-keys.ts @@ -1,7 +1,6 @@ import type { ConstValueType } from '@packages/shared' export const CONST_KEYS = { - minRegularOrderValue: 'minRegularOrderValue', freeDeliveryThreshold: 'freeDeliveryThreshold', deliveryCharge: 'deliveryCharge', flashFreeDeliveryThreshold: 'flashFreeDeliveryThreshold', @@ -28,7 +27,6 @@ export const CONST_KEYS = { } as const; export const CONST_LABELS: Record = { - minRegularOrderValue: 'Minimum Regular Order Value', freeDeliveryThreshold: 'Free Delivery Threshold', deliveryCharge: 'Delivery Charge', flashFreeDeliveryThreshold: 'Flash Free Delivery Threshold', @@ -59,7 +57,6 @@ export type ConstKey = (typeof CONST_KEYS)[keyof typeof CONST_KEYS]; export const CONST_KEYS_ARRAY = Object.values(CONST_KEYS) as ConstKey[]; export const CONST_TYPES: Record = { - minRegularOrderValue: 'number', freeDeliveryThreshold: 'number', deliveryCharge: 'number', flashFreeDeliveryThreshold: 'number', @@ -86,7 +83,6 @@ export const CONST_TYPES: Record = { }; export const CONST_VISIBILITY: Record = { - minRegularOrderValue: true, freeDeliveryThreshold: true, deliveryCharge: true, flashFreeDeliveryThreshold: true, @@ -126,7 +122,7 @@ export const REGION_CONST_KEYS = [ /** Keys stored in the region_bound_consts table (one row per bound). */ export const BOUND_CONST_KEYS = [ - 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge', + 'freeDeliveryThreshold', 'deliveryCharge', 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', ] as const diff --git a/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts b/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts index 0daeca8..a77ecfb 100644 --- a/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts +++ b/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts @@ -91,7 +91,6 @@ export async function scaffoldEssentialConsts(boundId: number) { supportEmail: pickRaw(region['supportEmail'], ''), welcomeMessage: pickRaw(region['welcomeMessage'], ''), // region_bound_consts - minRegularOrderValue: pickNumber(boundConsts['minRegularOrderValue'], 0), freeDeliveryThreshold: pickNumber(boundConsts['freeDeliveryThreshold'], 200), deliveryCharge: pickNumber(boundConsts['deliveryCharge'], 0), flashFreeDeliveryThreshold: pickNumber(boundConsts['flashFreeDeliveryThreshold'], 500), diff --git a/apps/backend/src/trpc/apis/user-apis/apis/auth.ts b/apps/backend/src/trpc/apis/user-apis/apis/auth.ts index 532487c..d4f5ddc 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/auth.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/auth.ts @@ -270,7 +270,9 @@ export const authRouter = router({ updateProfile: protectedProcedure .input(z.object({ name: z.string().min(1).optional(), - email: z.string().email('Invalid email format').optional(), + // Email is optional; an empty string means "no change". The format is + // validated in the handler when a non-empty value is supplied. + email: z.string().optional(), mobile: z.string().min(1).optional(), password: z.string().min(6, 'Password must be at least 6 characters').optional(), bio: z.string().optional().nullable(), @@ -288,9 +290,12 @@ export const authRouter = router({ const { name, email, mobile, password, bio, dateOfBirth, gender, occupation, profileImageUrl } = input - if (email) { + // Empty email means "leave unchanged" (mobile-only accounts have no email). + const cleanEmail = email?.trim() || undefined + + if (cleanEmail) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailRegex.test(email)) { + if (!emailRegex.test(cleanEmail)) { throw new ApiError('Invalid email format', 400); } } @@ -302,8 +307,8 @@ export const authRouter = router({ } } - if (email) { - const existingEmail = await getUserAuthByEmailInDb(email.toLowerCase()) + if (cleanEmail) { + const existingEmail = await getUserAuthByEmailInDb(cleanEmail.toLowerCase()) if (existingEmail && existingEmail.id !== userId) { throw new ApiError('Email already registered', 409) } @@ -324,7 +329,7 @@ export const authRouter = router({ const updatedUser = await updateUserProfileInDb(userId, { name: name?.trim(), - email: email?.toLowerCase().trim(), + email: cleanEmail?.toLowerCase(), mobile: mobile?.replace(/\D/g, ''), hashedPassword, profileImage: profileImageUrl ?? undefined, @@ -339,7 +344,7 @@ export const authRouter = router({ ? await generateSignedUrlFromS3Url(userDetail.profileImage) : null - const authHeader = ctx.req.header('authorization'); + const authHeader = ctx.req.headers.get('authorization'); const token = authHeader?.replace('Bearer ', '') || '' const response: UserAuthResponse = { diff --git a/apps/backend/src/trpc/apis/user-apis/apis/order.ts b/apps/backend/src/trpc/apis/user-apis/apis/order.ts index f82e49e..0dd7632 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts @@ -1,7 +1,6 @@ import { router, protectedProcedure } from "@/src/trpc/trpc-index"; import { z } from "zod"; import { - applyDiscountToUserOrder, cancelUserOrderTransaction, checkUserSuspended, composeUnitNotation, @@ -94,9 +93,9 @@ const placeOrderUtil = async (params: { const parsed = raw == null ? NaN : Number(raw); return Number.isFinite(parsed) ? parsed : 0; }; - const minOrderValue = isFlashDelivery + const freeDeliveryThreshold = isFlashDelivery ? numSetting(CONST_KEYS.flashFreeDeliveryThreshold) - : numSetting(CONST_KEYS.minRegularOrderValue); + : numSetting(CONST_KEYS.freeDeliveryThreshold); const deliveryCharge = isFlashDelivery ? numSetting(CONST_KEYS.flashDeliveryCharge) : numSetting(CONST_KEYS.deliveryCharge); @@ -210,10 +209,30 @@ const placeOrderUtil = async (params: { const appliedCoupon = await validateAndGetUserCoupon(couponId, userId, totalAmount); - const expectedDeliveryCharge = - totalAmount < minOrderValue ? deliveryCharge : 0; + // Mirror the customer app's pricing model: the coupon discounts the whole + // cart subtotal, and delivery is decided on the post-discount total. + let discountAmount = 0; + if (appliedCoupon) { + const maxValue = appliedCoupon.maxValue + ? parseFloat(appliedCoupon.maxValue.toString()) + : 0; - const totalWithDelivery = totalAmount + expectedDeliveryCharge; + if (appliedCoupon.discountPercent) { + const percentDiscount = + (totalAmount * parseFloat(appliedCoupon.discountPercent.toString())) / 100; + discountAmount = Math.min(percentDiscount, maxValue || Infinity); + } else if (appliedCoupon.flatDiscount) { + const flatDiscount = parseFloat(appliedCoupon.flatDiscount.toString()); + discountAmount = Math.min(flatDiscount, maxValue || totalAmount); + } + } + + const finalTotal = totalAmount - discountAmount; + + const expectedDeliveryCharge = + finalTotal < freeDeliveryThreshold ? deliveryCharge : 0; + + const totalWithDelivery = finalTotal + expectedDeliveryCharge; type OrderData = { order: Omit; @@ -236,16 +255,10 @@ const placeOrderUtil = async (params: { }, 0 ); - const subOrderTotalWithDelivery = subOrderTotal + expectedDeliveryCharge; - - const orderGroupProportion = subOrderTotal / totalAmount; - const orderTotalAmount = isFirstOrder ? subOrderTotalWithDelivery : subOrderTotal; - - const { finalOrderTotal: finalOrderAmount } = applyDiscountToUserOrder( - orderTotalAmount, - appliedCoupon, - orderGroupProportion - ); + const orderGroupProportion = totalAmount > 0 ? subOrderTotal / totalAmount : 0; + const orderDiscount = discountAmount * orderGroupProportion; + const orderDelivery = isFirstOrder ? expectedDeliveryCharge : 0; + const finalOrderAmount = subOrderTotal - orderDiscount + orderDelivery; const order: Omit = { userId, @@ -256,7 +269,7 @@ const placeOrderUtil = async (params: { isOnlinePayment: paymentMethod === "online", paymentInfoId: null, totalAmount: finalOrderAmount.toString(), - deliveryCharge: isFirstOrder ? expectedDeliveryCharge.toString() : "0", + deliveryCharge: orderDelivery.toString(), readableId: -1, userNotes: userNotes || null, orderGroupId, diff --git a/apps/backend/src/trpc/trpc-index.ts b/apps/backend/src/trpc/trpc-index.ts index 09d16f0..aa591ec 100644 --- a/apps/backend/src/trpc/trpc-index.ts +++ b/apps/backend/src/trpc/trpc-index.ts @@ -2,7 +2,9 @@ import { initTRPC, TRPCError } from '@trpc/server'; import type { Context as HonoContext } from 'hono'; export interface Context { - req: HonoContext['req']; + // The tRPC fetch adapter (@hono/trpc-server) passes the raw fetch Request as + // `req` (see app.ts createContext), not Hono's HonoRequest. + req: Request; c: HonoContext; user?: any; staffUser?: { diff --git a/apps/backend/tests/BUGS.md b/apps/backend/tests/BUGS.md index 70636bb..a31e436 100644 --- a/apps/backend/tests/BUGS.md +++ b/apps/backend/tests/BUGS.md @@ -72,6 +72,11 @@ still receives an error — a silent partial success. **Pinned by:** `tests/api/misc-procedures.test.ts` — "pins: updateProfile crashes after writing the change". +> **Fixed (FC-15/AU-07):** `Context.req` is now typed as the fetch `Request` the +> adapter actually passes, and `updateProfile` reads +> `ctx.req.headers.get('authorization')`. The optional email was also relaxed: +> an empty email means "no change" (the client only requires it when registering). + ### 4. `user.auth.updatePassword` silently does nothing `packages/db_helper_sqlite/src/user-apis/auth.ts:177` (`upsertUserPassword`) @@ -101,6 +106,12 @@ constraint code, or do an explicit select-then-insert/update. **Pinned by:** `tests/api/misc-procedures.test.ts` — "pins: updatePassword reports success but the old password still works". +> **Fixed (FC-16/AU-08):** `upsertUserPassword` now does an explicit +> select-then-update-or-insert (updating every row for the user, which also +> repairs existing duplicates), and a `uniqueIndex` on `user_creds.user_id` was +> added to the schema. Existing duplicate rows must be deduped before the index +> migration can be applied (the local DB has duplicates for users 379, 908, 1311). + --- ## High — money @@ -133,6 +144,12 @@ coupon therefore discounts the delivery fee as well. **Pinned by:** `tests/api/coupon-math.test.ts` — "pins: a percentage coupon discounts the delivery fee too". +> **Fixed (FC-08):** `placeOrderUtil` now computes the coupon discount on the +> whole cart **subtotal** and decides delivery on the **post-discount** total +> (`finalTotal < freeDeliveryThreshold`), mirroring the customer app. A +> percentage coupon no longer touches the delivery fee. (FC-07 is fixed too: the +> threshold key is now `freeDeliveryThreshold`, not `minRegularOrderValue`.) + ### 7. Money is never rounded Nothing rounds `totalAmount`; it is written with `.toString()` on a raw float, so @@ -153,9 +170,15 @@ first-order-only, but **not** `isUserBased`, `applicableUsers`, `skuIds` or filter by applicability, so user B can spend a coupon issued to user A by passing its id to `placeOrder`. -**Pinned by:** `tests/api/coupon-ux.test.ts` — "pins: user B can apply a coupon +**Pinned by:** `tests/api/coupon-ux.test.ts` — "rejects user B applying a coupon 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. + ### 9. Cancelling an order does not release its coupon usage `recordUserCouponUsage` runs at placement; `cancelOrderTransaction` never touches @@ -240,6 +263,12 @@ Two identical `placeOrder` calls create two orders (`orderGroupId` is **Pinned by:** `tests/api/place-order-edge-cases.test.ts`. +> **Mitigated client-side (FC-17/OR-12):** the Place Order button is disabled while a +> submit is in flight and `handlePlaceOrder` early-returns via a synchronous `useRef` +> guard, so an accidental double-tap cannot submit twice. **Server-side idempotency is +> still absent** — a direct API replay or network retry can create duplicates. A +> client-generated idempotency key remains the proper fix if/when wanted. + --- ## Low — error handling / lifecycle diff --git a/apps/backend/tests/api/admin-ops.test.ts b/apps/backend/tests/api/admin-ops.test.ts index 85674c3..4591df0 100644 --- a/apps/backend/tests/api/admin-ops.test.ts +++ b/apps/backend/tests/api/admin-ops.test.ts @@ -96,6 +96,19 @@ describe('admin ops', () => { expect(error).toBeInstanceOf(Error) }) + it('rejects deleting a store that still has products', async () => { + const target = await createStoreWithSku() + + const error = await captureError(() => + admin.admin.store.deleteStore.mutate({ storeId: target.storeId }) + ) + expect(error.message).toMatch(/still has products/i) + + // The store (and its products) are untouched. + const still = await admin.admin.store.getStoreById.query({ id: target.storeId }) + expect(still).toBeTruthy() + }) + it('places two concurrent orders for different slots', async () => { const slotA = await createFutureSlot([skuId], { deliveryInHours: 4, freezeInHours: 3 }) const slotB = await createFutureSlot([skuId], { deliveryInHours: 8, freezeInHours: 7 }) @@ -105,11 +118,13 @@ describe('admin ops', () => { user.user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId: slotA.slotId }], addressId: address.addressId, + regionId: 1, paymentMethod: 'cod', }), user.user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId: slotB.slotId }], addressId: address.addressId, + regionId: 1, paymentMethod: 'cod', }), ]) diff --git a/apps/backend/tests/api/admin-tags.test.ts b/apps/backend/tests/api/admin-tags.test.ts index 5c27961..47de2b8 100644 --- a/apps/backend/tests/api/admin-tags.test.ts +++ b/apps/backend/tests/api/admin-tags.test.ts @@ -3,16 +3,21 @@ */ import { apiClient, uniqueSuffix } from '../helpers/api' +import { createStoreWithSku } from '../helpers/fixtures' import { staffSession } from '../helpers/sessions' describe('admin product tag CRUD', () => { let admin: ReturnType let tagId = 0 let tagName = '' + let skuId = 0 beforeAll(async () => { const staff = await staffSession() admin = apiClient(staff.token) + + const store = await createStoreWithSku() + skuId = store.skuId }) it('creates a tag that getProductTags returns', async () => { @@ -63,4 +68,16 @@ describe('admin product tag CRUD', () => { : ((list as { tags?: { id: number }[] }).tags ?? []) expect(tags.some((t) => t.id === tagId)).toBe(false) }) + + it('deleteProductTag removes a tag that has products', async () => { + const created = await admin.admin.product.createProductTag.mutate({ + tagName: `API Tag w/ product ${uniqueSuffix()}`, + isDashboardTag: true, + productIds: [skuId], + }) + const id = (created as { tag: { id: number } }).tag.id + + const res = await admin.admin.product.deleteProductTag.mutate({ id }) + expect((res as { message?: string }).message ?? '').toMatch(/deleted/i) + }) }) diff --git a/apps/backend/tests/api/coupon-math.test.ts b/apps/backend/tests/api/coupon-math.test.ts index 5e74de8..7ce24d5 100644 --- a/apps/backend/tests/api/coupon-math.test.ts +++ b/apps/backend/tests/api/coupon-math.test.ts @@ -1,13 +1,15 @@ /** * Coupon discount maths at placeOrder time. * - * The discount is computed server-side in applyDiscountToOrder - * (packages/db_helper_sqlite/src/user-apis/order.ts) and persisted to + * The discount is computed server-side in placeOrderUtil + * (apps/backend/src/trpc/apis/user-apis/apis/order.ts) and persisted to * orders.totalAmount. These tests read the order row returned by placeOrder * (totalAmount is the stored string). * - * KNOWN BUGS are pinned here (negative totals, percentage taken on the - * delivery-inclusive base, no rounding). See tests/BUGS.md. + * The backend mirrors the customer app's model: the coupon discounts the whole + * cart subtotal, and delivery is decided on the post-discount total. Remaining + * KNOWN BUGS are pinned here (negative totals for >=100% coupons, no rounding). + * See tests/BUGS.md. */ import { apiClient, captureError, uniqueSuffix } from '../helpers/api' @@ -38,7 +40,7 @@ describe('coupon discount maths', () => { let roundingSkuId = 0 let roundingSlotId = 0 let deliveryCharge = 0 - let minOrderValue = 0 + let freeDeliveryThreshold = 0 beforeAll(async () => { const staff = await staffSession() @@ -66,11 +68,11 @@ describe('coupon discount maths', () => { roundingSkuId = rounding.skuId roundingSlotId = roundingSlot.slotId deliveryCharge = asNumber(consts.deliveryCharge) - minOrderValue = asNumber(consts.minRegularOrderValue) + freeDeliveryThreshold = asNumber(consts.freeDeliveryThreshold) // The totals below assume these thresholds. - expect(minOrderValue).toBeGreaterThan(UNIT_PRICE) - expect(minOrderValue).toBeLessThan(500) + expect(freeDeliveryThreshold).toBeGreaterThan(UNIT_PRICE) + expect(freeDeliveryThreshold).toBeLessThan(500) }) const createCoupon = async (over: Record = {}) => { @@ -91,6 +93,7 @@ describe('coupon discount maths', () => { apiClient(userToken).user.order.placeOrder.mutate({ selectedItems: items, addressId, + regionId: 1, paymentMethod: 'cod', ...(couponId ? { couponId } : {}), }) as unknown as Promise @@ -102,7 +105,7 @@ describe('coupon discount maths', () => { const res = await place([{ skuId, quantity: 100, slotId }], coupon.id) - // 500 >= minOrderValue -> free delivery; 10% of 500 = 50. + // 500 >= freeDeliveryThreshold -> free delivery; 10% of 500 = 50. expect(total(res)).toBe(450) }) @@ -138,12 +141,14 @@ describe('coupon discount maths', () => { expect(total(res)).toBeLessThan(0) }) - it('pins: a 100% coupon zeroes the order without going negative', async () => { + it('a 100% coupon zeroes the goods but delivery still applies', async () => { const coupon = await createCoupon({ discountPercent: 100 }) const res = await place([{ skuId, quantity: 100, slotId }], coupon.id) - expect(total(res)).toBe(0) + // Goods 500 - 100% = 0; 0 is below the free-delivery threshold, so the + // delivery charge is added on top (matching the customer app). + expect(total(res)).toBe(deliveryCharge) }) it('accepts a cart exactly at the coupon minOrder and rejects below it', async () => { @@ -161,20 +166,14 @@ describe('coupon discount maths', () => { expect(error.message).toMatch(/minimum requirement/i) }) - /** - * KNOWN BUG: the first sub-order of every placeOrder discounts - * `subOrderTotal + deliveryCharge` (the delivery-inclusive total), so a - * percentage coupon also discounts the delivery fee. It should apply to the - * goods subtotal only. - */ - it('pins: a percentage coupon discounts the delivery fee too', async () => { + it('applies a percentage coupon to the goods subtotal only', async () => { const coupon = await createCoupon({ discountPercent: 10 }) - // 1 * 5 = 5 < minOrderValue -> delivery charge applies; first sub-order - // total = 5 + deliveryCharge. + // 1 * 5 = 5; 10% off the goods = 4.5. Delivery is decided on 4.5, which is + // below the free-delivery threshold, so the charge is added on top. const res = await place([{ skuId, quantity: 1, slotId }], coupon.id) - expect(total(res)).toBeCloseTo((UNIT_PRICE + deliveryCharge) * 0.9, 6) + expect(total(res)).toBeCloseTo(UNIT_PRICE * 0.9 + deliveryCharge, 6) }) it('splits a flat discount across slots by orderGroupProportion', async () => { @@ -188,7 +187,7 @@ describe('coupon discount maths', () => { coupon.id ) - // 500 >= minOrderValue -> no delivery, so both sub-orders are the plain + // 500 >= freeDeliveryThreshold -> no delivery, so both sub-orders are the plain // subtotal. Proportions 0.4 / 0.6 -> discounts 8 / 12. const totals = res.data .map((order) => parseFloat(order.totalAmount)) diff --git a/apps/backend/tests/api/coupon-ux.test.ts b/apps/backend/tests/api/coupon-ux.test.ts index 4b7476d..ab14f54 100644 --- a/apps/backend/tests/api/coupon-ux.test.ts +++ b/apps/backend/tests/api/coupon-ux.test.ts @@ -1,8 +1,8 @@ /** * Coupon UX surfaces: reserved-code redemption, getMyCoupons, the admin create - * guards and the user-scoping bypass at placeOrder. + * guards and the user-scoping guard at placeOrder. * - * See tests/BUGS.md for the pinned defects. + * See tests/BUGS.md. */ import { apiClient, captureError, uniqueSuffix } from '../helpers/api' @@ -71,6 +71,7 @@ describe('coupon UX', () => { apiClient(user.token).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity, slotId }], addressId: user.addressId, + regionId: 1, paymentMethod: 'cod', ...(couponId ? { couponId } : {}), }) @@ -228,12 +229,7 @@ describe('coupon UX', () => { }) }) - /** - * KNOWN BUG: placeOrder's validateAndGetCoupon never checks isUserBased / - * applicableUsers, so user B can spend a coupon that was issued to user A. - * Only the display endpoints filter by applicability. See tests/BUGS.md. - */ - it('pins: user B can apply a coupon issued to user A', async () => { + it('rejects user B applying a coupon issued to user A', async () => { const coupon = await createCoupon({ isUserBased: true, isApplyForAll: false, @@ -241,11 +237,12 @@ describe('coupon UX', () => { flatDiscount: 5, }) - // 3 * 100 = 300 >= minOrderValue -> no delivery, so this isolates the - // scoping bypass: 300 - 5 = 295. - const res = await place(userB, coupon.id, 3) + // 3 * 100 = 300 >= threshold -> no delivery, isolating the scope check. + const error = await captureError(() => place(userB, coupon.id, 3)) + expect(error.message).toMatch(/not applicable/i) - expect(res.success).toBe(true) - expect(parseFloat(res.data[0].totalAmount)).toBe(295) + // The intended user can still spend it. + const ok = await place(userA, coupon.id, 3) + expect(ok.success).toBe(true) }) }) diff --git a/apps/backend/tests/api/misc-procedures.test.ts b/apps/backend/tests/api/misc-procedures.test.ts index 1c6a0b2..00f2ae2 100644 --- a/apps/backend/tests/api/misc-procedures.test.ts +++ b/apps/backend/tests/api/misc-procedures.test.ts @@ -14,6 +14,7 @@ import { import { staffSession } from '../helpers/sessions' const addressBody = (over: Record = {}) => ({ + regionId: 1, name: 'API Address', phone: '9999999999', addressLine1: '1 API Street', @@ -68,6 +69,7 @@ describe('misc procedures', () => { await apiClient(user.token).user.order.placeOrder.mutate({ selectedItems: [{ skuId: store.skuId, quantity: 1, slotId: slot.slotId }], addressId: orderAddressId, + regionId: 1, paymentMethod: 'cod', }) @@ -172,22 +174,16 @@ describe('misc procedures', () => { }) describe('user auth', () => { - /** - * KNOWN BUG: updateProfile calls ctx.req.header('authorization') at - * auth.ts:342, but ctx.req is a fetch Request (only .headers.get exists), so - * it throws "ctx.req.header is not a function". The profile IS updated - * first, so the client sees an error after the server changed the data. - */ - it('pins: updateProfile crashes after writing the change', async () => { + it('updates the profile and returns the new name', async () => { const user = await registerUserWithAddress() const newName = `Renamed ${uniqueSuffix()}` - const error = await captureError(() => - apiClient(user.token).user.auth.updateProfile.mutate({ name: newName }) - ) - expect(error.message).toMatch(/ctx\.req\.header is not a function/i) + const res = await apiClient(user.token).user.auth.updateProfile.mutate({ + name: newName, + bio: 'hello bio', + }) + expect(res.success).toBe(true) - // The write landed before the crash. const self = await apiClient(user.token).user.user.getSelfData.query() expect(self.data.user.name).toBe(newName) }) @@ -201,14 +197,7 @@ describe('misc procedures', () => { expect(error).toBeInstanceOf(Error) }) - /** - * KNOWN BUG: user_creds has no UNIQUE(user_id) and upsertUserPassword only - * falls back to UPDATE on the Postgres code 23505, so on D1 the insert - * succeeds and creates a second credentials row. getUserAuthCreds then - * returns the original, so the old password keeps working and the new one - * never does. See tests/BUGS.md. - */ - it('pins: updatePassword reports success but the old password still works', async () => { + it('updatePassword: the new password works and the old one fails', async () => { const suffix = uniqueSuffix() const mobile = `9${String(Math.floor(Math.random() * 1e9)).padStart(9, '0')}` @@ -224,16 +213,16 @@ describe('misc procedures', () => { }) expect(res.success).toBe(true) - // The old password still authenticates... - const oldLogin = await apiClient().user.auth.login.mutate({ + // The new password authenticates... + const newLogin = await apiClient().user.auth.login.mutate({ identifier: mobile, - password: 'OldPass123', + password: 'NewPass456', }) - expect(oldLogin.data.token).toBeTruthy() + expect(newLogin.data.token).toBeTruthy() - // ...and the new one does not. + // ...and the old one no longer does. const error = await captureError(() => - apiClient().user.auth.login.mutate({ identifier: mobile, password: 'NewPass456' }) + apiClient().user.auth.login.mutate({ identifier: mobile, password: 'OldPass123' }) ) expect(error.message).toMatch(/invalid credentials/i) }) @@ -314,7 +303,7 @@ describe('misc procedures', () => { }) it('exposes internalAppVersion to the user app via essentialConsts', async () => { - const consts = (await apiClient().common.essentialConsts.query()) as { + const consts = (await apiClient().common.essentialConsts.query({ boundId: 1 })) as { internalAppVersion?: number } expect(typeof consts.internalAppVersion).toBe('number') diff --git a/apps/backend/tests/api/order-rules.test.ts b/apps/backend/tests/api/order-rules.test.ts index dc9cbc3..b0ac300 100644 --- a/apps/backend/tests/api/order-rules.test.ts +++ b/apps/backend/tests/api/order-rules.test.ts @@ -1,8 +1,8 @@ /** - * Order business rules: delivery charge vs the minimum order value, per-slot + * Order business rules: delivery charge vs the free-delivery threshold, per-slot * grouping, slot capacity and the flash-delivery gate. * - * Uses a tiny-priced SKU (5) so a single unit sits below `minRegularOrderValue`. + * Uses a tiny-priced SKU (5) so a single unit sits below `freeDeliveryThreshold`. */ import { apiClient, captureError } from '../helpers/api' @@ -19,7 +19,7 @@ describe('order rules', () => { let slotId = 0 let secondSlotId = 0 let charge = 0 - let minOrder = 0 + let freeDeliveryThreshold = 0 beforeAll(async () => { const store = await createStoreWithSku({ price: UNIT_PRICE }) @@ -38,28 +38,30 @@ describe('order rules', () => { slotId = slot.slotId secondSlotId = secondSlot.slotId charge = asNumber(consts.deliveryCharge) - minOrder = asNumber(consts.minRegularOrderValue) + freeDeliveryThreshold = asNumber(consts.freeDeliveryThreshold) }) - it('adds the configured delivery charge below the minimum order value', async () => { - // Guard: this case is only meaningful while a single unit is below the minimum. - expect(minOrder).toBeGreaterThan(UNIT_PRICE) + it('adds the configured delivery charge below the free-delivery threshold', async () => { + // Guard: this case is only meaningful while a single unit is below the threshold. + expect(freeDeliveryThreshold).toBeGreaterThan(UNIT_PRICE) const res = await apiClient(token).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, + regionId: 1, paymentMethod: 'cod', }) expect(res.data[0].deliveryCharge).toBe(String(charge)) }) - it('waives the delivery charge at or above the minimum order value', async () => { - const quantity = Math.ceil(minOrder / UNIT_PRICE) + 1 + it('waives the delivery charge at or above the free-delivery threshold', async () => { + const quantity = Math.ceil(freeDeliveryThreshold / UNIT_PRICE) + 1 const res = await apiClient(token).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity, slotId }], addressId, + regionId: 1, paymentMethod: 'cod', }) @@ -73,6 +75,7 @@ describe('order rules', () => { { skuId, quantity: 1, slotId: secondSlotId }, ], addressId, + regionId: 1, paymentMethod: 'cod', }) @@ -97,6 +100,7 @@ describe('order rules', () => { apiClient(token).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, + regionId: 1, paymentMethod: 'cod', }) ) @@ -119,6 +123,7 @@ describe('order rules', () => { apiClient(token).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId: null }], addressId, + regionId: 1, paymentMethod: 'cod', isFlashDelivery: true, }) @@ -134,6 +139,7 @@ describe('order rules', () => { apiClient(token).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 0, slotId }], addressId, + regionId: 1, paymentMethod: 'cod', }) ) diff --git a/apps/superadmin-ui/src/routes/regions.tsx b/apps/superadmin-ui/src/routes/regions.tsx index 6602d8a..2cef2d2 100644 --- a/apps/superadmin-ui/src/routes/regions.tsx +++ b/apps/superadmin-ui/src/routes/regions.tsx @@ -17,7 +17,6 @@ export const Route = createFileRoute('/regions')({ // Per-bound business keys (region_bound_consts). const SETTING_KEYS = [ - 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge', 'flashFreeDeliveryThreshold', @@ -37,7 +36,6 @@ const REGION_SETTING_KEYS = [ ] as const const SETTING_LABELS: Record = { - minRegularOrderValue: 'Minimum Regular Order Value', freeDeliveryThreshold: 'Free Delivery Threshold', deliveryCharge: 'Delivery Charge', flashFreeDeliveryThreshold: 'Flash Free Delivery Threshold', diff --git a/apps/user-ui/components/PaymentAndOrderComponent.tsx b/apps/user-ui/components/PaymentAndOrderComponent.tsx index a8435d5..04220f3 100644 --- a/apps/user-ui/components/PaymentAndOrderComponent.tsx +++ b/apps/user-ui/components/PaymentAndOrderComponent.tsx @@ -1,4 +1,4 @@ -import React, { useState, useMemo } from 'react'; +import React, { useState, useMemo, useRef } from 'react'; import { View, Alert, Platform } from 'react-native'; import { useRouter } from 'expo-router'; import { tw, LoadingDialog, MyText, MyTouchableOpacity } from 'common-ui'; @@ -50,6 +50,9 @@ const PaymentAndOrderComponent: React.FC = ({ const queryClient = useQueryClient(); const utils = trpc.useUtils(); const [isLoadingDialogOpen, setIsLoadingDialogOpen] = useState(false); + // Synchronous re-entrancy guard so a double-tap can't fire placeOrder twice + // (state-based isPending updates only after a re-render). + const submittingRef = useRef(false); const [paymentMethod, setPaymentMethod] = useState<'online' | 'cod'>('cod'); const userNotes = useCheckoutStore((state) => state.userNotes); @@ -104,6 +107,7 @@ const PaymentAndOrderComponent: React.FC = ({ Alert.alert('Error', message); }, onSettled: () => { + submittingRef.current = false; setIsLoadingDialogOpen(false); }, }); @@ -129,6 +133,9 @@ const PaymentAndOrderComponent: React.FC = ({ const handlePlaceOrder = () => { + // Ignore re-entrant presses while a submit is already in flight. + if (submittingRef.current || placeOrderMutation.isPending) return; + if (!selectedAddress) { Alert.alert('Error', 'Please select an address'); return; @@ -156,9 +163,9 @@ const PaymentAndOrderComponent: React.FC = ({ return; } + submittingRef.current = true; setIsLoadingDialogOpen(true); - const orderData = { selectedItems: availableItems.map(itemId => { const item = cartItems.find(cartItem => cartItem.id === itemId); @@ -354,8 +361,8 @@ const PaymentAndOrderComponent: React.FC = ({ diff --git a/apps/user-ui/components/registration-form.tsx b/apps/user-ui/components/registration-form.tsx index edda2b9..533622c 100644 --- a/apps/user-ui/components/registration-form.tsx +++ b/apps/user-ui/components/registration-form.tsx @@ -93,8 +93,9 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit = return; } - // Validate email - if (!data.email.trim()) { + // Email is required when registering; optional when editing (mobile-only + // accounts have no email). + if (!isEdit && !data.email.trim()) { setError("email", { type: "manual", message: "Email is required", @@ -102,7 +103,7 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit = return; } - if (!validateEmail(data.email)) { + if (data.email.trim() && !validateEmail(data.email)) { setError("email", { type: "manual", message: "Please enter a valid email address", diff --git a/apps/user-ui/tests/KNOWN-GAPS.md b/apps/user-ui/tests/KNOWN-GAPS.md index 0d7c4ce..594ef10 100644 --- a/apps/user-ui/tests/KNOWN-GAPS.md +++ b/apps/user-ui/tests/KNOWN-GAPS.md @@ -48,26 +48,22 @@ when getSelfData fails but leaves the stale token in storage". return finalTotal < threshold ? charge : 0 // finalTotal is POST-discount ``` -The backend waives delivery from the **pre-discount** total and from a different -constant (`minRegularOrderValue` vs the client's `freeDeliveryThreshold`). A -coupon that drops the total under the threshold re-adds the delivery fee, so: +**Resolved (2026-10-10):** the backend now uses this exact model — discount the +cart subtotal, then `finalTotal < freeDeliveryThreshold` — so the client and the +persisted order agree. Previously the backend waived delivery from the +**pre-discount** total and from a different constant (`minRegularOrderValue` vs +the client's `freeDeliveryThreshold`), which is what produced the mismatch. +`minRegularOrderValue` has been removed entirely. -* the coupon is worth less than its label says, and -* the payable amount can **rise** above the un-couponed one. +Note the post-discount rule is now the single, intended behaviour on both sides: +a coupon that drops the total under the threshold re-adds the delivery fee, so a +small coupon can still make the payable amount rise above the un-couponed total. +That is by design (it matches the cart), not a client/backend divergence. -Concretely: cart of ₹260 → free delivery → pay ₹260. Apply a ₹20 coupon → -₹240 < ₹249 → delivery re-added → pay ₹255. The user paid ₹5 more to use a -coupon advertised as "save ₹20". - -**Fix:** evaluate the threshold against the pre-discount total and align the -constant with the backend's. - -**Pinned by:** `tests/screens/cart-money.test.tsx` is silent on the coupon case -(`cart-coupons.test.tsx` owns that), and -`tests/screens/cart-coupons.test.tsx` — "re-adds the delivery fee when the -discount drops the total below the threshold" (the same behaviour is asserted on -the checkout side by `tests/screens/checkout-coupons.test.tsx` — "charges -delivery again when the discount drops the total below the threshold"). +**Pinned by:** `tests/screens/cart-coupons.test.tsx` — "re-adds the delivery fee +when the discount drops the total below the threshold" (the same behaviour is +asserted on the checkout side by `tests/screens/checkout-coupons.test.tsx` — +"charges delivery again when the discount drops the total below the threshold"). --- diff --git a/apps/user-ui/tests/components/payment-and-order.test.tsx b/apps/user-ui/tests/components/payment-and-order.test.tsx index f5bf576..eb0dee0 100644 --- a/apps/user-ui/tests/components/payment-and-order.test.tsx +++ b/apps/user-ui/tests/components/payment-and-order.test.tsx @@ -166,4 +166,30 @@ describe('PaymentAndOrderComponent', () => { expect(Alert.alert).toHaveBeenCalledWith('Error', expect.any(String)) ) }) + + it('ignores a second press while the order is in flight', async () => { + let resolveOrder: (value: unknown) => void = () => {} + const api = setupApiMocks({ + procedures: { + 'user.order.placeOrder': () => + new Promise((resolve) => { + resolveOrder = resolve + }), + }, + }) + + renderWithProviders(, { + centralStores: false, + }) + + const button = screen.getByTestId('place-order-button') + fireEvent.press(button) + fireEvent.press(button) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder')) + // The double-tap must not submit twice. + expectProcedureCalled(api.fetchMock, 'user.order.placeOrder', { times: 1 }) + + resolveOrder(PLACE_ORDER_OK) + }) }) diff --git a/apps/web-ui/src/hooks/prominent-api-hooks.ts b/apps/web-ui/src/hooks/prominent-api-hooks.ts index c349cb7..fc88b20 100644 --- a/apps/web-ui/src/hooks/prominent-api-hooks.ts +++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts @@ -66,7 +66,6 @@ export function useRegionalConsts() { freeDeliveryThreshold: pickNumber('freeDeliveryThreshold', (data as any)?.freeDeliveryThreshold), flashDeliveryCharge: pickNumber('flashDeliveryCharge', (data as any)?.flashDeliveryCharge), flashFreeDeliveryThreshold: pickNumber('flashFreeDeliveryThreshold', (data as any)?.flashFreeDeliveryThreshold), - minRegularOrderValue: pickNumber('minRegularOrderValue', (data as any)?.minRegularOrderValue), } }, [data]) } diff --git a/change-log.txt b/change-log.txt index ffc8e7c..2e0c898 100644 --- a/change-log.txt +++ b/change-log.txt @@ -1356,3 +1356,877 @@ user-ui - All login/setup flows are password-only; OTP/SMS testing explicitly excluded. - Replaced OTP authentication and OTP-created-account cases with password identifier coverage and password-change/re-login coverage, preserving existing case IDs. + +[2026-10-10 01:31:35 +0530] Added docs/e2e-sanity-test-results.md (execution results for the plan). + - Ran high-risk + daily-sanity subset via Maestro (iOS customer/admin apps) and direct + tRPC probes: RG-01/02/03/06/10, SEC-01..05, BL-01/02/03/06, CP-01, AU-01/05, + CT-01/04/08/09, AD-05, OR-01, SL-01, PD-01/02, PAY-01. + - Confirmed 9 defects (D1..D9): customer token can mutate global consts (critical); + cross-region SKU + unassigned/OOS SKU accepted by placeOrder; client/backend + delivery-fee formula divergence (₹200 / ₹20 mismatches); min-order not enforced; + non-atomic region create on D1; 500-instead-of-404; instructions persist post-order. + - No application source changed. Created test-only staff/products/slots/coupon/orders + in the disposable local DB via the app's own admin/superadmin APIs. Removed the + half-created region (id 4) left by the RG-02 bug. + +[2026-10-10 09:25:57 +0530] Continued docs/e2e-sanity-test-results.md — full second pass (~108/133 cases). + - Added results for categories B (auth), C (products), D (discovery), E (slots), + G (addresses), H (bill), I (coupons), J (orders), K (flash), L (vendor/support), + and SEC-06/07/08. Extended the defect list to D1..D19. + - New confirmed defects: D12 deleteProductTag FK failure; D13 deleteStore orphans + products; D14 frozen slot accepted by placeOrder; D15 updatePassword duplicates + user_creds (no effect); D16 updateProfile 500 (ctx.req.header); D17 no order + idempotency; D18 incoherent address region/bound; D19 auth 500 vs 401. + - Restored the disposable DB to baseline after testing (store 1 + 41 products, + region consts, slot membership, product flags). No source changed. + +[2026-10-10 09:52:53 +0530] Third pass on docs/e2e-sanity-test-results.md (~120/133 cases). + - Ran the remaining API cases (BL-04/05, CP-02/07/08, PD-07/10/11, DS-05/07, FL-04) + and UI cases (AU-02 cart-survives-login, AU-06 logout, AU-07 edit-profile, CT-03/06/07/10, + DS-08 search) plus simulator GPS cases (RG-04, RG-08). + - New defect D20: the cart does not reflect an out-of-stock item (stays orderable). + - Notes: region B bound has an empty polygon (GPS can never resolve to B); logout does + not clear the local cart; first-order/SKU/user/region coupon restrictions partly missing. + - Restored flash=false, removed extra slots/fixtures. No application source changed. + +[2026-10-10 09:58:00 +0530] Added docs/e2e-sanity-failed-cases.md (detailed failure report). + - One section per FAIL case (FC-01..FC-20): symptom, repro steps, expected vs actual, + evidence (order/entity ids), root cause with file/function, and suggested fix. + - Cross-linked from docs/e2e-sanity-test-results.md. No application source changed. + +[2026-10-10 10:05:00 +0530] Added docs/maestro-mcp-agent-guidelines.md (field guide for future agents). + - Environment map, golden rules, working Maestro run patterns, iOS/web gotchas + (hideKeyboard, masked secure fields, eraseText/pasteText, deep-link alert, + screenshots/inspect_screen, permissions, simctl location), tRPC wire format, + cache/versioning, fixtures, verified recipes, false-positive list, run checklist. + - No application source changed. + +[2026-10-10 10:26:19 +0530] .gitignore: ignore generated Expo native iOS projects (prebuild/CocoaPods output). + - These are created by `expo run:ios` (Podfile, Podfile.lock, Pods/, xcodeproj, build/) + and are build artifacts, not source; matches the existing apps/*/android/ rules. + + --- a/.gitignore + +++ b/.gitignore + @@ + apps/user-ui/android/ + apps/admin-ui/android/ + +apps/user-ui/ios/ + +apps/admin-ui/ios/ + .maestro-output/* + +[2026-10-10 10:35:35 +0530] FC-01 (SEC-01): lock down admin.const router; delete dead global/legacy procedures. + - No production UI caller existed (admin apps use admin.region.*; superadmin UI uses + superadmin.const.*), so the four admin global/legacy procedures are removed. The two + surviving compat procedures now require a staff token; updateConstants additionally + rejects global-scope keys (globals are superadmin-only). + + --- a/apps/backend/src/trpc/apis/admin-apis/apis/const.ts + +++ b/apps/backend/src/trpc/apis/admin-apis/apis/const.ts + @@ + -import { router, protectedProcedure } from '@/src/trpc/trpc-index' + +import { router, staffProcedure } from '@/src/trpc/trpc-index' + import { z } from 'zod'; + +import { TRPCError } from '@trpc/server' + import { computeConstants } from '@/src/lib/const-store' + import { refreshGenKv, refreshGenKvForRegion } from '@/src/lib/gen-store' + import { CONST_SCOPE } from '@/src/lib/const-keys' + import { scheduleStoreInitialization } from '@/src/stores/store-initializer' + import { + getAllConstants as getAllConstantsFromDb, + upsertConstants as upsertConstantsInDb, + - getAllGlobalConsts, + - upsertGlobalConsts, + - getLegacyConsts, + - upsertLegacyConsts, + } from '@/src/dbService' + @@ + -const toRows = (constants: Constant[]) => + - constants.map((c) => ({ key: c.key, value: c.value == null ? null : String(c.value) })) + - + export const constRouter = router({ + // Backward-compat: merged global + legacy view. Writes route by key scope. + - getConstants: protectedProcedure + + getConstants: staffProcedure + .query(async (): Promise => { + return getAllConstantsFromDb(); + }), + + - updateConstants: protectedProcedure + + updateConstants: staffProcedure + .input(constantsInput) + .mutation(async ({ input, ctx }): Promise => { + const { constants } = input; + + const invalidKeys = constants + .filter(c => !CONST_SCOPE[c.key]) + .map(c => c.key); + + if (invalidKeys.length > 0) { + throw new Error(`Invalid constant keys: ${invalidKeys.join(', ')}`); + } + + + // Global constants (versionNum, playStoreUrl, …) are superadmin-only and are + + // managed via superadmin.const.*. Never let a region staff token write them + + // through the merged route. + + const globalKeys = constants + + .filter((c) => CONST_SCOPE[c.key] === 'global') + + .map((c) => c.key) + + + + if (globalKeys.length > 0) { + + throw new TRPCError({ + + code: 'FORBIDDEN', + + message: `Global constants are superadmin-only: ${globalKeys.join(', ')}`, + + }) + + } + + + const regionId = ctx.staffUser?.regionId ?? null + await upsertConstantsInDb(constants, regionId ?? undefined) + ... + }), + - + - // Global consts (global_consts table). + - getGlobalConstants: protectedProcedure + - .query(async (): Promise => { + - const values = await getAllGlobalConsts() + - return Object.entries(values).map(([key, value]) => ({ key, value })) + - }), + - + - updateGlobalConstants: protectedProcedure + - .input(constantsInput) + - .mutation(async ({ input }): Promise => { + - await upsertGlobalConsts(toRows(input.constants)) + - await computeConstants() + - await refreshGenKv() + - return { + - success: true, + - updatedCount: input.constants.length, + - keys: input.constants.map(c => c.key), + - } + - }), + - + - // Legacy leftovers (key_val_store table). + - getLegacyConstants: protectedProcedure + - .query(async (): Promise => { + - const values = await getLegacyConsts() + - return Object.entries(values).map(([key, value]) => ({ key, value })) + - }), + - + - updateLegacyConstants: protectedProcedure + - .input(constantsInput) + - .mutation(async ({ input }): Promise => { + - await upsertLegacyConsts(toRows(input.constants)) + - await computeConstants() + - if (input.constants.some((c) => CACHE_AFFECTING_KEYS.includes(c.key))) { + - await scheduleStoreInitialization() + - } + - return { + - success: true, + - updatedCount: input.constants.length, + - keys: input.constants.map(c => c.key), + - } + - }), + }); + + --- a/apps/backend/tests/api/authorization-matrix.test.ts + +++ b/apps/backend/tests/api/authorization-matrix.test.ts + @@ + - it('pins: a user token CAN change config via admin.const.updateConstants', async () => { + - const before = await getConstants() + - const original = before.minOrderAmountForCoupon + - + - try { + - await apiClient(userToken).admin.const.updateConstants.mutate({ + - constants: [{ key: 'minOrderAmountForCoupon', value: 4321 }], + - }) + - expect(asNumber((await getConstants()).minOrderAmountForCoupon)).toBe(4321) + - } finally { + - if (original !== undefined) await setConst('minOrderAmountForCoupon', original) + - } + - }) + - + // ...moved to the "staff-guarded admin procedures" block, inverted: + + it('rejects a user token on admin.const.updateConstants', async () => { + + const error = await captureError(() => + + apiClient(userToken).admin.const.updateConstants.mutate({ + + constants: [{ key: 'minOrderAmountForCoupon', value: 4321 }], + + }) + + ) + + expect(error.message).toMatch(/UNAUTHORIZED|unauthorized/i) + + }) + + + + it('rejects a staff token writing a global constant via admin.const.updateConstants', async () => { + + const staff = await staffSession() + + const error = await captureError(() => + + apiClient(staff.token).admin.const.updateConstants.mutate({ + + constants: [{ key: 'versionNum', value: '9.9.9' }], + + }) + + ) + + expect(error.message).toMatch(/superadmin-only/i) + + }) + - it('rejects a user token on admin.coupon.create', async () => { ... }) [kept] + (also drops now-unused imports asNumber/getConstants/setConst if no longer referenced) + + Docs (no code): apps/backend/tests/BUGS.md entry #1 (drop admin.const.updateConstants from + the reachable list); docs/e2e-sanity-failed-cases.md FC-01 + docs/e2e-sanity-test-results.md D1 + marked fixed. No migrations run. No tests run. + +[2026-10-10 10:45:42 +0530] FC-02/FC-03/FC-13: validate order items and slots in placeOrderUtil. + - New helper getDeliverySlotById (raw slot row) in user-apis/slots.ts, exported as + getUserDeliverySlotById. placeOrderUtil now: + * per item: product region must equal the order region (409); product must not be + isDeleted / isOutOfStock / isSuspended (400). + * per slot (scheduled only): slotId must be non-null; slot must exist, belong to the + region (409), be isActive, have freezeTime > now and deliveryTime > now, and carry + every ordered skuId in slot.skuIds (400). + Covers FC-02 (cross-region SKU), FC-03 (unassigned/OOS) and FC-13 (frozen slot). + - No schema/migration changes. + + --- a/packages/db_helper_sqlite/src/user-apis/slots.ts + +++ b/packages/db_helper_sqlite/src/user-apis/slots.ts + @@ + export async function getActiveSlotsList(regionId: number): Promise { + + + +export async function getDeliverySlotById(slotId: number): Promise { + + const slot = await db.query.deliverySlotInfo.findFirst({ + + where: eq(deliverySlotInfo.id, slotId), + + }) + + return slot ?? null + +} + + --- a/packages/db_helper_sqlite/index.ts + +++ b/packages/db_helper_sqlite/index.ts + @@ + export { + // User Slots + getActiveSlotsList as getUserActiveSlotsList, + getProductAvailability as getUserProductAvailability, + + getDeliverySlotById as getUserDeliverySlotById, + } from './src/user-apis/slots' + + --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts + +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts + @@ + import { + ... + getUserSlotCapacityStatus, + + getUserDeliverySlotById, + ... + } from "@/src/dbService"; + @@ + for (const item of selectedItems) { + const product = await getOrderProductById(item.skuId); + if (!product) { + throw new ApiError(`Product ${item.skuId} not found`, 400); + } + + + + // SEC-04: the SKU must belong to the region being ordered into. + + if ((product.product?.regionId ?? null) !== params.regionId) { + + throw new ApiError(`Product ${item.skuId} is not available in this region`, 409); + + } + + + + // SEC-05: never sell a deleted, out-of-stock or suspended product. + + if (product.isDeleted || product.isOutOfStock || product.marketStats?.isSuspended) { + + throw new ApiError(`Product ${item.skuId} is unavailable`, 400); + + } + + + if (!ordersBySlot.has(item.slotId)) { ... } + } + @@ + if (params.isFlash) { ... } + + + +// SEC-05 / SL-04: validate every scheduled slot (existence, region, state, + +// freeze/delivery time) and that it carries the ordered SKUs. + +if (!params.isFlash) { + + for (const [slotId, items] of ordersBySlot) { + + if (slotId == null) throw new ApiError("A delivery slot is required for scheduled orders", 400); + + const slot = await getUserDeliverySlotById(slotId); + + if (!slot) throw new ApiError("Selected delivery slot not found", 400); + + if (slot.regionId !== params.regionId) + + throw new ApiError("Selected delivery slot belongs to a different region", 409); + + if (!slot.isActive) throw new ApiError("Selected delivery slot is not available", 400); + + const now = Date.now(); + + if (slot.freezeTime.getTime() <= now) + + throw new ApiError("Selected delivery slot is closed for orders", 400); + + if (slot.deliveryTime.getTime() <= now) + + throw new ApiError("Selected delivery slot has already passed", 400); + + const slotSkuIds = new Set(slot.skuIds ?? []); + + for (const item of items) { + + if (!slotSkuIds.has(item.skuId)) + + throw new ApiError(`Product ${item.skuId} is not available in the selected delivery slot`, 400); + + } + + } + +} + + --- a/apps/backend/tests/api/place-order-edge-cases.test.ts + +++ b/apps/backend/tests/api/place-order-edge-cases.test.ts + @@ + - const place = (over) => apiClient(userToken).user.order.placeOrder.mutate({ + - selectedItems: [{ skuId, quantity: 1, slotId }], addressId, paymentMethod: 'cod', ...over }) + + const place = (over) => apiClient(userToken).user.order.placeOrder.mutate({ + + selectedItems: [{ skuId, quantity: 1, slotId }], addressId, regionId: 1, + + paymentMethod: 'cod', ...over }) + @@ + - it('pins: an out-of-stock product is still orderable', ... expect(res.success).toBe(true) + + it('rejects an out-of-stock product', ... expect(error.message).toMatch(/unavailable/i) + - it('pins: an inactive slot is accepted', ... expect(res.success).toBe(true) + + it('rejects an inactive slot', ... expect(error.message).toMatch(/not available/i) + - it('pins: a slot whose delivery time has passed is accepted', ... + + it('rejects a slot whose delivery time has passed', ... + - it('pins: a slot that does not carry the ordered SKU is accepted', ... + + it('rejects a slot that does not carry the ordered SKU', ... /not available in the selected/i) + + Docs (no code): apps/backend/tests/BUGS.md #13/#16; docs/e2e-sanity-failed-cases.md + FC-02/FC-03/FC-13 + docs/e2e-sanity-test-results.md SEC-04/SEC-05/SL-04/D2/D3/D14. + No migrations run. No tests run. + +[2026-10-10 10:52:10 +0530] Test fixtures: pass the now-required regionId (1) to user.address.createAddress. + - Pre-existing staleness (createAddress requires regionId since the multi-region work); + matches the existing Mahabubnagar/region-1 assumption in these fixtures. + + --- a/apps/backend/tests/helpers/fixtures.ts + +++ b/apps/backend/tests/helpers/fixtures.ts + @@ + const created = await client.user.address.createAddress.mutate({ + + regionId: 1, + name: 'API Test Address', + phone: '9999999999', + addressLine1: '1 API Test Street', + city: 'Mahabubnagar', + state: 'Telangana', + pincode: '509001', + isDefault: true, + }) + (applied to both ensureUserAddress and registerUserWithAddress) + +[2026-10-10 11:24:13 +0530] FC-07/FC-08: backend placeOrder now uses the customer app's pricing model. + - Threshold key: minRegularOrderValue -> freeDeliveryThreshold (flash unchanged). + - Discount computed on the whole cart subtotal (frontend formula: percent + min(subtotal*pct/100, maxValue || Infinity); flat min(flat, maxValue || subtotal)), + then delivery decided on the post-discount total: finalTotal < threshold ? charge : 0. + - Per suborder: discount allocated by subtotal proportion; delivery charge kept on the + first suborder; total = subOrderTotal - orderDiscount + orderDelivery. + - Drops the applyDiscountToUserOrder call (percent coupon no longer discounts delivery). + - No nested ternaries. No schema/migration changes. + + --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts + +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts + @@ + import { + - applyDiscountToUserOrder, + cancelUserOrderTransaction, + ... + } from "@/src/dbService"; + @@ + - const minOrderValue = isFlashDelivery + + const freeDeliveryThreshold = isFlashDelivery + ? numSetting(CONST_KEYS.flashFreeDeliveryThreshold) + - : numSetting(CONST_KEYS.minRegularOrderValue); + + : numSetting(CONST_KEYS.freeDeliveryThreshold); + @@ + const appliedCoupon = await validateAndGetUserCoupon(couponId, userId, totalAmount); + -const expectedDeliveryCharge = totalAmount < minOrderValue ? deliveryCharge : 0; + -const totalWithDelivery = totalAmount + expectedDeliveryCharge; + +let discountAmount = 0; + +if (appliedCoupon) { + + const maxValue = appliedCoupon.maxValue ? parseFloat(appliedCoupon.maxValue.toString()) : 0; + + if (appliedCoupon.discountPercent) { + + const percentDiscount = (totalAmount * parseFloat(appliedCoupon.discountPercent.toString())) / 100; + + discountAmount = Math.min(percentDiscount, maxValue || Infinity); + + } else if (appliedCoupon.flatDiscount) { + + const flat = parseFloat(appliedCoupon.flatDiscount.toString()); + + discountAmount = Math.min(flat, maxValue || totalAmount); + + } + +} + +const finalTotal = totalAmount - discountAmount; + +const expectedDeliveryCharge = finalTotal < freeDeliveryThreshold ? deliveryCharge : 0; + +const totalWithDelivery = finalTotal + expectedDeliveryCharge; + @@ + - const subOrderTotalWithDelivery = subOrderTotal + expectedDeliveryCharge; + - const orderGroupProportion = subOrderTotal / totalAmount; + - const orderTotalAmount = isFirstOrder ? subOrderTotalWithDelivery : subOrderTotal; + - const { finalOrderTotal: finalOrderAmount } = applyDiscountToUserOrder( + - orderTotalAmount, appliedCoupon, orderGroupProportion) + + const orderGroupProportion = totalAmount > 0 ? subOrderTotal / totalAmount : 0; + + const orderDiscount = discountAmount * orderGroupProportion; + + const orderDelivery = isFirstOrder ? expectedDeliveryCharge : 0; + + const finalOrderAmount = subOrderTotal - orderDiscount + orderDelivery; + @@ + - deliveryCharge: isFirstOrder ? expectedDeliveryCharge.toString() : "0", + + deliveryCharge: orderDelivery.toString(), + + --- a/apps/backend/tests/api/coupon-math.test.ts + +++ b/apps/backend/tests/api/coupon-math.test.ts + @@ + apiClient(userToken).user.order.placeOrder.mutate({ + selectedItems: items, + addressId, + + regionId: 1, + paymentMethod: 'cod', + @@ + -it('pins: a percentage coupon discounts the delivery fee too', ... + - expect(total(res)).toBeCloseTo((UNIT_PRICE + deliveryCharge) * 0.9, 6) + +it('applies a percentage coupon to the goods subtotal only', ... + + expect(total(res)).toBeCloseTo(UNIT_PRICE * 0.9 + deliveryCharge, 6) + @@ + -it('pins: a 100% coupon zeroes the order without going negative', ... + - expect(total(res)).toBe(0) + +it('a 100% coupon zeroes the goods but still adds delivery', ... + + expect(total(res)).toBe(deliveryCharge) + (header comment updated; coupon-math is otherwise stale w.r.t. the region/bound refactor) + + Docs (no code): apps/backend/tests/BUGS.md #6 (fixed); docs/e2e-sanity-failed-cases.md + FC-07/FC-08 + docs/e2e-sanity-test-results.md BL-03/BL-06/D4/D5/D10. + No migrations run. No tests run. + +[2026-10-10 11:32:49 +0530] Remove the dead `minRegularOrderValue` bound constant (resolves FC-06). + - It was not enforced as a minimum and no longer used as the delivery threshold. + Removed from both const-key registries, the essential-consts payload, the web-ui + hook, the three admin/superadmin bound editors, the sqlite/postgres seeds, and the + two tests that read it (now use freeDeliveryThreshold). + - NOT touched: applied migration 0006 (still seeds a row) — a future migration should + stop seeding it / delete the orphan region_bound_consts rows; user owns migrations. + + --- a/apps/backend/src/lib/const-keys.ts + +++ b/apps/backend/src/lib/const-keys.ts + @@ CONST_KEYS / CONST_LABELS / CONST_TYPES / CONST_VISIBILITY / BOUND_CONST_KEYS + - minRegularOrderValue: 'minRegularOrderValue', + - minRegularOrderValue: 'Minimum Regular Order Value', + - minRegularOrderValue: 'number', + - minRegularOrderValue: true, + - 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge', + + 'freeDeliveryThreshold', 'deliveryCharge', + + --- a/packages/db_helper_sqlite/src/lib/const-keys.ts + +++ b/packages/db_helper_sqlite/src/lib/const-keys.ts + @@ CONST_KEYS / CONST_LABELS / CONST_TYPES / CONST_VISIBILITY / CONST_DEFAULTS / BOUND_CONST_KEYS + - minRegularOrderValue: 'minRegularOrderValue', + - minRegularOrderValue: 'Minimum Regular Order Value', + - minRegularOrderValue: 'number', + - minRegularOrderValue: true, + - minRegularOrderValue: 300, + - 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge', + + 'freeDeliveryThreshold', 'deliveryCharge', + + --- a/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts + +++ b/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts + @@ + - minRegularOrderValue: pickNumber(boundConsts['minRegularOrderValue'], 0), + freeDeliveryThreshold: pickNumber(boundConsts['freeDeliveryThreshold'], 200), + + --- a/apps/web-ui/src/hooks/prominent-api-hooks.ts + +++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts + @@ + - minRegularOrderValue: pickNumber('minRegularOrderValue', (data as any)?.minRegularOrderValue), + } + + --- a/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx + +++ a/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx + @@ BOUND_KEYS / CONST_LABELS / KEY_TYPES + - 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge', + + 'freeDeliveryThreshold', 'deliveryCharge', + - minRegularOrderValue: 'Minimum Regular Order Value', + - minRegularOrderValue: 'number', + + --- a/apps/admin-web/src/routes/dashboard.customize-app.tsx + +++ b/apps/admin-web/src/routes/dashboard.customize-app.tsx + @@ (same three removals as admin-ui) + + --- a/apps/superadmin-ui/src/routes/regions.tsx + +++ b/apps/superadmin-ui/src/routes/regions.tsx + @@ SETTING_KEYS / SETTING_LABELS + - 'minRegularOrderValue', + - minRegularOrderValue: 'Minimum Regular Order Value', + + --- a/packages/db_helper_sqlite/src/db/seed.sql + +++ b/packages/db_helper_sqlite/src/db/seed.sql + @@ + -INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('minRegularOrderValue', '300'); + + --- a/packages/db_helper_postgres/src/db/seed.ts + +++ b/packages/db_helper_postgres/src/db/seed.ts + @@ + - { key: CONST_KEYS.minRegularOrderValue, value: minOrderValue }, + + --- a/apps/backend/tests/api/order-rules.test.ts + +++ b/apps/backend/tests/api/order-rules.test.ts + @@ + - let minOrder = 0 + + let freeDeliveryThreshold = 0 + - minOrder = asNumber(consts.minRegularOrderValue) + + freeDeliveryThreshold = asNumber(consts.freeDeliveryThreshold) + - expect(minOrder).toBeGreaterThan(UNIT_PRICE) + + expect(freeDeliveryThreshold).toBeGreaterThan(UNIT_PRICE) + - const quantity = Math.ceil(minOrder / UNIT_PRICE) + 1 + + const quantity = Math.ceil(freeDeliveryThreshold / UNIT_PRICE) + 1 + (comments updated) + + --- a/apps/backend/tests/api/coupon-math.test.ts + +++ b/apps/backend/tests/api/coupon-math.test.ts + @@ + - let minOrderValue = 0 + + let freeDeliveryThreshold = 0 + - minOrderValue = asNumber(consts.minRegularOrderValue) + + freeDeliveryThreshold = asNumber(consts.freeDeliveryThreshold) + (assertions/comments updated) + + Docs (no code): docs/e2e-sanity-failed-cases.md FC-06 (resolved by removal); + docs/e2e-sanity-test-results.md BL-02/D6; apps/user-ui/tests/KNOWN-GAPS.md. + No migrations run. No tests run. + +[2026-10-10 11:52:42 +0530] FC-04 (SEC-06): enforce user-based coupon scope at redemption. + - validateAndGetCoupon now loads the coupon's applicableUsers and rejects when the + coupon isUserBased (and not isApplyForAll) and the ordering user is not listed. + - SKU (FC-09) and region (FC-10) scoping deliberately NOT enforced: SKU-specific + coupons are not created today and region-scoped coupons are not wanted; those are + false flags for now. + + --- a/packages/db_helper_sqlite/src/user-apis/order.ts + +++ b/packages/db_helper_sqlite/src/user-apis/order.ts + @@ + const coupon = await db.query.coupons.findFirst({ + where: eq(coupons.id, couponId), + with: { + usages: { where: eq(couponUsage.userId, userId) }, + + applicableUsers: true, + }, + }) + if (!coupon) throw new Error('Invalid coupon') + + + +// User-based coupons are only spendable by their listed users (the display + +// endpoints already hide them from everyone else). + +if (coupon.isUserBased && !coupon.isApplyForAll) { + + const applicableUsers = coupon.applicableUsers ?? [] + + if (!applicableUsers.some((au) => au.userId === userId)) { + + throw new Error('This coupon is not applicable to your account') + + } + +} + + + if (coupon.isInvalidated) throw new Error('Coupon is no longer valid') + + --- a/apps/backend/tests/api/coupon-ux.test.ts + +++ b/apps/backend/tests/api/coupon-ux.test.ts + @@ + apiClient(user.token).user.order.placeOrder.mutate({ + selectedItems: [{ skuId, quantity, slotId }], + addressId: user.addressId, + + regionId: 1, + paymentMethod: 'cod', + @@ + -it('pins: user B can apply a coupon issued to user A', ... expect(total).toBe(295) + +it('rejects a user B applying a coupon issued to user A', ... + + expect(error.message).toMatch(/not applicable/i) + (header comment updated) + + Docs (no code): apps/backend/tests/BUGS.md #8 (fixed); docs/e2e-sanity-failed-cases.md + FC-04 (fixed) + FC-09/FC-10 (false flags); docs/e2e-sanity-test-results.md SEC-06/CP-04/ + CP-05/CP-11 + the matching defect row. + No migrations run. No tests run. + +[2026-10-10 12:03:04 +0530] FC-11/FC-12: stop store-delete orphaning; make tag delete work. + - deleteStore now refuses to delete a store that still has products (plain Error, + 500) and no longer nulls product_info.store_id. + - deleteProductTag now deletes the product_tags junction rows first (transaction), + so the FK no longer blocks deleting a tag that has products. + - No schema/migration changes (no FK cascade added). + + --- a/packages/db_helper_sqlite/src/admin-apis/store.ts + +++ b/packages/db_helper_sqlite/src/admin-apis/store.ts + @@ + -import { eq, inArray, and } from 'drizzle-orm' + +import { eq, inArray, and, sql } from 'drizzle-orm' + @@ + export async function deleteStore(regionId: number, id: number): Promise<{ message: string }> { + const existing = await db.query.storeInfo.findFirst({ + where: and(eq(storeInfo.id, id), eq(storeInfo.regionId, regionId)), + columns: { id: true }, + }) + if (!existing) { + throw new Error('Store not found') + } + - + - return await db.transaction(async (tx) => { + - await tx.update(productInfo).set({ storeId: null }).where(eq(productInfo.storeId, id)) + - const [deletedStore] = await tx.delete(storeInfo).where(eq(storeInfo.id, id)).returning() + - if (!deletedStore) throw new Error('Store not found') + - return { message: 'Store deleted successfully' } + - }) + + + + // A store cannot be deleted while products still reference it — that would + + // orphan them. Reassign or remove the products first. + + const [{ count }] = await db + + .select({ count: sql`count(*)` }) + + .from(productInfo) + + .where(eq(productInfo.storeId, id)) + + if (Number(count) > 0) { + + throw new Error('Cannot delete a store that still has products. Remove or reassign them first.') + + } + + + + await db.delete(storeInfo).where(eq(storeInfo.id, id)) + + + + return { message: 'Store deleted successfully' } + } + + --- a/packages/db_helper_sqlite/src/admin-apis/product.ts + +++ b/packages/db_helper_sqlite/src/admin-apis/product.ts + @@ + export async function deleteProductTag(regionId: number, tagId: number): Promise { + - const [deleted] = await db.delete(productTagInfo) + - .where(and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId))) + - .returning({ id: productTagInfo.id }) + - return !!deleted + + return db.transaction(async (tx) => { + + const tag = await tx.query.productTagInfo.findFirst({ + + where: and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)), + + columns: { id: true }, + + }) + + if (!tag) return false + + + + // Drop the product associations first; the product_tags FK blocks the tag + + // delete otherwise. + + await tx.delete(productTags).where(eq(productTags.tagId, tagId)) + + await tx.delete(productTagInfo) + + .where(and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId))) + + return true + + }) + } + + --- a/apps/backend/tests/api/admin-ops.test.ts + +++ b/apps/backend/tests/api/admin-ops.test.ts + @@ (after "deletes a store") + + it('rejects deleting a store that still has products', async () => { + + const target = await createStoreWithSku() + + const error = await captureError(() => + + admin.admin.store.deleteStore.mutate({ storeId: target.storeId }) + + ) + + expect(error.message).toMatch(/still has products/i) + + }) + + --- a/apps/backend/tests/api/admin-tags.test.ts + +++ b/apps/backend/tests/api/admin-tags.test.ts + @@ + +import { createStoreWithSku } from '../helpers/fixtures' + @@ beforeAll + + const store = await createStoreWithSku() + + skuId = store.skuId + @@ (new test) + + it('deleteProductTag removes a tag that has products', async () => { + + const created = await admin.admin.product.createProductTag.mutate({ + + tagName: `API Tag w/ product ${uniqueSuffix()}`, + + isDashboardTag: true, + + productIds: [skuId], + + }) + + const id = (created as { tag: { id: number } }).tag.id + + const res = await admin.admin.product.deleteProductTag.mutate({ id }) + + expect((res as { message?: string }).message ?? '').toMatch(/deleted/i) + + }) + + Docs (no code): docs/e2e-sanity-failed-cases.md FC-11/FC-12 + docs/e2e-sanity-test-results.md + PD-13/DS-02/D12/D13. + No migrations run. No tests run. + +[2026-10-10 12:35:14 +0530] FC-14 (CT-07) closed as a false flag (docs only, no source). + - Reproduced on the simulator: cart held sku 155; toggleOutOfStock{id:155} bumped availability + av-17 -> av-18 (published av-18 shows isOutOfStock:true); relaunch + open cart showed the line + normally, then ~70 s later (the app's essentialConsts refetchInterval of 60 s) it correctly + rendered "Out of Stock". The cart already flags/filters/blocks OOS; the E2E observed the + pre-propagation window. Report's root cause was inaccurate. + - docs/e2e-sanity-failed-cases.md FC-14 + summary row + fix-order line; + docs/e2e-sanity-test-results.md CT-07 + D20. Stock restored; no source changed. + +[2026-10-10 12:41:56 +0530] FC-15 (AU-07) + FC-16 (AU-08): fix profile update and password change. + FC-15: + - Context.req is the tRPC fetch adapter's Request (not HonoRequest); corrected the + type in trpc-index.ts and switched auth.ts to ctx.req.headers.get('authorization'). + - Relaxed the optional email: the backend now treats an empty email as "no change" + (zod no longer forces .email() on ''), and the client form only requires email in + registration mode, not edit. + FC-16: + - upsertUserPassword now does an explicit select-then-update-or-insert (updates ALL + rows for the user, repairing existing duplicates) instead of relying on Postgres + error 23505. + - Added a unique index on user_creds.user_id in the schema (migration handled by the + user; existing duplicate rows must be deduped before the index can be created). + + --- a/apps/backend/src/trpc/trpc-index.ts + +++ b/apps/backend/src/trpc/trpc-index.ts + @@ + - req: HonoContext['req']; + + req: Request; + + --- a/apps/backend/src/trpc/apis/user-apis/apis/auth.ts + +++ b/apps/backend/src/trpc/apis/user-apis/apis/auth.ts + @@ + - email: z.string().email('Invalid email format').optional(), + + email: z.string().optional(), + @@ + - if (email) { ... regex ... } + + const cleanEmail = email?.trim() || undefined + + if (cleanEmail) { ... regex ... } + @@ + - email: email?.toLowerCase().trim(), + + email: cleanEmail?.toLowerCase(), + @@ + - const authHeader = ctx.req.header('authorization'); + + const authHeader = ctx.req.headers.get('authorization'); + + --- a/apps/user-ui/components/registration-form.tsx + +++ a/apps/user-ui/components/registration-form.tsx + @@ + - // Validate email + - if (!data.email.trim()) { setError("email", { message: "Email is required" }); return; } + - if (!validateEmail(data.email)) { ... } + + // Email is required on registration only; optional when editing. + + if (!isEdit && !data.email.trim()) { setError("email", { message: "Email is required" }); return; } + + if (data.email.trim() && !validateEmail(data.email)) { ... } + + --- a/packages/db_helper_sqlite/src/user-apis/auth.ts + +++ b/packages/db_helper_sqlite/src/user-apis/auth.ts + @@ + -export async function upsertUserPassword(userId, hashedPassword) { + - try { await db.insert(userCreds).values({ userId, userPassword: hashedPassword }); return } + - catch (error) { if (error.code === '23505') { await db.update(...).where(eq(userCreds.userId, userId)); return } throw error } + -} + +export async function upsertUserPassword(userId, hashedPassword) { + + const existing = await db.select({ id: userCreds.id }).from(userCreds) + + .where(eq(userCreds.userId, userId)).limit(1) + + if (existing.length > 0) { + + await db.update(userCreds).set({ userPassword: hashedPassword }).where(eq(userCreds.userId, userId)) + + } else { + + await db.insert(userCreds).values({ userId, userPassword: hashedPassword }) + + } + +} + + --- a/packages/db_helper_sqlite/src/db/schema.ts + +++ b/packages/db_helper_sqlite/src/db/schema.ts + @@ userCreds + -export const userCreds = sqliteTable('user_creds', { ... }) + +export const userCreds = sqliteTable('user_creds', { ... }, (t) => ({ + + unq_user_creds_user: uniqueIndex('unique_user_creds_user').on(t.userId), + +})) + + --- a/apps/backend/tests/api/misc-procedures.test.ts + +++ a/apps/backend/tests/api/misc-procedures.test.ts + @@ + -it('pins: updateProfile crashes after writing the change', ... expect(error).toMatch(/ctx.req.header is not a function/) + +it('updates the profile and returns the new name', ... expect(res.success).toBe(true); getSelfData reflects it + -it('pins: updatePassword reports success but the old password still works', ...) + +it('updatePassword: new password works and the old one fails', ...) + + Docs (no code): apps/backend/tests/BUGS.md #3/#4; docs/e2e-sanity-failed-cases.md + FC-15/FC-16; docs/e2e-sanity-test-results.md AU-07/AU-08 + D15/D16. + No migrations run. No tests run. + +[2026-10-10 12:50:42 +0530] Added hand-written migration 0008_user_creds_unique.sql. + - Collapses existing duplicate user_creds rows (keep MAX(id) per user) and creates + the unique index on user_creds(user_id) matching the schema declaration. + Required because CREATE UNIQUE INDEX fails while duplicates exist (users 379, 908, 1311). + - Not run (user applies migrations). No journal/meta edit; SQL-only as requested. + + --- a/packages/db_helper_sqlite/drizzle/0008_user_creds_unique.sql + +++ b/packages/db_helper_sqlite/drizzle/0008_user_creds_unique.sql + @@ + +-- Migration: enforce one credentials row per user. + +-- ... + +DELETE FROM `user_creds` + +WHERE `id` NOT IN (SELECT MAX(`id`) FROM `user_creds` GROUP BY `user_id`); + +--> statement-breakpoint + +CREATE UNIQUE INDEX `unique_user_creds_user` ON `user_creds` (`user_id`); + +[2026-10-10 12:53:21 +0530] Added migration 0009_remove_min_regular_order_value.sql. + - minRegularOrderValue was removed from the app earlier this session, leaving orphan + region_bound_consts rows (4) and a legacy key_val_store row. This migration deletes + them; it runs after 0006 (which seeds the bound rows), so fresh installs are cleaned too. + - Not run (user applies migrations). SQL-only. + + --- a/packages/db_helper_sqlite/drizzle/0009_remove_min_regular_order_value.sql + +++ b/packages/db_helper_sqlite/drizzle/0009_remove_min_regular_order_value.sql + @@ + +DELETE FROM `region_bound_consts` WHERE `key` = 'minRegularOrderValue'; + +--> statement-breakpoint + +DELETE FROM `key_val_store` WHERE `key` = 'minRegularOrderValue'; + +[2026-10-10 12:54:31 +0530] Merged 0008 + 0009 into one migration file (applied as a single go). + - Removed 0008_user_creds_unique.sql and 0009_remove_min_regular_order_value.sql. + - Added 0008_user_creds_unique_and_min_order_cleanup.sql containing both the + user_creds dedupe + unique index and the minRegularOrderValue row cleanup. + - Not run (user applies migrations). SQL-only. + +[2026-10-10 12:58:04 +0530] FC-17 (OR-12): client-side double-submit guard (server idempotency deferred). + - PaymentAndOrderComponent: handlePlaceOrder now early-returns while a submit is in + flight (a synchronous useRef guard + placeOrderMutation.isPending), and the Place + Order button is disabled while pending. Stops accidental double-taps; the server + still has no idempotency key, so API replays/network retries are not covered. + - Added a test asserting a second press while in flight does not re-call placeOrder. + + --- a/apps/user-ui/components/PaymentAndOrderComponent.tsx + +++ a/apps/user-ui/components/PaymentAndOrderComponent.tsx + @@ + -import React, { useState, useMemo } from 'react'; + +import React, { useState, useMemo, useRef } from 'react'; + @@ + + const submittingRef = useRef(false); + @@ onSettled + - setIsLoadingDialogOpen(false); + + submittingRef.current = false; + + setIsLoadingDialogOpen(false); + @@ + const handlePlaceOrder = () => { + + if (submittingRef.current || placeOrderMutation.isPending) return; + + submittingRef.current = true; + if (!selectedAddress) { ... } + @@ button + - disabled={!selectedAddress} + + disabled={!selectedAddress || placeOrderMutation.isPending} + (opacity also keyed on the same condition) + + --- a/apps/user-ui/tests/components/payment-and-order.test.tsx + +++ a/apps/user-ui/tests/components/payment-and-order.test.tsx + @@ + + it('ignores a second press while the order is in flight', async () => { ... procCount === 1 }) + + Docs (no code): docs/e2e-sanity-failed-cases.md FC-17 + summary row; + docs/e2e-sanity-test-results.md OR-12 + its defect row; apps/backend/tests/BUGS.md #17. + No migrations run. No tests run. + +[2026-10-10 13:03:57 +0530] FC-19 (RG-02): make createRegionWithBounds atomic on D1. + - Reproduced: superadmin.regions.create with two bounds at priority "1" returned the + unique-priority error but left region 5 with zero bounds (D1 does not roll back the + region insert with the failed bound insert). + - Fix: validate bounds before any insert (>=1 bound, unique priorities) and add a + compensating cleanup that removes the region + its child rows if a later insert + fails, so a failed create never leaves a half-created region. + + --- a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts + +++ a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts + @@ + export async function createRegionWithBounds(input) { + + // Validate before touching the DB: D1 does not reliably roll back a + + // multi-statement drizzle transaction, so a bad payload must never reach the + + // inserts (it would leave a region with no bounds behind). + + if (!input.bounds || input.bounds.length === 0) + + throw new Error('A region must be created with at least one bound') + + const priorities = input.bounds.map((b) => String(b.priority)) + + if (new Set(priorities).size !== priorities.length) + + throw new Error('Each bound priority must be unique within the region') + + + return db.transaction(async (tx) => { + const [region] = await tx.insert(regions).values(...).returning() + + try { + const inserted = await tx.insert(regionBounds).values(...).returning() + await tx.insert(regionConsts).values(defaultRegionRows(region.id)).onConflictDoNothing() + const boundRows = inserted.flatMap(...) + if (boundRows.length > 0) await tx.insert(regionBoundConsts).values(boundRows).onConflictDoNothing() + return { region: toSummary(region), bounds: inserted.map(toBoundDto) } + + } catch (error) { + + await tx.delete(regionBoundConsts).where(eq(regionBoundConsts.regionId, region.id)) + + await tx.delete(regionConsts).where(eq(regionConsts.regionId, region.id)) + + await tx.delete(regionBounds).where(eq(regionBounds.regionId, region.id)) + + await tx.delete(regions).where(eq(regions.id, region.id)) + + throw error + + } + }) + } + + Docs (no code): docs/e2e-sanity-failed-cases.md FC-19 + summary row; + docs/e2e-sanity-test-results.md RG-02 + its defect row. + No migrations run. No tests run. diff --git a/packages/db_helper_postgres/src/db/seed.ts b/packages/db_helper_postgres/src/db/seed.ts index bd43727..8684f3c 100644 --- a/packages/db_helper_postgres/src/db/seed.ts +++ b/packages/db_helper_postgres/src/db/seed.ts @@ -107,7 +107,6 @@ export async function seed() { // Seed key-val store constants using CONST_KEYS const constantsToSeed = [ { key: CONST_KEYS.readableOrderId, value: 0 }, - { key: CONST_KEYS.minRegularOrderValue, value: minOrderValue }, { key: CONST_KEYS.freeDeliveryThreshold, value: minOrderValue }, { key: CONST_KEYS.deliveryCharge, value: deliveryCharge }, { key: CONST_KEYS.flashFreeDeliveryThreshold, value: 500 }, diff --git a/packages/db_helper_sqlite/drizzle/0008_user_creds_unique_and_min_order_cleanup.sql b/packages/db_helper_sqlite/drizzle/0008_user_creds_unique_and_min_order_cleanup.sql new file mode 100644 index 0000000..7896e1e --- /dev/null +++ b/packages/db_helper_sqlite/drizzle/0008_user_creds_unique_and_min_order_cleanup.sql @@ -0,0 +1,26 @@ +-- Migration: user_creds uniqueness + removal of the retired `minRegularOrderValue`. +-- +-- Two independent cleanups bundled into one migration (applied together). +-- +-- 1) user_creds.user_id must be unique. +-- upsertUserPassword used to insert a fresh row on D1 (no UNIQUE(user_id) to +-- trip the Postgres 23505 fallback), so accounts accumulated duplicate rows and +-- login kept reading the stale one — a password change had no effect. The app +-- now selects-then-updates; this makes the invariant explicit. Existing +-- duplicates must be collapsed first (keep the newest row per user, which +-- carries the most recently set password) or CREATE UNIQUE INDEX aborts. +-- +-- 2) Drop the retired `minRegularOrderValue` constant. +-- It was never enforced as a minimum order value, and the delivery threshold +-- now uses `freeDeliveryThreshold`. Delete its leftover rows. 0006 seeds +-- `region_bound_consts.minRegularOrderValue` for fresh installs; this migration +-- runs after it, so those seeded rows are removed too. + +DELETE FROM `user_creds` +WHERE `id` NOT IN (SELECT MAX(`id`) FROM `user_creds` GROUP BY `user_id`); +--> statement-breakpoint +CREATE UNIQUE INDEX IF NOT EXISTS `unique_user_creds_user` ON `user_creds` (`user_id`); +--> statement-breakpoint +DELETE FROM `region_bound_consts` WHERE `key` = 'minRegularOrderValue'; +--> statement-breakpoint +DELETE FROM `key_val_store` WHERE `key` = 'minRegularOrderValue'; diff --git a/packages/db_helper_sqlite/src/admin-apis/product.ts b/packages/db_helper_sqlite/src/admin-apis/product.ts index fcd5093..e5155cd 100644 --- a/packages/db_helper_sqlite/src/admin-apis/product.ts +++ b/packages/db_helper_sqlite/src/admin-apis/product.ts @@ -812,10 +812,22 @@ export async function updateProductTag(regionId: number, tagId: number, input: U } export async function deleteProductTag(regionId: number, tagId: number): Promise { - const [deleted] = await db.delete(productTagInfo) - .where(and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId))) - .returning({ id: productTagInfo.id }) - return !!deleted + return db.transaction(async (tx) => { + const tag = await tx.query.productTagInfo.findFirst({ + where: and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)), + columns: { id: true }, + }) + if (!tag) return false + + // Drop the product associations first; the product_tags FK blocks the tag + // delete otherwise. + await tx.delete(productTags).where(eq(productTags.tagId, tagId)) + await tx + .delete(productTagInfo) + .where(and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId))) + + return true + }) } export async function checkProductTagExistsByName(tagName: string): Promise { diff --git a/packages/db_helper_sqlite/src/admin-apis/store.ts b/packages/db_helper_sqlite/src/admin-apis/store.ts index db08f8d..1c84fa3 100644 --- a/packages/db_helper_sqlite/src/admin-apis/store.ts +++ b/packages/db_helper_sqlite/src/admin-apis/store.ts @@ -1,6 +1,6 @@ import { db } from '../db/db_index' import { storeInfo, productInfo, productSkus, staffUsers } from '../db/schema' -import { eq, inArray, and } from 'drizzle-orm' +import { eq, inArray, and, sql } from 'drizzle-orm' import { runBatched } from '../lib/run-batched' import type { Store, CreateStoreInput, UpdateStoreInput } from '@packages/shared' @@ -176,23 +176,22 @@ export async function deleteStore(regionId: number, id: number): Promise<{ messa throw new Error('Store not found') } - return await db.transaction(async (tx) => { - await tx - .update(productInfo) - .set({ storeId: null }) - .where(eq(productInfo.storeId, id)) + // A store cannot be deleted while products still reference it — that would + // orphan them. Reassign or remove the products first. + const [{ count }] = await db + .select({ count: sql`count(*)` }) + .from(productInfo) + .where(eq(productInfo.storeId, id)) - const [deletedStore] = await tx - .delete(storeInfo) - .where(eq(storeInfo.id, id)) - .returning() + if (Number(count) > 0) { + throw new Error( + 'Cannot delete a store that still has products. Remove or reassign them first.' + ) + } - if (!deletedStore) { - throw new Error('Store not found') - } + await db.delete(storeInfo).where(eq(storeInfo.id, id)) - return { - message: 'Store deleted successfully', - } - }) + return { + message: 'Store deleted successfully', + } } diff --git a/packages/db_helper_sqlite/src/db/schema.ts b/packages/db_helper_sqlite/src/db/schema.ts index 3e13448..4ad8b4d 100644 --- a/packages/db_helper_sqlite/src/db/schema.ts +++ b/packages/db_helper_sqlite/src/db/schema.ts @@ -101,7 +101,9 @@ export const userCreds = sqliteTable('user_creds', { userId: integer('user_id').notNull().references(() => users.id), userPassword: text('user_password').notNull(), createdAt: timestampText('created_at').notNull().default(sql`CURRENT_TIMESTAMP`), -}) +}, (t) => ({ + unq_user_creds_user: uniqueIndex('unique_user_creds_user').on(t.userId), +})) export const addresses = sqliteTable('addresses', { id: integer().primaryKey({ autoIncrement: true }), diff --git a/packages/db_helper_sqlite/src/db/seed.sql b/packages/db_helper_sqlite/src/db/seed.sql index 6628a27..6353f79 100644 --- a/packages/db_helper_sqlite/src/db/seed.sql +++ b/packages/db_helper_sqlite/src/db/seed.sql @@ -36,7 +36,6 @@ WHERE r.role_name = 'marketer' -- Seed key-val store constants INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('readableOrderId', '0'); -INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('minRegularOrderValue', '300'); INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('freeDeliveryThreshold', '300'); INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('deliveryCharge', '20'); INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('flashFreeDeliveryThreshold', '500'); diff --git a/packages/db_helper_sqlite/src/lib/const-keys.ts b/packages/db_helper_sqlite/src/lib/const-keys.ts index deb1b14..604e4ae 100644 --- a/packages/db_helper_sqlite/src/lib/const-keys.ts +++ b/packages/db_helper_sqlite/src/lib/const-keys.ts @@ -1,7 +1,6 @@ import type { ConstValueType } from '@packages/shared' export const CONST_KEYS = { - minRegularOrderValue: 'minRegularOrderValue', freeDeliveryThreshold: 'freeDeliveryThreshold', deliveryCharge: 'deliveryCharge', flashFreeDeliveryThreshold: 'flashFreeDeliveryThreshold', @@ -30,7 +29,6 @@ export const CONST_KEYS = { } as const export const CONST_LABELS: Record = { - minRegularOrderValue: 'Minimum Regular Order Value', freeDeliveryThreshold: 'Free Delivery Threshold', deliveryCharge: 'Delivery Charge', flashFreeDeliveryThreshold: 'Flash Free Delivery Threshold', @@ -63,7 +61,6 @@ export type ConstKey = (typeof CONST_KEYS)[keyof typeof CONST_KEYS] export const CONST_KEYS_ARRAY = Object.values(CONST_KEYS) as ConstKey[] export const CONST_TYPES: Record = { - minRegularOrderValue: 'number', freeDeliveryThreshold: 'number', deliveryCharge: 'number', flashFreeDeliveryThreshold: 'number', @@ -92,7 +89,6 @@ export const CONST_TYPES: Record = { } export const CONST_VISIBILITY: Record = { - minRegularOrderValue: true, freeDeliveryThreshold: true, deliveryCharge: true, flashFreeDeliveryThreshold: true, @@ -126,7 +122,6 @@ export const CONST_VISIBILITY: Record = { * form (and saving it writes the real row). */ export const CONST_DEFAULTS: Record = { - minRegularOrderValue: 300, freeDeliveryThreshold: 300, deliveryCharge: 20, flashFreeDeliveryThreshold: 500, @@ -198,7 +193,7 @@ export const REGION_CONST_KEYS = [ /** Keys stored in the region_bound_consts table (one row per bound). */ export const BOUND_CONST_KEYS = [ - 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge', + 'freeDeliveryThreshold', 'deliveryCharge', 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', ] as const diff --git a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts b/packages/db_helper_sqlite/src/superadmin-apis/regions.ts index f57ffc0..4a90967 100644 --- a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts +++ b/packages/db_helper_sqlite/src/superadmin-apis/regions.ts @@ -131,32 +131,53 @@ export async function createRegion(input: CreateRegionInput): Promise { + // Validate before touching the DB. D1 does not reliably roll back a + // multi-statement drizzle transaction, so an invalid payload must never reach + // the inserts — otherwise it leaves a region with no bounds behind. + if (!input.bounds || input.bounds.length === 0) { + throw new Error('A region must be created with at least one bound') + } + const priorities = input.bounds.map((bound) => String(bound.priority)) + if (new Set(priorities).size !== priorities.length) { + throw new Error('Each bound priority must be unique within the region') + } + return db.transaction(async (tx) => { const [region] = await tx .insert(regions) .values({ name: input.name, description: input.description ?? null }) .returning() - const inserted = await tx - .insert(regionBounds) - .values( - input.bounds.map((bound) => ({ - regionId: region.id, - description: bound.description ?? null, - geojson: bound.geojson, - priority: String(bound.priority), - })) - ) - .returning() + try { + const inserted = await tx + .insert(regionBounds) + .values( + input.bounds.map((bound) => ({ + regionId: region.id, + description: bound.description ?? null, + geojson: bound.geojson, + priority: String(bound.priority), + })) + ) + .returning() - await tx.insert(regionConsts).values(defaultRegionRows(region.id)).onConflictDoNothing() + await tx.insert(regionConsts).values(defaultRegionRows(region.id)).onConflictDoNothing() - const boundRows = inserted.flatMap((bound) => defaultBoundRows(region.id, bound.id)) - if (boundRows.length > 0) { - await tx.insert(regionBoundConsts).values(boundRows).onConflictDoNothing() + const boundRows = inserted.flatMap((bound) => defaultBoundRows(region.id, bound.id)) + if (boundRows.length > 0) { + await tx.insert(regionBoundConsts).values(boundRows).onConflictDoNothing() + } + + return { region: toSummary(region), bounds: inserted.map(toBoundDto) } + } catch (error) { + // Compensate: D1 may leave the region insert committed when a later + // statement fails, so remove everything created for this region. + await tx.delete(regionBoundConsts).where(eq(regionBoundConsts.regionId, region.id)) + await tx.delete(regionConsts).where(eq(regionConsts.regionId, region.id)) + await tx.delete(regionBounds).where(eq(regionBounds.regionId, region.id)) + await tx.delete(regions).where(eq(regions.id, region.id)) + throw error } - - return { region: toSummary(region), bounds: inserted.map(toBoundDto) } }) } diff --git a/packages/db_helper_sqlite/src/user-apis/auth.ts b/packages/db_helper_sqlite/src/user-apis/auth.ts index 3347355..fc7bece 100644 --- a/packages/db_helper_sqlite/src/user-apis/auth.ts +++ b/packages/db_helper_sqlite/src/user-apis/auth.ts @@ -175,21 +175,28 @@ export async function createUserWithMobile(mobile: string) { } export async function upsertUserPassword(userId: number, hashedPassword: string) { - try { - await db.insert(userCreds).values({ - userId, - userPassword: hashedPassword, - }) + // Explicit select-then-update-or-insert: on D1 there is no UNIQUE(user_id) + // enforcement to trip the Postgres 23505 path, so the old insert-first + // approach created duplicate credentials rows and left the stale one in use. + const existing = await db + .select({ id: userCreds.id }) + .from(userCreds) + .where(eq(userCreds.userId, userId)) + .limit(1) + + if (existing.length > 0) { + // Update every row for this user so any pre-existing duplicates are repaired. + await db + .update(userCreds) + .set({ userPassword: hashedPassword }) + .where(eq(userCreds.userId, userId)) return - } catch (error: any) { - if (error.code === '23505') { - await db.update(userCreds).set({ - userPassword: hashedPassword, - }).where(eq(userCreds.userId, userId)) - return - } - throw error } + + await db.insert(userCreds).values({ + userId, + userPassword: hashedPassword, + }) } export async function deleteUserAccount(userId: number) { diff --git a/packages/db_helper_sqlite/src/user-apis/order.ts b/packages/db_helper_sqlite/src/user-apis/order.ts index db39c1a..9ee7e65 100644 --- a/packages/db_helper_sqlite/src/user-apis/order.ts +++ b/packages/db_helper_sqlite/src/user-apis/order.ts @@ -112,10 +112,22 @@ export async function validateAndGetCoupon( where: eq(coupons.id, couponId), with: { usages: { where: eq(couponUsage.userId, userId) }, + applicableUsers: true, }, }) if (!coupon) throw new Error('Invalid coupon') + + // User-based coupons are only spendable by their listed users. The display + // endpoints already hide them from everyone else, but placeOrder accepts a raw + // couponId, so the scope must be enforced here too. + if (coupon.isUserBased && !coupon.isApplyForAll) { + const applicableUsers = coupon.applicableUsers ?? [] + if (!applicableUsers.some((au) => au.userId === userId)) { + throw new Error('This coupon is not applicable to your account') + } + } + if (coupon.isInvalidated) throw new Error('Coupon is no longer valid') if (coupon.validTill && new Date(coupon.validTill) < new Date()) throw new Error('Coupon has expired')