From 713420c8bbc223e664dccecef5a750d2d5008b85 Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:31:20 +0530 Subject: [PATCH] enh --- .../dashboard/customize-app/index.tsx | 3 +- .../src/routes/dashboard.customize-app.tsx | 3 +- apps/backend/src/lib/const-keys.ts | 3 +- apps/backend/src/lib/flash-delivery-cron.ts | 14 +- apps/backend/src/sqliteImporter.ts | 2 + .../trpc/apis/admin-apis/apis/complaint.ts | 2 + .../apis/common-apis/common-trpc-index.ts | 3 +- .../apis/superadmin-apis/apis/complaint.ts | 56 +++ .../apis/superadmin-trpc-index.ts | 2 + .../src/trpc/apis/user-apis/apis/address.ts | 15 +- .../src/trpc/apis/user-apis/apis/complaint.ts | 8 +- .../src/trpc/apis/user-apis/apis/coupon.ts | 32 +- .../src/trpc/apis/user-apis/apis/order.ts | 35 +- .../src/trpc/apis/user-apis/apis/user.ts | 19 +- apps/backend/tests/BUGS.md | 6 + apps/backend/tests/api/coupon-math.test.ts | 45 +- .../superadmin-ui/src/components/AppShell.tsx | 3 +- apps/superadmin-ui/src/routeTree.gen.ts | 21 + apps/superadmin-ui/src/routes/complaints.tsx | 95 ++++ apps/superadmin-ui/src/routes/regions.tsx | 2 +- apps/user-ui/components/CartAddressGate.tsx | 30 +- .../components/LocationTestWrapper.tsx | 50 ++- apps/user-ui/components/cart-page.tsx | 407 ++++++++++++------ apps/user-ui/components/checkout-page.tsx | 28 +- .../src/components/NotifRegionSync.tsx | 11 +- apps/user-ui/src/store/locationStore.ts | 24 ++ .../user-ui/tests/screens/cart-money.test.tsx | 2 +- change-log.txt | 239 ++++++++++ docs/test-cases/README.md | 4 +- .../coupon-stacking-and-cart-guards.md | 110 +++++ .../drizzle/0006_regions_and_superadmins.sql | 30 +- packages/db_helper_sqlite/index.ts | 7 + .../src/admin-apis/complaint.ts | 48 +-- .../db_helper_sqlite/src/admin-apis/user.ts | 10 +- packages/db_helper_sqlite/src/db/schema.ts | 1 + .../db_helper_sqlite/src/lib/const-keys.ts | 3 +- .../src/superadmin-apis/complaint.ts | 71 +++ .../src/user-apis/complaint.ts | 42 +- .../db_helper_sqlite/src/user-apis/coupon.ts | 1 + .../db_helper_sqlite/src/user-apis/order.ts | 13 +- .../src/user-apis/user-regions.ts | 44 +- packages/shared/cart-pricing.ts | 158 +++++-- packages/shared/types/complaint.types.ts | 2 + packages/shared/types/user.ts | 3 + .../ui/src/components/bottom-dropdown.tsx | 42 +- 45 files changed, 1431 insertions(+), 318 deletions(-) create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/complaint.ts create mode 100644 apps/superadmin-ui/src/routes/complaints.tsx create mode 100644 docs/test-cases/coupon-stacking-and-cart-guards.md create mode 100644 packages/db_helper_sqlite/src/superadmin-apis/complaint.ts 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 23c585d..02aa632 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx @@ -14,12 +14,13 @@ type ConstTab = 'region' | 'bound' // Region tab: region_consts minus the version counters (owned by the cache // pipeline) and tagsOrder (edited on its own Tag Orders screen). const REGION_KEYS = [ - 'popularItems', 'allItemsOrder', 'isFlashDeliveryEnabled', + 'popularItems', 'allItemsOrder', 'supportMobile', 'supportEmail', 'welcomeMessage', ] const BOUND_KEYS = [ 'freeDeliveryThreshold', 'deliveryCharge', 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', + 'isFlashDeliveryEnabled', ] const CONST_LABELS: Record = { diff --git a/apps/admin-web/src/routes/dashboard.customize-app.tsx b/apps/admin-web/src/routes/dashboard.customize-app.tsx index 04308f1..3459e46 100644 --- a/apps/admin-web/src/routes/dashboard.customize-app.tsx +++ b/apps/admin-web/src/routes/dashboard.customize-app.tsx @@ -17,12 +17,13 @@ type ConstTab = 'region' | 'bound' // Region tab: region_consts minus the version counters (owned by the cache // pipeline) and tagsOrder (edited on its own Tag Orders screen). const REGION_KEYS = [ - 'popularItems', 'allItemsOrder', 'isFlashDeliveryEnabled', + 'popularItems', 'allItemsOrder', 'supportMobile', 'supportEmail', 'welcomeMessage', ] const BOUND_KEYS = [ 'freeDeliveryThreshold', 'deliveryCharge', 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', + 'isFlashDeliveryEnabled', ] const CONST_LABELS: Record = { diff --git a/apps/backend/src/lib/const-keys.ts b/apps/backend/src/lib/const-keys.ts index a0a3db3..b7fe951 100644 --- a/apps/backend/src/lib/const-keys.ts +++ b/apps/backend/src/lib/const-keys.ts @@ -117,7 +117,7 @@ export const GLOBAL_CONST_KEYS = [ /** Keys stored in the region_consts table (one row per region). */ export const REGION_CONST_KEYS = [ 'products_version_num', 'availability_version_num', 'slots_version_num', - 'popularItems', 'allItemsOrder', 'tagsOrder', 'isFlashDeliveryEnabled', + 'popularItems', 'allItemsOrder', 'tagsOrder', 'supportMobile', 'supportEmail', 'welcomeMessage', ] as const @@ -125,6 +125,7 @@ export const REGION_CONST_KEYS = [ export const BOUND_CONST_KEYS = [ 'freeDeliveryThreshold', 'deliveryCharge', 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', + 'isFlashDeliveryEnabled', ] as const /** Keys that remain in the legacy key_val_store table. */ diff --git a/apps/backend/src/lib/flash-delivery-cron.ts b/apps/backend/src/lib/flash-delivery-cron.ts index 2ce803b..6fda035 100644 --- a/apps/backend/src/lib/flash-delivery-cron.ts +++ b/apps/backend/src/lib/flash-delivery-cron.ts @@ -1,4 +1,4 @@ -import { getAllRegions, upsertRegionConsts } from '@/src/dbService' +import { getAllRegions, getBoundsForRegion, upsertBoundSettings } from '@/src/dbService' import { CONST_KEYS } from '@/src/lib/const-keys' import { computeConstants } from '@/src/lib/const-store' import { refreshGenKv } from '@/src/lib/gen-store' @@ -26,12 +26,16 @@ export async function runFlashDeliveryToggleCron(params: { const enabled = cron === CRON_TURN_ON_FLASH_DELIVERY console.log('flash delivery cron: toggling isFlashDeliveryEnabled', { cron, enabled }) - // isFlashDeliveryEnabled is region-scoped (region_consts) — flip it for every region. + // isFlashDeliveryEnabled is BOUND-scoped (region_bound_consts) — flip it on + // every bound of every region. const regions = await getAllRegions() for (const region of regions) { - await upsertRegionConsts(region.id, [ - { key: CONST_KEYS.isFlashDeliveryEnabled, value: String(enabled) }, - ]) + const bounds = await getBoundsForRegion(region.id) + for (const bound of bounds) { + await upsertBoundSettings(bound.id, [ + { key: CONST_KEYS.isFlashDeliveryEnabled, value: String(enabled) }, + ]) + } } await computeConstants() await refreshGenKv() diff --git a/apps/backend/src/sqliteImporter.ts b/apps/backend/src/sqliteImporter.ts index 3d0ee17..f969b0c 100644 --- a/apps/backend/src/sqliteImporter.ts +++ b/apps/backend/src/sqliteImporter.ts @@ -295,4 +295,6 @@ export { getBoundSettings, upsertBoundSettings, getEffectiveRegionSettings, + // Superadmin - Complaints + getAllComplaintsForSuperadmin, } from '../../../packages/db_helper_sqlite' diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/complaint.ts b/apps/backend/src/trpc/apis/admin-apis/apis/complaint.ts index 8ea54d1..a695b27 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/complaint.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/complaint.ts @@ -24,6 +24,7 @@ export const complaintRouter = router({ userName: string | null; userMobile: string | null; orderId: number | null; + regionId: number | null; status: string; createdAt: Date; images: string[]; @@ -48,6 +49,7 @@ export const complaintRouter = router({ userName: c.userName, userMobile: c.userMobile, orderId: c.orderId, + regionId: c.regionId, status: c.isResolved ? 'resolved' : 'pending', createdAt: c.createdAt, images, 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 aa3b97c..f3b499d 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 @@ -66,7 +66,6 @@ export async function scaffoldEssentialConsts(boundId: number) { slots_version_num: pickNumber(region['slots_version_num'], 0), popularItems: pickRaw(region['popularItems'], null), allItemsOrder: pickRaw(region['allItemsOrder'], null), - isFlashDeliveryEnabled: pickBool(region['isFlashDeliveryEnabled'], false), supportMobile: pickRaw(region['supportMobile'], ''), supportEmail: pickRaw(region['supportEmail'], ''), welcomeMessage: pickRaw(region['welcomeMessage'], ''), @@ -75,6 +74,8 @@ export async function scaffoldEssentialConsts(boundId: number) { deliveryCharge: pickNumber(boundConsts['deliveryCharge'], 0), flashFreeDeliveryThreshold: pickNumber(boundConsts['flashFreeDeliveryThreshold'], 500), flashDeliveryCharge: pickNumber(boundConsts['flashDeliveryCharge'], 69), + // Per bound: each bound switches flash delivery on/off independently. + isFlashDeliveryEnabled: pickBool(boundConsts['isFlashDeliveryEnabled'], false), // env + identity assetsDomain: getAssetsDomain(), apiCacheKey: getApiCacheKey(), diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/complaint.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/complaint.ts new file mode 100644 index 0000000..63dd283 --- /dev/null +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/complaint.ts @@ -0,0 +1,56 @@ +import { router, superadminProcedure } from '@/src/trpc/trpc-index' +import { z } from 'zod' +import { scaffoldAssetUrl } from '@/src/lib/s3-client' +import { getAllComplaintsForSuperadmin } from '@/src/dbService' + +export const superadminComplaintRouter = router({ + getAll: superadminProcedure + .input(z.object({ + cursor: z.number().optional(), + limit: z.number().default(20), + })) + .query(async ({ input }): Promise<{ + complaints: Array<{ + id: number; + text: string; + userId: number; + userName: string | null; + userMobile: string | null; + orderId: number | null; + regionId: number | null; + regionName: string | null; + status: string; + createdAt: Date; + images: string[]; + response: string | null; + }>; + nextCursor?: number; + }> => { + const { cursor, limit } = input; + + const { complaints, hasMore } = await getAllComplaintsForSuperadmin(cursor, limit); + + const complaintsWithImageUrls = complaints.map((c) => ({ + id: c.id, + text: c.complaintBody, + userId: c.userId, + userName: c.userName, + userMobile: c.userMobile, + orderId: c.orderId, + regionId: c.regionId, + regionName: c.regionName, + status: c.isResolved ? 'resolved' : 'pending', + createdAt: c.createdAt, + images: scaffoldAssetUrl((c.images as string[]) || []), + response: c.response, + })); + + return { + complaints: complaintsWithImageUrls, + nextCursor: + hasMore && complaints.length > 0 + ? complaints[complaints.length - 1].id + : undefined, + }; + }), +}) diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts index e0a7cb4..851fe55 100644 --- a/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts @@ -8,6 +8,7 @@ import { superadminStoresRouter } from '@/src/trpc/apis/superadmin-apis/apis/sto import { superadminGlobalProductsRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-products' import { superadminProductsRouter } from '@/src/trpc/apis/superadmin-apis/apis/products' import { superadminGlobalCouponsRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-coupons' +import { superadminComplaintRouter } from '@/src/trpc/apis/superadmin-apis/apis/complaint' export const superadminRouter = router({ auth: superadminAuthRouter, @@ -19,6 +20,7 @@ export const superadminRouter = router({ globalProducts: superadminGlobalProductsRouter, globalCoupons: superadminGlobalCouponsRouter, products: superadminProductsRouter, + complaint: superadminComplaintRouter, }) export type SuperadminRouter = typeof superadminRouter diff --git a/apps/backend/src/trpc/apis/user-apis/apis/address.ts b/apps/backend/src/trpc/apis/user-apis/apis/address.ts index 3407836..27da1ab 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/address.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/address.ts @@ -15,6 +15,7 @@ import { getEffectiveBoundId as getEffectiveBoundIdInDb, upsertUserRegion, reconcileUserRegions, + syncUserNotifCredRegion, } from '@/src/dbService' import type { UserAddressResponse, @@ -116,11 +117,13 @@ export const addressRouter = router({ googleMapsUrl, }) - // Record the user<->region association for this address's region. Auxiliary - // and derived from the addresses, so a failure here must not fail the - // address write that already committed. + // Record the user<->region association for this address's region, and move + // the push token onto it. Adding an address is the ONLY thing that changes + // a token's region. Both are auxiliary and derived, so a failure here must + // not fail the address write that already committed. try { await upsertUserRegion(userId, input.regionId, 'address') + await syncUserNotifCredRegion(userId) } catch (error) { console.error('[address.createAddress] user-region association failed', error) } @@ -208,10 +211,11 @@ export const addressRouter = router({ }) // The address may have moved region: reconcile the user's associations - // (insert the new region, drop an old one no other address uses). Best - // effort: the update above already committed. + // (insert the new region, drop an old one no other address uses) and move + // the push token with it. Best effort: the update above already committed. try { await reconcileUserRegions(userId) + await syncUserNotifCredRegion(userId) } catch (error) { console.error('[address.updateAddress] user-region reconcile failed', error) } @@ -260,6 +264,7 @@ export const addressRouter = router({ // effort: the delete above already committed. try { await reconcileUserRegions(userId) + await syncUserNotifCredRegion(userId) } catch (error) { console.error('[address.deleteAddress] user-region reconcile failed', error) } diff --git a/apps/backend/src/trpc/apis/user-apis/apis/complaint.ts b/apps/backend/src/trpc/apis/user-apis/apis/complaint.ts index 44bbd74..450ccbc 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/complaint.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/complaint.ts @@ -31,9 +31,11 @@ export const complaintRouter = router({ let orderIdNum: number | null = null; if (orderId) { - const readableIdMatch = orderId.match(/^ORD(\d+)$/); - if (readableIdMatch) { - orderIdNum = parseInt(readableIdMatch[1]); + // The app sends the raw numeric order id (e.g. "137"); the display form + // "ORD137" is also accepted for backwards compatibility. + const orderIdMatch = orderId.match(/^(?:ORD-?)?(\d+)$/); + if (orderIdMatch) { + orderIdNum = parseInt(orderIdMatch[1]); } } diff --git a/apps/backend/src/trpc/apis/user-apis/apis/coupon.ts b/apps/backend/src/trpc/apis/user-apis/apis/coupon.ts index d8533f6..6ff8805 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/coupon.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/coupon.ts @@ -2,7 +2,6 @@ import { router, protectedProcedure } from '@/src/trpc/trpc-index' import { z } from 'zod' import { ApiError } from '@/src/lib/api-error' import { - getUserActiveCouponsWithRelations as getUserActiveCouponsWithRelationsInDb, getUserAllCouponsWithRelations as getUserAllCouponsWithRelationsInDb, getUserReservedCouponByCode as getUserReservedCouponByCodeInDb, redeemUserReservedCoupon as redeemUserReservedCouponInDb, @@ -38,23 +37,34 @@ const generateCouponDescription = (coupon: { discountPercent?: string | null; fl export const userCouponRouter = router({ getEligible: protectedProcedure .input(z.object({ regionId: z.number().int().positive().optional() }).optional()) - .query(async ({ ctx, input }): Promise => { + .query(async ({ ctx }): Promise => { try { - const userId = ctx.user.userId; - - const allCoupons = await getUserActiveCouponsWithRelationsInDb(userId, input?.regionId) - // Filter to only coupons applicable to current user + // Fetch every coupon (any region) and keep the ones the customer may see. + // Region / first-order / usage / min-order ineligibility is NOT filtered + // here — the client shows those coupons disabled with a reason. Only the + // coupons the customer must never see are dropped: expired, invalidated, + // and other users' personal coupons. + const allCoupons = await getUserAllCouponsWithRelationsInDb(userId) + const now = new Date(); const isFirstOrder = (await getUserOrderCountInDb(userId)) === 0; - const applicableCoupons = allCoupons.filter(coupon => { - if (coupon.isFirstOrderOnly && !isFirstOrder) return false; - if(!coupon.isUserBased) return true; + + const visibleCoupons = allCoupons.filter(coupon => { + const isNotExpired = !coupon.validTill || new Date(coupon.validTill) > now; + const isNotInvalidated = !coupon.isInvalidated; + const isNotUsedUp = + !coupon.maxLimitForUser || + (coupon.usages?.length ?? 0) < coupon.maxLimitForUser; const applicableUsers = coupon.applicableUsers || []; - return applicableUsers.some(au => au.userId === userId); + const isAllowedForUser = + !coupon.isUserBased || + coupon.isApplyForAll || + applicableUsers.some(au => au.userId === userId); + return isNotExpired && isNotInvalidated && isNotUsedUp && isAllowedForUser; }); - return { success: true, data: applicableCoupons }; + return { success: true, data: visibleCoupons, isFirstOrder }; } catch(e) { console.log(e) 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 cded519..948200d 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts @@ -91,6 +91,26 @@ const placeOrderUtil = async (params: { regionId = address.regionId; } + // Flash delivery is enabled per BOUND (region_bound_consts). The delivery + // address's bound is authoritative, so the flag is read from the same bound + // chain the pricing below uses — a client-supplied region/bound can never turn + // flash on for an address whose bound has it switched off. + if (isFlashDelivery) { + const constBoundId = + resolvedBoundId ?? address.boundId ?? params.boundId ?? (await getEffectiveBoundId(regionId)); + const flashSettings = + (constBoundId != null ? await getRegionSettingsForBound(regionId, constBoundId) : null) ?? + (await getEffectiveRegionSettings(regionId)); + const raw = flashSettings?.settings?.[CONST_KEYS.isFlashDeliveryEnabled]; + const isFlashEnabled = raw === 'true' || raw === '1'; + if (!isFlashEnabled) { + throw new ApiError( + "Flash delivery is currently unavailable. Please opt for scheduled delivery.", + 403 + ); + } + } + // Bound-level constants (delivery charge/thresholds/min order) come from the bound the // delivery address resolves to, so pricing cannot be changed by a client-supplied id. // Only when the address carries no bound do we fall back to the bound the client is @@ -237,8 +257,9 @@ const placeOrderUtil = async (params: { }); // The discount is computed on GOODS subtotals only (delivery — flash or - // scheduled — never enters the base), per sub-order, with multiple coupons - // stacking percentage-first and each capped by its own maxValue. + // scheduled — never enters the base). Multiple coupons stack sequentially in + // the order the customer applied them, each capped by its own maxValue and + // rounded to the nearest rupee. const pricing = computeCartPricing({ subOrders: subOrderInputs, coupons: validatedCoupons.map((c) => ({ @@ -390,14 +411,8 @@ export const orderRouter = router({ isFlashDelivery, } = input; - if (isFlashDelivery) { - const effective = await getEffectiveRegionSettings(regionId); - const raw = effective?.settings?.[CONST_KEYS.isFlashDeliveryEnabled]; - const isFlashDeliveryEnabled = raw === 'true' || raw === '1'; - if (!isFlashDeliveryEnabled) { - throw new ApiError("Flash delivery is currently unavailable. Please opt for scheduled delivery.", 403); - } - } + // Flash delivery availability is checked inside placeOrderUtil, where the + // delivery address's bound is known (the flag is per bound). if (!isFlashDelivery) { const slotIds = [...new Set(selectedItems.filter(i => i.slotId !== null).map(i => i.slotId as number))]; diff --git a/apps/backend/src/trpc/apis/user-apis/apis/user.ts b/apps/backend/src/trpc/apis/user-apis/apis/user.ts index 282446d..5a52bcb 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/user.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/user.ts @@ -12,6 +12,7 @@ import { getUserUnloggedToken as getUserUnloggedTokenInDb, upsertUserUnloggedToken as upsertUserUnloggedTokenInDb, upsertUserRegion as upsertUserRegionInDb, + getUserAddressRegionId as getUserAddressRegionIdInDb, } from '@/src/dbService' import type { UserSelfDataResponse, @@ -82,10 +83,22 @@ export const userRouter = router({ if (userId) { // AUTHENTICATED USER - // The region is auxiliary: it must never stop the token from being - // registered. Carry a region captured while signed out onto the account's - // creds unless this call already carries one. + // The push token's region follows the user's ADDRESS, not where the + // device currently is: a tracked location in another region must not + // move it. Only an address change moves the token (see address.ts, which + // calls syncUserNotifCredRegion). So when the user has an address, its + // region wins over the caller-supplied browsing region. Fall back to the + // caller's region when the user has no address. let effectiveRegionId: number | null = regionId ?? null + try { + effectiveRegionId = (await getUserAddressRegionIdInDb(userId)) ?? effectiveRegionId + } catch (error) { + console.error('[user.savePushToken] reading the address region failed', error) + } + + // Still nothing (no address, no region on this call): carry a region + // captured while signed out. The region is auxiliary: it must never stop + // the token from being registered. if (effectiveRegionId == null) { try { effectiveRegionId = (await getUserUnloggedTokenInDb(token))?.regionId ?? null diff --git a/apps/backend/tests/BUGS.md b/apps/backend/tests/BUGS.md index 1fba3cd..02bda6c 100644 --- a/apps/backend/tests/BUGS.md +++ b/apps/backend/tests/BUGS.md @@ -158,6 +158,12 @@ percentage discounts leave float noise (e.g. `999 - 15%`). **Pinned by:** `tests/api/coupon-math.test.ts` — "pins: amounts are stored unrounded". +> **Fixed (coupon stacking):** coupon discounts are now rounded to the nearest +> rupee in the shared `computeCartPricing` / `computeCouponStack` +> (`packages/shared/cart-pricing.ts`) and multiple coupons stack **sequentially in +> the order the customer applied them**. `orders.totalAmount` no longer carries +> float noise. + --- ## Medium — coupon rules diff --git a/apps/backend/tests/api/coupon-math.test.ts b/apps/backend/tests/api/coupon-math.test.ts index 90cb065..b3d1e66 100644 --- a/apps/backend/tests/api/coupon-math.test.ts +++ b/apps/backend/tests/api/coupon-math.test.ts @@ -6,10 +6,11 @@ * orders.totalAmount. These tests read the order row returned by placeOrder * (totalAmount is the stored string). * - * 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. + * The backend mirrors the customer app's model: coupons discount the goods + * subtotal and delivery is decided on the post-discount total. Multiple coupons + * stack sequentially in the order they are applied, each rounded to the nearest + * rupee. Remaining KNOWN BUGS are pinned here (negative totals for >=100% + * coupons). See tests/BUGS.md. */ import { apiClient, captureError, uniqueSuffix } from '../helpers/api' @@ -88,14 +89,16 @@ describe('coupon discount maths', () => { const place = ( items: { skuId: number; quantity: number; slotId: number | null }[], - couponId?: number + couponId?: number | number[] ): Promise => apiClient(userToken).user.order.placeOrder.mutate({ selectedItems: items, addressId, regionId: 1, paymentMethod: 'cod', - ...(couponId ? { couponIds: [couponId] } : {}), + ...(couponId != null + ? { couponIds: Array.isArray(couponId) ? couponId : [couponId] } + : {}), }) as unknown as Promise const total = (res: Placed) => parseFloat(res.data[0].totalAmount) @@ -197,11 +200,7 @@ describe('coupon discount maths', () => { expect(totals[0] + totals[1]).toBe(480) }) - /** - * KNOWN BUG: money is never rounded, so a percentage discount leaves float - * noise in orders.totalAmount (here 849.15 is not representable exactly). - */ - it('pins: amounts are stored unrounded', async () => { + it('rounds the discount to the nearest rupee', async () => { const coupon = await createCoupon({ discountPercent: 15 }) const res = await place( @@ -209,8 +208,28 @@ describe('coupon discount maths', () => { coupon.id ) - // 999 - 15%. Assert the exact JS string, i.e. no rounding was applied. - expect(res.data[0].totalAmount).toBe(String(999 - (999 * 15) / 100)) + // 999 - round(15% of 999 = 149.85) = 999 - 150 = 849. + expect(total(res)).toBe(849) + }) + + it('stacks multiple coupons sequentially in the order applied', async () => { + const tenPct = await createCoupon({ discountPercent: 10 }) + const flat100 = await createCoupon({ flatDiscount: 100 }) + + // 200 * 5 = 1000. Above the free-delivery threshold, so delivery is free. + // 10% first: -100 -> 900; then flat 100 -> 800. + const pctThenFlat = await place( + [{ skuId, quantity: 200, slotId }], + [tenPct.id, flat100.id] + ) + expect(total(pctThenFlat)).toBe(800) + + // Same two coupons, reversed: flat 100 first -> 900; then 10% of 900 = 90 -> 810. + const flatThenPct = await place( + [{ skuId, quantity: 200, slotId }], + [flat100.id, tenPct.id] + ) + expect(total(flatThenPct)).toBe(810) }) it('enforces maxLimitForUser', async () => { diff --git a/apps/superadmin-ui/src/components/AppShell.tsx b/apps/superadmin-ui/src/components/AppShell.tsx index 5946a0f..8833a01 100644 --- a/apps/superadmin-ui/src/components/AppShell.tsx +++ b/apps/superadmin-ui/src/components/AppShell.tsx @@ -1,6 +1,6 @@ import React, { useState } from 'react' import { Link } from '@tanstack/react-router' -import { LayoutDashboard, Send, Settings2, Menu, X, LogOut, Map, UserCog, Store, Package } from 'lucide-react' +import { LayoutDashboard, Send, Settings2, Menu, X, LogOut, Map, UserCog, Store, Package, MessageSquare } from 'lucide-react' import { useAuth } from '../lib/auth-context' const NAV = [ @@ -9,6 +9,7 @@ const NAV = [ { to: '/global-stores', label: 'Stores', icon: Store }, { to: '/global-products', label: 'Products', icon: Package }, { to: '/staff', label: 'Admin Users', icon: UserCog }, + { to: '/complaints', label: 'Complaints', icon: MessageSquare }, { to: '/send-notifications', label: 'Admin Notifs', icon: Send }, { to: '/constants', label: 'App Constants', icon: Settings2 }, ] as const diff --git a/apps/superadmin-ui/src/routeTree.gen.ts b/apps/superadmin-ui/src/routeTree.gen.ts index 9c0c4da..db0ef85 100644 --- a/apps/superadmin-ui/src/routeTree.gen.ts +++ b/apps/superadmin-ui/src/routeTree.gen.ts @@ -10,6 +10,7 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' +import { Route as ComplaintsRouteImport } from './routes/complaints' import { Route as ConstantsRouteImport } from './routes/constants' import { Route as DashboardRouteImport } from './routes/dashboard' import { Route as GlobalProductsRouteImport } from './routes/global-products' @@ -24,6 +25,11 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) +const ComplaintsRoute = ComplaintsRouteImport.update({ + id: '/complaints', + path: '/complaints', + getParentRoute: () => rootRouteImport, +} as any) const ConstantsRoute = ConstantsRouteImport.update({ id: '/constants', path: '/constants', @@ -67,6 +73,7 @@ const StaffRoute = StaffRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute + '/complaints': typeof ComplaintsRoute '/constants': typeof ConstantsRoute '/dashboard': typeof DashboardRoute '/global-products': typeof GlobalProductsRoute @@ -78,6 +85,7 @@ export interface FileRoutesByFullPath { } export interface FileRoutesByTo { '/': typeof IndexRoute + '/complaints': typeof ComplaintsRoute '/constants': typeof ConstantsRoute '/dashboard': typeof DashboardRoute '/global-products': typeof GlobalProductsRoute @@ -90,6 +98,7 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute + '/complaints': typeof ComplaintsRoute '/constants': typeof ConstantsRoute '/dashboard': typeof DashboardRoute '/global-products': typeof GlobalProductsRoute @@ -103,6 +112,7 @@ export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: | '/' + | '/complaints' | '/constants' | '/dashboard' | '/global-products' @@ -114,6 +124,7 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: | '/' + | '/complaints' | '/constants' | '/dashboard' | '/global-products' @@ -125,6 +136,7 @@ export interface FileRouteTypes { id: | '__root__' | '/' + | '/complaints' | '/constants' | '/dashboard' | '/global-products' @@ -137,6 +149,7 @@ export interface FileRouteTypes { } export interface RootRouteChildren { IndexRoute: typeof IndexRoute + ComplaintsRoute: typeof ComplaintsRoute ConstantsRoute: typeof ConstantsRoute DashboardRoute: typeof DashboardRoute GlobalProductsRoute: typeof GlobalProductsRoute @@ -156,6 +169,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/complaints': { + id: '/complaints' + path: '/complaints' + fullPath: '/complaints' + preLoaderRoute: typeof ComplaintsRouteImport + parentRoute: typeof rootRouteImport + } '/constants': { id: '/constants' path: '/constants' @@ -217,6 +237,7 @@ declare module '@tanstack/react-router' { const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, + ComplaintsRoute: ComplaintsRoute, ConstantsRoute: ConstantsRoute, DashboardRoute: DashboardRoute, GlobalProductsRoute: GlobalProductsRoute, diff --git a/apps/superadmin-ui/src/routes/complaints.tsx b/apps/superadmin-ui/src/routes/complaints.tsx new file mode 100644 index 0000000..2d82eb2 --- /dev/null +++ b/apps/superadmin-ui/src/routes/complaints.tsx @@ -0,0 +1,95 @@ +import { createFileRoute } from '@tanstack/react-router' +import { AppContainer, MyButton, p as MyText } from 'web-components' +import { ProtectedRoute } from '../components/ProtectedRoute' +import { AppShell } from '../components/AppShell' +import { trpc } from '../lib/trpc-client' + +export const Route = createFileRoute('/complaints')({ + component: () => ( + + + + + + ), +}) + +function ComplaintsPage() { + const query = trpc.superadmin.complaint.getAll.useInfiniteQuery( + { limit: 20 }, + { getNextPageParam: (lastPage) => lastPage.nextCursor } + ) + + const complaints = query.data?.pages.flatMap((page) => page.complaints) ?? [] + + return ( + +
+ Complaints + + Every complaint across all regions, newest first. A complaint tagged "No region" + could not be placed in a region, so it is only visible here. + + + {query.isLoading && Loading complaints…} + + {!query.isLoading && complaints.length === 0 && ( + No complaints yet. + )} + +
+ {complaints.map((item) => ( +
+
+ + Complaint #{item.id} + +
+ + {item.status === 'resolved' ? 'Resolved' : 'Pending'} + + + {item.regionName ?? 'No region'} + +
+
+ + {item.text} + + + {item.userName || item.userMobile || 'Unknown user'} + {item.orderId ? ` · Order #${item.orderId}` : ''} + {` · ${new Date(item.createdAt).toLocaleString()}`} + + + {item.response && ( +
+ Admin reply + {item.response} +
+ )} +
+ ))} +
+ + {query.hasNextPage && ( +
+ void query.fetchNextPage()} + disabled={query.isFetchingNextPage} + className="rounded-lg bg-blue-500 px-4 py-2 text-white disabled:opacity-50" + > + {query.isFetchingNextPage ? 'Loading…' : 'Load more'} + +
+ )} +
+
+ ) +} diff --git a/apps/superadmin-ui/src/routes/regions.tsx b/apps/superadmin-ui/src/routes/regions.tsx index 0b41bb4..2424ad2 100644 --- a/apps/superadmin-ui/src/routes/regions.tsx +++ b/apps/superadmin-ui/src/routes/regions.tsx @@ -23,6 +23,7 @@ const SETTING_KEYS = [ 'deliveryCharge', 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', + 'isFlashDeliveryEnabled', ] as const // Region-level keys (region_consts). Version counters are owned by the cache @@ -31,7 +32,6 @@ const REGION_SETTING_KEYS = [ 'popularItems', 'allItemsOrder', 'tagsOrder', - 'isFlashDeliveryEnabled', 'supportMobile', 'supportEmail', 'welcomeMessage', diff --git a/apps/user-ui/components/CartAddressGate.tsx b/apps/user-ui/components/CartAddressGate.tsx index bb181e4..8c1af42 100644 --- a/apps/user-ui/components/CartAddressGate.tsx +++ b/apps/user-ui/components/CartAddressGate.tsx @@ -1,10 +1,13 @@ -import React, { useState } from 'react' +import React, { useEffect, useState } from 'react' import { View, Modal } from 'react-native' import MaterialIcons from '@expo/vector-icons/MaterialIcons' import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui' import AddressForm from '@/src/components/AddressForm' import { useLocationStore } from '@/src/store/locationStore' +// How often to re-check the device location while we still have no fix. +const LOCATION_POLL_MS = 3000 + interface CartAddressGateProps { /** Called once the first address has been saved. */ onDone: () => void @@ -19,8 +22,33 @@ interface CartAddressGateProps { */ const CartAddressGate: React.FC = ({ onDone, onBack }) => { const coords = useLocationStore((state) => state.coords) + const probeLocation = useLocationStore((state) => state.probe) + const refreshPosition = useLocationStore((state) => state.refresh) const [mode, setMode] = useState<'none' | 'current' | 'other'>('none') + // The store takes its fix once per app launch, so a user who turns the location + // on after landing here would never see the "current location" option enable. + // While we have no fix, keep checking and take one as soon as the location is + // usable. Polling stops as soon as coords arrive. + useEffect(() => { + if (coords) return + + let cancelled = false + const check = async () => { + // A fix is already in flight; don't stack another one on top. + if (useLocationStore.getState().status === 'locating') return + const usable = await probeLocation() + if (cancelled || !usable) return + void refreshPosition() + } + + const timer = setInterval(() => void check(), LOCATION_POLL_MS) + return () => { + cancelled = true + clearInterval(timer) + } + }, [coords, probeLocation, refreshPosition]) + return ( diff --git a/apps/user-ui/components/LocationTestWrapper.tsx b/apps/user-ui/components/LocationTestWrapper.tsx index 75f87e3..f2ecf45 100644 --- a/apps/user-ui/components/LocationTestWrapper.tsx +++ b/apps/user-ui/components/LocationTestWrapper.tsx @@ -1,11 +1,15 @@ -import React, { useEffect } from 'react' +import React, { useEffect, useRef } from 'react' import { ActivityIndicator, Linking, Platform, View } from 'react-native' import { MyText, theme, tw } from 'common-ui' import type { ReactParentComponent } from '@packages/shared' import { trpc } from '../src/trpc-client' import { useRegion } from '@/src/hooks/useRegion' +import { useLocationStore } from '@/src/store/locationStore' import LocationFallbackFlow from '@/src/components/location/LocationFallbackFlow' +// How often the gate re-checks the device location while it is up. +const LOCATION_POLL_MS = 3000 + const LoadingScreen: React.FC<{ label?: string }> = ({ label }) => ( @@ -30,8 +34,52 @@ const LocationTestWrapper: React.FC = ({ children }) => { hydrated, isResolvingRegion, locationStatus, + refreshLocation, } = useRegion() + const probeLocation = useLocationStore((state) => state.probe) + + // The region decision happens once per app launch, so a user who leaves for the + // OS settings and turns the location on would come back to a page that never + // notices. While this gate is up, poll for the location becoming usable and + // re-run the decision when it does (which unmounts the gate if it resolves). + // + // `refreshLocation` is a fresh function on every render, so it is held in a ref + // to keep the polling effect from restarting on each render. + const refreshLocationRef = useRef(refreshLocation) + useEffect(() => { + refreshLocationRef.current = refreshLocation + }) + + // Only meaningful once the first decision has settled. + const gateUp = regionId == null && hydrated && !isResolvingRegion + // Last probe result. The first one only seeds the baseline: we act on a change + // (location just turned on / permission just granted), never on the poll itself. + const wasLocationUsable = useRef(null) + + useEffect(() => { + if (!gateUp) return + + let cancelled = false + const check = async () => { + const usable = await probeLocation() + if (cancelled) return + + const previous = wasLocationUsable.current + wasLocationUsable.current = usable + if (usable && previous === false) { + refreshLocationRef.current() + } + } + + void check() + const timer = setInterval(() => void check(), LOCATION_POLL_MS) + return () => { + cancelled = true + clearInterval(timer) + } + }, [gateUp, probeLocation]) + const { data: regions } = trpc.common.listRegions.useQuery() // Tell the user *why* the location isn't usable before asking for an address. diff --git a/apps/user-ui/components/cart-page.tsx b/apps/user-ui/components/cart-page.tsx index 23e8e6d..ee1b013 100644 --- a/apps/user-ui/components/cart-page.tsx +++ b/apps/user-ui/components/cart-page.tsx @@ -36,7 +36,7 @@ import CartAddressGate from '@/components/CartAddressGate'; import { useAddressStore } from '@/src/store/addressStore'; import { useCheckoutStore } from '@/src/store/checkoutStore'; import type { FlashDeliveryProps } from '@packages/shared'; -import { computeCouponDiscount, computeEligibleSubtotal, type CartLine } from '@packages/shared'; +import { computeCouponStack, computeEligibleSubtotal, type CartLine } from '@packages/shared'; const formatDeliverySlot = (deliveryTime: string): string => { const time = dayjs(deliveryTime); @@ -275,49 +275,78 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps [cartItems, quantities, productsById] ); + // Cart lines (in-stock only) with their effective unit price, in the shared + // shape the coupon helpers expect. Declared before the coupon list so coupon + // targeting can be evaluated against the cart. + const cartLines = useMemo( + () => + cartItems + .filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock) + .map((item) => { + const product = productsById[item.skuId]; + const unitPrice = isFlashDelivery + ? (product?.flashPrice ?? product?.price ?? 0) + : (product?.price || 0); + return { + skuId: item.skuId, + quantity: quantities[item.id] || item.quantity, + unitPrice: Number(unitPrice), + }; + }), + [cartItems, productSlotsMap, productsById, isFlashDelivery, quantities] + ); + + // Every coupon we're allowed to surface (the API already drops expired, + // invalidated, usage-limit-exceeded and other users' personal coupons). + // Ineligible ones are kept but flagged with the reason, and sorted to the end. const eligibleCoupons = useMemo(() => { if (!couponsRaw?.data) return []; - return couponsRaw.data - .map((coupon) => { - let isEligible = true; - let ineligibilityReason = ""; - if ( - coupon.maxLimitForUser && - coupon.usages.length >= coupon.maxLimitForUser - ) { - isEligible = false; - ineligibilityReason = "Usage limit exceeded"; - } - if (coupon.minOrder && parseFloat(coupon.minOrder) > baseTotalPrice) { - isEligible = false; - ineligibilityReason = `Min order ₹${coupon.minOrder}`; - } - return { - id: coupon.id, - code: coupon.couponCode, - discountType: coupon.discountPercent ? "percentage" : "flat", - discountValue: parseFloat( - coupon.discountPercent || coupon.flatDiscount || "0" - ), - maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined, - minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined, - description: generateCouponDescription(coupon), - exclusiveApply: coupon.exclusiveApply, - // Raw fields so the shared coupon helpers can be used directly. - discountPercent: coupon.discountPercent, - flatDiscount: coupon.flatDiscount, - applicableSkuIds: [ - ...(coupon.applicableProducts || []).map((p: any) => p.skuId), - ...(Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : []), - ], - isEligible, - ineligibilityReason: isEligible ? undefined : ineligibilityReason, - }; - }) - .filter( - (coupon) => coupon.ineligibilityReason !== "Usage limit exceeded" - ); - }, [couponsRaw, baseTotalPrice]); + const isFirstOrder = couponsRaw.isFirstOrder ?? true; + + const mapped = couponsRaw.data.map((coupon) => { + const applicableSkuIds = [ + ...(coupon.applicableProducts || []).map((p: any) => p.skuId), + ...(Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : []), + ]; + + let reason: string | undefined; + if (coupon.regionId != null && regionId != null && coupon.regionId !== regionId) { + reason = "Not valid in your region"; + } else if (coupon.isFirstOrderOnly && !isFirstOrder) { + reason = "Valid on your first order only"; + } else if (coupon.minOrder && parseFloat(coupon.minOrder) > baseTotalPrice) { + const shortfall = Math.ceil(parseFloat(coupon.minOrder) - baseTotalPrice); + reason = `Add ₹${shortfall} more to use this coupon`; + } else if ( + applicableSkuIds.length > 0 && + computeEligibleSubtotal(cartLines, { applicableSkuIds }) <= 0 + ) { + reason = "No applicable items in your cart"; + } + + return { + id: coupon.id, + code: coupon.couponCode, + discountType: coupon.discountPercent ? "percentage" : "flat", + discountValue: parseFloat( + coupon.discountPercent || coupon.flatDiscount || "0" + ), + maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined, + minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined, + description: generateCouponDescription(coupon), + exclusiveApply: coupon.exclusiveApply, + // Raw fields so the shared coupon helpers can be used directly. + discountPercent: coupon.discountPercent, + flatDiscount: coupon.flatDiscount, + applicableSkuIds, + isEligible: !reason, + ineligibilityReason: reason, + }; + }); + + // Applicable coupons first, disabled ones at the end (stable within groups). + return mapped.sort((a, b) => Number(b.isEligible) - Number(a.isEligible)); + }, [couponsRaw, baseTotalPrice, cartLines, regionId]); const updateCartItem = useUpdateCartItem({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, cartType); const removeFromCart = useRemoveFromCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, cartType); @@ -367,33 +396,19 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps }; }, [slotsData]); - // Calculate coupon discount - const selectedCoupons = useMemo( - () => - eligibleCoupons?.filter( - (coupon) => selectedCouponIds.includes(coupon.id) && coupon.isEligible - ) ?? [], - [eligibleCoupons, selectedCouponIds] + // Coupons currently applied, kept in the order the user selected them — the + // order matters because coupons stack sequentially. + const couponById = useMemo( + () => new Map(eligibleCoupons.map((coupon) => [coupon.id, coupon])), + [eligibleCoupons] ); - // Cart lines (in-stock only) with their effective unit price, in the shared - // shape the coupon helpers expect. - const cartLines = useMemo( + const selectedCoupons = useMemo( () => - cartItems - .filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock) - .map((item) => { - const product = productsById[item.skuId]; - const unitPrice = isFlashDelivery - ? (product?.flashPrice ?? product?.price ?? 0) - : (product?.price || 0); - return { - skuId: item.skuId, - quantity: quantities[item.id] || item.quantity, - unitPrice: Number(unitPrice), - }; - }), - [cartItems, productSlotsMap, productsById, isFlashDelivery, quantities] + selectedCouponIds + .map((id) => couponById.get(id)) + .filter((coupon): coupon is NonNullable => !!coupon && coupon.isEligible), + [selectedCouponIds, couponById] ); const totalPrice = cartItems @@ -416,40 +431,80 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps const saving = marketPrice - Number(price); return sum + (saving > 0 ? saving : 0) * quantity; }, 0); - const dropdownData = useMemo( - () => + // "Save ₹x" for an option = the MARGINAL saving of adding it to the current + // selection (coupons stack, so a coupon's worth depends on what is already on). + // A coupon that is already applied shows its own current contribution. + const dropdownData = useMemo(() => { + const base = computeCouponStack(cartLines, selectedCoupons); + const selectedIds = new Set(selectedCoupons.map((c) => c.id)); + return ( eligibleCoupons?.map((coupon) => { - const discount = computeCouponDiscount( - computeEligibleSubtotal(cartLines, { applicableSkuIds: coupon.applicableSkuIds }), - coupon - ); - const saveString = !isNaN(discount) ? ` (Save ₹${discount})` : ""; - const baseLabel = `${coupon.code} - ${coupon.description}${coupon.isEligible ? saveString : "" - }`; - const label = coupon.isEligible - ? baseLabel - : `${baseLabel} (${coupon.ineligibilityReason})`; - return { - label, - value: coupon.id, - disabled: !coupon.isEligible, - }; - }) || [], - [eligibleCoupons, cartLines] - ); + // Disabled coupons can't be applied: row 1 shows just the code (with the + // italic "Disabled" badge), row 2 the reason. No "Save" preview. + if (!coupon.isEligible) { + return { + label: coupon.code, + value: coupon.id, + disabled: true, + note: coupon.ineligibilityReason, + }; + } + let save: number; + if (selectedIds.has(coupon.id)) { + save = base.perCoupon.find((entry) => entry.couponId === coupon.id)?.discount ?? 0; + } else { + const withCoupon = computeCouponStack(cartLines, [...selectedCoupons, coupon]); + save = withCoupon.discountTotal - base.discountTotal; + } + return { + label: `${coupon.code} - ${coupon.description} (Save ₹${save})`, + value: coupon.id, + disabled: false, + }; + }) || [] + ); + }, [eligibleCoupons, cartLines, selectedCoupons]); + + // The coupon dropdown is a multi-select: it toggles an id and reports the whole + // new list. An exclusive coupon still replaces every other selection (and + // nothing may be added alongside one), so the toggle is filtered here. + const handleCouponSelectionChange = (value: string | number | string[] | number[]) => { + const next = (Array.isArray(value) ? value : []).map((v) => Number(v)); + + setSelectedCouponIds((prev) => { + const added = next.find((id) => !prev.includes(id)); + const removed = prev.find((id) => !next.includes(id)); + + // A deselect (or a no-op change) needs no exclusivity handling. + if (added == null || removed != null) return next; + + const coupon = eligibleCoupons.find((c) => c.id === added); + const hasExclusive = prev.some( + (pid) => eligibleCoupons.find((c) => c.id === pid)?.exclusiveApply + ); + // An exclusive coupon replaces every other selection. + if (coupon?.exclusiveApply || hasExclusive) return [added]; + return next; + }); + }; + + // What each applied coupon takes off, keyed by coupon id. Coupons stack in the + // order they were selected, so a later coupon only sees what the earlier ones + // left behind (this must match the backend's computeCartPricing). + const couponDiscounts = useMemo(() => { + const discounts: Record = {}; + const { perCoupon } = computeCouponStack(cartLines, selectedCoupons); + perCoupon.forEach((entry) => { + discounts[entry.couponId] = entry.discount; + }); + return discounts; + }, [selectedCoupons, cartLines]); + + // Sum of the per-coupon discounts, so the bill's lines always add up to it. const discountAmount = useMemo( - () => - selectedCoupons?.reduce( - (sum, coupon) => - sum + - computeCouponDiscount( - computeEligibleSubtotal(cartLines, { applicableSkuIds: coupon.applicableSkuIds }), - coupon - ), - 0 - ) || 0, - [selectedCoupons, cartLines] + () => Object.values(couponDiscounts).reduce((sum, value) => sum + value, 0), + [couponDiscounts] ); const finalTotal = totalPrice - discountAmount; @@ -480,6 +535,62 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps const hasAvailableItems = cartItems.some(item => !productSlotsMap[item.skuId]?.isOutOfStock); + // Checkout blockers (scheduled delivery only). An in-stock item can't be + // delivered when its SKU has no slots published at all ("not in the slots + // file"), when the slot chosen for it is no longer offered for that item, or + // when that slot's freeze time has passed. Any such item disables the checkout + // button, and the reason is shown beneath it. + const slotCheck = useMemo<{ blocked: boolean; itemIds: number[]; message: string | null }>(() => { + if (isFlashDelivery) { + return { blocked: false, itemIds: [], message: null }; + } + + const now = dayjs(); + const noSlots: number[] = []; // SKU missing from the slots file (or no slots) + const unavailable: number[] = []; // selected slot not offered for the item + const closed: number[] = []; // selected slot's freeze time passed + + cartItems.forEach((item) => { + if (productSlotsMap[item.skuId]?.isOutOfStock) return; + + const productSlots = slotsData?.[item.skuId]; + if (!productSlots || productSlots.length === 0) { + noSlots.push(item.id); + return; + } + + const slot = productSlots.find((s) => s.id === selectedSlots[item.id]); + if (!slot) { + unavailable.push(item.id); + return; + } + + if (dayjs(slot.freezeTime).isBefore(now)) { + closed.push(item.id); + } + }); + + if (noSlots.length > 0 || unavailable.length > 0) { + return { + blocked: true, + itemIds: [...noSlots, ...unavailable], + message: + 'Some items in your cart are no longer available for delivery. Please remove them to continue.', + }; + } + if (closed.length > 0) { + return { + blocked: true, + itemIds: closed, + message: + 'The delivery slot for some items has closed. Please pick a new slot to continue.', + }; + } + return { blocked: false, itemIds: [], message: null }; + }, [isFlashDelivery, cartItems, productSlotsMap, slotsData, selectedSlots]); + + const isCheckoutDisabled = slotCheck.blocked; + const slotGroups = useMemo(() => { if (isFlashDelivery || cartItems.length === 0) return []; @@ -1117,22 +1228,9 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps { - if (!value) return; - const id = Number(value); - const coupon = eligibleCoupons.find((c) => c.id === id); - if (!coupon) return; - setSelectedCouponIds((prev) => { - if (prev.includes(id)) return prev; - const hasExclusive = prev.some( - (pid) => eligibleCoupons.find((c) => c.id === pid)?.exclusiveApply - ); - // An exclusive coupon replaces every other selection. - if (coupon.exclusiveApply || hasExclusive) return [id]; - return [...prev, id]; - }); - }} + value={selectedCouponIds} + onValueChange={handleCouponSelectionChange} + multiple placeholder={ eligibleCoupons.length === 0 ? "No coupons available" @@ -1140,6 +1238,39 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps } /> + {/* Selected coupons, each removable with the "x" on its right */} + {selectedCouponIds.length > 0 && ( + + {selectedCouponIds.map((id) => { + const coupon = eligibleCoupons.find((c) => c.id === id); + if (!coupon) return null; + return ( + + + {coupon.code} + + + setSelectedCouponIds((prev) => + prev.filter((cid) => cid !== id) + ) + } + style={tw`p-0.5`} + activeOpacity={0.7} + > + + + + ); + })} + + )} + {eligibleCoupons.length === 0 && ( No coupons available for this order @@ -1217,31 +1348,35 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps ₹{Math.trunc(totalPrice)} - {/* Total Discount */} + {/* Products discount (market-price savings) */} {totalSavings > 1 && ( - Total Discount + Products discount ₹{Math.trunc(totalSavings)} )} - {/* Discount */} - {discountAmount > 0 && ( - - Product Discount - -₹{Math.trunc(discountAmount)} - - )} - - {/* Applied Coupon */} - {selectedCoupons.length > 0 && ( - - Coupon Applied - setCouponDialogOpen(true)}> - {selectedCoupons.map((coupon) => coupon.code).join(', ')} + {/* Coupon discounts: every applied coupon and what it takes off */} + {selectedCoupons.map((coupon) => ( + + setCouponDialogOpen(true)} + activeOpacity={0.7} + > + + + {coupon.code} + + + -₹{Math.trunc(couponDiscounts[coupon.id] || 0)} + - )} + ))} {/* Delivery Fee */} @@ -1302,7 +1437,8 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps { const availableItems = cartItems .filter(item => { @@ -1391,6 +1527,15 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps + + {slotCheck.blocked && ( + + + + {slotCheck.message} + + + )} )} diff --git a/apps/user-ui/components/checkout-page.tsx b/apps/user-ui/components/checkout-page.tsx index b7ffe69..b0ff271 100644 --- a/apps/user-ui/components/checkout-page.tsx +++ b/apps/user-ui/components/checkout-page.tsx @@ -17,7 +17,7 @@ import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent'; import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay'; import { useAddressStore } from '@/src/store/addressStore'; import type { FlashDeliveryProps } from '@packages/shared'; -import { computeCouponDiscount, computeEligibleSubtotal, type CartLine } from '@packages/shared'; +import { computeCouponStack, type CartLine } from '@packages/shared'; const CheckoutPage: React.FC = ({ isFlashDelivery = false }) => { const params = useLocalSearchParams(); @@ -204,12 +204,19 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) }).filter(coupon => coupon.ineligibilityReason !== 'Usage limit exceeded'); }, [couponsRaw, totalPrice]); + // Coupons applied, kept in the order the user selected them: coupons stack + // sequentially, so the order changes the result. + const couponById = useMemo( + () => new Map(eligibleCoupons.map((coupon) => [coupon.id, coupon])), + [eligibleCoupons] + ); + const selectedCoupons = useMemo( () => - eligibleCoupons?.filter( - (coupon) => selectedCouponIds.includes(coupon.id) && coupon.isEligible - ) ?? [], - [eligibleCoupons, selectedCouponIds] + selectedCouponIds + .map((id) => couponById.get(id)) + .filter((coupon): coupon is NonNullable => !!coupon && coupon.isEligible), + [selectedCouponIds, couponById] ); // Lines being ordered, with their effective unit price, for the shared helpers. @@ -228,16 +235,7 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) ); const discountAmount = useMemo( - () => - selectedCoupons?.reduce( - (sum, coupon) => - sum + - computeCouponDiscount( - computeEligibleSubtotal(cartLines, { applicableSkuIds: coupon.applicableSkuIds }), - coupon - ), - 0 - ) || 0, + () => computeCouponStack(cartLines, selectedCoupons).discountTotal, [selectedCoupons, cartLines] ); diff --git a/apps/user-ui/src/components/NotifRegionSync.tsx b/apps/user-ui/src/components/NotifRegionSync.tsx index a315859..c8210cf 100644 --- a/apps/user-ui/src/components/NotifRegionSync.tsx +++ b/apps/user-ui/src/components/NotifRegionSync.tsx @@ -4,8 +4,8 @@ import { useRegion } from '@/src/hooks/useRegion' import { useNotification } from '@/services/notif-service/notif-context' /** - * Keeps the region stored alongside the push credentials in step with the user's - * region, and records a location-derived user<->region association. + * Registers the push token with the user's current region and records a + * location-derived user<->region association. * * It renders inside NotificationProvider (see app/_layout.tsx), which is the * only place the push token is available. Both ways a region becomes known land @@ -16,8 +16,11 @@ import { useNotification } from '@/services/notif-service/notif-context' * fallback switches the region, which clears the gate and mounts this * component with the new region already in place. * - * The region is carried with the push token, so the notif-creds API stores it - * (nullable) for whichever token the device registered. + * The region sent here is only a fallback: for a signed-in user who has an + * address, the server ignores it and keeps the token on their ADDRESS's region + * (see syncUserNotifCredRegion). A tracked location therefore records the + * association below but can never move the token to another region — only adding + * or moving an address does that. */ const NotifRegionSync: React.FC = () => { const { expoPushToken, notifPermission } = useNotification() diff --git a/apps/user-ui/src/store/locationStore.ts b/apps/user-ui/src/store/locationStore.ts index 784183e..67954c2 100644 --- a/apps/user-ui/src/store/locationStore.ts +++ b/apps/user-ui/src/store/locationStore.ts @@ -33,6 +33,13 @@ interface LocationStoreState { stop: () => void /** Force a fresh permission check + fix (used by a manual "use my location"). */ refresh: () => Promise + /** + * Side-effect-free "is the device location usable right now?" (permission + * granted AND services enabled). Takes no fix and touches neither `status` nor + * `coords`, so a screen that polls it while waiting for the user to turn the + * location on does not flicker the way `refresh()` would. + */ + probe: () => Promise } // Abort the fix read if the GPS never answers, so the UI can fall back to @@ -132,4 +139,21 @@ export const useLocationStore = create((set, get) => ({ }) } }, + + probe: async () => { + try { + const { status } = await Location.getForegroundPermissionsAsync() + if (status !== 'granted') return false + + // Device location services (GPS) can be off independently of the app + // permission, and turning them on does not re-prompt. + const servicesEnabled = + typeof Location.hasServicesEnabledAsync === 'function' + ? await Location.hasServicesEnabledAsync() + : true + return servicesEnabled + } catch { + return false + } + }, })) diff --git a/apps/user-ui/tests/screens/cart-money.test.tsx b/apps/user-ui/tests/screens/cart-money.test.tsx index 8c752b8..539ce17 100644 --- a/apps/user-ui/tests/screens/cart-money.test.tsx +++ b/apps/user-ui/tests/screens/cart-money.test.tsx @@ -137,7 +137,7 @@ describe('cart money math', () => { renderWithProviders() - await waitFor(() => expect(screen.getByText('Total Discount')).toBeVisible()) + await waitFor(() => expect(screen.getByText('Products discount')).toBeVisible()) expect(screen.getByText('₹5')).toBeVisible() }) diff --git a/change-log.txt b/change-log.txt index 09829fb..e548af4 100644 --- a/change-log.txt +++ b/change-log.txt @@ -4421,3 +4421,242 @@ user-ui also reassigns user_id, keeping the "does not erase a known region" rule. One row per token, owned by whoever registered it last, so the previous account stops receiving on that device. No schema/migration change. No dependency added. No tests run. + +2026-10-15 17:37:57 The push token's region now follows the user's ADDRESS, never the device + location. Location in region n + an address in region m must leave the token on m; only an + address change may move it. + + packages/db_helper_sqlite/src/user-apis/user-regions.ts + - + getUserAddressRegionId(userId): the user's delivery region = their default address's + region, else the region of their newest address (by id), else null. + - + syncUserNotifCredRegion(userId): UPDATE notif_creds SET region_id =
+ WHERE user_id = . No-op when the user has no address (never erases a known region). + packages/db_helper_sqlite/index.ts + - export the two new helpers (next to the other user-region exports). + apps/backend/src/trpc/apis/user-apis/apis/user.ts + - savePushToken (authed branch): the token's region is the user's ADDRESS region when they + have one, overriding the caller-supplied browsing region; the signed-out carry-over is + now only read when there is no address AND the caller sent no region. + - + import getUserAddressRegionId as getUserAddressRegionIdInDb. + apps/backend/src/trpc/apis/user-apis/apis/address.ts + - createAddress: also syncUserNotifCredRegion(userId) in the existing best-effort block. + - updateAddress / deleteAddress: same call next to reconcileUserRegions (address moved, + address removed). Still best effort: the address write has already committed. + - + import syncUserNotifCredRegion. + apps/user-ui/src/components/NotifRegionSync.tsx + - comment only: the region it sends is no longer authoritative for users with an address. + Net effect: adding/moving/removing an address moves the token's region; a tracked location + still records the user<->region association (recordTrackedRegion / from_location) but can no + longer change the token's region. No schema/migration change. No dependency added. + No tests run. + +2026-10-15 17:44:22 Cart page coupon picker (apps/user-ui/components/cart-page.tsx): + selected coupons now highlight in the dropdown, and the selection is listed as removable + chips under it. + + - The "Available Coupons" BottomDropdown was used in single mode with value="" and the + multi-select done by hand, so BottomDropdown never saw a selection and nothing could + highlight. Switched it to the component's existing multiple mode: value={selectedCouponIds} + (numbers), multiple. + - + handleCouponSelectionChange(value): the dropdown now reports the whole toggled list, so + this converts it to ids and keeps the exclusive-coupon rule (an exclusive coupon replaces + everything; nothing can be added alongside one). A deselect is passed straight through. + - + a row of chips directly under the dropdown: one chip per selected coupon showing its code + and an "x" (MaterialIcons close) that removes that coupon. Chips use bg-pink-50 / + border-pink-200 / text-pink-700 (same pink accent as the Offers & Coupons section). + - The existing "Remove coupons" link is left as-is (clears all in one go). + No other file changed. No dependency added. No tests run. + +2026-10-15 17:48:08 Cart bill section (apps/user-ui/components/cart-page.tsx): list every + applied coupon with the discount it brings in, instead of one aggregated line. + + - + couponDiscounts memo: coupon id -> the discount computeCouponDiscount() gives that coupon + on its own eligible subtotal (same expression the dropdown already used for "Save ₹x"). + - discountAmount is now derived from couponDiscounts, so the per-coupon rows always sum to + the total the bill subtracts. + - Bill details: replaced the single "Product Discount -₹X" row and the "Coupon Applied" + codes row with one row per applied coupon - offer icon + coupon code on the left, the + coupon's own discount (green, -₹X) on the right. Tapping a coupon still opens the existing + "Applied Coupons" dialog, so that stays reachable. + No other file changed. No dependency added. No tests run. + +2026-10-15 17:57:18 Location gate: poll for the device location so turning it on updates the page + (apps/user-ui/src/store/locationStore.ts, apps/user-ui/components/LocationTestWrapper.tsx). + + Why: the region decision runs ONCE per app launch (locationStore.start is idempotent and + useRegion settles its startup check once). A user sent to the OS settings from the region gate + therefore came back to a page that never noticed the location had been turned on. + + - locationStore: + probe(): Promise - a side-effect-free check of "permission granted + AND services enabled" using getForegroundPermissionsAsync + hasServicesEnabledAsync. It does + NOT set status/coords and takes no fix, so a screen that polls it never flickers (refresh() + would set status 'locating' -> the gate would swap in the "Finding your region..." spinner). + - LocationTestWrapper: while the gate is up (no region, hydrated, not resolving) it runs + probe() every 3s and, when the result goes false -> true (location just turned on / permission + just granted), calls useRegion().refreshLocation() to re-run the region decision - which + unmounts the gate if the location now resolves. The first probe only seeds the baseline, so + the gate never re-resolves on its own; refreshLocation is held in a ref to keep the effect + stable. + No other file changed. No dependency added. No tests run. + +2026-10-15 18:01:02 CartAddressGate: same 3s location poll + (apps/user-ui/components/CartAddressGate.tsx). + + The "Address of current Location" option is disabled until the store has coords, and the store + takes its fix once per launch - so turning the location on after landing here never enabled it. + + - While there are no coords yet, probe() every 3s and, when the location is usable, call the + store's refresh() to take a fresh fix (which populates coords -> the option enables and its + label switches to the coordinates). Skips a tick while a fix is already in flight + (status 'locating'), and stops polling as soon as coords exist. + - Uses the store's refresh(), not useRegion().refreshLocation(): a region is already known on + this screen, and re-running the region decision here would be wrong. + No other file changed. No dependency added. No tests run. + +2026-10-15 18:16:33 Move "Enable Flash Delivery" (isFlashDeliveryEnabled) from region level + (region_consts) to bound level (region_bound_consts). Purely bound-scoped: no region default, + no inheritance. Each bound switches flash delivery on/off independently. + + packages/db_helper_sqlite/src/lib/const-keys.ts + apps/backend/src/lib/const-keys.ts + - isFlashDeliveryEnabled moved REGION_CONST_KEYS -> BOUND_CONST_KEYS (CONST_SCOPE is derived). + apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts + - scaffoldEssentialConsts: read it from the bound consts (moved into the region_bound_consts + block) instead of the region consts. The payload is already built per bound, so the client + contract is unchanged. + apps/backend/src/trpc/apis/user-apis/apis/order.ts + - placeOrder flash guard: resolve the delivery address's bound (resolvedBoundId ?? address + .boundId ?? params.boundId ?? effective bound) and read getRegionSettingsForBound, falling + back to the region's effective bound. Was getEffectiveRegionSettings(regionId). + apps/backend/src/lib/flash-delivery-cron.ts + - the 6:30 PM on / 9:30 PM off cron now flips the flag on EVERY BOUND (was every region). + apps/superadmin-ui/src/routes/regions.tsx + - key moved REGION_SETTING_KEYS -> SETTING_KEYS (per-bound editor). + apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx + apps/admin-web/src/routes/dashboard.customize-app.tsx + - key moved REGION_KEYS -> BOUND_KEYS (the bound tab already saves via + admin.region.updateBoundSettings). + packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql (not yet applied to prod, + so edited in place): + - dropped the region_consts seed for the key + - + a region_bound_consts seed for every bound of Mahabubnagar, carrying over the legacy + global value (key_val_store) -> '1.0' / enabled, then that legacy row is deleted as before + - removed the key from the region-level key_val_store fallback list + apps/backend/dev-migration-flash-delivery-bound.sql (NEW, dev only) + - the same move for the already-migrated dev DB: every bound inherits its region's current + value, then the region row is deleted. + apps/backend/migrated.sql: DELIBERATELY UNCHANGED. It is the pre-region baseline dump (no + regions/consts tables, key_val_store isFlashDeliveryEnabled='1.0'), imported before 0000..0006. + Editing it would break the new seed, which reads that very row. + Not done (needs a switch / not asked): tests. tests/helpers/consts.ts setConst routes through + updateConstants, which ignores bound-scope keys, so the flash tests and the admin-ui + customize-app-hub test need a bound-settings setter / tab move. No tests run. + - Coupon stacking: switched multiple coupons from parallel (each on the full + eligible base) to a sequential waterfall applied in the order the user selected + them, each rounded to the nearest rupee. Files: + * packages/shared/cart-pricing.ts: add computeCouponStack(); rewrite + computeCartPricing to run the stack over per-line remainders, allocate each + coupon's rounded discount to sub-orders (reconciled to sum exactly), and drop + the percent-first re-sort. computeCouponDiscount/computeEligibleSubtotal kept. + * packages/db_helper_sqlite/src/user-apis/order.ts: validateAndGetCoupons no + longer re-sorts percent-first; keeps the caller's (selection) order. + * apps/backend/src/trpc/apis/user-apis/apis/order.ts: comment updated only. + * apps/user-ui/components/cart-page.tsx: build selectedCoupons in selection + order; marginal "Save Rs x" from the shared stack; per-coupon discounts from + the stack (integers). + * apps/user-ui/components/checkout-page.tsx: same order-preserving selection + + shared stack for the discount total. + * apps/backend/tests/api/coupon-math.test.ts: rounding pin updated; multi-coupon + order-sensitive cases added. + maxValue cap unchanged (still enforced + still shown in UI); minOrder still + validated on the original eligible subtotal. No schema/migration change. Tests + not run. + - apps/user-ui/components/cart-page.tsx: relabelled the savings row from + "Total Discount" to "Products discount" (it shows the market-price gap, i.e. + totalSavings). Updated apps/user-ui/tests/screens/cart-money.test.tsx to match. + No tests run. + - apps/user-ui/components/cart-page.tsx: block checkout when an in-stock item can't + be delivered on scheduled delivery — its SKU has no slots in the slots file, the + selected slot is no longer offered for the item, or the selected slot's freeze + time has passed. The checkout button is disabled and the reason is shown beneath + it. Flash delivery is unaffected. No tests run. + - Coupon dropdown: show every coupon the customer may see (not expired, not + invalidated, not another user's personal coupon) and mark the unusable ones + disabled at the end of the list with a reason. Reasons: region ("Not valid in + your region"), first-order-only ("Valid on your first order only"), usage limit + ("You've reached the usage limit"), min order not met ("Add Rs X more..."), no + matching items ("No applicable items in your cart"). + * apps/backend/src/trpc/apis/user-apis/apis/coupon.ts: getEligible no longer + filters by region/first-order; returns all visible coupons + `isFirstOrder`. + Still excludes expired, invalidated, and other users' personal coupons. + * packages/shared/types/user.ts: UserCoupon gains optional `regionId`; + UserEligibleCouponsResponse gains optional `isFirstOrder`. + * packages/db_helper_sqlite/src/user-apis/coupon.ts: map regionId. + * packages/ui/src/components/bottom-dropdown.tsx: optional second line (`note`) + + italic "Disabled" badge on disabled options (backwards compatible). + * apps/user-ui/components/cart-page.tsx: compute reasons, order eligible first, + two-row disabled options; cartLines moved above eligibleCoupons. + No tests run. + - Coupon dropdown: also hide usage-limit-exceeded coupons (like expired / + invalidated / other users' personal) instead of listing them disabled. + * apps/backend/src/trpc/apis/user-apis/apis/coupon.ts: getEligible drops + coupons whose per-user usage reached maxLimitForUser. + * apps/user-ui/components/cart-page.tsx: removed the "usage limit" reason + branch (now unreachable). No tests run. + - Timestamp: 2026-10-15 20:12:03 + Fix: complaints were saved with order_id = NULL, so the admin-ui (and user-ui) + complaints screens could never show the related order. The app sends the raw + numeric order id (e.g. "137"), but the raise handler only parsed the display + form "ORD137". + File: apps/backend/src/trpc/apis/user-apis/apis/complaint.ts + Diff: + - const readableIdMatch = orderId.match(/^ORD(\d+)$/); + - if (readableIdMatch) { + - orderIdNum = parseInt(readableIdMatch[1]); + - } + + // The app sends the raw numeric order id (e.g. "137"); the display + + // form "ORD137" is also accepted for backwards compatibility. + + const orderIdMatch = orderId.match(/^(?:ORD-?)?(\d+)$/); + + if (orderIdMatch) { + + orderIdNum = parseInt(orderIdMatch[1]); + + } + - Timestamp: 2026-10-15 20:25:19 + Feature: region-scoped complaints. Complaints now carry region_id (nullable); + region admins see only their region's complaints, superadmin gets an + all-complaints list. Region is resolved at raise time: order's region -> + user's default address region -> newest address region -> user_regions row -> + NULL. Existing complaints backfilled (all -> Mahabubnagar) inside the same + 0006 migration since it is not yet applied to production. + Files: + * packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + __new_complaints: + `region_id` integer + FK -> regions(id); + copy SELECT injects (SELECT id FROM regions WHERE name='Mahabubnagar'); + + CREATE INDEX idx_complaints_region ON complaints(region_id). + * packages/db_helper_sqlite/src/db/schema.ts + complaints: + regionId: integer('region_id').references(() => regions.id) + * packages/shared/types/complaint.types.ts + Complaint: + regionId: number | null + * packages/db_helper_sqlite/src/user-apis/complaint.ts + + resolveComplaintRegionId(userId, orderId); createComplaint stores it. + * packages/db_helper_sqlite/src/admin-apis/complaint.ts + getComplaints/getComplaintById/resolveComplaint scope by complaints.regionId + (drop orders join / order-region checks). + * packages/db_helper_sqlite/src/admin-apis/user.ts + getUnresolvedComplaintsCount scopes by complaints.regionId. + * apps/backend/src/trpc/apis/admin-apis/apis/complaint.ts + getAll returns regionId. + * packages/db_helper_sqlite/src/superadmin-apis/complaint.ts (new) + getAllComplaintsForSuperadmin(cursor, limit) -> complaint + user + region name. + * packages/db_helper_sqlite/index.ts + apps/backend/src/sqliteImporter.ts + export the new superadmin helper. + * apps/backend/src/trpc/apis/superadmin-apis/apis/complaint.ts (new) + + superadmin-trpc-index.ts: register superadmin.complaint.getAll. + * apps/superadmin-ui/src/routes/complaints.tsx (new) + + apps/superadmin-ui/src/components/AppShell.tsx: nav + page. + No tests run; migrations not run. + - Timestamp: 2026-10-15 20:29:15 + Temporary (non-repo) delta SQL for the already-migrated local D1, since the + region-scoped complaints column is now folded into 0006 (already applied + locally without it). File: + /private/var/folders/6t/3blzq7_j6p95xzry6t7c14hw0000gn/T/opencode/add_complaints_region.sql + (ALTER TABLE complaints ADD COLUMN region_id + backfill + idx_complaints_region). diff --git a/docs/test-cases/README.md b/docs/test-cases/README.md index f188e98..03d0d4d 100644 --- a/docs/test-cases/README.md +++ b/docs/test-cases/README.md @@ -6,7 +6,7 @@ This folder contains feature-by-feature acceptance and regression checklists for **All cases are proposed and NOT RUN.** A listed expected result is a requirement to verify, not a claim that the implementation currently satisfies it. Known review defects are intentionally covered. Documentation creation does not authorize running tests, sending notifications, charging payments, deleting data, or applying migrations. -Inventory: **45 feature checklists and 815 uniquely identified cases**, plus this index. Features are grouped by business responsibility; closely related operations share a checklist (for example stock, offer flags and suspension). Reuse the shared boundary/security matrix rather than assuming a finite list can cover every possible input. +Inventory: **46 feature checklists and 862 uniquely identified cases**, plus this index. Features are grouped by business responsibility; closely related operations share a checklist (for example stock, offer flags and suspension). Reuse the shared boundary/security matrix rather than assuming a finite list can cover every possible input. Sources: current routers/screens/helpers, existing API tests, [sanity plan](../e2e-sanity-test-plan.md), and [branch review](../multi-region-i2-review.md). Older sanity-plan statements that coupons ignore regions/SKUs are superseded here by the newer coupon requirements. Vendor snippets and reviews remain conditional/legacy coverage; online gateway cases are readiness coverage until implementation is enabled. @@ -50,7 +50,7 @@ Use unique run prefixes. Do not delete regions for cleanup: region deletion is u | Catalog administration | [Regional stores](regional-stores.md), [Global stores](global-stores.md), [Regional products](regional-products.md), [Global products/elevation](global-products.md), [Prices/stock/suspension](prices-stock-suspension.md), [Combos](combos.md) | | Merchandising | [Catalog/search](catalog-search.md), [Tags/order](product-tags-ordering.md), [Groups](product-groups.md), [Banners](banners.md) | | Purchasing | [Slots](scheduled-slots.md), [Cart](cart.md), [Addresses](addresses.md), [Checkout](checkout.md), [Pricing](pricing-delivery-fees.md), [Flash](flash-delivery.md) | -| Coupons | [Administration](coupon-management.md), [Eligibility/stacking](coupon-application.md), [Reserved/cancellation coupons](reserved-coupons.md) | +| Coupons | [Administration](coupon-management.md), [Eligibility/stacking](coupon-application.md), [Stacking & cart guards](coupon-stacking-and-cart-guards.md), [Reserved/cancellation coupons](reserved-coupons.md) | | Order operations | [Placement/history](orders.md), [Fulfillment](fulfillment.md), [Cancellation](cancellation.md), [Edits/rebalance](order-edits-rebalance.md), [Delivery sequence/maps](delivery-operations.md), [Payment/refund readiness](payments-refunds.md) | | Support | [Complaints](complaints.md), [Customer operations/incidents](customer-management-incidents.md), [Notifications](notifications.md) | | Infrastructure | [Uploads](uploads-images.md), [Cache publication](cache-publication.md), [Jobs/health](jobs-health.md), [Security](authorization-api-contracts.md), [Recovery/platform/accessibility](recovery-platform-accessibility.md) | diff --git a/docs/test-cases/coupon-stacking-and-cart-guards.md b/docs/test-cases/coupon-stacking-and-cart-guards.md new file mode 100644 index 0000000..94147b5 --- /dev/null +++ b/docs/test-cases/coupon-stacking-and-cart-guards.md @@ -0,0 +1,110 @@ +# Coupon stacking, coupon list, cart discount label and checkout guards + +Status: proposed checklist (NOT RUN). Covers the recently added behaviour only: +sequential coupon stacking (rounded to the nearest rupee, applied in the customer's +selection order), the cart coupon dropdown's visibility/ineligibility rules, the +cart "Products discount" row, the cart checkout guard for closed/unavailable +delivery slots, and the backend `create-user` script. + +Priority and evidence rules follow the [catalog README](README.md). Money cases +must be checked on the **persisted** order and the order-detail response, not just +the cart preview — assert `goods − stored discount + delivery = payable` per +sub-order and in aggregate, with no negative/non-finite values. + +Fixtures: reuse the shared fixtures (Regions A/B, A1/A2 bounds, coupons, slots +S1/S2 plus inactive/frozen/past, products P/Q/G, multi-slot cart). Use a second +isolated customer for ownership cases. + +## Decisions these cases assume (now agreed) + +- Coupons stack **sequentially on the remaining amount**, in the **order the + customer applied them** (chips shown in the same order). +- Each coupon's discount is **rounded to the nearest rupee** (`Math.round`); no + decimals on discounts. +- `maxValue` still caps **that** coupon's discount, computed on the reduced base. +- `minOrder` is validated against the **original** eligible subtotal (pre-discount). +- Hidden entirely: **expired**, **invalidated**, **usage-limit-exceeded**, and + **other users' personal** coupons. +- The checkout guard applies to **scheduled delivery only** (flash is exempt). + +## A. Sequential coupon stacking (shared math + backend authoritative) + +| ID | Priority | Action / input | Expected result | +|---|---|---|---| +| CSQ-01 | P0 | ₹1000 cart; apply 10% then flat ₹100. | Discounts 100 then 100 → 200; payable 800. | +| CSQ-02 | P0 | Same coupons, applied flat ₹100 then 10%. | 100 then 90 → 190; payable 810. Order changes the result. | +| CSQ-03 | P0 | 15% on ₹999. | Discount rounds to 150 (nearest rupee); payable 849, no decimals. | +| CSQ-04 | P0 | 10% then 20% on ₹1000. | 100 then 180 → 280; payable 720 (second uses the remaining). | +| CSQ-05 | P1 | Percentage with `maxValue` after a prior coupon. | Cap applies to its own reduced base (50% max ₹100 on ₹900 → 100). | +| CSQ-06 | P1 | Flat discount larger than the remaining eligible amount. | Discount clamped to remaining; totals never negative. | +| CSQ-07 | P1 | Targeted coupon (SKU X) then whole-cart coupon. | Targeted discount hits only X's line; the next coupon sees the whole cart's remainder. | +| CSQ-08 | P1 | Two targeted coupons overlapping on SKU X. | The second coupon's base excludes the first's discount on X. | +| CSQ-09 | P1 | Multi-slot cart with one coupon. | Per-sub-order shares sum exactly to the coupon discount; delivery charged once on the primary sub-order. | +| CSQ-10 | P0 | Place the order after stacking. | Cart preview = checkout = persisted `totalAmount` = order detail: `goods − discount + delivery`. | +| CSQ-11 | P1 | ≥100% coupon (e.g. 150%). | Goods never below zero; delivery may still be added; no negative totals. | +| CSQ-12 | P1 | Single coupon (regression). | Only change vs old behaviour is rounding to the nearest rupee. | +| CSQ-13 | P2 | Exclusive coupon combined with any other. | Combination rejected; exclusive applies alone. | +| CSQ-14 | P2 | Rounding exactly at `.5` (e.g. discount 149.5). | Rounds up (nearest rupee), consistently on client and server. | + +## B. Coupon list visibility and disabled reasons (cart dropdown) + +| ID | Priority | Action / input | Expected result | +|---|---|---|---| +| CLS-01 | P0 | Open the coupon dropdown on a populated cart. | Every coupon the customer may see is listed; applicable first, disabled last. | +| CLS-02 | P0 | Inspect a disabled row. | Row 1: CODE + italic **Disabled**; row 2: the reason. Not tappable. | +| CLS-03 | P0 | Coupon scoped to another region. | Shown disabled: "Not valid in your region". | +| CLS-04 | P0 | First-order-only coupon, customer already ordered. | Shown disabled: "Valid on your first order only". | +| CLS-05 | P1 | `minOrder` above cart subtotal. | Shown disabled: "Add ₹X more to use this coupon" (X = shortfall). | +| CLS-06 | P1 | Targeted coupon matching no cart items. | Shown disabled: "No applicable items in your cart". | +| CLS-07 | P0 | Expired coupon. | Not shown anywhere. | +| CLS-08 | P0 | Admin-invalidated coupon. | Not shown. | +| CLS-09 | P0 | Coupon whose per-user usage reached `maxLimitForUser`. | Not shown. | +| CLS-10 | P0 | Another user's personal coupon (U2 while logged in as U1). | Not shown. | +| CLS-11 | P1 | Eligible coupon. | Single line: `CODE - description (Save ₹x)`. | +| CLS-12 | P1 | "Save ₹x" with other coupons already applied. | Shows the **marginal** saving given the current selection (not standalone). | +| CLS-13 | P1 | Already-applied coupon in the dropdown. | Shows its own current contribution; selecting it is idempotent. | +| CLS-14 | P1 | Add then remove a coupon. | Remaining coupons re-sort (eligible first); disabled reasons recompute. | +| CLS-15 | P2 | Change region while the cart is open. | Region-mismatched coupons move to disabled with the reason; others update. | + +## C. Cart "Products discount" row + +| ID | Priority | Action / input | Expected result | +|---|---|---|---| +| CDIS-01 | P1 | Cart with market-price savings > ₹1. | Row label reads **Products discount** (was "Total Discount"). | +| CDIS-02 | P1 | Savings ≤ ₹1. | Row is hidden. | +| CDIS-03 | P2 | Coupons applied. | Coupon lines remain separate from the Products discount row; bill lines still sum to the total. | + +## D. Cart checkout guard for delivery slots (scheduled delivery) + +| ID | Priority | Action / input | Expected result | +|---|---|---|---| +| CGRD-01 | P0 | Item whose SKU has no entry in the slots file (or an empty list). | Checkout button disabled; error below: "Some items in your cart are no longer available for delivery…". | +| CGRD-02 | P0 | Item whose selected slot is no longer offered for it. | Checkout disabled; same "no longer available" error. | +| CGRD-03 | P0 | Item whose selected slot's freeze time has passed. | Checkout disabled; error: "The delivery slot for some items has closed…". | +| CGRD-04 | P0 | All items have valid, upcoming slots. | Checkout enabled; no error banner. | +| CGRD-05 | P1 | Out-of-stock item present. | Guard ignores OOS items (handled by the existing per-item badge); does not block on them alone. | +| CGRD-06 | P1 | Flash-delivery cart. | Guard does not apply; checkout remains enabled. | +| CGRD-07 | P1 | Recover by selecting a valid slot. | Guard clears immediately; checkout re-enables. | +| CGRD-08 | P1 | Tap the disabled button. | No navigation and no order created. | +| CGRD-09 | P2 | Error styling. | Red banner with icon directly below the action buttons. | + +## E. Backend `create-user` script + +| ID | Priority | Action / input | Expected result | +|---|---|---|---| +| USR-01 | P1 | `bun run create-user -- --mobile --password

[--name --email]`. | Row in `users` + bcrypt row in `user_creds`; login (email or mobile) succeeds. | +| USR-02 | P1 | Repeat without `--update`. | Refuses ("already exists"); no duplicate rows. | +| USR-03 | P1 | Repeat with `--update`. | Password reset; login with the new password, old one rejected. | +| USR-04 | P2 | `--show-sql`. | Prints the SQL and exits without writing. | +| USR-05 | P2 | `--remote`. | Applies to the remote D1 (verify with a read). | +| USR-06 | P1 | Inspect the stored hash. | bcrypt `$2b$`/`$2a$`; `bcrypt.compare` accepts it. | + +## Suggested automated coverage + +- `apps/backend/tests/api/coupon-math.test.ts` — extend for CSQ-01/02/04 (order-sensitive), CSQ-03 (rounding), CSQ-10 (persisted parity); keep the single-coupon regression. +- `apps/backend/tests/api/coupon-ux.test.ts` — CLS-03/07/08/09/10 (what `getEligible` returns / omits). +- `apps/user-ui/tests/screens/cart-coupons.test.tsx` — CLS-01/02/11/12/13/14 (list order, disabled layout, marginal save). +- `apps/user-ui/tests/screens/cart-money.test.tsx` — CDIS-01 (label) and CSQ totals/rounding. +- `apps/user-ui/tests/screens/cart-screen.test.tsx` — CGRD-01..04, 07, 08 (button disabled/enabled + error text). +- `apps/backend/tests/api/order-flow.test.ts` / `order-rules.test.ts` — CSQ-10 persisted-money identity. +- Staging/manual — CGRD with real slot lifecycle (past/inactive/full), CLS-15 region switch, USR-02/03/05. diff --git a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql index 05cb37f..0eb0010 100644 --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql +++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql @@ -15,6 +15,7 @@ -- * global keys + per-region version counters + region-level business keys -- -> `region_consts` (global ones -> `global_consts`) -- * per-bound business keys -> `region_bound_consts` +-- (incl. `isFlashDeliveryEnabled`, which each bound switches independently) -- -- Phases, kept in the original dependency order: -- 1. regions / region_bounds / superadmins + seeds (from 0006) @@ -631,17 +632,22 @@ CREATE TABLE `__new_complaints` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `user_id` integer NOT NULL, `order_id` integer, + `region_id` integer, `complaint_body` text NOT NULL, `images` text, `response` text, `is_resolved` integer DEFAULT false NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, - FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action + FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action, + FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint -INSERT INTO `__new_complaints` (`id`,`user_id`,`order_id`,`complaint_body`,`images`,`response`,`is_resolved`,`created_at`) -SELECT `id`,`user_id`,`order_id`,`complaint_body`,`images`,`response`,`is_resolved`,`created_at` FROM `complaints`; +-- Backfill the complaint's region: every pre-existing complaint belongs to the +-- region the whole dataset is being backfilled into (Mahabubnagar). Region-less +-- is allowed going forward, so the column stays nullable. +INSERT INTO `__new_complaints` (`id`,`user_id`,`order_id`,`region_id`,`complaint_body`,`images`,`response`,`is_resolved`,`created_at`) +SELECT `id`,`user_id`,`order_id`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar'),`complaint_body`,`images`,`response`,`is_resolved`,`created_at` FROM `complaints`; --> statement-breakpoint CREATE TABLE `__new_user_incidents` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, @@ -835,6 +841,8 @@ CREATE INDEX `idx_home_banners_region` ON `home_banners` (`region_id`); CREATE INDEX `idx_addresses_region` ON `addresses` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_orders_region` ON `orders` (`region_id`); +--> statement-breakpoint +CREATE INDEX `idx_complaints_region` ON `complaints` (`region_id`); --> statement-breakpoint -- ===================================================================== @@ -892,9 +900,6 @@ INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`) SELECT `id`, 'allItemsOrder', '[]' FROM `regions` WHERE `name` = 'Mahabubnagar'; --> statement-breakpoint INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`) -SELECT `id`, 'isFlashDeliveryEnabled', 'false' FROM `regions` WHERE `name` = 'Mahabubnagar'; ---> statement-breakpoint -INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`) SELECT `id`, 'supportMobile', '8688182552' FROM `regions` WHERE `name` = 'Mahabubnagar'; --> statement-breakpoint INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`) @@ -908,7 +913,7 @@ SELECT `id`, 'welcomeMessage', 'Hi! Thank you for your first order at Freshyo. W INSERT OR IGNORE INTO `region_consts` (`region_id`, `key`, `value`) SELECT r.`id`, kv.`key`, kv.`value` FROM `regions` r, `key_val_store` kv -WHERE kv.`key` IN ('popularItems','allItemsOrder','tagsOrder','isFlashDeliveryEnabled','supportMobile','supportEmail','welcomeMessage'); +WHERE kv.`key` IN ('popularItems','allItemsOrder','tagsOrder','supportMobile','supportEmail','welcomeMessage'); --> statement-breakpoint -- Per-bound business keys (formerly seeded into region_bound_settings in 0006). INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`) @@ -923,6 +928,17 @@ SELECT b.`id`, b.`region_id`, 'flashFreeDeliveryThreshold', '500' FROM `regions` INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`) SELECT b.`id`, b.`region_id`, 'flashDeliveryCharge', '69' FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar'; --> statement-breakpoint +-- "Enable Flash Delivery" is a BOUND-level key (each bound switches flash +-- delivery on/off independently), so it is seeded per bound, not per region. +-- Carried over from the pre-existing global value so the move changes nothing; +-- normalised to 'true'/'false' (what the admin editors write) because the legacy +-- key_val_store value was numeric ('1.0'). +INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`) +SELECT b.`id`, b.`region_id`, 'isFlashDeliveryEnabled', + CASE WHEN lower(COALESCE((SELECT `value` FROM `key_val_store` WHERE `key` = 'isFlashDeliveryEnabled'), 'false')) + IN ('1', 'true', '1.0') THEN 'true' ELSE 'false' END +FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar'; +--> statement-breakpoint -- Keep only the leftover keys in key_val_store (same set 0009 keeps). DELETE FROM `key_val_store` WHERE `key` IN ( 'versionNum','playStoreUrl','appStoreUrl','internalAppVersion', diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts index 0db562c..5761448 100644 --- a/packages/db_helper_sqlite/index.ts +++ b/packages/db_helper_sqlite/index.ts @@ -275,6 +275,8 @@ export { upsertUserRegion, reconcileUserRegions, getUserRegions, + getUserAddressRegionId, + syncUserNotifCredRegion, type UserRegionSource, } from './src/user-apis/user-regions' @@ -460,6 +462,11 @@ export { invalidateGlobalCoupon, } from './src/superadmin-apis/global-coupons' +export { + getAllComplaintsForSuperadmin, + type SuperadminComplaint, +} from './src/superadmin-apis/complaint' + export { listAllProducts, elevateProductToGlobal, diff --git a/packages/db_helper_sqlite/src/admin-apis/complaint.ts b/packages/db_helper_sqlite/src/admin-apis/complaint.ts index 2c26de8..bb7e9e3 100644 --- a/packages/db_helper_sqlite/src/admin-apis/complaint.ts +++ b/packages/db_helper_sqlite/src/admin-apis/complaint.ts @@ -1,33 +1,17 @@ import { db } from '../db/db_index' -import { complaints, orders, users } from '../db/schema' -import { eq, desc, lt, and, or, isNull } from 'drizzle-orm' +import { complaints, users } from '../db/schema' +import { eq, desc, lt, and } from 'drizzle-orm' import type { Complaint, ComplaintWithUser } from '@packages/shared' export async function getComplaintById(regionId: number, id: number): Promise { + // Complaints are scoped to the region stored on the row, so a region admin can + // only read one that belongs to them. const complaint = await db.query.complaints.findFirst({ - where: eq(complaints.id, id), + where: and(eq(complaints.id, id), eq(complaints.regionId, regionId)), }) - if (!complaint) { - return null - } - - if (complaint.orderId == null) { - return complaint - } - - const [order] = await db - .select({ regionId: orders.regionId }) - .from(orders) - .where(eq(orders.id, complaint.orderId)) - .limit(1) - - if (!order || order.regionId !== regionId) { - return null - } - - return complaint + return complaint ?? null } export async function getComplaints( @@ -35,7 +19,7 @@ export async function getComplaints( cursor?: number, limit: number = 20 ): Promise<{ complaints: ComplaintWithUser[]; hasMore: boolean }> { - const regionCondition = or(isNull(complaints.orderId), eq(orders.regionId, regionId)) + const regionCondition = eq(complaints.regionId, regionId) const whereCondition = cursor ? and(lt(complaints.id, cursor), regionCondition) : regionCondition @@ -46,6 +30,7 @@ export async function getComplaints( complaintBody: complaints.complaintBody, userId: complaints.userId, orderId: complaints.orderId, + regionId: complaints.regionId, isResolved: complaints.isResolved, response: complaints.response, createdAt: complaints.createdAt, @@ -55,7 +40,6 @@ export async function getComplaints( }) .from(complaints) .leftJoin(users, eq(complaints.userId, users.id)) - .leftJoin(orders, eq(complaints.orderId, orders.id)) .where(whereCondition) .orderBy(desc(complaints.id)) .limit(limit + 1) @@ -69,6 +53,7 @@ export async function getComplaints( complaintBody: c.complaintBody, userId: c.userId, orderId: c.orderId, + regionId: c.regionId, isResolved: c.isResolved, response: c.response, createdAt: c.createdAt, @@ -85,24 +70,13 @@ export async function resolveComplaint( id: number, response?: string ): Promise { - // Same region pattern as getComplaintById: orderless complaints are visible - // to every region; order-backed ones only to the order's region. + // Only the region the complaint belongs to may resolve it. const complaint = await db.query.complaints.findFirst({ - where: eq(complaints.id, id), + where: and(eq(complaints.id, id), eq(complaints.regionId, regionId)), }) if (!complaint) { return false } - if (complaint.orderId != null) { - const [order] = await db - .select({ regionId: orders.regionId }) - .from(orders) - .where(eq(orders.id, complaint.orderId)) - .limit(1) - if (!order || order.regionId !== regionId) { - return false - } - } await db .update(complaints) diff --git a/packages/db_helper_sqlite/src/admin-apis/user.ts b/packages/db_helper_sqlite/src/admin-apis/user.ts index 96d39d2..445d346 100644 --- a/packages/db_helper_sqlite/src/admin-apis/user.ts +++ b/packages/db_helper_sqlite/src/admin-apis/user.ts @@ -1,6 +1,6 @@ import { db } from '../db/db_index' import { users, userDetails, orders, orderItems, complaints, notifCreds, unloggedUserTokens, userIncidents, orderStatus } from '../db/schema' -import { eq, sql, desc, asc, count, max, inArray, and, or, isNull } from 'drizzle-orm' +import { eq, sql, desc, asc, count, max, inArray, and } from 'drizzle-orm' export async function getUserByMobile(mobile: string): Promise { const [existingUser] = await db @@ -16,13 +16,7 @@ export async function getUnresolvedComplaintsCount(regionId: number): Promise users.id), orderId: integer('order_id').references(() => orders.id), + regionId: integer('region_id').references(() => regions.id), complaintBody: text('complaint_body').notNull(), images: jsonText('images'), response: text('response'), diff --git a/packages/db_helper_sqlite/src/lib/const-keys.ts b/packages/db_helper_sqlite/src/lib/const-keys.ts index 604e4ae..336da6e 100644 --- a/packages/db_helper_sqlite/src/lib/const-keys.ts +++ b/packages/db_helper_sqlite/src/lib/const-keys.ts @@ -187,7 +187,7 @@ export const GLOBAL_CONST_KEYS = [ /** Keys stored in the region_consts table (one row per region). */ export const REGION_CONST_KEYS = [ 'products_version_num', 'availability_version_num', 'slots_version_num', - 'popularItems', 'allItemsOrder', 'tagsOrder', 'isFlashDeliveryEnabled', + 'popularItems', 'allItemsOrder', 'tagsOrder', 'supportMobile', 'supportEmail', 'welcomeMessage', ] as const @@ -195,6 +195,7 @@ export const REGION_CONST_KEYS = [ export const BOUND_CONST_KEYS = [ 'freeDeliveryThreshold', 'deliveryCharge', 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', + 'isFlashDeliveryEnabled', ] as const /** Keys that remain in the legacy key_val_store table. */ diff --git a/packages/db_helper_sqlite/src/superadmin-apis/complaint.ts b/packages/db_helper_sqlite/src/superadmin-apis/complaint.ts new file mode 100644 index 0000000..5d24acf --- /dev/null +++ b/packages/db_helper_sqlite/src/superadmin-apis/complaint.ts @@ -0,0 +1,71 @@ +import { db } from '../db/db_index' +import { complaints, regions, users } from '../db/schema' +import { desc, eq, lt } from 'drizzle-orm' + +export interface SuperadminComplaint { + id: number + complaintBody: string + userId: number + userName: string | null + userMobile: string | null + orderId: number | null + regionId: number | null + regionName: string | null + isResolved: boolean + response: string | null + createdAt: Date + images: string[] +} + +/** + * Every complaint across every region for the superadmin, newest first. + * `regionName` is null for a region-less complaint (one whose region could not be + * resolved when it was raised — no region admin can see those). + */ +export async function getAllComplaintsForSuperadmin( + cursor?: number, + limit: number = 20 +): Promise<{ complaints: SuperadminComplaint[]; hasMore: boolean }> { + const rows = await db + .select({ + id: complaints.id, + complaintBody: complaints.complaintBody, + userId: complaints.userId, + orderId: complaints.orderId, + regionId: complaints.regionId, + regionName: regions.name, + isResolved: complaints.isResolved, + response: complaints.response, + createdAt: complaints.createdAt, + images: complaints.images, + userName: users.name, + userMobile: users.mobile, + }) + .from(complaints) + .leftJoin(users, eq(complaints.userId, users.id)) + .leftJoin(regions, eq(complaints.regionId, regions.id)) + .where(cursor ? lt(complaints.id, cursor) : undefined) + .orderBy(desc(complaints.id)) + .limit(limit + 1) + + const hasMore = rows.length > limit + const page = hasMore ? rows.slice(0, limit) : rows + + return { + complaints: page.map((c) => ({ + id: c.id, + complaintBody: c.complaintBody, + userId: c.userId, + userName: c.userName, + userMobile: c.userMobile, + orderId: c.orderId, + regionId: c.regionId, + regionName: c.regionName, + isResolved: c.isResolved, + response: c.response, + createdAt: c.createdAt, + images: (c.images as string[]) || [], + })), + hasMore, + } +} diff --git a/packages/db_helper_sqlite/src/user-apis/complaint.ts b/packages/db_helper_sqlite/src/user-apis/complaint.ts index 412a3a0..6c0a731 100644 --- a/packages/db_helper_sqlite/src/user-apis/complaint.ts +++ b/packages/db_helper_sqlite/src/user-apis/complaint.ts @@ -1,6 +1,7 @@ import { db } from '../db/db_index' -import { complaints } from '../db/schema' -import { asc, eq } from 'drizzle-orm' +import { complaints, orders, userRegions } from '../db/schema' +import { asc, desc, eq } from 'drizzle-orm' +import { getUserAddressRegionId } from './user-regions' import type { UserComplaint } from '@packages/shared' export async function getUserComplaints(userId: number): Promise { @@ -27,15 +28,52 @@ export async function getUserComplaints(userId: number): Promise { + if (orderId != null) { + const [order] = await db + .select({ regionId: orders.regionId }) + .from(orders) + .where(eq(orders.id, orderId)) + .limit(1) + + if (order?.regionId != null) return order.regionId + } + + const addressRegionId = await getUserAddressRegionId(userId) + if (addressRegionId != null) return addressRegionId + + const [association] = await db + .select({ regionId: userRegions.regionId }) + .from(userRegions) + .where(eq(userRegions.userId, userId)) + .orderBy(desc(userRegions.fromLocation), asc(userRegions.id)) + .limit(1) + + return association?.regionId ?? null +} + export async function createComplaint( userId: number, orderId: number | null, complaintBody: string, images?: string[] | null ): Promise { + const regionId = await resolveComplaintRegionId(userId, orderId) + await db.insert(complaints).values({ userId, orderId, + regionId, complaintBody, images: images || null, }) diff --git a/packages/db_helper_sqlite/src/user-apis/coupon.ts b/packages/db_helper_sqlite/src/user-apis/coupon.ts index f593f4c..e511b3a 100644 --- a/packages/db_helper_sqlite/src/user-apis/coupon.ts +++ b/packages/db_helper_sqlite/src/user-apis/coupon.ts @@ -20,6 +20,7 @@ const mapCoupon = (coupon: CouponRow): UserCoupon => ({ id: coupon.id, couponCode: coupon.couponCode, isUserBased: coupon.isUserBased, + regionId: coupon.regionId ?? null, discountPercent: coupon.discountPercent ? coupon.discountPercent.toString() : null, flatDiscount: coupon.flatDiscount ? coupon.flatDiscount.toString() : null, minOrder: coupon.minOrder ? coupon.minOrder.toString() : null, diff --git a/packages/db_helper_sqlite/src/user-apis/order.ts b/packages/db_helper_sqlite/src/user-apis/order.ts index 8c6696b..5b6ef69 100644 --- a/packages/db_helper_sqlite/src/user-apis/order.ts +++ b/packages/db_helper_sqlite/src/user-apis/order.ts @@ -114,8 +114,9 @@ export interface ValidatedCoupon extends CouponValidationResult { } /** - * Validate every coupon the customer is trying to apply and return them in - * stacking order (percentage first, then flat). Enforces: + * Validate every coupon the customer is trying to apply and return them in the + * order they were requested (the caller's selection order) — coupons stack + * sequentially, so this order is meaningful and must be preserved. Enforces: * - dedupe + existence * - exclusive coupons cannot be combined with any other coupon * - user-based applicability, invalidated, expiry, per-user usage limit @@ -218,12 +219,8 @@ export async function validateAndGetCoupons(params: { }) } - // Percentage coupons first, then flat (stable within each group). - validated.sort((a, b) => { - const rank = (c: ValidatedCoupon) => (c.discountPercent ? 0 : 1) - return rank(a) - rank(b) - }) - + // Preserve the caller's (selection) order: coupons apply sequentially, so the + // order changes the result and must not be re-sorted here. return validated } diff --git a/packages/db_helper_sqlite/src/user-apis/user-regions.ts b/packages/db_helper_sqlite/src/user-apis/user-regions.ts index 1f85b7f..b9edaa1 100644 --- a/packages/db_helper_sqlite/src/user-apis/user-regions.ts +++ b/packages/db_helper_sqlite/src/user-apis/user-regions.ts @@ -1,6 +1,6 @@ import { db } from '../db/db_index' -import { addresses, userRegions } from '../db/schema' -import { and, eq } from 'drizzle-orm' +import { addresses, notifCreds, userRegions } from '../db/schema' +import { and, desc, eq } from 'drizzle-orm' /** * How a user got associated with a region: because they have an address there @@ -88,3 +88,43 @@ export async function getUserRegions(userId: number) { orderBy: (table, { asc }) => asc(table.regionId), }) } + +/** + * The region that stands for the user's delivery location: their default + * address's region, else the region of their newest address (highest id). + * `null` when the user has no address in any region. + */ +export async function getUserAddressRegionId(userId: number): Promise { + const [defaultAddress] = await db + .select({ regionId: addresses.regionId }) + .from(addresses) + .where(and(eq(addresses.userId, userId), eq(addresses.isDefault, true))) + .limit(1) + + if (defaultAddress?.regionId != null) return defaultAddress.regionId + + const [newestAddress] = await db + .select({ regionId: addresses.regionId }) + .from(addresses) + .where(eq(addresses.userId, userId)) + .orderBy(desc(addresses.id)) + .limit(1) + + return newestAddress?.regionId ?? null +} + +/** + * Point every push token this user owns at their address region. + * + * The push-token region tracks the user's ADDRESS, never the device's current + * location — a device physically in another region must not move the token. This + * is therefore the ONLY place the token's region may change, and it runs after an + * address is added, moved or removed. A user with no address keeps whatever + * region they already had (a known region is never erased). + */ +export async function syncUserNotifCredRegion(userId: number): Promise { + const regionId = await getUserAddressRegionId(userId) + if (regionId == null) return + + await db.update(notifCreds).set({ regionId }).where(eq(notifCreds.userId, userId)) +} diff --git a/packages/shared/cart-pricing.ts b/packages/shared/cart-pricing.ts index 8a5dc7a..af0cc26 100644 --- a/packages/shared/cart-pricing.ts +++ b/packages/shared/cart-pricing.ts @@ -7,8 +7,11 @@ * is never part of the base. * - A coupon with no `applicableSkuIds` applies to the whole cart; otherwise it * only discounts the line items whose skuId is in the target set. - * - Multiple coupons stack: percentage coupons first, then flat, each capped by - * its own `maxValue`; the combined discount never exceeds the goods subtotal. + * - Multiple coupons apply SEQUENTIALLY, in the order they are given (the user's + * selection order): the first coupon discounts the subtotal, the second discounts + * whatever is left, and so on. Each coupon's discount is rounded to the nearest + * rupee. + * - The combined discount never exceeds the goods subtotal. */ export interface CouponMoney { @@ -59,6 +62,11 @@ export interface CartPricingResult { grandTotal: number } +export interface CouponStackEntry { + couponId: number + discount: number +} + const toNum = (v: string | number | null | undefined): number => { if (v == null) return 0 const n = typeof v === 'number' ? v : parseFloat(v) @@ -92,10 +100,10 @@ export function computeEligibleSubtotal( } /** - * Discount a single coupon contributes on its eligible subtotal: + * Raw (unrounded) discount a single coupon contributes on a given subtotal: * percent: min(subtotal * pct / 100, maxValue || Infinity) * flat: min(flat, maxValue || subtotal) - * Clamped to [0, eligibleSubtotal]. + * Clamped to [0, eligibleSubtotal]. Callers that need whole rupees round it. */ export function computeCouponDiscount( eligibleSubtotal: number, @@ -116,17 +124,92 @@ export function computeCouponDiscount( return discount } -const couponRank = (coupon: CouponMoney): number => - toNum(coupon.discountPercent) ? 0 : 1 +interface StackLine extends CartLine { + group: number +} + +interface StackCouponResult { + couponId: number + discount: number + /** where this coupon's discount landed, keyed by the line's group (sub-order) */ + shareByGroup: Map +} + +/** + * Apply coupons one after another over a shared set of line amounts. Each coupon + * discounts only what is still remaining on its eligible lines, so later coupons + * see the money the earlier ones left behind. Discounts are rounded to the nearest + * rupee and the eligible lines' remainders are reduced proportionally. + */ +function runStack( + lines: StackLine[], + coupons: TargetedCoupon[] +): { perCoupon: StackCouponResult[]; remaining: number[] } { + const remaining = lines.map((line) => line.unitPrice * line.quantity) + const perCoupon: StackCouponResult[] = [] + + for (const coupon of coupons) { + const idx: number[] = [] + for (let i = 0; i < lines.length; i++) { + if (lineEligibleForCoupon(lines[i].skuId, coupon)) idx.push(i) + } + + const eligible = idx.reduce((sum, i) => sum + remaining[i], 0) + let discount = 0 + const shareByGroup = new Map() + + if (eligible > 0) { + const raw = computeCouponDiscount(eligible, coupon) + discount = Math.max(0, Math.min(Math.round(raw), Math.round(eligible))) + if (discount > 0) { + for (const i of idx) { + const portion = discount * (remaining[i] / eligible) + remaining[i] = Math.max(0, remaining[i] - portion) + const group = lines[i].group + shareByGroup.set(group, (shareByGroup.get(group) ?? 0) + portion) + } + } + } + + perCoupon.push({ couponId: coupon.id, discount, shareByGroup }) + } + + return { perCoupon, remaining } +} + +/** + * The per-coupon discount each coupon contributes when applied in the given order, + * rounded to whole rupees, plus the total. This is the single source of truth the + * cart/checkout screens use for their per-coupon ("Save ₹x") and total figures, so + * the app and the backend always agree. + */ +export function computeCouponStack( + lines: CartLine[], + coupons: TargetedCoupon[] +): { perCoupon: CouponStackEntry[]; discountTotal: number } { + const grouped: StackLine[] = lines.map((line) => ({ ...line, group: 0 })) + const { perCoupon } = runStack(grouped, coupons) + const entries = perCoupon.map((c) => ({ + couponId: c.couponId, + discount: c.discount, + })) + return { + perCoupon: entries, + discountTotal: entries.reduce((sum, e) => sum + e.discount, 0), + } +} /** * Price a (possibly split) cart with zero or more coupons. * - * Each coupon's discount is computed on its cart-wide eligible subtotal, then - * allocated to the sub-orders by that sub-order's share of the eligible subtotal - * (targeted coupons therefore land only on the sub-orders that hold the items). - * The combined discount is capped at the goods subtotal. The single cart-level - * delivery charge is attached to the primary sub-order (highest goods subtotal). + * Coupons are applied in the order given: each discounts what is still remaining + * on its eligible lines (the cart-wide eligible subtotal minus what the earlier + * coupons already took), rounded to the nearest rupee. Each coupon's discount is + * then allocated to the sub-orders by that sub-order's share of the eligible + * remaining amount (targeted coupons therefore land only on the sub-orders that + * hold the items), reconciled so the per-sub-order shares sum exactly. The single + * cart-level delivery charge is attached to the primary sub-order (highest goods + * subtotal). */ export function computeCartPricing(params: { subOrders: CartSubOrderInput[] @@ -148,34 +231,57 @@ export function computeCartPricing(params: { if (subOrderGoods[i] > subOrderGoods[primaryIndex]) primaryIndex = i } - const orderedCoupons = [...coupons].sort( - (a, b) => couponRank(a) - couponRank(b) - ) + // Flatten every sub-order's lines so the waterfall runs across the whole cart + // while remembering which sub-order each line belongs to. + const flat: StackLine[] = [] + subOrders.forEach((so, group) => { + so.items.forEach((item) => flat.push({ ...item, group })) + }) + + const { perCoupon } = runStack(flat, coupons) const perSubOrderCoupon: CouponDiscountShare[][] = subOrders.map(() => []) let discountTotal = 0 - for (const coupon of orderedCoupons) { - const allItems = subOrders.flatMap((so) => so.items) - const eligibleTotal = computeEligibleSubtotal(allItems, coupon) - const discount = computeCouponDiscount(eligibleTotal, coupon) - if (discount <= 0) continue + for (const coupon of perCoupon) { + discountTotal += coupon.discount + if (coupon.discount <= 0 || coupon.shareByGroup.size === 0) continue - for (let i = 0; i < subOrders.length; i++) { - const subEligible = computeEligibleSubtotal(subOrders[i].items, coupon) - const share = eligibleTotal > 0 ? discount * (subEligible / eligibleTotal) : 0 - perSubOrderCoupon[i].push({ couponId: coupon.id, discount: share }) + const groups = [...coupon.shareByGroup.keys()].sort((a, b) => a - b) + const rawShares = groups.map((g) => coupon.shareByGroup.get(g) ?? 0) + const rawSum = rawShares.reduce((sum, v) => sum + v, 0) + + // Scale the raw shares onto the rounded discount, round each sub-order share, + // and fold the 1-rupee drift into the largest share so they sum exactly. + const scaled = + rawSum > 0 ? rawShares.map((v) => (v * coupon.discount) / rawSum) : rawShares + const rounded = scaled.map((v) => Math.round(v)) + const drift = coupon.discount - rounded.reduce((sum, v) => sum + v, 0) + if (drift !== 0 && rounded.length > 0) { + let maxI = 0 + for (let i = 1; i < rounded.length; i++) { + if (scaled[i] > scaled[maxI]) maxI = i + } + rounded[maxI] += drift } - discountTotal += discount + + groups.forEach((group, i) => { + if (rounded[i] !== 0) { + perSubOrderCoupon[group].push({ + couponId: coupon.couponId, + discount: rounded[i], + }) + } + }) } - // Never discount more than the goods subtotal. + // Defensive: never discount more than the goods subtotal. if (discountTotal > goodsSubtotal && discountTotal > 0) { const factor = goodsSubtotal / discountTotal for (let i = 0; i < perSubOrderCoupon.length; i++) { perSubOrderCoupon[i] = perSubOrderCoupon[i].map((entry) => ({ ...entry, - discount: entry.discount * factor, + discount: Math.round(entry.discount * factor), })) } discountTotal = goodsSubtotal diff --git a/packages/shared/types/complaint.types.ts b/packages/shared/types/complaint.types.ts index 6387a36..89d12c2 100644 --- a/packages/shared/types/complaint.types.ts +++ b/packages/shared/types/complaint.types.ts @@ -8,6 +8,8 @@ export interface Complaint { complaintBody: string; userId: number; orderId: number | null; + /** Region the complaint belongs to at raise time; null only when it can't be resolved. */ + regionId: number | null; isResolved: boolean; response: string | null; createdAt: Date; diff --git a/packages/shared/types/user.ts b/packages/shared/types/user.ts index 90e5fb7..cb253a3 100644 --- a/packages/shared/types/user.ts +++ b/packages/shared/types/user.ts @@ -424,6 +424,7 @@ export interface UserCoupon { id: number; couponCode: string; isUserBased: boolean; + regionId?: number | null; discountPercent: string | null; flatDiscount: string | null; minOrder: string | null; @@ -447,6 +448,8 @@ export interface UserCouponWithRelations extends UserCoupon { export interface UserEligibleCouponsResponse { success: boolean; data: UserCouponWithRelations[]; + /** Whether the caller is still eligible for first-order-only coupons. */ + isFirstOrder?: boolean; } export interface UserCouponDisplay { diff --git a/packages/ui/src/components/bottom-dropdown.tsx b/packages/ui/src/components/bottom-dropdown.tsx index b7a97df..ada36f3 100644 --- a/packages/ui/src/components/bottom-dropdown.tsx +++ b/packages/ui/src/components/bottom-dropdown.tsx @@ -12,6 +12,8 @@ import type { DropdownBaseProps } from './dropdown'; // Bottom/multi dropdown option — shared base + per-option disabled flag export interface DropdownOption extends BaseDropdownOption { disabled?: boolean; + /** Optional second line shown under the label (e.g. why it is disabled). */ + note?: string; } interface BottomDropdownProps extends DropdownBaseProps { @@ -209,6 +211,7 @@ const BottomDropdown: React.FC = ({ filteredOptions.map((option) => { const selected = isSelected(option.value); const isDisabled = option.disabled || disabled; + const [code, rest] = (option.label as string).split(' - ', 2); return ( = ({ onPress={() => !isDisabled && handleSelect(option.value)} disabled={isDisabled} > + - {(() => { - const labelStr = option.label as string; - const [code, rest] = labelStr.split(' - ', 2); - return ( - - {code} - {rest ? ` - ${rest}` : ''} - - ); - })()} - + style={[ + selected ? tw`text-brand700 font-semibold` : tw`text-gray-800`, + isDisabled && tw`text-gray-400`, + ]} + > + {code} + {rest ? ` - ${rest}` : ''} + {option.disabled && option.note ? ( + Disabled + ) : null} + + {!!option.note && ( + + {option.note} + + )} + {selected && ( )}