From eb4d844317b3dbe2defaf975fe979d3163f4ed34 Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:00:23 +0530 Subject: [PATCH] enh --- .../app/(drawer)/dashboard/products/edit.tsx | 6 +- .../components/context/staff-auth-context.tsx | 10 + .../src/routes/dashboard.products.edit.tsx | 6 +- apps/backend/src/jobs/cache-creator.ts | 27 +- .../src/trpc/apis/admin-apis/apis/product.ts | 2 + .../trpc/apis/admin-apis/apis/staff-user.ts | 2 +- .../src/trpc/apis/admin-apis/apis/store.ts | 32 +- .../superadmin-apis/apis/global-products.ts | 3 +- .../trpc/apis/superadmin-apis/apis/regions.ts | 13 +- .../trpc/apis/superadmin-apis/apis/staff.ts | 23 + .../src/routes/global-products.tsx | 3 +- .../src/routes/send-notifications.tsx | 2 +- apps/web-ui/src/hooks/prominent-api-hooks.ts | 95 +- apps/web-ui/src/routes/home.checkout.tsx | 2 +- change-log.txt | 822 ++++++++++++++++++ .../db_helper_sqlite/src/admin-apis/order.ts | 21 +- .../src/admin-apis/product.ts | 6 +- .../db_helper_sqlite/src/admin-apis/user.ts | 10 +- packages/shared/cart-pricing.ts | 91 +- packages/shared/types/admin.ts | 3 + 20 files changed, 1097 insertions(+), 82 deletions(-) diff --git a/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx b/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx index e2bb50e..7e97170 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx @@ -63,7 +63,9 @@ export default function EditProduct() { isOffer: sku.isOffer || false, isComboOnly: sku.isComboOnly || false, isDeleted: sku.isDeleted || false, - isSuspended: sku.isSuspended || false, + // Global products are market-data-only for a regional admin: the toggle is + // this region's suspension, not the superadmin kill-switch. + isSuspended: (productData.isGlobal ? sku.isSuspendedInRegion : sku.isSuspended) || false, features: (sku.features || []).map((f) => ({ featureName: f.featureName, featureValue: f.featureValue, @@ -167,6 +169,8 @@ export default function EditProduct() { isComboOnly: variant.isComboOnly || false, isDeleted: variant.isDeleted || false, isSuspended: variant.isSuspended || false, + // Read only by the regional market-data path (global products). + isSuspendedInRegion: productData?.isGlobal ? (variant.isSuspended || false) : undefined, features: variant.features.map((attr: any) => ({ featureName: attr.featureName, featureValue: attr.featureValue, diff --git a/apps/admin-web/src/components/context/staff-auth-context.tsx b/apps/admin-web/src/components/context/staff-auth-context.tsx index cbedad1..ff71b0b 100644 --- a/apps/admin-web/src/components/context/staff-auth-context.tsx +++ b/apps/admin-web/src/components/context/staff-auth-context.tsx @@ -33,6 +33,16 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => { const navigate = useNavigate() const location = useLocation() + // Only the JWT survives a reload. Restore the staff identity (and therefore + // regionId) from the authenticated endpoint so region-scoped screens such as + // the vendor-snippet slot picker are not permanently disabled until re-login. + const meQuery = trpc.admin.staffUser.me.useQuery(undefined, { + enabled: isLoggedIn, + }) + useEffect(() => { + if (meQuery.data) setStaff(meQuery.data) + }, [meQuery.data]) + useEffect(() => { const checkAuth = async () => { const token = await getJWT() diff --git a/apps/admin-web/src/routes/dashboard.products.edit.tsx b/apps/admin-web/src/routes/dashboard.products.edit.tsx index 4230449..2ec3711 100644 --- a/apps/admin-web/src/routes/dashboard.products.edit.tsx +++ b/apps/admin-web/src/routes/dashboard.products.edit.tsx @@ -59,7 +59,9 @@ function EditProduct() { isOffer: sku.isOffer || false, isComboOnly: sku.isComboOnly || false, isDeleted: sku.isDeleted || false, - isSuspended: sku.isSuspended || false, + // Global products are market-data-only for a regional admin: the toggle is + // this region's suspension, not the superadmin kill-switch. + isSuspended: (productData.isGlobal ? sku.isSuspendedInRegion : sku.isSuspended) || false, features: (sku.features || []).map((f) => ({ featureName: f.featureName, featureValue: f.featureValue, @@ -160,6 +162,8 @@ function EditProduct() { isComboOnly: variant.isComboOnly || false, isDeleted: variant.isDeleted || false, isSuspended: variant.isSuspended || false, + // Read only by the regional market-data path (global products). + isSuspendedInRegion: productData?.isGlobal ? (variant.isSuspended || false) : undefined, features: variant.features.map((attr: any) => ({ featureName: attr.featureName, featureValue: attr.featureValue, diff --git a/apps/backend/src/jobs/cache-creator.ts b/apps/backend/src/jobs/cache-creator.ts index 2ba15bb..5d91aca 100644 --- a/apps/backend/src/jobs/cache-creator.ts +++ b/apps/backend/src/jobs/cache-creator.ts @@ -4,6 +4,10 @@ import { ensureWorkerInit } from '@/src/lib/worker-init' const LAST_TRIGGER_KEY = 'lastTrigger' const PENDING_REGIONS_KEY = 'pendingRegions' +// Explicit "every region must be regenerated" marker. A regional request must +// never narrow this: a global change (e.g. a global product edit) affects every +// region's cache files. +const ALL_REGIONS_PENDING_KEY = 'allRegionsPending' const ALARM_DELAY_MINUTES = 0.5 // const ALARM_DELAY_MINUTES = 0.1 @@ -25,11 +29,22 @@ export class CacheCreator { // Accumulate per-region regeneration requests. Empty = all regions. // No global mutable current-region: pending ids are drained by the alarm. if (regionId != null && Number.isFinite(regionId)) { - const pending = ((await this.state.storage.get(PENDING_REGIONS_KEY)) as number[] | undefined) ?? [] - if (!pending.includes(regionId)) { - pending.push(regionId) - await this.state.storage.put(PENDING_REGIONS_KEY, pending) + // Regional request: add to the drain list unless a global run is already + // pending (that run regenerates every region, so this request is covered). + const allPending = (await this.state.storage.get(ALL_REGIONS_PENDING_KEY)) as boolean | undefined + if (!allPending) { + const pending = ((await this.state.storage.get(PENDING_REGIONS_KEY)) as number[] | undefined) ?? [] + if (!pending.includes(regionId)) { + pending.push(regionId) + await this.state.storage.put(PENDING_REGIONS_KEY, pending) + } } + } else { + // Global request (e.g. a global product edit): every region's cache files + // must be regenerated. Record that explicitly and drop the per-region list, + // so a later regional request in the same debounce window cannot narrow it. + await this.state.storage.put(ALL_REGIONS_PENDING_KEY, true) + await this.state.storage.delete(PENDING_REGIONS_KEY) } const alarmAt = dayjs(now).add(ALARM_DELAY_MINUTES, 'minute').valueOf() @@ -66,9 +81,11 @@ export class CacheCreator { console.log({isQualify, threshold, curr: dayjs(lastTrigger)}) if (isQualify) { const pending = ((await this.state.storage.get(PENDING_REGIONS_KEY)) as number[] | undefined) ?? [] + const allRegionsPending = (await this.state.storage.get(ALL_REGIONS_PENDING_KEY)) as boolean | undefined await this.state.storage.delete(PENDING_REGIONS_KEY) + await this.state.storage.delete(ALL_REGIONS_PENDING_KEY) - if (pending.length === 0) { + if (allRegionsPending || pending.length === 0) { await initializeAllStores() } else { for (const regionId of pending) { diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/product.ts b/apps/backend/src/trpc/apis/admin-apis/apis/product.ts index 68a30db..aea79a4 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/product.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/product.ts @@ -292,6 +292,7 @@ export const productRouter = router({ isComboOnly: z.boolean().optional().default(false), isDeleted: z.boolean().optional().default(false), isSuspended: z.boolean().optional().default(false), + isSuspendedInRegion: z.boolean().optional(), features: z.array(z.object({ featureName: z.string().nullable().optional(), featureValue: z.string().min(1, 'Value is required'), @@ -342,6 +343,7 @@ export const productRouter = router({ isComboOnly: sku.isComboOnly, isDeleted: sku.isDeleted ?? false, isSuspended: sku.isSuspended, + isSuspendedInRegion: sku.isSuspendedInRegion, features: sku.features.map((f) => ({ featureName: f.featureName?.trim() || null, featureValue: f.featureValue, diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts b/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts index 0e167cf..3187b24 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts @@ -144,7 +144,7 @@ export const staffUserRouter = router({ return { success: true }; }), - sendAdminNotification: protectedProcedure + sendAdminNotification: staffProcedure .input(z.object({ title: z.string().min(1, 'Title is required'), text: z.string().min(1, 'Message is required'), diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/store.ts b/apps/backend/src/trpc/apis/admin-apis/apis/store.ts index ab9929a..7499dad 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/store.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/store.ts @@ -92,28 +92,17 @@ export const storeRouter = router({ const existingStore = await getStoreByIdFromDb(ctx.staffUser!.regionId, id); - if (!existingStore) { + // getStoreById also returns global stores (visible in every region), but only + // the region's own non-global stores are editable. Reject before touching any + // asset: updateStoreInDb enforces the same rule, but only after this resolver + // would have deleted the old image. + if (!existingStore || existingStore.isGlobal || existingStore.regionId !== ctx.staffUser!.regionId) { throw new ApiError("Store not found", 404); } const oldImageKey = existingStore.imageUrl; const newImageKey = imageUrl ? extractKeyFromPresignedUrl(imageUrl) : oldImageKey; - // Delete old image only if: - // 1. New image provided and keys are different, OR - // 2. No new image but old exists (clearing the image) - if (oldImageKey && ( - (newImageKey && newImageKey !== oldImageKey) || - (!newImageKey) - )) { - try { - await deleteImageUtil({keys: [oldImageKey]}); - } catch (error) { - console.error('Failed to delete old image:', error); - // Continue with update even if deletion fails - } - } - const updatedStore = await updateStoreInDb( ctx.staffUser!.regionId, id, @@ -125,6 +114,17 @@ export const storeRouter = router({ products ); + // Delete the replaced image only after the update was accepted, so a rejected + // edit cannot remove an image that is still referenced. A failed delete only + // leaves an orphaned asset. + if (oldImageKey && newImageKey !== oldImageKey) { + try { + await deleteImageUtil({keys: [oldImageKey]}); + } catch (error) { + console.error('Failed to delete old image:', error); + } + } + // Reinitialize stores to reflect changes await scheduleStoreInitialization(ctx.staffUser!.regionId) diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/global-products.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/global-products.ts index 94ad414..434a5ce 100644 --- a/apps/backend/src/trpc/apis/superadmin-apis/apis/global-products.ts +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/global-products.ts @@ -11,6 +11,7 @@ import { } from '@/src/dbService' const skuInput = z.object({ + id: z.number().int().positive().optional(), name: z.string().optional().nullable(), price: z.number().nonnegative('Price must be positive'), marketPrice: z.number().optional().nullable(), @@ -104,7 +105,7 @@ export const superadminGlobalProductsRouter = router({ incrementStep: rest.incrementStep, productType: rest.productType, skus: rest.skus.map((sku) => ({ - id: (sku as any).id, + id: sku.id, name: sku.name ?? null, price: sku.price, marketPrice: sku.marketPrice ?? null, diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts index c0ffcba..3d0cfdb 100644 --- a/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts @@ -85,11 +85,16 @@ export const superadminRegionsRouter = router({ priority: bound.priority, })), }) - // New region's cache files are generated at creation (fire-and-forget). - const { createRegionCacheFiles } = await import('@/src/lib/cloud_cache') - createRegionCacheFiles(region.id).catch((error) => { + // New region's cache files are generated at creation. Await the work so it stays + // attached to this request's lifetime; a bare fire-and-forget promise can be + // cancelled once the response is sent. Best-effort: a failure is logged and the + // region is still returned as created. + try { + const { createRegionCacheFiles } = await import('@/src/lib/cloud_cache') + await createRegionCacheFiles(region.id) + } catch (error) { console.error(`Failed to generate cache files for new region ${region.id}:`, error) - }) + } return { ...region, bounds } } catch (error) { throw new ApiError( diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts index a5c1dcd..ad51f1e 100644 --- a/apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts @@ -12,8 +12,31 @@ import { checkStaffRoleExists, getRegionById, } from '@/src/dbService' +import { notifyAllAdmins } from '@/src/lib/admin-notif' export const superadminStaffRouter = router({ + // Superadmins are a distinct principal from staff, so they cannot call the + // admin-side staffUser.sendAdminNotification (protectedProcedure). Same + // behaviour, guarded for this router. + sendAdminNotification: superadminProcedure + .input(z.object({ + title: z.string().min(1, 'Title is required'), + text: z.string().min(1, 'Message is required'), + imageUrl: z.string().optional(), + })) + .mutation(async ({ input }) => { + const { title, text, imageUrl } = input + const queuedCount = await notifyAllAdmins({ + title, + body: text, + imageUrl: imageUrl || null, + }) + return { + success: true, + message: `Notification queued for ${queuedCount} admins`, + } + }), + list: superadminProcedure.query(async () => { const staff = await getAllStaff() return { diff --git a/apps/superadmin-ui/src/routes/global-products.tsx b/apps/superadmin-ui/src/routes/global-products.tsx index d0b6c33..40d3e47 100644 --- a/apps/superadmin-ui/src/routes/global-products.tsx +++ b/apps/superadmin-ui/src/routes/global-products.tsx @@ -273,12 +273,13 @@ function GlobalProductsTab() { {editing ? ( { setEditingId(null); refresh() }} onCancel={() => setEditingId(null)} /> ) : ( - + )} {listQuery.isLoading && Loading products…} diff --git a/apps/superadmin-ui/src/routes/send-notifications.tsx b/apps/superadmin-ui/src/routes/send-notifications.tsx index 615d94a..5acb834 100644 --- a/apps/superadmin-ui/src/routes/send-notifications.tsx +++ b/apps/superadmin-ui/src/routes/send-notifications.tsx @@ -22,7 +22,7 @@ function SendAdminNotifications() { const [text, setText] = useState('') const [imageUrl, setImageUrl] = useState('') - const { mutate, isPending } = trpc.admin.staffUser.sendAdminNotification.useMutation({ + const { mutate, isPending } = trpc.superadmin.staff.sendAdminNotification.useMutation({ onSuccess: (response) => { void alert(`Success\n\n${response.message}`) setTitle('') diff --git a/apps/web-ui/src/hooks/prominent-api-hooks.ts b/apps/web-ui/src/hooks/prominent-api-hooks.ts index 4e714e9..876d78a 100644 --- a/apps/web-ui/src/hooks/prominent-api-hooks.ts +++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts @@ -2,6 +2,8 @@ import { useMemo, useEffect, useState } from 'react' import { useQuery } from '@tanstack/react-query' import axios from 'axios' import { trpc } from '../lib/trpc-client' +import { useAuth } from '../lib/auth-context' +import { useAddressStore } from '../lib/stores' import { useRegionStore } from '../lib/stores/region-store' import type { ProductPriceFlags, EffectiveRegionSettings } from '@packages/shared' import type { @@ -15,17 +17,94 @@ import type { } from '@backend/trpc/router' import { CACHE_FILENAMES } from '@packages/shared' +const essentialConstsKey = (boundId: number) => `essential_consts_b${boundId}` + +// The only persisted discovery payload: the small per-bound consts object. +const readEssentialConstsSnapshot = (boundId: number): string | null => { + try { + return typeof localStorage === 'undefined' ? null : localStorage.getItem(essentialConstsKey(boundId)) + } catch { + return null + } +} + +const writeEssentialConstsSnapshot = (boundId: number, value: string): void => { + try { + if (typeof localStorage !== 'undefined') { + localStorage.setItem(essentialConstsKey(boundId), value) + } + } catch { + // Quota or privacy mode — the snapshot is only a fast-start optimisation. + } +} + export const useGetEssentialConsts = () => { const selectedRegionId = useRegionStore((state) => state.selectedRegionId) - // FIXED CONTRACT: essentialConsts REQUIRES {regionId}. The input is cast so - // this typechecks against the current backend (which takes no input and - // ignores the extra field at runtime) and the future one. tRPC includes the - // input in the query key, so switching regions refetches discovery. No - // region selected -> the query stays disabled (the region gate covers this). - const query = trpc.common.essentialConsts.useQuery({ regionId: selectedRegionId ?? 0 } as any, { - refetchInterval: 60000, - enabled: selectedRegionId != null, + const selectedRegion = useRegionStore((state) => state.selectedRegion) + const { isAuthenticated } = useAuth() + const selectedAddressId = useAddressStore((state) => state.selectedAddressId) + + // The active bound (least-priority bound among the user's addresses in the + // region, else the region's effective bound) drives the constants. Derived + // server-side — the client does not know bound priorities. + const activeBoundQuery = trpc.common.activeBound.useQuery( + { regionId: selectedRegionId ?? 0 }, + { enabled: selectedRegionId != null, staleTime: 60000 } + ) + const activeBoundId = activeBoundQuery.data?.boundId ?? selectedRegion?.effectiveBoundId ?? null + + // At checkout the selected address's bound overrides the active bound. + const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, { + enabled: isAuthenticated && selectedAddressId != null, }) + const selectedAddress = addressesData?.data?.find((address) => address.id === selectedAddressId) + const boundId = + selectedAddress && selectedAddress.regionId === selectedRegionId && selectedAddress.boundId != null + ? selectedAddress.boundId + : activeBoundId + + const [initialData, setInitialData] = useState(undefined) + const [isReady, setIsReady] = useState(false) + + // Rehydrate the snapshot for THIS bound before the request is allowed. + useEffect(() => { + let cancelled = false + setIsReady(false) + setInitialData(undefined) + if (boundId == null) { + setIsReady(true) + return + } + const raw = readEssentialConstsSnapshot(boundId) + if (cancelled) return + if (raw) { + try { + setInitialData(JSON.parse(raw) as DiscoveryData) + } catch { + // ignore corrupt snapshot + } + } + setIsReady(true) + return () => { + cancelled = true + } + }, [boundId]) + + // The backend resolves the flat payload for a single bound. tRPC includes the + // input in the query key, so switching bounds refetches discovery. + const query = trpc.common.essentialConsts.useQuery({ boundId: boundId ?? 0 }, { + refetchInterval: 60000, + enabled: isReady && boundId != null, + placeholderData: initialData, + }) + + // Persist the latest response under this bound's key. + useEffect(() => { + if (query.data && boundId != null) { + writeEssentialConstsSnapshot(boundId, JSON.stringify(query.data)) + } + }, [query.data, boundId]) + return { ...query, refetch: query.refetch } } diff --git a/apps/web-ui/src/routes/home.checkout.tsx b/apps/web-ui/src/routes/home.checkout.tsx index 1569fb6..27c9b8a 100644 --- a/apps/web-ui/src/routes/home.checkout.tsx +++ b/apps/web-ui/src/routes/home.checkout.tsx @@ -94,7 +94,7 @@ function CheckoutPage() { selectedItems: cartItems.map((item) => ({ skuId: item.skuId, quantity: item.quantity, - slotId: null, + slotId: item.slotId ?? null, })), addressId: selectedAddressId, regionId: selectedRegionId, diff --git a/change-log.txt b/change-log.txt index faba1b8..b4b9bed 100644 --- a/change-log.txt +++ b/change-log.txt @@ -5786,3 +5786,825 @@ user-ui payment_state/refund_coupon_id; recreates idx_orders_region + idx_complaints_region. Validated on a scratch copy: counts preserved, foreign_key_check + integrity_check clean, complaints.region_id kept. + +2026-10-17 16:16:25 FIX: name search bypassed regional customer isolation (notification picker). + + packages/db_helper_sqlite/src/admin-apis/user.ts + - searchUsers(): the raw SQL chunk `mobile LIKE ? OR name LIKE ?` was passed as the + second operand of and(), so Drizzle rendered + WHERE (EXISTS (... region = ?) AND mobile LIKE ? OR name LIKE ?) + and SQL precedence made the name branch escape the region filter: + (EXISTS AND mobile LIKE) OR (name LIKE) + A regional admin searching by name received out-of-region customers (name + mobile) + in the getUsersForNotification recipient picker. + - Wrapped the two LIKE predicates in Drizzle's or() so the region EXISTS is ANDed with + both: and(inRegion, or(sql`mobile LIKE`, sql`name LIKE`)). + + Diff: +--- a/packages/db_helper_sqlite/src/admin-apis/user.ts ++++ b/packages/db_helper_sqlite/src/admin-apis/user.ts +@@ -1,4 +1,4 @@ +-import { eq, sql, desc, asc, count, max, inArray, and } from 'drizzle-orm' ++import { eq, sql, desc, asc, count, max, inArray, and, or } from 'drizzle-orm' +@@ -221,7 +221,12 @@ export async function searchUsers(regionId: number, search?: string): Promise { + .from(users) +- .where(and(inRegion, sql`${users.mobile} LIKE ${`%${search.trim()}%`} OR ${users.name} LIKE ${`%${search.trim()}%`}`)) ++ .where(and( ++ inRegion, ++ or( ++ sql`${users.mobile} LIKE ${`%${search.trim()}%`}`, ++ sql`${users.name} LIKE ${`%${search.trim()}%`}`, ++ ), ++ )) + + Verified with an in-memory sqlite3 repro: the old predicate returned an out-of-region user + for a name search; the grouped predicate returns no rows. No test suite run. + +2026-10-17 16:18:52 FIX: web-ui discovery sent the wrong required input (essentialConsts needs boundId). + + apps/web-ui/src/hooks/prominent-api-hooks.ts + - useGetEssentialConsts() sent { regionId } behind an `as any` cast; the backend procedure + is common.essentialConsts .input(z.object({ boundId: z.number().int().positive() })), + so every request after a region was selected failed Zod validation (BAD_REQUEST) and no + discovery payload arrived. useCacheUrl() then returned null, leaving products / + availability / stores / slots / banners disabled. + - Rewritten to mirror apps/user-ui/src/hooks/prominent-api-hooks.ts (#68) + useRegion(): + * active bound = trpc.common.activeBound for the browsing region (server-derived + least-priority bound among the user's addresses, else the region's effective bound), + falling back to selectedRegion.effectiveBoundId while that query is in flight; + * the selected checkout address's bound overrides it when it belongs to the same region; + * query input is { boundId: boundId ?? 0 } (placeholder while disabled), typed - no `as any`; + * enabled: isReady && boundId != null; + * last response persisted per bound in localStorage under `essential_consts_b` + and rehydrated as placeholderData, same as user-ui's StorageServiceCasual snapshot; + * stale "essentialConsts REQUIRES {regionId}" comment removed. + - Deliberate difference from user-ui: no launch-location bound, because web-ui has no + location store / launch region resolution (its RegionGate only validates the saved region). + + Diff: +--- a/apps/web-ui/src/hooks/prominent-api-hooks.ts ++++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts +@@ + import { trpc } from '../lib/trpc-client' ++import { useAuth } from '../lib/auth-context' ++import { useAddressStore } from '../lib/stores' + import { useRegionStore } from '../lib/stores/region-store' +@@ +-export const useGetEssentialConsts = () => { +- const selectedRegionId = useRegionStore((state) => state.selectedRegionId) +- // FIXED CONTRACT: essentialConsts REQUIRES {regionId}. The input is cast so +- // this typechecks against the current backend (which takes no input and +- // ignores the extra field at runtime) and the future one. tRPC includes the +- // input in the query key, so switching regions refetches discovery. No +- // region selected -> the query stays disabled (the region gate covers this). +- const query = trpc.common.essentialConsts.useQuery({ regionId: selectedRegionId ?? 0 } as any, { +- refetchInterval: 60000, +- enabled: selectedRegionId != null, +- }) +- return { ...query, refetch: query.refetch } +-} ++const essentialConstsKey = (boundId: number) => `essential_consts_b${boundId}` ++ ++// The only persisted discovery payload: the small per-bound consts object. ++const readEssentialConstsSnapshot = (boundId: number): string | null => { ++ try { ++ return typeof localStorage === 'undefined' ? null : localStorage.getItem(essentialConstsKey(boundId)) ++ } catch { ++ return null ++ } ++} ++ ++const writeEssentialConstsSnapshot = (boundId: number, value: string): void => { ++ try { ++ if (typeof localStorage !== 'undefined') { ++ localStorage.setItem(essentialConstsKey(boundId), value) ++ } ++ } catch { ++ // Quota or privacy mode — the snapshot is only a fast-start optimisation. ++ } ++} ++ ++export const useGetEssentialConsts = () => { ++ const selectedRegionId = useRegionStore((state) => state.selectedRegionId) ++ const selectedRegion = useRegionStore((state) => state.selectedRegion) ++ const { isAuthenticated } = useAuth() ++ const selectedAddressId = useAddressStore((state) => state.selectedAddressId) ++ ++ // The active bound (least-priority bound among the user's addresses in the ++ // region, else the region's effective bound) drives the constants. Derived ++ // server-side — the client does not know bound priorities. ++ const activeBoundQuery = trpc.common.activeBound.useQuery( ++ { regionId: selectedRegionId ?? 0 }, ++ { enabled: selectedRegionId != null, staleTime: 60000 } ++ ) ++ const activeBoundId = activeBoundQuery.data?.boundId ?? selectedRegion?.effectiveBoundId ?? null ++ ++ // At checkout the selected address's bound overrides the active bound. ++ const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, { ++ enabled: isAuthenticated && selectedAddressId != null, ++ }) ++ const selectedAddress = addressesData?.data?.find((address) => address.id === selectedAddressId) ++ const boundId = ++ selectedAddress && selectedAddress.regionId === selectedRegionId && selectedAddress.boundId != null ++ ? selectedAddress.boundId ++ : activeBoundId ++ ++ const [initialData, setInitialData] = useState(undefined) ++ const [isReady, setIsReady] = useState(false) ++ ++ // Rehydrate the snapshot for THIS bound before the request is allowed. ++ useEffect(() => { ++ let cancelled = false ++ setIsReady(false) ++ setInitialData(undefined) ++ if (boundId == null) { ++ setIsReady(true) ++ return ++ } ++ const raw = readEssentialConstsSnapshot(boundId) ++ if (cancelled) return ++ if (raw) { ++ try { ++ setInitialData(JSON.parse(raw) as DiscoveryData) ++ } catch { ++ // ignore corrupt snapshot ++ } ++ } ++ setIsReady(true) ++ return () => { ++ cancelled = true ++ } ++ }, [boundId]) ++ ++ // The backend resolves the flat payload for a single bound. tRPC includes the ++ // input in the query key, so switching bounds refetches discovery. ++ const query = trpc.common.essentialConsts.useQuery({ boundId: boundId ?? 0 }, { ++ refetchInterval: 60000, ++ enabled: isReady && boundId != null, ++ placeholderData: initialData, ++ }) ++ ++ // Persist the latest response under this bound's key. ++ useEffect(() => { ++ if (query.data && boundId != null) { ++ writeEssentialConstsSnapshot(boundId, JSON.stringify(query.data)) ++ } ++ }, [query.data, boundId]) ++ ++ return { ...query, refetch: query.refetch } ++} + +2026-10-17 16:21:36 FIX: superadmin global-product updates discarded SKU IDs (duplicate variants on save). + + apps/backend/src/trpc/apis/superadmin-apis/apis/global-products.ts + - skuInput (shared by create/update) did not declare `id`, so Zod stripped the IDs the + superadmin-ui sends (global-products.tsx:412 `id: s.id`). The update resolver then read + `(sku as any).id` (always undefined), and updateProduct's upsert branch + (packages/db_helper_sqlite/src/admin-apis/product.ts:668) requires sku.id != null, so + EVERY variant took the insert path: saving an edit added a new product_skus row per + variant (plus product_market_stats for all regions) while the originals stayed untouched. + Suspending/deleting a variant therefore created a suspended/deleted duplicate and left + the original live/purchasable, and the active-combo suspension guard (product.ts:618-620) + was skipped because it also requires sku.id != null. + - Added `id: z.number().int().positive().optional()` to skuInput and replaced the + `(sku as any).id` cast with `sku.id`. Mirrors the regional admin schema + (admin-apis/apis/product.ts:283 + :333). Create is unaffected: its mapper never reads id. + + Diff: +--- a/apps/backend/src/trpc/apis/superadmin-apis/apis/global-products.ts ++++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/global-products.ts +@@ -13,6 +13,7 @@ + const skuInput = z.object({ ++ id: z.number().int().positive().optional(), + name: z.string().optional().nullable(), + price: z.number().nonnegative('Price must be positive'), +@@ -104,7 +105,7 @@ + productType: rest.productType, + skus: rest.skus.map((sku) => ({ +- id: (sku as any).id, ++ id: sku.id, + name: sku.name ?? null, + +2026-10-17 16:23:18 FIX: rejected regional store edits could delete a global store's image. + + apps/backend/src/trpc/apis/admin-apis/apis/store.ts + - updateStore fetched the target with getStoreById(regionId, id), whose visibility + predicate is "own region OR global" (packages/db_helper_sqlite/src/admin-apis/store.ts:30-31). + A global store therefore passed the existence check, the resolver deleted its old image + BEFORE calling updateStoreInDb, and only then updateStoreInDb rejected the write + (it requires region_id = region AND is_global = false, :97-103). Result: the image key + shared by every region was deleted from the bucket while the store row still referenced + it, and the mutation failed. + The same pre-delete ordering also destroyed the image whenever the update was rejected + for another reason (e.g. resolveInRegionProductIds rejecting a foreign/invalid product). + - Two changes: + 1. Reject non-editable stores up front: not found, OR isGlobal, OR regionId != caller's + region -> ApiError("Store not found", 404), before any asset is touched. + 2. Moved the old-image deletion to AFTER updateStoreInDb succeeds, so a rejected edit can + never remove a still-referenced image; a failed delete now only leaves an orphaned asset + (logged), which is safe. + + Diff: +--- a/apps/backend/src/trpc/apis/admin-apis/apis/store.ts ++++ b/apps/backend/src/trpc/apis/admin-apis/apis/store.ts +@@ -93,22 +93,17 @@ + const existingStore = await getStoreByIdFromDb(ctx.staffUser!.regionId, id); + +- if (!existingStore) { ++ // getStoreById also returns global stores (visible in every region), but only ++ // the region's own non-global stores are editable. Reject before touching any ++ // asset: updateStoreInDb enforces the same rule, but only after this resolver ++ // would have deleted the old image. ++ if (!existingStore || existingStore.isGlobal || existingStore.regionId !== ctx.staffUser!.regionId) { + throw new ApiError("Store not found", 404); + } + + const oldImageKey = existingStore.imageUrl; + const newImageKey = imageUrl ? extractKeyFromPresignedUrl(imageUrl) : oldImageKey; + +- // Delete old image only if: +- // 1. New image provided and keys are different, OR +- // 2. No new image but old exists (clearing the image) +- if (oldImageKey && ( +- (newImageKey && newImageKey !== oldImageKey) || +- (!newImageKey) +- )) { +- try { +- await deleteImageUtil({keys: [oldImageKey]}); +- } catch (error) { +- console.error('Failed to delete old image:', error); +- // Continue with update even if deletion fails +- } +- } +- + const updatedStore = await updateStoreInDb( + ctx.staffUser!.regionId, + id, +@@ -121,6 +116,17 @@ + products + ); + ++ // Delete the replaced image only after the update was accepted, so a rejected ++ // edit cannot remove an image that is still referenced. A failed delete only ++ // leaves an orphaned asset. ++ if (oldImageKey && newImageKey !== oldImageKey) { ++ try { ++ await deleteImageUtil({keys: [oldImageKey]}); ++ } catch (error) { ++ console.error('Failed to delete old image:', error); ++ } ++ } ++ + +2026-10-17 16:32:26 FIX: regional cache requests could suppress a pending global regeneration. + + apps/backend/src/jobs/cache-creator.ts + - schedule() only recorded region ids. A global request (no regionId, e.g. a global + product/store create/update/delete) recorded nothing, relying on "empty pending list = + all regions". If a regional request landed in the same 0.5-minute debounce window it + filled pendingRegions, so alarm() saw a non-empty list and regenerated only that region. + Every other region kept the stale catalog (global product edit -> region-A banner edit + -> only region A regenerated). + - Added an explicit `allRegionsPending` flag: + * schedule(undefined / non-finite) sets the flag and clears pendingRegions — a global + change always means every region; + * schedule(regionId) still appends to pendingRegions, but never when the global flag is + set (the global run already covers that region); + * alarm() drains both keys; if allRegionsPending is set (or pendingRegions is empty, + preserving the old default) it calls initializeAllStores() for every region, otherwise + it regenerates the listed regions. + Regional requests can therefore no longer narrow a pending global run. + + Diff: +--- a/apps/backend/src/jobs/cache-creator.ts ++++ b/apps/backend/src/jobs/cache-creator.ts +@@ -5,6 +5,7 @@ + const LAST_TRIGGER_KEY = 'lastTrigger' + const PENDING_REGIONS_KEY = 'pendingRegions' ++const ALL_REGIONS_PENDING_KEY = 'allRegionsPending' +@@ -27,10 +28,22 @@ + if (regionId != null && Number.isFinite(regionId)) { +- const pending = ((await this.state.storage.get(PENDING_REGIONS_KEY)) as number[] | undefined) ?? [] +- if (!pending.includes(regionId)) { +- pending.push(regionId) +- await this.state.storage.put(PENDING_REGIONS_KEY, pending) ++ // Regional request: add to the drain list unless a global run is already ++ // pending (it regenerates every region, so this request is covered). ++ const allPending = (await this.state.storage.get(ALL_REGIONS_PENDING_KEY)) as boolean | undefined ++ if (!allPending) { ++ const pending = ((await this.state.storage.get(PENDING_REGIONS_KEY)) as number[] | undefined) ?? [] ++ if (!pending.includes(regionId)) { ++ pending.push(regionId) ++ await this.state.storage.put(PENDING_REGIONS_KEY, pending) ++ } + } ++ } else { ++ // Global request (e.g. a global product edit): every region must be ++ // regenerated. Record it explicitly and drop the per-region list so a later ++ // regional request in the same debounce window cannot narrow it. ++ await this.state.storage.put(ALL_REGIONS_PENDING_KEY, true) ++ await this.state.storage.delete(PENDING_REGIONS_KEY) + } +@@ -68,10 +81,15 @@ + const pending = ((await this.state.storage.get(PENDING_REGIONS_KEY)) as number[] | undefined) ?? [] ++ const allRegionsPending = (await this.state.storage.get(ALL_REGIONS_PENDING_KEY)) as boolean | undefined + await this.state.storage.delete(PENDING_REGIONS_KEY) ++ await this.state.storage.delete(ALL_REGIONS_PENDING_KEY) + +- if (pending.length === 0) { ++ if (allRegionsPending || pending.length === 0) { + await initializeAllStores() + } else { + +2026-10-17 16:33:56 FIX: /home/checkout sent slotId: null for every scheduled cart line. + + apps/web-ui/src/routes/home.checkout.tsx + - handlePlaceOrder built selectedItems with a hardcoded `slotId: null` while sending + isFlashDelivery: false. placeOrder groups lines by slot and, for non-flash orders, + rejects a null group with "A delivery slot is required for scheduled orders" + (apps/backend/src/trpc/apis/user-apis/apis/order.ts:190-194) - so every non-empty + scheduled checkout on this route failed, regardless of the selected slots. + - Now forwards each cart line's selected slot: `slotId: item.slotId ?? null`, matching + PaymentAndOrderComponent (the live /checkout path). Flash checkout keeps null, which is + correct because slot validation is skipped for flash orders. + - Note: /home/checkout is an unlinked duplicate of /checkout (no in-app navigation targets + it; only direct URL / AppLayout's hideShellRoutes reference it). Left in place; say the + word if it should be removed instead. + + Diff: +--- a/apps/web-ui/src/routes/home.checkout.tsx ++++ b/apps/web-ui/src/routes/home.checkout.tsx +@@ -94,7 +94,7 @@ + selectedItems: cartItems.map((item) => ({ + skuId: item.skuId, + quantity: item.quantity, +- slotId: null, ++ slotId: item.slotId ?? null, + })), + +2026-10-17 16:35:38 FIX: new-region cache generation was detached from the Worker request lifetime. + + apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts + - create() called createRegionCacheFiles(region.id) with only .catch(), i.e. a bare + fire-and-forget promise. The mutation returned immediately; once the response was sent + the Worker isolate could be torn down and cancel the uploads, leaving a created region + with no (or partial) products/availability/stores/slots/banners/essential-consts files. + - Now the generation is awaited inside the request, wrapped in its own try/catch so a + cache failure is logged and the (already-created) region is still returned instead of + being misreported by the outer catch as "Could not create region with bounds". + + Diff: +--- a/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts ++++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts +@@ -88,10 +88,14 @@ +- // New region's cache files are generated at creation (fire-and-forget). +- const { createRegionCacheFiles } = await import('@/src/lib/cloud_cache') +- createRegionCacheFiles(region.id).catch((error) => { +- console.error(`Failed to generate cache files for new region ${region.id}:`, error) +- }) ++ // New region's cache files are generated at creation. Await the work so it stays ++ // attached to this request's lifetime; a bare fire-and-forget promise can be ++ // cancelled once the response is sent. Best-effort: a failure is logged and the ++ // region is still returned as created. ++ try { ++ const { createRegionCacheFiles } = await import('@/src/lib/cloud_cache') ++ await createRegionCacheFiles(region.id) ++ } catch (error) { ++ console.error(`Failed to generate cache files for new region ${region.id}:`, error) ++ } + return { ...region, bounds } + +2026-10-17 16:37:13 FIX: Superadmin global-product Edit reused the create form's draft state. + + apps/superadmin-ui/src/routes/global-products.tsx + - GlobalProductsTab renders and + at the same tree position with the same component type and no + key. React therefore reconciled them as one instance, and because GlobalProductForm + seeds its useState values from props only on mount (lines 346-353), clicking Edit kept + the blank create draft (or a previously edited product's draft) while the mutation + targeted the newly selected product id - saving that stale draft over it. + - Keyed both branches so a product change remounts the form and re-seeds every field: + key={`edit-${editing.id}`} for edit, key="create" for the create branch. + This also clears the form when the edit is saved/cancelled and when switching directly + from one product to another. + + Diff: +--- a/apps/superadmin-ui/src/routes/global-products.tsx ++++ b/apps/superadmin-ui/src/routes/global-products.tsx +@@ -274,12 +274,13 @@ + {editing ? ( + { setEditingId(null); refresh() }} + onCancel={() => setEditingId(null)} + /> + ) : ( +- ++ + )} + +2026-10-17 16:41:20 FIX: regional admin order pagination was bounded by a global order-ID window. + + packages/db_helper_sqlite/src/admin-apis/order.ts - getAllOrders() + - The first page computed maxId from the GLOBALLY newest order (no region filter) and + kept only `id > maxId - limit - 5`; later pages kept `id < cursor AND id > cursor - + limit - 5`. With another region creating more than limit + 5 newer orders, the quiet + region's window contained no rows, so the list came back empty with nextCursor + undefined even though the region had (older, pending) orders - and those orders could + never be reached. + - Now paginates the region's own matching rows directly (keyset on id): + * no cursor -> region (+ filters), newest first, limit + 1 fetched for hasMore; + * cursor -> region (+ filters) AND id < cursor. + The global maxId lookup and both `limit + 5` bounds are gone. + - orderBy changed from desc(orders.createdAt) to desc(orders.id) so the sort key matches + the cursor (id). createdAt is second-resolution SQLite CURRENT_TIMESTAMP, so ties made + createdAt-based ordering non-deterministic while the cursor was id-based. + - Removed the now-unused `gt` import. + + Diff: +--- a/packages/db_helper_sqlite/src/admin-apis/order.ts ++++ b/packages/db_helper_sqlite/src/admin-apis/order.ts +@@ -12,7 +12,7 @@ +-import { and, desc, eq, gt, inArray, lt, SQL } from 'drizzle-orm' ++import { and, desc, eq, inArray, lt, SQL } from 'drizzle-orm' +@@ -415,16 +415,11 @@ + let whereCondition: SQL | undefined = eq(orders.regionId, regionId) + +- if(!cursor) { +- // Get max order ID for initial pagination +- const [maxOrder] = await db +- .select() +- .from(orders) +- .orderBy(desc(orders.id)) +- .limit(1) +- +- const maxId = maxOrder?.id ?? 0 +- const threshold = maxId - limit - 5 +- whereCondition = and(whereCondition, gt(orders.id, threshold)) +- } ++ // Keyset pagination over the region's own rows: the cursor is the id of the last ++ // order returned, so each page is just the next `limit + 1` rows below it. A page ++ // bounded by a window derived from the globally newest order id could come back ++ // empty (and cursor-less) for a region whose orders are older than that window. + if (cursor) { + whereCondition = and(whereCondition, lt(orders.id, cursor)) +- whereCondition = and(whereCondition, gt(orders.id, cursor-limit-5)) + } +@@ -457,7 +452,7 @@ + const allOrders = await db.query.orders.findMany({ + where: whereCondition, +- orderBy: desc(orders.createdAt), ++ orderBy: desc(orders.id), + limit: limit + 1, + +2026-10-17 16:45:13 FIX: unrelated regional market edits cleared a SKU's regional suspension. + + Root cause: the admin SKU mapper exposed only the global structural kill-switch + (product_skus.is_suspended) as `isSuspended`, never product_market_stats.is_suspended_in_region. + The regional product form seeded its Suspend toggle from `isSuspended`, and + updateProductMarketDataForRegion fell back to that same field + (`sku.isSuspendedInRegion ?? sku.isSuspended ?? false`). So after a regional suspension the + form reopened as "not suspended", and the next save (e.g. a price edit) wrote false and + re-enabled the SKU in that region. + + packages/shared/types/admin.ts + - AdminSku gains `isSuspendedInRegion: boolean` (documented as this region's market-stats + suspension, separate from the global kill-switch). + + packages/db_helper_sqlite/src/admin-apis/product.ts + - mapSku returns `isSuspendedInRegion: marketStats?.isSuspendedInRegion ?? false`. + - updateProductMarketDataForRegion writes `isSuspendedInRegion` only when the caller + supplies it (conditional spread) and no longer falls back to `sku.isSuspended`, so an + omitted field preserves the stored regional value and an unrelated edit cannot clear it. + + apps/backend/src/trpc/apis/admin-apis/apis/product.ts + - updateProduct input: added `isSuspendedInRegion: z.boolean().optional()` (Zod would + otherwise strip it). + - skuInputs mapping forwards `isSuspendedInRegion`. + + apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx and + apps/admin-web/src/routes/dashboard.products.edit.tsx + - Initial values seed the Suspend toggle from `isSuspendedInRegion` for global products + (market-data-only edits) and from `isSuspended` for the region's own products. + - Submit sends `isSuspendedInRegion` for global products; regional products keep writing + the SKU's own isSuspended via the structural path. + + Diffs: +--- a/packages/shared/types/admin.ts ++++ b/packages/shared/types/admin.ts +@@ -282,6 +282,9 @@ + isOutOfStock: boolean + isSuspended: boolean ++ /** This region's suspension (product_market_stats.is_suspended_in_region), ++ * separate from the global superadmin kill-switch (`isSuspended`). */ ++ isSuspendedInRegion: boolean + isFlashAvailable: boolean +--- a/packages/db_helper_sqlite/src/admin-apis/product.ts ++++ b/packages/db_helper_sqlite/src/admin-apis/product.ts +@@ -197,6 +197,7 @@ + isOutOfStock: marketStats?.isOutOfStock ?? false, + isSuspended: sku.isSuspended, ++ isSuspendedInRegion: marketStats?.isSuspendedInRegion ?? false, + isFlashAvailable: marketStats?.isFlashAvailable ?? false, +@@ -542,7 +543,11 @@ + isOutOfStock: sku.isOutOfStock ?? false, +- isSuspendedInRegion: sku.isSuspendedInRegion ?? sku.isSuspended ?? false, ++ // Regional suspension is its own flag. Never fall back to the global ++ // structural `isSuspended`: an unrelated price/stock edit must not ++ // re-enable a SKU this region suspended. Omitted -> keep the value. ++ ...(sku.isSuspendedInRegion !== undefined && { isSuspendedInRegion: sku.isSuspendedInRegion }), + isOffer: sku.isOffer ?? false, +--- a/apps/backend/src/trpc/apis/admin-apis/apis/product.ts ++++ b/apps/backend/src/trpc/apis/admin-apis/apis/product.ts +@@ -291,6 +291,7 @@ + isDeleted: z.boolean().optional().default(false), + isSuspended: z.boolean().optional().default(false), ++ isSuspendedInRegion: z.boolean().optional(), + features: z.array(z.object({ +@@ -341,6 +342,7 @@ + isDeleted: sku.isDeleted ?? false, + isSuspended: sku.isSuspended, ++ isSuspendedInRegion: sku.isSuspendedInRegion, + features: sku.features.map((f) => ({ +--- a/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx ++++ b/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx +@@ -64,7 +64,9 @@ + isDeleted: sku.isDeleted || false, +- isSuspended: sku.isSuspended || false, ++ // Global products are market-data-only for a regional admin: the toggle is ++ // this region's suspension, not the superadmin kill-switch. ++ isSuspended: (productData.isGlobal ? sku.isSuspendedInRegion : sku.isSuspended) || false, + features: (sku.features || []).map((f) => ({ +@@ -167,6 +169,8 @@ + isDeleted: variant.isDeleted || false, + isSuspended: variant.isSuspended || false, ++ // Read only by the regional market-data path (global products). ++ isSuspendedInRegion: productData?.isGlobal ? (variant.isSuspended || false) : undefined, + features: variant.features.map((attr: any) => ({ +--- a/apps/admin-web/src/routes/dashboard.products.edit.tsx ++++ b/apps/admin-web/src/routes/dashboard.products.edit.tsx +@@ -60,7 +60,9 @@ + isDeleted: sku.isDeleted || false, +- isSuspended: sku.isSuspended || false, ++ // Global products are market-data-only for a regional admin: the toggle is ++ // this region's suspension, not the superadmin kill-switch. ++ isSuspended: (productData.isGlobal ? sku.isSuspendedInRegion : sku.isSuspended) || false, + features: (sku.features || []).map((f) => ({ +@@ -160,6 +162,8 @@ + isDeleted: variant.isDeleted || false, + isSuspended: variant.isSuspended || false, ++ // Read only by the regional market-data path (global products). ++ isSuspendedInRegion: productData?.isGlobal ? (variant.isSuspended || false) : undefined, + features: variant.features.map((attr: any) => ({ + +2026-10-17 16:49:45 FIX: coupon allocation could persist negative sub-order totals. + + packages/shared/cart-pricing.ts - computeCartPricing() + - Each coupon's rounded discount was split across its eligible sub-orders with + roundSharesOnto() in isolation, ignoring what earlier coupons had already allocated to + those sub-orders. Two Rs.101 sub-orders with two stackable Rs.101 coupons came out as + shares [100, 102]: the second sub-order was discounted below zero and its persisted + orders.totalAmount became -1. + - Added allocateBounded(weights, total, caps): proportional whole-rupee allocation that + never exceeds a per-sub-order cap, re-distributing the rounding shortfall to other + eligible sub-orders (largest weight first) so the coupon still allocates its full + amount while staying inside every balance. + - computeCartPricing now tracks allocatedByGroup[] and caps each coupon's per-group share + at max(0, subOrderGoods[group] - alreadyAllocated). discountTotal accumulates the + actually allocated amounts (never more than the goods subtotal), so it always equals the + sum of per-sub-order couponDiscounts. + - Removed the old post-hoc scaling fallback (discountTotal > goodsSubtotal) - impossible + once shares are capped per sub-order - and clamped each persisted total at min 0: + `total: Math.max(0, goodsSubtotal - discount + delivery)`. + + Diff: +--- a/packages/shared/cart-pricing.ts ++++ b/packages/shared/cart-pricing.ts +@@ -294,6 +294,41 @@ function roundSharesOnto(rawShares: number[], total: number): number[] { + return rounded + } + ++/** ++ * Allocate `total` whole rupees across `weights` proportionally, never exceeding ++ * `caps[i]`. The amounts sum to min(total, sum(caps)); the rounding shortfall is ++ * folded onto the largest weights that still have headroom. ++ */ ++function allocateBounded(weights: number[], total: number, caps: number[]): number[] { ++ const capTotal = caps.reduce((sum, cap) => sum + Math.max(0, cap), 0) ++ const target = Math.max(0, Math.min(total, capTotal)) ++ if (target === 0) return weights.map(() => 0) ++ ++ const allocated = roundSharesOnto(weights, target) ++ for (let i = 0; i < allocated.length; i++) { ++ allocated[i] = Math.max(0, Math.min(allocated[i], Math.max(0, caps[i]))) ++ } ++ ++ // Proportional rounding can push a share past its sub-order's remaining ++ // balance (or the usable cap). Re-allocate the shortfall one rupee at a time, ++ // largest weight first, so the coupon still discounts its full amount and the ++ // shares still sum exactly. ++ let shortfall = target - allocated.reduce((sum, value) => sum + value, 0) ++ while (shortfall > 0) { ++ let pick = -1 ++ for (let i = 0; i < allocated.length; i++) { ++ if (allocated[i] >= Math.max(0, caps[i])) continue ++ if (pick === -1 || (weights[i] ?? 0) > (weights[pick] ?? 0)) pick = i ++ } ++ if (pick === -1) break ++ allocated[pick] += 1 ++ shortfall -= 1 ++ } ++ ++ return allocated ++} ++ + /** One cart line's share of a coupon's discount. */ +@@ -402,28 +437,34 @@ export function computeCartPricing(params: { + const { perCoupon } = runStack(flat, coupons) + + const perSubOrderCoupon: CouponDiscountShare[][] = subOrders.map(() => []) ++ // What each sub-order has already absorbed, so later coupons can only take ++ // what is still left there. ++ const allocatedByGroup = subOrders.map(() => 0) + let discountTotal = 0 + + for (const coupon of perCoupon) { +- discountTotal += coupon.discount + if (coupon.discount <= 0 || coupon.shareByGroup.size === 0) continue + + const groups = [...coupon.shareByGroup.keys()].sort((a, b) => a - b) + const rawShares = groups.map((g) => coupon.shareByGroup.get(g) ?? 0) ++ // Cap each share at the sub-order's remaining balance so no sub-order can be ++ // discounted below zero; the shortfall is re-allocated within those caps. ++ const caps = groups.map((g) => Math.max(0, subOrderGoods[g] - allocatedByGroup[g])) ++ const rounded = allocateBounded(rawShares, coupon.discount, caps) ++ const allocated = rounded.reduce((sum, value) => sum + value, 0) ++ if (allocated <= 0) continue + +- // 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 rounded = roundSharesOnto(rawShares, coupon.discount) +- ++ discountTotal += allocated + groups.forEach((group, i) => { +- if (rounded[i] !== 0) { +- perSubOrderCoupon[group].push({ +- couponId: coupon.couponId, +- discount: rounded[i], +- }) +- } ++ if (rounded[i] === 0) return ++ perSubOrderCoupon[group].push({ ++ couponId: coupon.couponId, ++ discount: rounded[i], ++ }) ++ allocatedByGroup[group] += rounded[i] + }) + } +- +- // 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: Math.round(entry.discount * factor), +- })) +- } +- discountTotal = goodsSubtotal +- } +@@ -447,7 +478,9 @@ export function computeCartPricing(params: { + goodsSubtotal: subOrderGoods[i], + discount, + delivery: subDelivery, +- total: subOrderGoods[i] - discount + subDelivery, ++ // Shares are capped per sub-order, so this never goes negative; clamped ++ // defensively because the figure is persisted and shown as money. ++ total: Math.max(0, subOrderGoods[i] - discount + subDelivery), + couponDiscounts: perSubOrderCoupon[i], + } + }) + +2026-10-17 16:50:56 CORRECTION to the coupon-allocation fix (allocateBounded refinements). + + packages/shared/cart-pricing.ts - allocateBounded() + - Whole-rupee shares cannot be capped by a fractional balance, so caps are floored + (`Math.max(0, Math.floor(cap))`) and target = min(total, sum(limits)). + - Reconciles drift in BOTH directions: the previous shortfall-only loop handled clamping, + but roundSharesOnto can also return a negative share when many small groups round up + (e.g. 8 lines of 1 with a flat-4 coupon), and clamping that to 0 makes the split + over-allocate. Added a subtract loop (take from the largest shares first) so the split + always sums to exactly the coupon's rounded discount while staying within every limit. + - Final helper: + const limits = caps.map((cap) => Math.max(0, Math.floor(cap))) + const target = Math.max(0, Math.min(total, limits.reduce((s, l) => s + l, 0))) + if (target === 0) return weights.map(() => 0) + const allocated = roundSharesOnto(weights, target) + // clamp to [0, limit] + // diff = target - sum(allocated): add (largest weight with headroom), subtract + // (largest share) until diff === 0 + - Verified with a tsx matrix (report case, 100% x2, uneven 100+2, 10% baseline, targeted + coupon, delivery, maxValue, 8x1 drift case, sub-rupee goods): no sub-order discount + exceeds its goods subtotal, no total is negative, discountTotal === sum of shares, + grandTotal === sum of sub-order totals. Backend tsc clean. + +2026-10-17 16:53:38 FIX: admin-web lost the staff region on reload, disabling vendor-snippet slot selection. + + Root cause: StaffAuthProvider only persists/restores the JWT. After a reload it set + isLoggedIn = true but left `staff` (and therefore `regionId`) null until the next login. + VendorSnippetForm gates its slot query on `regionId != null`, so slots never loaded and a + non-permanent snippet could not be created (it validates that a slot is selected). + + apps/admin-web/src/components/context/staff-auth-context.tsx + - Added a `trpc.admin.staffUser.me` query gated on `isLoggedIn` (the endpoint is a + staffProcedure returning the signed-in staff's id, name, regionId and regionName) and + an effect that stores the result in `staff`. Region-scoped screens now get regionId + after a reload, and the sidebar identity block renders the real staff name instead of + being hidden. Server-side restore also avoids trusting a stale persisted region if the + staff member is moved between regions. + + Diff: +--- a/apps/admin-web/src/components/context/staff-auth-context.tsx ++++ b/apps/admin-web/src/components/context/staff-auth-context.tsx +@@ -34,6 +34,15 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => { + const navigate = useNavigate() + const location = useLocation() + ++ // Only the JWT survives a reload. Restore the staff identity (and therefore ++ // regionId) from the authenticated endpoint so region-scoped screens such as ++ // the vendor-snippet slot picker are not permanently disabled until re-login. ++ const meQuery = trpc.admin.staffUser.me.useQuery(undefined, { ++ enabled: isLoggedIn, ++ }) ++ useEffect(() => { ++ if (meQuery.data) setStaff(meQuery.data) ++ }, [meQuery.data]) ++ + useEffect(() => { + const checkAuth = async () => { + +2026-10-17 16:54:32 FIX: superadmin "Admin Notifs" sent through a user/staff-only endpoint (always UNAUTHORIZED). + + Root cause: superadmin-ui has its own login (superadmin.auth.login -> ctx.superadmin), but + /send-notifications called trpc.admin.staffUser.sendAdminNotification, which is a + protectedProcedure (accepts ctx.user or ctx.staffUser only). A superadmin-only principal + was therefore rejected with UNAUTHORIZED on every send. + + apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts + - Added sendAdminNotification guarded by superadminProcedure, same input schema and + notifyAllAdmins() call/response as the admin endpoint (which stays for admin-ui). + + apps/superadmin-ui/src/routes/send-notifications.tsx + - Caller switched to trpc.superadmin.staff.sendAdminNotification. + + Diff: +--- a/apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts ++++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts +@@ -10,6 +10,7 @@ + } from '@/src/dbService' ++import { notifyAllAdmins } from '@/src/lib/admin-notif' + + export const superadminStaffRouter = router({ ++ sendAdminNotification: superadminProcedure ++ .input(z.object({ ++ title: z.string().min(1, 'Title is required'), ++ text: z.string().min(1, 'Message is required'), ++ imageUrl: z.string().optional(), ++ })) ++ .mutation(async ({ input }) => { ++ const { title, text, imageUrl } = input ++ const queuedCount = await notifyAllAdmins({ ++ title, ++ body: text, ++ imageUrl: imageUrl || null, ++ }) ++ return { ++ success: true, ++ message: `Notification queued for ${queuedCount} admins`, ++ } ++ }), ++ + list: superadminProcedure.query(async () => { +--- a/apps/superadmin-ui/src/routes/send-notifications.tsx ++++ b/apps/superadmin-ui/src/routes/send-notifications.tsx +@@ -25 +25 @@ +- const { mutate, isPending } = trpc.admin.staffUser.sendAdminNotification.useMutation({ ++ const { mutate, isPending } = trpc.superadmin.staff.sendAdminNotification.useMutation({ + +2026-10-17 16:57:05 FIX: admin sendAdminNotification was callable by customer tokens. + + apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts + - sendAdminNotification used protectedProcedure, whose guard accepts ctx.user OR + ctx.staffUser. The context resolves a customer token into ctx.user and there is no + namespace-level guard on the admin router, so any authenticated customer could push + notifications to every admin device. Switched the procedure to staffProcedure, which + accepts only ctx.staffUser (admin-ui's token). Superadmin sends use the new + superadmin.staff.sendAdminNotification endpoint. + + Diff: +--- a/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts ++++ b/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts +@@ -145 +145 @@ +- sendAdminNotification: protectedProcedure ++ sendAdminNotification: staffProcedure diff --git a/packages/db_helper_sqlite/src/admin-apis/order.ts b/packages/db_helper_sqlite/src/admin-apis/order.ts index 63e6368..f895862 100644 --- a/packages/db_helper_sqlite/src/admin-apis/order.ts +++ b/packages/db_helper_sqlite/src/admin-apis/order.ts @@ -8,7 +8,7 @@ import { orders, orderStatus, } from '../db/schema' -import { and, desc, eq, gt, inArray, lt, SQL } from 'drizzle-orm' +import { and, desc, eq, inArray, lt, SQL } from 'drizzle-orm' import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order' import type { AdminOrderDetails, @@ -414,21 +414,12 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput): let whereCondition: SQL | undefined = eq(orders.regionId, regionId) - if(!cursor) { - // Get max order ID for initial pagination - const [maxOrder] = await db - .select() - .from(orders) - .orderBy(desc(orders.id)) - .limit(1) - - const maxId = maxOrder?.id ?? 0 - const threshold = maxId - limit - 5 - whereCondition = and(whereCondition, gt(orders.id, threshold)) - } + // Keyset pagination over the region's own rows: the cursor is the id of the last + // order returned, so each page is just the next `limit + 1` rows below it. A page + // bounded by a window derived from the globally newest order id could come back + // empty (and cursor-less) for a region whose orders are older than that window. if (cursor) { whereCondition = and(whereCondition, lt(orders.id, cursor)) - whereCondition = and(whereCondition, gt(orders.id, cursor-limit-5)) } if (slotId) { whereCondition = and(whereCondition, eq(orders.slotId, slotId)) @@ -456,7 +447,7 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput): const allOrders = await db.query.orders.findMany({ where: whereCondition, - orderBy: desc(orders.createdAt), + orderBy: desc(orders.id), limit: limit + 1, with: { user: true, diff --git a/packages/db_helper_sqlite/src/admin-apis/product.ts b/packages/db_helper_sqlite/src/admin-apis/product.ts index f35956c..74c09c8 100644 --- a/packages/db_helper_sqlite/src/admin-apis/product.ts +++ b/packages/db_helper_sqlite/src/admin-apis/product.ts @@ -198,6 +198,7 @@ const mapSku = ( imageKeys: getStringArray(sku.images), isOutOfStock: marketStats?.isOutOfStock ?? false, isSuspended: sku.isSuspended, + isSuspendedInRegion: marketStats?.isSuspendedInRegion ?? false, isFlashAvailable: marketStats?.isFlashAvailable ?? false, flashPrice: marketStats?.flashPrice ? String(marketStats.flashPrice) : null, isOffer: marketStats?.isOffer ?? false, @@ -542,7 +543,10 @@ async function updateProductMarketDataForRegion(regionId: number, id: number, in isFlashAvailable: sku.isFlashAvailable ?? false, flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null, isOutOfStock: sku.isOutOfStock ?? false, - isSuspendedInRegion: sku.isSuspendedInRegion ?? sku.isSuspended ?? false, + // Regional suspension is its own flag. Never fall back to the global + // structural `isSuspended`: an unrelated price/stock edit must not + // re-enable a SKU this region suspended. Omitted -> keep the value. + ...(sku.isSuspendedInRegion !== undefined && { isSuspendedInRegion: sku.isSuspendedInRegion }), isOffer: sku.isOffer ?? false, } const existing = await tx.query.productMarketStats.findFirst({ diff --git a/packages/db_helper_sqlite/src/admin-apis/user.ts b/packages/db_helper_sqlite/src/admin-apis/user.ts index 445d346..dcc0174 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 } from 'drizzle-orm' +import { eq, sql, desc, asc, count, max, inArray, and, or } from 'drizzle-orm' export async function getUserByMobile(mobile: string): Promise { const [existingUser] = await db @@ -221,7 +221,13 @@ export async function searchUsers(regionId: number, search?: string): Promise Math.max(0, Math.floor(cap))) + const capTotal = limits.reduce((sum, limit) => sum + limit, 0) + const target = Math.max(0, Math.min(total, capTotal)) + if (target === 0) return weights.map(() => 0) + + const allocated = roundSharesOnto(weights, target) + for (let i = 0; i < allocated.length; i++) { + allocated[i] = Math.max(0, Math.min(allocated[i], limits[i])) + } + + // Proportional rounding can push a share past its sub-order's remaining + // balance (or the usable cap), and can round the split up or down overall. + // Reconcile one rupee at a time so the coupon still discounts exactly its + // rounded amount and nothing exceeds a sub-order's balance. + let diff = target - allocated.reduce((sum, value) => sum + value, 0) + while (diff > 0) { + let pick = -1 + for (let i = 0; i < allocated.length; i++) { + if (allocated[i] >= limits[i]) continue + if (pick === -1 || (weights[i] ?? 0) > (weights[pick] ?? 0)) pick = i + } + if (pick === -1) break + allocated[pick] += 1 + diff -= 1 + } + while (diff < 0) { + let pick = -1 + for (let i = 0; i < allocated.length; i++) { + if (allocated[i] <= 0) continue + if (pick === -1 || allocated[i] > allocated[pick]) pick = i + } + if (pick === -1) break + allocated[pick] -= 1 + diff += 1 + } + + return allocated +} + /** One cart line's share of a coupon's discount. */ export interface CouponLineDiscount { skuId: number @@ -368,7 +414,8 @@ export function computeCouponStack( * 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 + * hold the items), reconciled so the per-sub-order shares sum exactly and never + * exceed a sub-order's remaining balance. The single * cart-level delivery charge is attached to the primary sub-order (highest goods * subtotal). */ @@ -402,41 +449,35 @@ export function computeCartPricing(params: { const { perCoupon } = runStack(flat, coupons) const perSubOrderCoupon: CouponDiscountShare[][] = subOrders.map(() => []) + // What each sub-order has already absorbed, so later coupons can only take + // what is still left there. + const allocatedByGroup = subOrders.map(() => 0) let discountTotal = 0 for (const coupon of perCoupon) { - discountTotal += coupon.discount if (coupon.discount <= 0 || coupon.shareByGroup.size === 0) continue const groups = [...coupon.shareByGroup.keys()].sort((a, b) => a - b) const rawShares = groups.map((g) => coupon.shareByGroup.get(g) ?? 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 rounded = roundSharesOnto(rawShares, coupon.discount) + // Cap each share at the sub-order's remaining balance so no sub-order can be + // discounted below zero; the shortfall is re-allocated within those caps. + const caps = groups.map((g) => Math.max(0, subOrderGoods[g] - allocatedByGroup[g])) + const rounded = allocateBounded(rawShares, coupon.discount, caps) + const allocated = rounded.reduce((sum, value) => sum + value, 0) + if (allocated <= 0) continue + discountTotal += allocated groups.forEach((group, i) => { - if (rounded[i] !== 0) { - perSubOrderCoupon[group].push({ - couponId: coupon.couponId, - discount: rounded[i], - }) - } + if (rounded[i] === 0) return + perSubOrderCoupon[group].push({ + couponId: coupon.couponId, + discount: rounded[i], + }) + allocatedByGroup[group] += rounded[i] }) } - // 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: Math.round(entry.discount * factor), - })) - } - discountTotal = goodsSubtotal - } - const finalTotal = goodsSubtotal - discountTotal const deliveryTotal = finalTotal < threshold ? charge : 0 @@ -448,7 +489,9 @@ export function computeCartPricing(params: { goodsSubtotal: subOrderGoods[i], discount, delivery: subDelivery, - total: subOrderGoods[i] - discount + subDelivery, + // Shares are capped per sub-order, so this never goes negative; clamped + // defensively because the figure is persisted and shown as money. + total: Math.max(0, subOrderGoods[i] - discount + subDelivery), couponDiscounts: perSubOrderCoupon[i], } }) diff --git a/packages/shared/types/admin.ts b/packages/shared/types/admin.ts index 200f962..6595d62 100644 --- a/packages/shared/types/admin.ts +++ b/packages/shared/types/admin.ts @@ -282,6 +282,9 @@ export interface AdminSku extends SkuFlagCore { imageKeys: string[] | null isOutOfStock: boolean isSuspended: boolean + /** This region's suspension (product_market_stats.is_suspended_in_region), + * separate from the global superadmin kill-switch (`isSuspended`). */ + isSuspendedInRegion: boolean isFlashAvailable: boolean flashPrice: string | null isOffer: boolean