From 6e5790e1fdfbec1fa77f8a372b6d23f9143c5efe Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:48:14 +0530 Subject: [PATCH] enh --- .commandcode/taste/taste/taste.md | 6 +- .../customize-app/all-items-order.tsx | 10 +- .../dashboard/customize-app/index.tsx | 245 +++-- .../dashboard/customize-app/popular-items.tsx | 10 +- .../(drawer)/dashboard/product-tags/order.tsx | 10 +- apps/admin-ui/components/OrderOptionsMenu.tsx | 2 +- .../dashboard.customize-app.ordering.tsx | 8 +- .../dashboard.customize-app.popular.tsx | 8 +- .../src/routes/dashboard.customize-app.tsx | 234 ++--- .../routes/dashboard.product-tags.order.tsx | 8 +- apps/backend/creds/demo.txt | 58 +- apps/backend/src/lib/cloud_cache.ts | 13 +- apps/backend/src/lib/const-keys.ts | 41 +- apps/backend/src/lib/const-store.ts | 117 +-- apps/backend/src/lib/flash-delivery-cron.ts | 10 +- apps/backend/src/lib/gen-store.ts | 84 +- apps/backend/src/lib/seed.ts | 27 +- apps/backend/src/map-assets/jcl.geojson | 74 ++ .../src/trpc/apis/admin-apis/apis/const.ts | 99 +- .../src/trpc/apis/admin-apis/apis/region.ts | 46 +- .../apis/common-apis/common-trpc-index.ts | 171 +++- .../src/trpc/apis/common-apis/common.ts | 41 +- .../trpc/apis/superadmin-apis/apis/const.ts | 52 + .../trpc/apis/superadmin-apis/apis/regions.ts | 93 +- .../apis/superadmin-trpc-index.ts | 2 + apps/superadmin-ui/package.json | 2 +- apps/superadmin-ui/src/routes/constants.tsx | 305 +++--- apps/superadmin-ui/src/routes/regions.tsx | 276 +++++- .../app/(drawer)/(tabs)/home/index.tsx | 100 +- apps/user-ui/app/(drawer)/(tabs)/me/index.tsx | 9 +- .../app/(drawer)/(tabs)/order-again/index.tsx | 2 + .../app/(drawer)/(tabs)/stores/index.tsx | 4 +- apps/user-ui/app/_layout.tsx | 7 +- .../components/CheckoutAddressSelector.tsx | 4 +- apps/user-ui/components/FirstUserWrapper.tsx | 4 +- .../components/LocationTestWrapper.tsx | 160 ++- .../components/PaymentAndOrderComponent.tsx | 4 +- .../QuickDeliveryAddressSelector.tsx | 4 +- apps/user-ui/components/SlotSpecificView.tsx | 2 + apps/user-ui/src/components/AddressForm.tsx | 4 +- apps/user-ui/src/components/LocationBar.tsx | 54 + apps/user-ui/src/components/RegionGate.tsx | 70 -- .../user-ui/src/components/RegionSelector.tsx | 4 +- apps/user-ui/src/hooks/prominent-api-hooks.ts | 93 +- apps/user-ui/src/hooks/useRegion.ts | 201 ++++ apps/user-ui/src/lib/is-emulator.ts | 41 + apps/user-ui/src/lib/region-switch.ts | 5 +- apps/user-ui/src/store/locationStore.ts | 136 +++ apps/user-ui/src/store/regionStore.ts | 55 +- .../components/location-wrapper.test.tsx | 14 +- apps/web-ui/src/hooks/prominent-api-hooks.ts | 13 +- change-log.txt | 420 ++++++++ ...consts-three-tables-part1-backend-admin.md | 254 +++++ docs/consts-three-tables-part2-user-ui.md | 122 +++ .../drizzle/0006_regions_and_superadmins.sql | 924 +++++++++++++++++- .../drizzle/0008_region_cache_versions.sql | 24 - .../drizzle/meta/_journal.json | 7 + .../removed_region_migrations.txt} | 229 +++++ packages/db_helper_sqlite/index.ts | 20 +- .../db_helper_sqlite/src/admin-apis/const.ts | 276 +++--- packages/db_helper_sqlite/src/db/db_index.ts | 2 +- packages/db_helper_sqlite/src/db/schema.ts | 48 +- packages/db_helper_sqlite/src/db/seed.ts | 38 +- .../db_helper_sqlite/src/lib/const-keys.ts | 48 +- .../src/lib/region-cache-versions.ts | 106 +- packages/db_helper_sqlite/src/lib/seed.ts | 20 + .../src/superadmin-apis/regions.ts | 216 +++- .../db_helper_sqlite/src/user-apis/product.ts | 5 +- packages/shared/types/region.types.ts | 30 + statement-breakpoint | 0 verify-regions.tmp.js | 76 ++ 71 files changed, 4533 insertions(+), 1374 deletions(-) create mode 100644 apps/backend/src/map-assets/jcl.geojson create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/const.ts create mode 100644 apps/user-ui/src/components/LocationBar.tsx delete mode 100644 apps/user-ui/src/components/RegionGate.tsx create mode 100644 apps/user-ui/src/hooks/useRegion.ts create mode 100644 apps/user-ui/src/lib/is-emulator.ts create mode 100644 apps/user-ui/src/store/locationStore.ts create mode 100644 docs/consts-three-tables-part1-backend-admin.md create mode 100644 docs/consts-three-tables-part2-user-ui.md delete mode 100644 packages/db_helper_sqlite/drizzle/0008_region_cache_versions.sql rename packages/db_helper_sqlite/drizzle/{0007_region_columns_backfill.sql => stale/removed_region_migrations.txt} (73%) create mode 100644 statement-breakpoint create mode 100644 verify-regions.tmp.js diff --git a/.commandcode/taste/taste/taste.md b/.commandcode/taste/taste/taste.md index 47402b1..6233058 100644 --- a/.commandcode/taste/taste/taste.md +++ b/.commandcode/taste/taste/taste.md @@ -7,7 +7,7 @@ - Prefers detailed analysis and explicit error/mistake checking before executing destructive operations, rather than just performing the action — e.g., before a git merge, or before deleting a row directly from the DB (asked "Can I simply delete the row from db. Will it cause any problems" about an unclaimed reserved coupon, expecting the agent to trace all referencing tables/FKs — couponUsages, couponApplicableUsers/Products — before answering). Confidence: 0.7 - Do not run `git stash` or other destructive git operations that would discard or modify working-tree changes without explicit permission. Confidence: 0.9 - When removing unused code (e.g., an unused tRPC procedure), prefers a complete cleanup: also remove internal helper methods used only by it, associated types, re-exports, orphaned hook/API files and their shared types, and even commented-out imports, leaving zero remaining references. Confidence: 0.9 -- Before removing or deciding on code, likes to first verify where it is actually used across the codebase (asks questions like "where is X used"), rather than removing based on assumption. Confidence: 0.4 +- Before removing or deciding on code, likes to first verify where it is actually used across the codebase (asks questions like "where is X used"), rather than removing based on assumption. Confidence: 0.5 - Prefers light/pastel colors for randomized or accent UI elements (e.g., tabs, chips). Confidence: 0.7 - Prefers minimal, flat tab/navigation UI: active state shown with a thick underline, no pill/chip backgrounds or rounded fills; communicates desired visual styles by sharing reference images/screenshots. Confidence: 0.8 - Wants the agent to come up with a plan first before implementing code changes. Confidence: 0.9 @@ -150,6 +150,10 @@ er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the - When he asks where/why some behavior lives ("where are we creating the product. show me the test code of it"), expects the answer to show the ACTUAL code — the exact file path, the function that performs the action, and the relevant snippet — not just a prose description of the flow or a high-level summary. Confidence: 0.55 - For feature coverage, expects the test to span roles end-to-end: exercise the admin/staff CRUD (create → read-back → update → delete) and THEN drive the same entity from the user's end to prove it actually takes effect — e.g. create a coupon as staff, then pass its id to the user's `placeOrder` and assert the order reflects the discount, and that deleting it drops it from eligibility and gets rejected on apply. Stated as "I want to test coupon crud, I then want to test it too. Apply it from user's end for an order." Prefers this combined admin-CRUD-plus-user-application flow in a single suite over an admin-only CRUD test. Confidence: 0.72 - Excludes flows that depend on real third-party services from automated test scope — payment-gateway flows (Razorpay-signed payloads) and OTP/SMS login are deliberately left out, while everything else must be covered. Repeats the exclusion across requests ("don't test payments, OTP Login do the rest"; "except the OTP, payments test rest all of the thingss"), treating untestable external-service paths as an accepted gap rather than investing in mocks/bypasses. Confidence: 0.6 +- When asking a narrow, targeted factual question (e.g. "tell me which table has that data"), wants the answer scoped to exactly what was asked — the direct fact (the table name) — not another expansive multi-section explanation; corrects over-answering explicitly ("I meant tell me which table has that data"). The broad end-to-end breakdowns he requests elsewhere are for when he asks for them, not a default response length. Confidence: 0.5 +- Prefers API payloads that are FLAT and fully resolved server-side: when a value can come from stacked scopes (bound → region → global), the backend must merge them into one flat JSON object so the client reads the final value directly, with no nested blocks and no client-side merge/precedence logic — "every bound should have all it's bound data, it's region's data and global data. It should be a flat json". Confidence: 0.7 +- When redesigning a data model, prefers a clean slate over patching the existing shape — instructs the agent to ignore the current implementation ("forget the current pattern") and re-specify storage from scratch, splitting what was one catch-all table into tables by natural scope instead of preserving legacy structure. Confidence: 0.6 +- When he changes a shared backend contract (response shape / query input), expects every consumer to be updated to the new shape in the same change and names the affected apps explicitly ("@apps/user-ui should be accomodated to expect this flat json and use this flat json") — a contract change is not done while any client still reads the old shape. Confidence: 0.65 e changes. Confidence: 0.95 er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the agent to mirror that pattern exactly, including details like item counts and container styling. Confidence: 0.9 als) rather than introducing new brand palettes; approval of a redesign's layout/composition does not imply approval of color or theme changes. Confidence: 0.95 diff --git a/apps/admin-ui/app/(drawer)/dashboard/customize-app/all-items-order.tsx b/apps/admin-ui/app/(drawer)/dashboard/customize-app/all-items-order.tsx index 31ed02e..813c8db 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/customize-app/all-items-order.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/customize-app/all-items-order.tsx @@ -91,10 +91,10 @@ export default function AllItemsOrder() { const [products, setProducts] = useState([]); const [hasChanges, setHasChanges] = useState(false); - // Get current order from constants - const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.const.getConstants.useQuery(); + // Get current order from the region constants + const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.region.getRegionConstants.useQuery(); const { data: allProducts, isLoading: isLoadingProducts, error: productsError } = trpc.common.product.getAllProductsSummary.useQuery(); - const updateConstants = trpc.admin.const.updateConstants.useMutation(); + const updateConstants = trpc.admin.region.updateRegionConstants.useMutation(); // Initialize products from constants useEffect(() => { @@ -169,14 +169,14 @@ export default function AllItemsOrder() { { constants: [{ key: 'allItemsOrder', - value: productIds + value: productIds.join(',') }] }, { onSuccess: () => { setHasChanges(false); Alert.alert('Success', 'All items order updated successfully!'); - utils.admin.const.getConstants.invalidate(); + utils.admin.region.getRegionConstants.invalidate(); }, onError: (error) => { Alert.alert('Error', 'Failed to update items order. Please try again.'); 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 4c10b26..d66a039 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx @@ -8,6 +8,20 @@ import MaterialIcons from '@expo/vector-icons/MaterialIcons'; type ConstantFormData = Record +type ConstTab = 'region' | 'bound' + +// --- key groups (mirrors packages/db_helper_sqlite/src/lib/const-keys.ts) --- +// 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', + 'supportMobile', 'supportEmail', 'welcomeMessage', +] +const BOUND_KEYS = [ + 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge', + 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', +] + const CONST_LABELS: Record = { minRegularOrderValue: 'Minimum Regular Order Value', freeDeliveryThreshold: 'Free Delivery Threshold', @@ -16,6 +30,7 @@ const CONST_LABELS: Record = { flashDeliveryCharge: 'Flash Delivery Charge', platformFeePercent: 'Platform Fee Percent', taxRate: 'Tax Rate', + tester: 'Tester', minOrderAmountForCoupon: 'Minimum Order Amount for Coupon', maxCouponDiscount: 'Maximum Coupon Discount', flashDeliverySlotId: 'Flash Delivery Slot ID', @@ -25,6 +40,7 @@ const CONST_LABELS: Record = { appStoreUrl: 'App Store URL', popularItems: 'Popular Items', allItemsOrder: 'All Items Order', + tagsOrder: 'Tags Order', isFlashDeliveryEnabled: 'Enable Flash Delivery', supportMobile: 'Support Mobile', supportEmail: 'Support Email', @@ -32,35 +48,9 @@ const CONST_LABELS: Record = { welcomeMessage: 'Welcome Message', }; -const CONST_VISIBILITY: Record = { - minRegularOrderValue: true, - freeDeliveryThreshold: true, - deliveryCharge: true, - flashFreeDeliveryThreshold: true, - flashDeliveryCharge: true, - platformFeePercent: false, - taxRate: false, - minOrderAmountForCoupon: false, - maxCouponDiscount: false, - flashDeliverySlotId: false, - readableOrderId: false, - versionNum: false, - playStoreUrl: false, - appStoreUrl: false, - popularItems: true, - allItemsOrder: true, - isFlashDeliveryEnabled: true, - supportMobile: true, - supportEmail: true, - internalAppVersion: false, - welcomeMessage: true, - tester: false, -}; +type ConstValueType = 'number' | 'boolean' | 'array' | 'string' -// The 11 constants that are edited per region bound. -type BoundValueType = 'number' | 'boolean' | 'array' | 'string' - -const BOUND_KEY_TYPES: Record = { +const KEY_TYPES: Record = { minRegularOrderValue: 'number', freeDeliveryThreshold: 'number', deliveryCharge: 'number', @@ -68,17 +58,27 @@ const BOUND_KEY_TYPES: Record = { flashDeliveryCharge: 'number', popularItems: 'array', allItemsOrder: 'array', + tagsOrder: 'array', isFlashDeliveryEnabled: 'boolean', supportMobile: 'string', supportEmail: 'string', welcomeMessage: 'string', + platformFeePercent: 'number', + taxRate: 'number', + tester: 'string', + minOrderAmountForCoupon: 'number', + maxCouponDiscount: 'number', + flashDeliverySlotId: 'number', + readableOrderId: 'number', + versionNum: 'string', + playStoreUrl: 'string', + appStoreUrl: 'string', + internalAppVersion: 'number', }; -const REGIONAL_KEYS = Object.keys(BOUND_KEY_TYPES); - /** Convert a stored string value into the type ConstantInput expects. */ -const parseBoundValue = (key: string, raw: string | null | undefined): any => { - const type = BOUND_KEY_TYPES[key] ?? 'string'; +const parseConstValue = (key: string, raw: string | null | undefined): any => { + const type = KEY_TYPES[key] ?? 'string'; if (raw === null || raw === undefined || raw === '') { if (type === 'number') return 0; @@ -101,9 +101,9 @@ const parseBoundValue = (key: string, raw: string | null | undefined): any => { } }; -/** Convert a form value back into the string stored by the bound settings API. */ -const serializeBoundValue = (key: string, value: any): string => { - const type = BOUND_KEY_TYPES[key] ?? 'string'; +/** Convert a form value back into the string stored by the constants API. */ +const serializeConstValue = (key: string, value: any): string => { + const type = KEY_TYPES[key] ?? 'string'; switch (type) { case 'number': { @@ -262,7 +262,7 @@ const ConstantInput: React.FC = ({ export default function CustomizeApp() { const router = useRouter(); - const [mode, setMode] = useState<'bounds' | 'global'>('bounds'); + const [tab, setTab] = useState('bound'); const [selectedBoundId, setSelectedBoundId] = useState(null); const { data: region } = trpc.admin.region.current.useQuery(); @@ -288,10 +288,13 @@ export default function CustomizeApp() { const updateBoundSettings = trpc.admin.region.updateBoundSettings.useMutation(); - // Global constants (unchanged API) — kept for non-regional keys. - const { data: constants, isLoading: isLoadingConstants, refetch: refetchConstants } = - trpc.admin.const.getConstants.useQuery(); - const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation(); + // Region-scoped constants (region_consts) for the caller's region. + const { + data: regionConstants, + isLoading: isLoadingRegionConstants, + refetch: refetchRegionConstants, + } = trpc.admin.region.getRegionConstants.useQuery(); + const updateRegionConstants = trpc.admin.region.updateRegionConstants.useMutation(); // Default-select the lowest-priority bound (first, ascending by priority). useEffect(() => { @@ -316,8 +319,8 @@ export default function CustomizeApp() { // Parse the selected bound's stored settings into form-ready values. const boundInitialValues: Record = useMemo(() => { const values: Record = {}; - for (const key of REGIONAL_KEYS) { - values[key] = parseBoundValue(key, boundSettings ? boundSettings[key] : null); + for (const key of BOUND_KEYS) { + values[key] = parseConstValue(key, boundSettings ? boundSettings[key] : null); } return values; }, [boundSettings]); @@ -326,13 +329,13 @@ export default function CustomizeApp() { if (selectedBoundId === null) return; const original = boundSettings ?? {}; - const changed = REGIONAL_KEYS.filter((key) => { - const next = serializeBoundValue(key, values[key]); + const changed = BOUND_KEYS.filter((key) => { + const next = serializeConstValue(key, values[key]); const prev = original[key] ?? null; return next !== prev; }).map((key) => ({ key, - value: serializeBoundValue(key, values[key]), + value: serializeConstValue(key, values[key]), })); if (changed.length === 0) { @@ -355,42 +358,47 @@ export default function CustomizeApp() { ); }; - const handleGlobalSubmit = (values: ConstantFormData) => { - // Filter out constants that haven't changed - const changedConstants = (constants || []).filter((constant) => { - const nextValue = values[constant.key] - return JSON.stringify(nextValue) !== JSON.stringify(constant.value) - }).map((constant) => ({ - key: constant.key, - value: values[constant.key], - })) + // --- Region tab --- + const regionValueByKey = useMemo(() => { + const map: Record = {}; + for (const row of regionConstants ?? []) map[row.key] = row.value as string | null; + return map; + }, [regionConstants]); - if (changedConstants.length === 0) { - Alert.alert('No Changes', 'No constants were modified.'); + const regionInitialValues: ConstantFormData = useMemo(() => { + const values: ConstantFormData = {}; + for (const key of REGION_KEYS) values[key] = parseConstValue(key, regionValueByKey[key]); + return values; + }, [regionValueByKey]); + + const handleRegionSubmit = (values: ConstantFormData) => { + const changed = REGION_KEYS.filter((key) => { + const next = serializeConstValue(key, values[key]); + const prev = regionValueByKey[key] ?? null; + return next !== prev; + }).map((key) => ({ key, value: serializeConstValue(key, values[key]) })); + + if (changed.length === 0) { + Alert.alert('No Changes', 'No region settings were modified.'); return; } - updateConstants( - { constants: changedConstants }, + updateRegionConstants.mutate( + { constants: changed }, { onSuccess: (response) => { - Alert.alert('Success', `Updated ${response.updatedCount} constants successfully.`); - refetchConstants(); + Alert.alert('Success', `Updated ${response.updatedCount} region settings successfully.`); + refetchRegionConstants(); }, onError: (error) => { - Alert.alert('Error', 'Failed to update constants. Please try again.'); - console.error('Update constants error:', error); + Alert.alert('Error', 'Failed to update region settings. Please try again.'); + console.error('Update region constants error:', error); }, } ); }; - const globalInitialValues: ConstantFormData = (constants ?? []).reduce((acc, constant) => { - acc[constant.key] = constant.value ?? '' - return acc - }, {} as ConstantFormData) - - const renderRegional = () => { + const renderBound = () => { if (isLoadingBounds) { return ( @@ -518,7 +526,7 @@ export default function CustomizeApp() { > {({ handleSubmit, values, setFieldValue }) => ( - {REGIONAL_KEYS.map((key) => ( + {BOUND_KEYS.map((key) => ( { - if (isLoadingConstants) { + const renderRegion = () => { + if (isLoadingRegionConstants) { return ( - Loading constants... - - ); - } - - if (!constants) { - return ( - - Failed to load constants + Loading region settings... ); } return ( - + {({ handleSubmit, values, setFieldValue }) => ( - These global constants are not region-specific and still apply app-wide. + Region settings apply to every bound in this region. - {constants.map((constant) => { - if (!CONST_VISIBILITY[constant.key]) { - return null - } - - return ( - - - - ) - })} + {REGION_KEYS.map((key) => ( + + + + ))} handleSubmit()} - disabled={isUpdating} - style={tw`bg-blue-500 p-4 rounded-lg mt-6 ${isUpdating ? 'opacity-50' : ''}`} + disabled={updateRegionConstants.isPending} + style={tw`bg-blue-500 p-4 rounded-lg mt-6 ${ + updateRegionConstants.isPending ? 'opacity-50' : '' + }`} > - {isUpdating ? 'Updating...' : 'Save Changes'} + {updateRegionConstants.isPending ? 'Saving...' : 'Save Changes'} @@ -605,6 +601,11 @@ export default function CustomizeApp() { ); }; + const tabs: { id: ConstTab; label: string }[] = [ + { id: 'region', label: 'Region' }, + { id: 'bound', label: 'Bound' }, + ]; + return ( Customize App @@ -612,35 +613,27 @@ export default function CustomizeApp() { {region?.name ? `Region: ${region.name}` : 'Regional business settings'} - {/* Top-level switch: per-bound regional settings vs. legacy global constants. */} + {/* Top-level switch: region vs. per-bound settings. */} - setMode('bounds')} - style={tw`flex-1 py-2 rounded-md ${mode === 'bounds' ? 'bg-white' : ''}`} - > - ( + setTab(t.id)} + style={tw`flex-1 py-2 rounded-md ${tab === t.id ? 'bg-white' : ''}`} > - Regional Settings - - - setMode('global')} - style={tw`flex-1 py-2 rounded-md ${mode === 'global' ? 'bg-white' : ''}`} - > - - Global Constants - - + + {t.label} + + + ))} - {mode === 'bounds' ? renderRegional() : renderGlobal()} + {tab === 'region' && renderRegion()} + {tab === 'bound' && renderBound()} ); } diff --git a/apps/admin-ui/app/(drawer)/dashboard/customize-app/popular-items.tsx b/apps/admin-ui/app/(drawer)/dashboard/customize-app/popular-items.tsx index aaae28a..562e8e7 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/customize-app/popular-items.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/customize-app/popular-items.tsx @@ -118,10 +118,10 @@ export default function CustomizePopularItems() { const [showAddDialog, setShowAddDialog] = useState(false); const [selectedProductIds, setSelectedProductIds] = useState([]); - // Get current popular items from constants - const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.const.getConstants.useQuery(); + // Get current popular items from the region constants + const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.region.getRegionConstants.useQuery(); const { data: allProducts, isLoading: isLoadingProducts, error: productsError } = trpc.common.product.getAllProductsSummary.useQuery(); - const updateConstants = trpc.admin.const.updateConstants.useMutation(); + const updateConstants = trpc.admin.region.updateRegionConstants.useMutation(); // Initialize popular products from constants useEffect(() => { @@ -203,14 +203,14 @@ export default function CustomizePopularItems() { { constants: [{ key: 'popularItems', - value: popularIds + value: popularIds.join(',') }] }, { onSuccess: () => { setHasChanges(false); Alert.alert('Success', 'Popular items updated successfully!'); - utils.admin.const.getConstants.invalidate(); + utils.admin.region.getRegionConstants.invalidate(); }, onError: (error) => { Alert.alert('Error', 'Failed to update popular items. Please try again.'); diff --git a/apps/admin-ui/app/(drawer)/dashboard/product-tags/order.tsx b/apps/admin-ui/app/(drawer)/dashboard/product-tags/order.tsx index d783c16..1f03deb 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/product-tags/order.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/product-tags/order.tsx @@ -82,10 +82,10 @@ export default function TagOrders() { const [tags, setTags] = useState([]); const [hasChanges, setHasChanges] = useState(false); - // Get current order from constants - const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.const.getConstants.useQuery(); + // Get current order from the region constants + const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.region.getRegionConstants.useQuery(); const { data: tagsData, isLoading: isLoadingTags, error: tagsError } = trpc.admin.product.getProductTags.useQuery(); - const updateConstants = trpc.admin.const.updateConstants.useMutation(); + const updateConstants = trpc.admin.region.updateRegionConstants.useMutation(); // Initialize tags from the tagsOrder constant useEffect(() => { @@ -158,14 +158,14 @@ export default function TagOrders() { { constants: [{ key: 'tagsOrder', - value: tagIds + value: tagIds.join(',') }] }, { onSuccess: () => { setHasChanges(false); Alert.alert('Success', 'Tag order updated successfully!'); - utils.admin.const.getConstants.invalidate(); + utils.admin.region.getRegionConstants.invalidate(); }, onError: (error) => { Alert.alert('Error', 'Failed to update tag order. Please try again.'); diff --git a/apps/admin-ui/components/OrderOptionsMenu.tsx b/apps/admin-ui/components/OrderOptionsMenu.tsx index 996b52b..3c33a63 100644 --- a/apps/admin-ui/components/OrderOptionsMenu.tsx +++ b/apps/admin-ui/components/OrderOptionsMenu.tsx @@ -54,7 +54,7 @@ export function OrderOptionsMenu({ onDial, }: OrderOptionsMenuProps) { const updateAddressCoordsMutation = trpc.admin.order.updateAddressCoords.useMutation(); - const { data: constants } = trpc.admin.const.getConstants.useQuery(); + const { data: constants } = trpc.admin.region.getRegionConstants.useQuery(); const welcomeMessage = constants?.find((c) => c.key === 'welcomeMessage')?.value; const handleAttachLocation = async () => { diff --git a/apps/admin-web/src/routes/dashboard.customize-app.ordering.tsx b/apps/admin-web/src/routes/dashboard.customize-app.ordering.tsx index c153e41..db46461 100644 --- a/apps/admin-web/src/routes/dashboard.customize-app.ordering.tsx +++ b/apps/admin-web/src/routes/dashboard.customize-app.ordering.tsx @@ -94,9 +94,9 @@ function AllItemsOrder() { const [products, setProducts] = useState([]) const [hasChanges, setHasChanges] = useState(false) - const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.const.getConstants.useQuery() + const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.region.getRegionConstants.useQuery() const { data: allProducts, isLoading: isLoadingProducts, error: productsError } = trpc.common.product.getAllProductsSummary.useQuery() - const updateConstants = trpc.admin.const.updateConstants.useMutation() + const updateConstants = trpc.admin.region.updateRegionConstants.useMutation() const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } })) @@ -165,14 +165,14 @@ function AllItemsOrder() { { constants: [{ key: 'allItemsOrder', - value: productIds, + value: productIds.join(','), }], }, { onSuccess: () => { setHasChanges(false) window.alert('All items order updated successfully!') - queryClient.invalidateQueries({ queryKey: ['const.getConstants'] }) + queryClient.invalidateQueries({ queryKey: ['region.getRegionConstants'] }) }, onError: (error) => { window.alert('Failed to update items order. Please try again.') diff --git a/apps/admin-web/src/routes/dashboard.customize-app.popular.tsx b/apps/admin-web/src/routes/dashboard.customize-app.popular.tsx index 0d4cad8..f2ee7cb 100644 --- a/apps/admin-web/src/routes/dashboard.customize-app.popular.tsx +++ b/apps/admin-web/src/routes/dashboard.customize-app.popular.tsx @@ -107,9 +107,9 @@ function CustomizePopularItems() { const [showAddDialog, setShowAddDialog] = useState(false) const [selectedProductIds, setSelectedProductIds] = useState([]) - const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.const.getConstants.useQuery() + const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.region.getRegionConstants.useQuery() const { data: allProducts, isLoading: isLoadingProducts, error: productsError } = trpc.common.product.getAllProductsSummary.useQuery() - const updateConstants = trpc.admin.const.updateConstants.useMutation() + const updateConstants = trpc.admin.region.updateRegionConstants.useMutation() const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } })) @@ -186,14 +186,14 @@ function CustomizePopularItems() { { constants: [{ key: 'popularItems', - value: popularIds, + value: popularIds.join(','), }], }, { onSuccess: () => { setHasChanges(false) window.alert('Popular items updated successfully!') - queryClient.invalidateQueries({ queryKey: ['const.getConstants'] }) + queryClient.invalidateQueries({ queryKey: ['region.getRegionConstants'] }) }, onError: (error) => { window.alert('Failed to update popular items. Please try again.') diff --git a/apps/admin-web/src/routes/dashboard.customize-app.tsx b/apps/admin-web/src/routes/dashboard.customize-app.tsx index 295cb99..53e1a0f 100644 --- a/apps/admin-web/src/routes/dashboard.customize-app.tsx +++ b/apps/admin-web/src/routes/dashboard.customize-app.tsx @@ -11,6 +11,20 @@ export const Route = createFileRoute('/dashboard/customize-app')({ type ConstantFormData = Record +type ConstTab = 'region' | 'bound' + +// --- key groups (mirrors packages/db_helper_sqlite/src/lib/const-keys.ts) --- +// 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', + 'supportMobile', 'supportEmail', 'welcomeMessage', +] +const BOUND_KEYS = [ + 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge', + 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', +] + const CONST_LABELS: Record = { minRegularOrderValue: 'Minimum Regular Order Value', freeDeliveryThreshold: 'Free Delivery Threshold', @@ -19,6 +33,7 @@ const CONST_LABELS: Record = { flashDeliveryCharge: 'Flash Delivery Charge', platformFeePercent: 'Platform Fee Percent', taxRate: 'Tax Rate', + tester: 'Tester', minOrderAmountForCoupon: 'Minimum Order Amount for Coupon', maxCouponDiscount: 'Maximum Coupon Discount', flashDeliverySlotId: 'Flash Delivery Slot ID', @@ -28,40 +43,17 @@ const CONST_LABELS: Record = { appStoreUrl: 'App Store URL', popularItems: 'Popular Items', allItemsOrder: 'All Items Order', + tagsOrder: 'Tags Order', isFlashDeliveryEnabled: 'Enable Flash Delivery', supportMobile: 'Support Mobile', supportEmail: 'Support Email', + internalAppVersion: 'Internal App Version', welcomeMessage: 'Welcome Message', } -const CONST_VISIBILITY: Record = { - minRegularOrderValue: true, - freeDeliveryThreshold: true, - deliveryCharge: true, - flashFreeDeliveryThreshold: true, - flashDeliveryCharge: true, - platformFeePercent: true, - taxRate: false, - minOrderAmountForCoupon: true, - maxCouponDiscount: false, - flashDeliverySlotId: true, - readableOrderId: false, - versionNum: true, - playStoreUrl: true, - appStoreUrl: true, - popularItems: true, - allItemsOrder: true, - isFlashDeliveryEnabled: true, - supportMobile: true, - supportEmail: true, - welcomeMessage: true, - tester: false, -} +type ConstValueType = 'number' | 'boolean' | 'array' | 'string' -// The 11 constants that are edited per region bound. -type BoundValueType = 'number' | 'boolean' | 'array' | 'string' - -const BOUND_KEY_TYPES: Record = { +const KEY_TYPES: Record = { minRegularOrderValue: 'number', freeDeliveryThreshold: 'number', deliveryCharge: 'number', @@ -69,17 +61,27 @@ const BOUND_KEY_TYPES: Record = { flashDeliveryCharge: 'number', popularItems: 'array', allItemsOrder: 'array', + tagsOrder: 'array', isFlashDeliveryEnabled: 'boolean', supportMobile: 'string', supportEmail: 'string', welcomeMessage: 'string', + platformFeePercent: 'number', + taxRate: 'number', + tester: 'string', + minOrderAmountForCoupon: 'number', + maxCouponDiscount: 'number', + flashDeliverySlotId: 'number', + readableOrderId: 'number', + versionNum: 'string', + playStoreUrl: 'string', + appStoreUrl: 'string', + internalAppVersion: 'number', } -const REGIONAL_KEYS = Object.keys(BOUND_KEY_TYPES) - /** Convert a stored string value into the type ConstantInput expects. */ -const parseBoundValue = (key: string, raw: string | null | undefined): any => { - const type = BOUND_KEY_TYPES[key] ?? 'string' +const parseConstValue = (key: string, raw: string | null | undefined): any => { + const type = KEY_TYPES[key] ?? 'string' if (raw === null || raw === undefined || raw === '') { if (type === 'number') return 0 @@ -102,9 +104,9 @@ const parseBoundValue = (key: string, raw: string | null | undefined): any => { } } -/** Convert a form value back into the string stored by the bound settings API. */ -const serializeBoundValue = (key: string, value: any): string => { - const type = BOUND_KEY_TYPES[key] ?? 'string' +/** Convert a form value back into the string stored by the constants API. */ +const serializeConstValue = (key: string, value: any): string => { + const type = KEY_TYPES[key] ?? 'string' switch (type) { case 'number': { @@ -260,7 +262,7 @@ function CustomizeApp() { const router = { push: (to: string) => navigate({ to: to as any }), } - const [mode, setMode] = useState<'bounds' | 'global'>('bounds') + const [tab, setTab] = useState('bound') const [selectedBoundId, setSelectedBoundId] = useState(null) const { data: region } = trpc.admin.region.current.useQuery() @@ -287,9 +289,14 @@ function CustomizeApp() { const { mutate: updateBoundSettings, isPending: isSavingBound } = trpc.admin.region.updateBoundSettings.useMutation() - // Global constants (unchanged API) — kept for non-regional keys. - const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery() - const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation() + // Region-scoped constants (region_consts) for the caller's region. + const { + data: regionConstants, + isLoading: isLoadingRegionConstants, + refetch: refetchRegionConstants, + } = trpc.admin.region.getRegionConstants.useQuery() + const { mutate: updateRegionConstants, isPending: isSavingRegion } = + trpc.admin.region.updateRegionConstants.useMutation() // Default-select the lowest-priority bound (first, ascending by priority). useEffect(() => { @@ -314,8 +321,8 @@ function CustomizeApp() { // Parse the selected bound's stored settings into form-ready values. const boundInitialValues: Record = useMemo(() => { const values: Record = {} - for (const key of REGIONAL_KEYS) { - values[key] = parseBoundValue(key, boundSettings ? boundSettings[key] : null) + for (const key of BOUND_KEYS) { + values[key] = parseConstValue(key, boundSettings ? boundSettings[key] : null) } return values }, [boundSettings]) @@ -324,13 +331,13 @@ function CustomizeApp() { if (selectedBoundId === null) return const original = boundSettings ?? {} - const changed = REGIONAL_KEYS.filter((key) => { - const next = serializeBoundValue(key, values[key]) + const changed = BOUND_KEYS.filter((key) => { + const next = serializeConstValue(key, values[key]) const prev = original[key] ?? null return next !== prev }).map((key) => ({ key, - value: serializeBoundValue(key, values[key]), + value: serializeConstValue(key, values[key]), })) if (changed.length === 0) { @@ -353,36 +360,47 @@ function CustomizeApp() { ) } - const handleGlobalSubmit = (values: ConstantFormData) => { - const changedConstants = (constants || []).filter((constant) => { - const nextValue = values[constant.key] - return JSON.stringify(nextValue) !== JSON.stringify(constant.value) - }).map((constant) => ({ - key: constant.key, - value: values[constant.key], - })) + // --- Region tab --- + const regionValueByKey = useMemo(() => { + const map: Record = {} + for (const row of regionConstants ?? []) map[row.key] = row.value as string | null + return map + }, [regionConstants]) - if (changedConstants.length === 0) { - window.alert('No constants were modified.') + const regionInitialValues: ConstantFormData = useMemo(() => { + const values: ConstantFormData = {} + for (const key of REGION_KEYS) values[key] = parseConstValue(key, regionValueByKey[key]) + return values + }, [regionValueByKey]) + + const handleRegionSubmit = (values: ConstantFormData) => { + const changed = REGION_KEYS.filter((key) => { + const next = serializeConstValue(key, values[key]) + const prev = regionValueByKey[key] ?? null + return next !== prev + }).map((key) => ({ key, value: serializeConstValue(key, values[key]) })) + + if (changed.length === 0) { + window.alert('No region settings were modified.') return } - updateConstants( - { constants: changedConstants }, + updateRegionConstants( + { constants: changed }, { onSuccess: (response) => { - window.alert(`Updated ${response.updatedCount} constants successfully.`) - refetch() + window.alert(`Updated ${response.updatedCount} region settings successfully.`) + refetchRegionConstants() }, onError: (error) => { - window.alert('Failed to update constants. Please try again.') - console.error('Update constants error:', error) + window.alert('Failed to update region settings. Please try again.') + console.error('Update region constants error:', error) }, }, ) } - const renderRegional = () => { + const renderBound = () => { if (isLoadingBounds) { return (
@@ -497,7 +515,7 @@ function CustomizeApp() { > {({ handleSubmit, values, setFieldValue }) => (
- {REGIONAL_KEYS.map((key) => ( + {BOUND_KEYS.map((key) => (
{ - if (isLoadingConstants) { + const renderRegion = () => { + if (isLoadingRegionConstants) { return ( -
- Loading constants... +
+ Loading region settings...
) } - if (!constants) { - return ( -
- Failed to load constants -
- ) - } - - const initialValues: ConstantFormData = constants.reduce((acc, constant) => { - acc[constant.key] = constant.value ?? '' - return acc - }, {} as ConstantFormData) - return ( - + {({ handleSubmit, values, setFieldValue }) => (
- These global constants are not region-specific and still apply app-wide. + Region settings apply to every bound in this region. - {constants.map((constant) => { - if (!CONST_VISIBILITY[constant.key]) { - return null - } - - return ( -
- -
- ) - })} + {REGION_KEYS.map((key) => ( +
+ +
+ ))}
@@ -587,6 +586,11 @@ function CustomizeApp() { ) } + const tabs: { id: ConstTab; label: string }[] = [ + { id: 'region', label: 'Region' }, + { id: 'bound', label: 'Bound' }, + ] + return (
@@ -598,27 +602,23 @@ function CustomizeApp() { Modify application settings. Changes will take effect immediately. - {/* Top-level switch: per-bound regional settings vs. legacy global constants. */} + {/* Top-level switch: region vs. per-bound settings. */}
- - + {tabs.map((t) => ( + + ))}
- {mode === 'bounds' ? renderRegional() : renderGlobal()} + {tab === 'region' && renderRegion()} + {tab === 'bound' && renderBound()}
) diff --git a/apps/admin-web/src/routes/dashboard.product-tags.order.tsx b/apps/admin-web/src/routes/dashboard.product-tags.order.tsx index 7bb2984..688437c 100644 --- a/apps/admin-web/src/routes/dashboard.product-tags.order.tsx +++ b/apps/admin-web/src/routes/dashboard.product-tags.order.tsx @@ -87,9 +87,9 @@ function TagOrders() { const [tags, setTags] = useState([]) const [hasChanges, setHasChanges] = useState(false) - const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.const.getConstants.useQuery() + const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.region.getRegionConstants.useQuery() const { data: tagsData, isLoading: isLoadingTags, error: tagsError } = trpc.admin.product.getProductTags.useQuery() - const updateConstants = trpc.admin.const.updateConstants.useMutation() + const updateConstants = trpc.admin.region.updateRegionConstants.useMutation() const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } })) @@ -156,14 +156,14 @@ function TagOrders() { { constants: [{ key: 'tagsOrder', - value: tagIds, + value: tagIds.join(','), }], }, { onSuccess: () => { setHasChanges(false) window.alert('Tag order updated successfully!') - queryClient.invalidateQueries({ queryKey: ['const.getConstants'] }) + queryClient.invalidateQueries({ queryKey: ['region.getRegionConstants'] }) }, onError: (error) => { window.alert('Failed to update tag order. Please try again.') diff --git a/apps/backend/creds/demo.txt b/apps/backend/creds/demo.txt index 7ed32f4..a8d45b4 100644 --- a/apps/backend/creds/demo.txt +++ b/apps/backend/creds/demo.txt @@ -1,4 +1,60 @@ bunx wrangler d1 execute --remote freshyo-backend-dev --file=../../packages/db_helper_sqlite/drizzle/0004_staff_notif_creds.sql --config wrangler.dev.toml -I've created the both namespaces. show the option in all places where an order has a kebab menu in admin app. \ No newline at end of file +I've created the both namespaces. show the option in all places where an order has a kebab menu in admin app. + + + + +global: +versionNum +playStoreUrl +appStoreUrl +internalAppVersion + + + + +region: +availability_version_num +slots_version_num +popularItems +isFlashDeliveryEnabled +supportMobile +supportEmail +welcomeMessage + + +region_bound: +minRegularOrderValue +freeDeliveryThreshold +deliveryCharge +flashFreeDeliveryThreshold +flashDeliveryCharge + + + +forget the current pattern, I want to change the consts model. I want to split it into three tables and keys in the like this +global_consts: just key, val columns +versionNum +playStoreUrl +appStoreUrl +internalAppVersion + +region_consts: key, val, regionId columns +availability_version_num +slots_version_num +popularItems +isFlashDeliveryEnabled +supportMobile +supportEmail +welcomeMessage +products_version_num(previously cache_version) + + +region_bound_consts: key, val, bound_id, region_id columns +minRegularOrderValue +freeDeliveryThreshold +deliveryCharge +flashFreeDeliveryThreshold +flashDeliveryCharge \ No newline at end of file diff --git a/apps/backend/src/lib/cloud_cache.ts b/apps/backend/src/lib/cloud_cache.ts index ceff3cf..37174a2 100644 --- a/apps/backend/src/lib/cloud_cache.ts +++ b/apps/backend/src/lib/cloud_cache.ts @@ -8,6 +8,7 @@ import { scaffoldStoreWithProducts } from '@/src/trpc/apis/user-apis/apis/stores import { getStoresSummary, getAllRegions, + getEffectiveBoundId, incrementRegionCacheVersion, incrementRegionAvailabilityVersionNum, incrementRegionSlotsVersionNum, @@ -16,7 +17,7 @@ import { imageUploadS3 } from '@/src/lib/s3-client' import { getApiCacheKey, getCloudflareApiToken, getCloudflareZoneId, getAssetsDomain } from '@/src/lib/env-exporter' import { CACHE_FILENAMES } from '@packages/shared' import { retryWithExponentialBackoff } from '@/src/lib/retry' -import { refreshGenKv } from '@/src/lib/gen-store' +import { refreshGenKvForRegion } from '@/src/lib/gen-store' const buildRegionCachePath = (regionId: number, version: number, filename: string) => `regions/${regionId}/v-${version}/${filename}` @@ -99,7 +100,7 @@ export async function createRegionCacheFiles(regionId: number): Promise { - const essentialConstsData = await scaffoldEssentialConsts(regionId) + const boundId = await getEffectiveBoundId(regionId) + if (boundId == null) throw new Error(`Region ${regionId} has no bound; cannot build essential-consts cache`) + const essentialConstsData = await scaffoldEssentialConsts(boundId) const jsonContent = JSON.stringify(essentialConstsData, null, 2) const buffer = Buffer.from(jsonContent, 'utf-8') return await imageUploadS3( @@ -199,7 +202,7 @@ export async function createSlotsCacheFile(regionId: number, refresh = true): Pr filePath ) - if (refresh) await refreshGenKv(regionId) + if (refresh) await refreshGenKvForRegion(regionId) return version } diff --git a/apps/backend/src/lib/const-keys.ts b/apps/backend/src/lib/const-keys.ts index 22ae47d..fa0121a 100644 --- a/apps/backend/src/lib/const-keys.ts +++ b/apps/backend/src/lib/const-keys.ts @@ -14,7 +14,7 @@ export const CONST_KEYS = { flashDeliverySlotId: 'flashDeliverySlotId', readableOrderId: 'readableOrderId', versionNum: 'versionNum', - cacheVersion: 'cache_version', + productsVersionNum: 'products_version_num', playStoreUrl: 'playStoreUrl', appStoreUrl: 'appStoreUrl', popularItems: 'popularItems', @@ -41,7 +41,7 @@ export const CONST_LABELS: Record = { flashDeliverySlotId: 'Flash Delivery Slot ID', readableOrderId: 'Readable Order ID', versionNum: 'Version Number', - 'cache_version': 'Cache Version', + 'products_version_num': 'Cache Version (products)', playStoreUrl: 'Play Store URL', appStoreUrl: 'App Store URL', popularItems: 'Popular Items', @@ -72,7 +72,7 @@ export const CONST_TYPES: Record = { flashDeliverySlotId: 'number', readableOrderId: 'number', versionNum: 'string', - 'cache_version': 'number', + 'products_version_num': 'number', playStoreUrl: 'string', appStoreUrl: 'string', popularItems: 'string', @@ -99,7 +99,7 @@ export const CONST_VISIBILITY: Record = { flashDeliverySlotId: true, readableOrderId: false, versionNum: true, - 'cache_version': false, + 'products_version_num': false, playStoreUrl: true, appStoreUrl: true, popularItems: true, @@ -111,3 +111,36 @@ export const CONST_VISIBILITY: Record = { internalAppVersion: true, welcomeMessage: true, }; + +/** Keys stored in the global_consts table. */ +export const GLOBAL_CONST_KEYS = [ + 'versionNum', 'playStoreUrl', 'appStoreUrl', 'internalAppVersion', +] as const + +/** 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', + 'supportMobile', 'supportEmail', 'welcomeMessage', +] as const + +/** Keys stored in the region_bound_consts table (one row per bound). */ +export const BOUND_CONST_KEYS = [ + 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge', + 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', +] as const + +/** Keys that remain in the legacy key_val_store table. */ +export const LEGACY_CONST_KEYS = [ + 'platformFeePercent', 'taxRate', 'tester', 'minOrderAmountForCoupon', + 'maxCouponDiscount', 'flashDeliverySlotId', 'readableOrderId', +] as const + +export type ConstScope = 'global' | 'region' | 'bound' | 'legacy' + +/** Which table each key belongs to. */ +export const CONST_SCOPE: Record = {} +for (const k of GLOBAL_CONST_KEYS) CONST_SCOPE[k] = 'global' +for (const k of REGION_CONST_KEYS) CONST_SCOPE[k] = 'region' +for (const k of BOUND_CONST_KEYS) CONST_SCOPE[k] = 'bound' +for (const k of LEGACY_CONST_KEYS) CONST_SCOPE[k] = 'legacy' diff --git a/apps/backend/src/lib/const-store.ts b/apps/backend/src/lib/const-store.ts index 77a49d8..bd834d0 100644 --- a/apps/backend/src/lib/const-store.ts +++ b/apps/backend/src/lib/const-store.ts @@ -1,102 +1,53 @@ -import { getAllKeyValStore } from '@/src/dbService' -// import redisClient from '@/src/lib/redis-client' +import { + getAllGlobalConsts, + getRegionConsts, + getBoundConsts, + getLegacyConsts, +} from '@/src/dbService' import { CONST_KEYS, CONST_KEYS_ARRAY, type ConstKey } from '@/src/lib/const-keys' -// const CONST_REDIS_PREFIX = 'const:'; - export const computeConstants = async (): Promise => { try { - console.log('Computing constants from database...'); - - const constants = await getAllKeyValStore(); - - // for (const constant of constants) { - // const redisKey = `${CONST_REDIS_PREFIX}${constant.key}`; - // const value = JSON.stringify(constant.value); - // await redisClient.set(redisKey, value); - // } - - console.log(`Computed ${constants.length} constants from DB`); + const legacy = await getLegacyConsts() + console.log(`Computed constants from key_val_store: ${Object.keys(legacy).length} rows`) } catch (error) { - console.error('Failed to compute constants:', error); - throw error; + console.error('Failed to compute constants:', error) + throw error } -}; +} export const getConstant = async (key: string): Promise => { - // const redisKey = `${CONST_REDIS_PREFIX}${key}`; - // const value = await redisClient.get(redisKey); - // - // if (!value) { - // return null; - // } - // - // try { - // return JSON.parse(value) as T; - // } catch { - // return value as unknown as T; - // } + const legacy = await getLegacyConsts() + if (key in legacy) return (legacy[key] ?? null) as T - const constants = await getAllKeyValStore(); - const entry = constants.find(c => c.key === key); + const globals = await getAllGlobalConsts() + if (key in globals) return (globals[key] ?? null) as T - if (!entry) { - return null; - } - - return entry.value as T; -}; + return null +} export const getConstants = async (keys: string[]): Promise> => { - // const redisKeys = keys.map(key => `${CONST_REDIS_PREFIX}${key}`); - // const values = await redisClient.MGET(redisKeys); - // - // const result: Record = {}; - // keys.forEach((key, index) => { - // const value = values[index]; - // if (!value) { - // result[key] = null; - // } else { - // try { - // result[key] = JSON.parse(value) as T; - // } catch { - // result[key] = value as unknown as T; - // } - // } - // }); - // - // return result; + const [legacy, globals] = await Promise.all([getLegacyConsts(), getAllGlobalConsts()]) + const merged = { ...legacy, ...globals } - const constants = await getAllKeyValStore(); - const constantsMap = new Map(constants.map(c => [c.key, c.value])); - - const result: Record = {}; + const result: Record = {} for (const key of keys) { - const value = constantsMap.get(key); - result[key] = (value !== undefined ? value : null) as T | null; + result[key] = (merged[key] ?? null) as T | null } + return result +} - return result; -}; +export const getGlobalConstValues = async (): Promise> => { + return getAllGlobalConsts() +} -export const getAllConstValues = async (): Promise> => { - // const result: Record = {}; - // - // for (const key of CONST_KEYS_ARRAY) { - // result[key] = await getConstant(key); - // } - // - // return result as Record; +export const getRegionConstValues = async (regionId: number): Promise> => { + return getRegionConsts(regionId) +} - const constants = await getAllKeyValStore(); - const constantsMap = new Map(constants.map(c => [c.key, c.value])); +export const getBoundConstValues = async (boundId: number): Promise> => { + return getBoundConsts(boundId) +} - const result: Record = {}; - for (const key of CONST_KEYS_ARRAY) { - result[key] = constantsMap.get(key) ?? null; - } - - return result as Record; -}; - -export { CONST_KEYS, CONST_KEYS_ARRAY }; +export { CONST_KEYS, CONST_KEYS_ARRAY } +export type { ConstKey } diff --git a/apps/backend/src/lib/flash-delivery-cron.ts b/apps/backend/src/lib/flash-delivery-cron.ts index 4079286..2ce803b 100644 --- a/apps/backend/src/lib/flash-delivery-cron.ts +++ b/apps/backend/src/lib/flash-delivery-cron.ts @@ -1,4 +1,4 @@ -import { toggleKeyVal } from '@/src/dbService' +import { getAllRegions, upsertRegionConsts } 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,7 +26,13 @@ export async function runFlashDeliveryToggleCron(params: { const enabled = cron === CRON_TURN_ON_FLASH_DELIVERY console.log('flash delivery cron: toggling isFlashDeliveryEnabled', { cron, enabled }) - await toggleKeyVal(CONST_KEYS.isFlashDeliveryEnabled, enabled) + // isFlashDeliveryEnabled is region-scoped (region_consts) — flip it for every region. + const regions = await getAllRegions() + for (const region of regions) { + await upsertRegionConsts(region.id, [ + { key: CONST_KEYS.isFlashDeliveryEnabled, value: String(enabled) }, + ]) + } await computeConstants() await refreshGenKv() } diff --git a/apps/backend/src/lib/gen-store.ts b/apps/backend/src/lib/gen-store.ts index a4547cc..46a0151 100644 --- a/apps/backend/src/lib/gen-store.ts +++ b/apps/backend/src/lib/gen-store.ts @@ -1,44 +1,54 @@ import { getGenKvNamespace } from '@/src/lib/env-exporter' -import { getAllRegions } from '@/src/dbService' +import { getAllRegions, getBoundsForRegion } from '@/src/dbService' import type { scaffoldEssentialConsts } from '@/src/trpc/apis/common-apis/common-trpc-index' -export const GEN_KV_KEY = 'essential_consts' +export const GEN_KV_KEY = 'essentialConsts' -export const genKvKeyForRegion = (regionId: number): string => `${GEN_KV_KEY}:${regionId}` +export const genKvKeyForBound = (boundId: number): string => `${GEN_KV_KEY}_${boundId}` export type EssentialConstsPayload = Awaited> // Dynamic import: gen-store must not statically import common-trpc-index, because // that module imports readEssentialConstsFromKv from here (cycle). -async function buildEssentialConsts(regionId: number): Promise { +async function buildEssentialConsts(boundId: number): Promise { const { scaffoldEssentialConsts } = await import( '../trpc/apis/common-apis/common-trpc-index' ) - return scaffoldEssentialConsts(regionId) + return scaffoldEssentialConsts(boundId) +} + +async function allBoundIds(): Promise { + const regions = await getAllRegions() + const ids: number[] = [] + for (const region of regions) { + const bounds = await getBoundsForRegion(region.id) + for (const bound of bounds) ids.push(bound.id) + } + return ids +} + +async function putBound(kv: any, boundId: number): Promise { + const payload = await buildEssentialConsts(boundId) + await kv.put(genKvKeyForBound(boundId), JSON.stringify(payload)) } /** - * Rebuilds the full regional essentialConsts response (constants + regional - * counters + env-derived fields + effective bound settings) from D1/env and - * mirrors it to KV under `essential_consts:{regionId}`. - * With no regionId, refreshes ALL regions (used by global-constant writers: - * seed, flash-delivery cron, admin const updates). No-op when KV is absent. + * Rebuilds the flat essentialConsts payload for one bound (or every bound of + * every region when boundId is omitted) and mirrors it to KV under + * `essentialConsts_{boundId}`. No-op when KV is absent. */ -export async function refreshGenKv(regionId?: number): Promise { +export async function refreshGenKv(boundId?: number): Promise { try { const kv = getGenKvNamespace() if (!kv) return - const regionIds = regionId != null - ? [regionId] - : (await getAllRegions()).map((r) => r.id) + const boundIds = boundId != null ? [boundId] : await allBoundIds() - for (const id of regionIds) { + for (const id of boundIds) { try { - const payload = await buildEssentialConsts(id) - await kv.put(genKvKeyForRegion(id), JSON.stringify(payload)) + await putBound(kv, id) } catch (error) { - console.error(`refreshGenKv failed for region ${id}:`, error) + console.error(`refreshGenKv failed for bound ${id}:`, error) } } } catch (error) { @@ -46,17 +56,31 @@ export async function refreshGenKv(regionId?: number): Promise { } } -/** - * Regional client read path: serve the precomputed response from KV. On a miss, - * build it from D1/env, backfill KV, and return. regionId is required — there - * is no global fallback. - */ -export async function readEssentialConstsFromKv(regionId?: number): Promise { - if (regionId == null) { - throw new Error('readEssentialConstsFromKv requires a regionId') - } +/** Rebuilds the KV mirror for every bound of one region. */ +export async function refreshGenKvForRegion(regionId: number): Promise { + try { + const kv = getGenKvNamespace() + if (!kv) return - const key = genKvKeyForRegion(regionId) + const bounds = await getBoundsForRegion(regionId) + for (const bound of bounds) { + try { + await putBound(kv, bound.id) + } catch (error) { + console.error(`refreshGenKv failed for bound ${bound.id}:`, error) + } + } + } catch (error) { + console.error('refreshGenKvForRegion failed:', error) + } +} + +/** + * Client read path: serve the precomputed payload for a bound from KV. On a + * miss, build it from D1/env, backfill KV, and return. + */ +export async function readEssentialConstsFromKv(boundId: number): Promise { + const key = genKvKeyForBound(boundId) try { const kv = getGenKvNamespace() @@ -68,13 +92,13 @@ export async function readEssentialConstsFromKv(regionId?: number): Promise + constants.map((c) => ({ key: c.key, value: c.value == null ? null : String(c.value) })) export const constRouter = router({ + // Backward-compat: merged global + legacy view. Writes route by key scope. getConstants: protectedProcedure .query(async (): Promise => { - // Using dbService helper (new implementation) - const constants = await getAllConstantsFromDb(); - - return constants; + return getAllConstantsFromDb(); }), updateConstants: protectedProcedure - .input(z.object({ - constants: z.array(z.object({ - key: z.string(), - value: z.any(), - })), - })) - .mutation(async ({ input }): Promise => { + .input(constantsInput) + .mutation(async ({ input, ctx }): Promise => { const { constants } = input; - const validKeys = Object.values(CONST_KEYS) as string[]; const invalidKeys = constants - .filter(c => !validKeys.includes(c.key)) + .filter(c => !CONST_SCOPE[c.key]) .map(c => c.key); if (invalidKeys.length > 0) { throw new Error(`Invalid constant keys: ${invalidKeys.join(', ')}`); } - console.log(input) - // Using dbService helper (new implementation) - await upsertConstantsInDb(constants); + const regionId = ctx.staffUser?.regionId ?? null + await upsertConstantsInDb(constants, regionId ?? undefined); - // Refresh all constants in Redis after database update await computeConstants(); - // Mirror the full essentialConsts response into KV for client reads. - await refreshGenKv(); + const touchedRegion = constants.some((c) => CONST_SCOPE[c.key] === 'region') + const touchedOther = constants.some((c) => CONST_SCOPE[c.key] !== 'region') + if (touchedOther) await refreshGenKv() + else if (touchedRegion && regionId != null) await refreshGenKvForRegion(regionId) - // Constants like tagsOrder are baked into the versioned cache files. - // Regenerate the cache (bumps cacheVersion) so the user app fetches the - // new data (e.g., the new tab order on the home page). if (constants.some((c) => CACHE_AFFECTING_KEYS.includes(c.key))) { await scheduleStoreInitialization() } @@ -64,4 +65,46 @@ export const constRouter = router({ keys: constants.map(c => c.key), }; }), + + // Global consts (global_consts table). + getGlobalConstants: protectedProcedure + .query(async (): Promise => { + const values = await getAllGlobalConsts() + return Object.entries(values).map(([key, value]) => ({ key, value })) + }), + + updateGlobalConstants: protectedProcedure + .input(constantsInput) + .mutation(async ({ input }): Promise => { + await upsertGlobalConsts(toRows(input.constants)) + await computeConstants() + await refreshGenKv() + return { + success: true, + updatedCount: input.constants.length, + keys: input.constants.map(c => c.key), + } + }), + + // Legacy leftovers (key_val_store table). + getLegacyConstants: protectedProcedure + .query(async (): Promise => { + const values = await getLegacyConsts() + return Object.entries(values).map(([key, value]) => ({ key, value })) + }), + + updateLegacyConstants: protectedProcedure + .input(constantsInput) + .mutation(async ({ input }): Promise => { + await upsertLegacyConsts(toRows(input.constants)) + await computeConstants() + if (input.constants.some((c) => CACHE_AFFECTING_KEYS.includes(c.key))) { + await scheduleStoreInitialization() + } + return { + success: true, + updatedCount: input.constants.length, + keys: input.constants.map(c => c.key), + } + }), }); diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/region.ts b/apps/backend/src/trpc/apis/admin-apis/apis/region.ts index 0416713..6923784 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/region.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/region.ts @@ -2,11 +2,15 @@ import { router, staffProcedure } from '@/src/trpc/trpc-index' import { z } from 'zod' import { TRPCError } from '@trpc/server' import { ApiError } from '@/src/lib/api-error' +import { refreshGenKvForRegion } from '@/src/lib/gen-store' +import { scheduleStoreInitialization } from '@/src/stores/store-initializer' import { getBoundsForRegion, getBoundById, getBoundSettings, upsertBoundSettings, + getRegionConstants, + upsertRegionConstants, getEffectiveRegionSettings, getRegionById, } from '@/src/dbService' @@ -20,6 +24,18 @@ async function assertBoundInRegion(boundId: number, regionId: number) { return bound } +const constRows = z.array(z.object({ + key: z.string(), + value: z.union([z.string(), z.number(), z.boolean(), z.null()]), +})) + +// Region-level keys that are baked into the versioned cache files; changing them +// requires regenerating the store cache so the user app picks it up. +const CACHE_AFFECTING_REGION_KEYS: string[] = ['tagsOrder'] + +// Version counters live in region_consts but are owned by the cache pipeline. +const isVersionKey = (key: string) => key.includes('version') + export const regionRouter = router({ current: staffProcedure.query(async ({ ctx }) => { return getRegionById(ctx.staffUser!.regionId) @@ -35,6 +51,32 @@ export const regionRouter = router({ return effective }), + // Region-scoped consts (region_consts) for the caller's region. + getRegionConstants: staffProcedure.query(async ({ ctx }) => { + const values = await getRegionConstants(ctx.staffUser!.regionId) + return Object.entries(values).map(([key, value]) => ({ key, value })) + }), + + updateRegionConstants: staffProcedure + .input(z.object({ constants: constRows })) + .mutation(async ({ input, ctx }) => { + const regionId = ctx.staffUser!.regionId + const rows = input.constants + .filter((c) => !isVersionKey(c.key)) + .map((c) => ({ key: c.key, value: c.value == null ? null : String(c.value) })) + + if (rows.length > 0) { + await upsertRegionConstants(regionId, rows) + await refreshGenKvForRegion(regionId) + } + + if (rows.some((c) => CACHE_AFFECTING_REGION_KEYS.includes(c.key))) { + await scheduleStoreInitialization() + } + + return { success: true, updatedCount: rows.length } + }), + getBoundSettings: staffProcedure .input(z.object({ boundId: z.number().int().positive() })) .query(async ({ input, ctx }) => { @@ -51,8 +93,10 @@ export const regionRouter = router({ })), })) .mutation(async ({ input, ctx }) => { - await assertBoundInRegion(input.boundId, ctx.staffUser!.regionId) + const regionId = ctx.staffUser!.regionId + await assertBoundInRegion(input.boundId, regionId) await upsertBoundSettings(input.boundId, input.settings) + await refreshGenKvForRegion(regionId) return { success: true, updatedCount: input.settings.length } }), }) 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 970c6a8..b59d565 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 @@ -3,67 +3,117 @@ import { commonRouter } from '@/src/trpc/apis/common-apis/common' import { getStoresSummary, healthCheck, - getRegionCacheVersions, + getBoundById, getAllRegions, + getAllRegionsWithBounds, getEffectiveRegionSettings, } from '@/src/dbService' -import type { StoresSummaryResponse } from '@packages/shared' +import type { StoresSummaryResponse, RegionGeoJson, ResolvedRegion } from '@packages/shared' import { polygon as turfPolygon, point as turfPoint } from '@turf/helpers'; import { booleanPointInPolygon } from '@turf/boolean-point-in-polygon'; import { z } from 'zod'; import { mbnrGeoJson } from '@/src/lib/mbnr-geojson' import { generateUploadUrl } from '@/src/lib/s3-client' import { ApiError } from '@/src/lib/api-error' -import { getAllConstValues } from '@/src/lib/const-store' +import { + getGlobalConstValues, + getRegionConstValues, + getBoundConstValues, +} from '@/src/lib/const-store' import { readEssentialConstsFromKv } from '@/src/lib/gen-store' -import { CONST_KEYS } from '@/src/lib/const-keys' import { getAssetsDomain, getApiCacheKey } from '@/src/lib/env-exporter' const polygon = turfPolygon(mbnrGeoJson.features[0].geometry.coordinates); -export async function scaffoldEssentialConsts(regionId: number) { - const consts = await getAllConstValues(); - const versions = await getRegionCacheVersions(regionId) - const regionSettings = await getEffectiveRegionSettings(regionId) +type BoundPolygon = ReturnType +// A bound's GeoJSON is a FeatureCollection; each feature geometry may be a +// Polygon or MultiPolygon. Flatten them into turf polygons for containment tests. +function boundToPolygons(geojson: RegionGeoJson): BoundPolygon[] { + const polygons: BoundPolygon[] = [] + for (const feature of geojson?.features ?? []) { + const geometry = feature?.geometry + if (!geometry) continue + if (geometry.type === 'Polygon') { + polygons.push(turfPolygon(geometry.coordinates as any)) + } else if (geometry.type === 'MultiPolygon') { + for (const coordinates of geometry.coordinates as any[]) { + polygons.push(turfPolygon(coordinates)) + } + } + } + return polygons +} + +export async function scaffoldEssentialConsts(boundId: number) { + const bound = await getBoundById(boundId) + if (!bound) throw new ApiError('Bound not found', 404) + + const regionId = bound.regionId + const [global, region, boundConsts] = await Promise.all([ + getGlobalConstValues(), + getRegionConstValues(regionId), + getBoundConstValues(boundId), + ]) + + const pickNumber = (raw: any, fallback: number): number => { + if (raw == null || raw === '') return fallback + const parsed = Number(raw) + return Number.isFinite(parsed) ? parsed : fallback + } + const pickRaw = (raw: any, fallback: any): any => (raw == null || raw === '' ? fallback : raw) + const pickBool = (raw: any, fallback: boolean): boolean => { + if (raw == null || raw === '') return fallback + if (typeof raw === 'boolean') return raw + const str = String(raw).toLowerCase() + return str === 'true' || str === '1' + } + + // Flat union of global + region + bound consts (+ env + identity). Key names + // match the three tables exactly so clients read one flat object. return { - freeDeliveryThreshold: consts[CONST_KEYS.freeDeliveryThreshold] ?? 200, - deliveryCharge: consts[CONST_KEYS.deliveryCharge] ?? 0, - flashFreeDeliveryThreshold: consts[CONST_KEYS.flashFreeDeliveryThreshold] ?? 500, - flashDeliveryCharge: consts[CONST_KEYS.flashDeliveryCharge] ?? 69, - popularItems: consts[CONST_KEYS.popularItems], - versionNum: consts[CONST_KEYS.versionNum], - playStoreUrl: consts[CONST_KEYS.playStoreUrl], - appStoreUrl: consts[CONST_KEYS.appStoreUrl], - webViewHtml: null, - webviewHtml: null, - isWebviewClosable: true, - isFlashDeliveryEnabled: consts[CONST_KEYS.isFlashDeliveryEnabled] ?? false, - supportMobile: consts[CONST_KEYS.supportMobile] ?? '', - supportEmail: consts[CONST_KEYS.supportEmail] ?? '', - internalAppVersion: consts[CONST_KEYS.internalAppVersion] ?? 1, + // global_consts + versionNum: pickRaw(global['versionNum'], null), + playStoreUrl: pickRaw(global['playStoreUrl'], null), + appStoreUrl: pickRaw(global['appStoreUrl'], null), + internalAppVersion: pickNumber(global['internalAppVersion'], 1), + // region_consts + products_version_num: pickNumber(region['products_version_num'], 0), + availability_version_num: pickNumber(region['availability_version_num'], 0), + 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'], ''), + // region_bound_consts + minRegularOrderValue: pickNumber(boundConsts['minRegularOrderValue'], 0), + freeDeliveryThreshold: pickNumber(boundConsts['freeDeliveryThreshold'], 200), + deliveryCharge: pickNumber(boundConsts['deliveryCharge'], 0), + flashFreeDeliveryThreshold: pickNumber(boundConsts['flashFreeDeliveryThreshold'], 500), + flashDeliveryCharge: pickNumber(boundConsts['flashDeliveryCharge'], 69), + // env + identity assetsDomain: getAssetsDomain(), apiCacheKey: getApiCacheKey(), regionId, - cacheVersion: versions.cacheVersion, - availabilityVersionNum: versions.availabilityVersionNum, - slotsVersionNum: versions.slotsVersionNum, - regionSettings, - }; + boundId, + // stale-client notice (overridden per-request in the procedure) + webViewHtml: null, + webviewHtml: null, + isWebviewClosable: true, + } } export const commonApiRouter = router({ product: commonRouter, - getStoresSummary: publicProcedure - .query(async (): Promise => { - // No-input shape preserved for existing admin UIs (separate workstream): - // aggregate the per-region store lists. - const regions = await getAllRegions(); - const perRegion = await Promise.all(regions.map((r) => getStoresSummary(r.id))); - + getStoresSummary: protectedProcedure + .query(async ({ ctx }): Promise => { + // Admin-only picker: the caller's OWN region only, not an aggregate. + const stores = await getStoresSummary(ctx.staffUser!.regionId); return { - stores: perRegion.flat(), + stores, }; }), @@ -146,6 +196,38 @@ export const commonApiRouter = router({ return getAllRegions(); }), + // Resolve device coordinates to a region + the bound that contains them. + // Every region is checked; within each region bounds are checked least + // priority first (lowest number wins). The first containing bound is returned. + resolveRegionByLocation: publicProcedure + .input(z.object({ + lat: z.number().min(-90).max(90), + lng: z.number().min(-180).max(180), + })) + .query(async ({ input }): Promise => { + const point = turfPoint([input.lng, input.lat]); // GeoJSON: [longitude, latitude] + const regions = await getAllRegionsWithBounds(); + + for (const region of regions) { + for (const bound of region.bounds) { + const polygons = boundToPolygons(bound.geojson); + if (polygons.some((poly) => booleanPointInPolygon(point, poly))) { + return { + region: { id: region.id, name: region.name, description: region.description }, + bound: { + id: bound.id, + regionId: bound.regionId, + description: bound.description, + priority: bound.priority, + }, + }; + } + } + } + + return null; + }), + // Effective business settings (from the region's lowest-priority bound). regionSettings: publicProcedure .input(z.object({ regionId: z.number().int().positive() })) @@ -158,19 +240,20 @@ export const commonApiRouter = router({ }), essentialConsts: publicProcedure - .input(z.object({ regionId: z.number().int().positive() })) + .input(z.object({ boundId: z.number().int().positive() })) .query(async ({ ctx, input }) => { + console.log({ boundId: input.boundId }) const requestUrl = ctx.req.url const host = new URL(requestUrl).host - console.log('essentialConsts request', { host, url: requestUrl }) const updateNotice = `
-

You're using an old version of app. please restart to update. Just close and open

-

With love, from Freshyo

-
` - - const response = await readEssentialConstsFromKv(input.regionId); +

You're using an old version of app. please restart to update. Just close and open

+

With love, from Freshyo

+
` + + const response = await readEssentialConstsFromKv(input.boundId); const shouldShowNotice = host.includes('raw') || host.includes('mf') - + + console.log('essentialConsts request', { host, url: requestUrl, ...response }) return { ...response, webviewHtml: shouldShowNotice ? updateNotice : null, diff --git a/apps/backend/src/trpc/apis/common-apis/common.ts b/apps/backend/src/trpc/apis/common-apis/common.ts index f5aff75..368a456 100644 --- a/apps/backend/src/trpc/apis/common-apis/common.ts +++ b/apps/backend/src/trpc/apis/common-apis/common.ts @@ -1,4 +1,4 @@ -import { router, publicProcedure } from '@/src/trpc/trpc-index' +import { router, publicProcedure, protectedProcedure } from '@/src/trpc/trpc-index' import { getSuspendedSkuIds, getNextDeliveryDateWithCapacity, @@ -8,10 +8,9 @@ import { getAvailabilityForCache, getAllProductsForCache, getAllDeliverySlotsForCache, - getAllRegions, } from '@/src/dbService' import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url, scaffoldAssetUrl } from '@/src/lib/s3-client' -import { getConstant } from '@/src/lib/const-store' +import { getRegionConstValues } from '@/src/lib/const-store' import { CONST_KEYS } from '@/src/lib/const-keys' // Re-export with original name for backwards compatibility @@ -66,8 +65,9 @@ export async function scaffoldProducts(regionId: number) { }; }) - // Order tags by the admin-defined tagsOrder (unknown tags go to the end). - const tagsOrderRaw = await getConstant(CONST_KEYS.tagsOrder) + // Order tags by the region's admin-defined tagsOrder (unknown tags go to the end). + const regionConsts = await getRegionConstValues(regionId) + const tagsOrderRaw = regionConsts[CONST_KEYS.tagsOrder] let tagsOrderIds: number[] = [] if (Array.isArray(tagsOrderRaw)) { tagsOrderIds = tagsOrderRaw.map((id: any) => parseInt(id)).filter((id: number) => !isNaN(id)) @@ -134,30 +134,17 @@ export async function scaffoldAvailability(regionId: number) { } export const commonRouter = router({ - getAllProductsSummary: publicProcedure - .query(async () => { - // No-input shape preserved for existing admin UIs (separate workstream): - // aggregate the per-region scaffolds. Each region's contribution is - // in-region; tags are deduped by id. - const regions = await getAllRegions() - const perRegion = await Promise.all(regions.map((r) => scaffoldProducts(r.id))) - const products = perRegion.flatMap((s) => s.products) - const tagsById = new Map() - for (const s of perRegion) { - for (const tag of s.tags) { - if (!tagsById.has(tag.id)) tagsById.set(tag.id, tag) - } - } - return { - products, - count: products.length, - tags: Array.from(tagsById.values()), - }; + getAllProductsSummary: protectedProcedure + .query(async ({ ctx }) => { + // Admin-only (the customer apps read the regional CDN cache files, not + // this endpoint): return the caller's OWN region only. + return scaffoldProducts(ctx.staffUser!.regionId) }), - getAllSkusSummary: publicProcedure - .query(async () => { - const skus = await getAllSkusSummaryInDb() + getAllSkusSummary: protectedProcedure + .query(async ({ ctx }) => { + // Admin-only SKU picker; scoped to the caller's region. + const skus = await getAllSkusSummaryInDb(ctx.staffUser!.regionId) return { skus } }), diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/const.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/const.ts new file mode 100644 index 0000000..28df6f2 --- /dev/null +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/const.ts @@ -0,0 +1,52 @@ +import { router, superadminProcedure } from '@/src/trpc/trpc-index' +import { z } from 'zod' +import { refreshGenKv } from '@/src/lib/gen-store' +import { + getAllGlobalConsts, + upsertGlobalConsts, + getLegacyConsts, + upsertLegacyConsts, +} from '@/src/dbService' +import type { Constant, ConstantUpdateResult } from '@packages/shared' + +const constantsInput = z.object({ + constants: z.array(z.object({ key: z.string(), value: z.any() })), +}) + +const toRows = (constants: Constant[]) => + constants.map((c) => ({ key: c.key, value: c.value == null ? null : String(c.value) })) + +export const superadminConstRouter = router({ + getGlobalConstants: superadminProcedure.query(async (): Promise => { + const values = await getAllGlobalConsts() + return Object.entries(values).map(([key, value]) => ({ key, value })) + }), + + updateGlobalConstants: superadminProcedure + .input(constantsInput) + .mutation(async ({ input }): Promise => { + await upsertGlobalConsts(toRows(input.constants)) + await refreshGenKv() + return { + success: true, + updatedCount: input.constants.length, + keys: input.constants.map((c) => c.key), + } + }), + + getLegacyConstants: superadminProcedure.query(async (): Promise => { + const values = await getLegacyConsts() + return Object.entries(values).map(([key, value]) => ({ key, value })) + }), + + updateLegacyConstants: superadminProcedure + .input(constantsInput) + .mutation(async ({ input }): Promise => { + await upsertLegacyConsts(toRows(input.constants)) + return { + success: true, + updatedCount: input.constants.length, + keys: input.constants.map((c) => c.key), + } + }), +}) 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 9eb4447..f7cde63 100644 --- a/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts @@ -2,10 +2,12 @@ import { router, superadminProcedure } from '@/src/trpc/trpc-index' import { z } from 'zod' import { TRPCError } from '@trpc/server' import { ApiError } from '@/src/lib/api-error' +import { refreshGenKvForRegion } from '@/src/lib/gen-store' +import { scheduleStoreInitialization } from '@/src/stores/store-initializer' import { getAllRegions, getRegionWithBounds, - createRegion, + createRegionWithBounds, updateRegion, getBoundsForRegion, getBoundById, @@ -13,6 +15,8 @@ import { updateRegionBound, getBoundSettings, upsertBoundSettings, + getRegionConstants, + upsertRegionConstants, getEffectiveRegionSettings, } from '@/src/dbService' @@ -30,6 +34,11 @@ const geojsonSchema = z.object({ ), }) +// Region-level keys baked into the versioned cache files (cache regen needed). +const CACHE_AFFECTING_REGION_KEYS: string[] = ['tagsOrder'] +// Version counters live in region_consts but are owned by the cache pipeline. +const isVersionKey = (key: string) => key.includes('version') + export const superadminRegionsRouter = router({ list: superadminProcedure.query(async () => { return getAllRegions() @@ -47,15 +56,38 @@ export const superadminRegionsRouter = router({ .input(z.object({ name: z.string().min(1), description: z.string().nullish(), + // A region is unusable without bounds; at least one must be provided. + bounds: z + .array(z.object({ + description: z.string().nullish(), + geojson: geojsonSchema, + priority: z.string().regex(/^-?\d+(\.\d+)?$/, 'Priority must be numeric'), + })) + .min(1, 'A region must be created with at least one bound'), })) .mutation(async ({ input }) => { - const region = await createRegion({ name: input.name, description: input.description ?? null }) - // New regions get cache files 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) - }) - return region + try { + const { region, bounds } = await createRegionWithBounds({ + name: input.name, + description: input.description ?? null, + bounds: input.bounds.map((bound) => ({ + description: bound.description ?? null, + geojson: bound.geojson, + 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) => { + console.error(`Failed to generate cache files for new region ${region.id}:`, error) + }) + return { ...region, bounds } + } catch (error) { + throw new ApiError( + 'Could not create region with bounds. Each bound priority must be unique within the region.', + 409 + ) + } }), update: superadminProcedure @@ -85,12 +117,15 @@ export const superadminRegionsRouter = router({ })) .mutation(async ({ input }) => { try { - return await createRegionBound({ + const bound = await createRegionBound({ regionId: input.regionId, description: input.description ?? null, geojson: input.geojson, priority: input.priority, }) + // A new bound can become the effective (lowest-priority) one. + await refreshGenKvForRegion(bound.regionId) + return bound } catch (error) { throw new ApiError( 'Could not create bound. Priority may already exist for this region.', @@ -110,6 +145,8 @@ export const superadminRegionsRouter = router({ try { const bound = await updateRegionBound(input) if (!bound) throw new TRPCError({ code: 'NOT_FOUND' }) + // Priority/geojson changes can change which bound is effective. + await refreshGenKvForRegion(bound.regionId) return bound } catch (error) { if (error instanceof TRPCError) throw error @@ -136,9 +173,47 @@ export const superadminRegionsRouter = router({ })) .mutation(async ({ input }) => { await upsertBoundSettings(input.boundId, input.settings) + // Bound settings are served from KV (essentialConsts payload), so the + // region's mirror must be rebuilt or clients keep reading stale values. + const bound = await getBoundById(input.boundId) + if (bound) { + await refreshGenKvForRegion(bound.regionId) + } return { success: true, updatedCount: input.settings.length } }), + getRegionConstants: superadminProcedure + .input(z.object({ regionId: z.number().int().positive() })) + .query(async ({ input }) => { + const values = await getRegionConstants(input.regionId) + return Object.entries(values).map(([key, value]) => ({ key, value })) + }), + + updateRegionConstants: superadminProcedure + .input(z.object({ + regionId: z.number().int().positive(), + constants: z.array(z.object({ + key: z.string(), + value: z.union([z.string(), z.number(), z.boolean(), z.null()]), + })), + })) + .mutation(async ({ input }) => { + const rows = input.constants + .filter((c) => !isVersionKey(c.key)) + .map((c) => ({ key: c.key, value: c.value == null ? null : String(c.value) })) + + if (rows.length > 0) { + await upsertRegionConstants(input.regionId, rows) + await refreshGenKvForRegion(input.regionId) + } + + if (rows.some((c) => CACHE_AFFECTING_REGION_KEYS.includes(c.key))) { + await scheduleStoreInitialization() + } + + return { success: true, updatedCount: rows.length } + }), + effectiveSettings: superadminProcedure .input(z.object({ regionId: z.number().int().positive() })) .query(async ({ input }) => { 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 89ce25a..22cfa09 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 @@ -2,11 +2,13 @@ import { router } from '@/src/trpc/trpc-index' import { superadminAuthRouter } from '@/src/trpc/apis/superadmin-apis/apis/auth' import { superadminRegionsRouter } from '@/src/trpc/apis/superadmin-apis/apis/regions' import { superadminStaffRouter } from '@/src/trpc/apis/superadmin-apis/apis/staff' +import { superadminConstRouter } from '@/src/trpc/apis/superadmin-apis/apis/const' export const superadminRouter = router({ auth: superadminAuthRouter, regions: superadminRegionsRouter, staff: superadminStaffRouter, + const: superadminConstRouter, }) export type SuperadminRouter = typeof superadminRouter diff --git a/apps/superadmin-ui/package.json b/apps/superadmin-ui/package.json index 3df653a..44b96f9 100644 --- a/apps/superadmin-ui/package.json +++ b/apps/superadmin-ui/package.json @@ -3,7 +3,7 @@ "private": true, "type": "module", "scripts": { - "dev": "vite dev", + "dev": "vite dev --host 0.0.0.0", "build": "vite build", "preview": "npm run build && wrangler dev", "typecheck": "tsc --noEmit", diff --git a/apps/superadmin-ui/src/routes/constants.tsx b/apps/superadmin-ui/src/routes/constants.tsx index e8bdfe5..8c71274 100644 --- a/apps/superadmin-ui/src/routes/constants.tsx +++ b/apps/superadmin-ui/src/routes/constants.tsx @@ -1,22 +1,25 @@ import { createFileRoute } from '@tanstack/react-router' -import React from 'react' +import React, { useMemo } from 'react' import { Formik } from 'formik' import { AppContainer, Checkbox, MyButton, p as MyText, pInput as PInput } from 'web-components' -import { ChevronRight, ListOrdered, Pencil } from 'lucide-react' import { trpc } from '../lib/trpc-client' import { ProtectedRoute } from '../components/ProtectedRoute' import { AppShell } from '../components/AppShell' type ConstantFormData = Record +// Global keys (global_consts table). +const GLOBAL_KEYS = ['versionNum', 'playStoreUrl', 'appStoreUrl', 'internalAppVersion'] +// Leftover keys (key_val_store table). +const LEGACY_KEYS = [ + 'platformFeePercent', 'taxRate', 'tester', 'minOrderAmountForCoupon', + 'maxCouponDiscount', 'flashDeliverySlotId', 'readableOrderId', +] + const CONST_LABELS: Record = { - minRegularOrderValue: 'Minimum Regular Order Value', - freeDeliveryThreshold: 'Free Delivery Threshold', - deliveryCharge: 'Delivery Charge', - flashFreeDeliveryThreshold: 'Flash Free Delivery Threshold', - flashDeliveryCharge: 'Flash Delivery Charge', platformFeePercent: 'Platform Fee Percent', taxRate: 'Tax Rate', + tester: 'Tester', minOrderAmountForCoupon: 'Minimum Order Amount for Coupon', maxCouponDiscount: 'Maximum Coupon Discount', flashDeliverySlotId: 'Flash Delivery Slot ID', @@ -24,36 +27,50 @@ const CONST_LABELS: Record = { versionNum: 'Version Number', playStoreUrl: 'Play Store URL', appStoreUrl: 'App Store URL', - popularItems: 'Popular Items', - allItemsOrder: 'All Items Order', - isFlashDeliveryEnabled: 'Enable Flash Delivery', - supportMobile: 'Support Mobile', - supportEmail: 'Support Email', internalAppVersion: 'Internal App Version', } const CONST_VISIBILITY: Record = { - minRegularOrderValue: true, - freeDeliveryThreshold: true, - deliveryCharge: true, - flashFreeDeliveryThreshold: true, - flashDeliveryCharge: true, + versionNum: true, + playStoreUrl: true, + appStoreUrl: true, + internalAppVersion: true, platformFeePercent: true, taxRate: false, + tester: false, minOrderAmountForCoupon: true, maxCouponDiscount: false, flashDeliverySlotId: true, readableOrderId: false, - versionNum: true, - playStoreUrl: true, - appStoreUrl: true, - popularItems: true, - allItemsOrder: true, - isFlashDeliveryEnabled: true, - supportMobile: true, - supportEmail: true, - internalAppVersion: true, - tester: false, +} + +type ConstValueType = 'number' | 'boolean' | 'array' | 'string' + +const KEY_TYPES: Record = { + versionNum: 'string', + playStoreUrl: 'string', + appStoreUrl: 'string', + internalAppVersion: 'number', + platformFeePercent: 'number', + taxRate: 'number', + tester: 'string', + minOrderAmountForCoupon: 'number', + maxCouponDiscount: 'number', + flashDeliverySlotId: 'number', + readableOrderId: 'number', +} + +const parseConstValue = (key: string, raw: string | null | undefined): any => { + const type = KEY_TYPES[key] ?? 'string' + if (raw === null || raw === undefined || raw === '') { + if (type === 'number') return 0 + return '' + } + if (type === 'number') { + const num = parseFloat(raw) + return isNaN(num) ? 0 : num + } + return raw } interface ConstantInputProps { @@ -65,48 +82,6 @@ interface ConstantInputProps { const ConstantInput: React.FC = ({ constantKey, value, setFieldValue }) => { const fieldName = constantKey - if (constantKey === 'popularItems') { - return ( -
- - {CONST_LABELS[constantKey] || constantKey} - - -
- ) - } - - if (constantKey === 'allItemsOrder') { - return ( -
- - {CONST_LABELS[constantKey] || constantKey} - - -
- ) - } - if (typeof value === 'boolean') { return (
@@ -140,23 +115,6 @@ const ConstantInput: React.FC = ({ constantKey, value, setFi ) } - if (Array.isArray(value)) { - return ( - { - const arrayValue = e.target.value - .split(',') - .map((s) => s.trim()) - .filter((s) => s.length > 0) - setFieldValue(fieldName, arrayValue) - }} - placeholder="Enter comma separated values" - /> - ) - } - return ( = ({ constantKey, value, setFi } function CustomizeApp() { - const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery() - const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation() + const { data: globalConstants, isLoading: isLoadingGlobals, refetch: refetchGlobals } = + trpc.superadmin.const.getGlobalConstants.useQuery() + const { data: legacyConstants, isLoading: isLoadingLegacy, refetch: refetchLegacy } = + trpc.superadmin.const.getLegacyConstants.useQuery() + const { mutate: updateGlobals, isPending: isUpdatingGlobals } = + trpc.superadmin.const.updateGlobalConstants.useMutation() + const { mutate: updateLegacy, isPending: isUpdatingLegacy } = + trpc.superadmin.const.updateLegacyConstants.useMutation() - const handleSubmit = (values: ConstantFormData) => { - const changedConstants = (constants || []) - .filter((constant) => { - const nextValue = values[constant.key] - return JSON.stringify(nextValue) !== JSON.stringify(constant.value) - }) - .map((constant) => ({ - key: constant.key, - value: values[constant.key], - })) + const globalValueByKey = useMemo(() => { + const map: Record = {} + for (const row of globalConstants ?? []) map[row.key] = row.value + return map + }, [globalConstants]) - if (changedConstants.length === 0) { + const legacyValueByKey = useMemo(() => { + const map: Record = {} + for (const row of legacyConstants ?? []) map[row.key] = row.value + return map + }, [legacyConstants]) + + const globalKeys = GLOBAL_KEYS.filter((k) => CONST_VISIBILITY[k]) + const legacyKeys = LEGACY_KEYS.filter((k) => CONST_VISIBILITY[k]) + + const globalInitialValues: ConstantFormData = useMemo(() => { + const values: ConstantFormData = {} + for (const key of globalKeys) values[key] = parseConstValue(key, globalValueByKey[key]) + return values + }, [globalKeys, globalValueByKey]) + + const legacyInitialValues: ConstantFormData = useMemo(() => { + const values: ConstantFormData = {} + for (const key of legacyKeys) values[key] = parseConstValue(key, legacyValueByKey[key]) + return values + }, [legacyKeys, legacyValueByKey]) + + const handleGlobalSubmit = (values: ConstantFormData) => { + const changed = globalKeys + .filter((key) => String(values[key]) !== (globalValueByKey[key] ?? '')) + .map((key) => ({ key, value: values[key] })) + + if (changed.length === 0) { window.alert('No Changes\n\nNo constants were modified.') return } - updateConstants( - { constants: changedConstants }, + updateGlobals( + { constants: changed }, { onSuccess: (response) => { window.alert(`Success\n\nUpdated ${response.updatedCount} constants successfully.`) - refetch() + refetchGlobals() }, onError: (error) => { window.alert('Error\n\nFailed to update constants. Please try again.') - console.error('Update constants error:', error) + console.error('Update global constants error:', error) }, } ) } - if (isLoadingConstants) { + const handleLegacySubmit = (values: ConstantFormData) => { + const changed = legacyKeys + .filter((key) => String(values[key]) !== (legacyValueByKey[key] ?? '')) + .map((key) => ({ key, value: values[key] })) + + if (changed.length === 0) { + window.alert('No Changes\n\nNo constants were modified.') + return + } + + updateLegacy( + { constants: changed }, + { + onSuccess: (response) => { + window.alert(`Success\n\nUpdated ${response.updatedCount} constants successfully.`) + refetchLegacy() + }, + onError: (error) => { + window.alert('Error\n\nFailed to update constants. Please try again.') + console.error('Update legacy constants error:', error) + }, + } + ) + } + + if (isLoadingGlobals || isLoadingLegacy) { return (
Loading constants... @@ -210,19 +220,6 @@ function CustomizeApp() { ) } - if (!constants) { - return ( -
- Failed to load constants -
- ) - } - - const initialValues: ConstantFormData = constants.reduce((acc, constant) => { - acc[constant.key] = constant.value ?? '' - return acc - }, {} as ConstantFormData) - return (
@@ -230,39 +227,55 @@ function CustomizeApp() { Customize App Constants - Modify application constants. Changes will take effect immediately. + Global constants apply app-wide. Region and per-bound settings are managed from the + Regions page. - - {({ handleSubmit, values, setFieldValue }) => ( -
- {constants.map((constant) => { - if (!CONST_VISIBILITY[constant.key]) { - return null - } - - return ( -
- +
+ Global + + {({ handleSubmit, values, setFieldValue }) => ( + + {globalKeys.map((key) => ( +
+
- ) - })} + ))} + + {isUpdatingGlobals ? 'Updating...' : 'Save global changes'} + + + )} +
+
- - {isUpdating ? 'Updating...' : 'Save Changes'} - - - )} - +
+ Legacy + + {({ handleSubmit, values, setFieldValue }) => ( +
+ {legacyKeys.map((key) => ( +
+ +
+ ))} + + {isUpdatingLegacy ? 'Updating...' : 'Save legacy changes'} + +
+ )} +
+
) diff --git a/apps/superadmin-ui/src/routes/regions.tsx b/apps/superadmin-ui/src/routes/regions.tsx index 61a5bbc..6602d8a 100644 --- a/apps/superadmin-ui/src/routes/regions.tsx +++ b/apps/superadmin-ui/src/routes/regions.tsx @@ -15,14 +15,21 @@ export const Route = createFileRoute('/regions')({ ), }) +// Per-bound business keys (region_bound_consts). const SETTING_KEYS = [ 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge', 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', +] as const + +// Region-level keys (region_consts). Version counters are owned by the cache +// pipeline and are intentionally not editable here. +const REGION_SETTING_KEYS = [ 'popularItems', 'allItemsOrder', + 'tagsOrder', 'isFlashDeliveryEnabled', 'supportMobile', 'supportEmail', @@ -37,21 +44,27 @@ const SETTING_LABELS: Record = { flashDeliveryCharge: 'Flash Delivery Charge', popularItems: 'Popular Items (JSON)', allItemsOrder: 'All Items Order (JSON)', + tagsOrder: 'Tags Order (JSON)', isFlashDeliveryEnabled: 'Enable Flash Delivery', supportMobile: 'Support Mobile', supportEmail: 'Support Email', welcomeMessage: 'Welcome Message', } +const isBooleanSetting = (key: string) => key === 'isFlashDeliveryEnabled' + +interface BoundDraft { + description: string + priority: string + geojson: string +} + +const emptyBound = (): BoundDraft => ({ description: '', priority: '', geojson: '' }) + function RegionsPage() { const regionsQuery = trpc.superadmin.regions.list.useQuery() - const createRegion = trpc.superadmin.regions.create.useMutation({ - onSuccess: () => regionsQuery.refetch(), - }) const [selectedRegionId, setSelectedRegionId] = useState(null) - const [newRegionName, setNewRegionName] = useState('') - const [newRegionDescription, setNewRegionDescription] = useState('') const regions = regionsQuery.data ?? [] @@ -63,38 +76,7 @@ function RegionsPage() { Create regions and manage the delivery bounds and settings for each region. -
- Add a region -
- setNewRegionName(e.target.value)} - placeholder="e.g. Mahabubnagar" - /> - setNewRegionDescription(e.target.value)} - placeholder="Optional" - /> -
- { - const region = await createRegion.mutateAsync({ - name: newRegionName.trim(), - description: newRegionDescription.trim() || null, - }) - setNewRegionName('') - setNewRegionDescription('') - setSelectedRegionId(region.id) - }} - className="mt-4 rounded-lg bg-blue-500 px-4 py-2 text-white disabled:opacity-50" - > - {createRegion.isPending ? 'Creating...' : 'Create region'} - -
+ setSelectedRegionId(regionId)} /> {regionsQuery.isLoading && Loading regions...} @@ -124,6 +106,152 @@ function RegionsPage() { ) } +function CreateRegionForm({ onCreated }: { onCreated: (regionId: number) => void }) { + const createRegion = trpc.superadmin.regions.create.useMutation() + const utils = trpc.useUtils() + + const [name, setName] = useState('') + const [description, setDescription] = useState('') + const [bounds, setBounds] = useState([emptyBound()]) + const [error, setError] = useState(null) + + const creating = createRegion.isPending + + const updateBound = (index: number, patch: Partial) => + setBounds((prev) => prev.map((bound, i) => (i === index ? { ...bound, ...patch } : bound))) + + const removeBound = (index: number) => + setBounds((prev) => (prev.length > 1 ? prev.filter((_, i) => i !== index) : prev)) + + const boundsValid = bounds.every( + (bound) => bound.priority.trim() !== '' && bound.geojson.trim() !== '' + ) + const canSubmit = name.trim() !== '' && bounds.length > 0 && boundsValid && !creating + + const handleSubmit = async () => { + setError(null) + try { + const parsedBounds = bounds.map((bound) => { + let geojson + try { + geojson = JSON.parse(bound.geojson) + } catch { + throw new Error('GeoJSON is not valid JSON') + } + return { + description: bound.description.trim() || null, + priority: bound.priority.trim(), + geojson, + } + }) + + const result = await createRegion.mutateAsync({ + name: name.trim(), + description: description.trim() || null, + bounds: parsedBounds, + }) + + setName('') + setDescription('') + setBounds([emptyBound()]) + utils.superadmin.regions.list.invalidate() + onCreated(result.id) + } catch (e) { + setError((e as Error).message || 'Could not create region with bounds') + } + } + + return ( +
+ Add a region + + A region must be created with at least one delivery bound. + + +
+ setName(e.target.value)} + placeholder="e.g. Mahabubnagar" + /> + setDescription(e.target.value)} + placeholder="Optional" + /> +
+ +
+
+ + Bounds ({bounds.length}) + + setBounds((prev) => [...prev, emptyBound()])} + className="rounded-lg border border-gray-300 px-3 py-1.5 text-xs text-gray-700" + > + + Add another bound + +
+ + {bounds.map((bound, index) => ( +
+
+ + Bound {index + 1} + + {bounds.length > 1 && ( + + )} +
+
+ updateBound(index, { description: e.target.value })} + placeholder="e.g. Mbnr-1" + /> + updateBound(index, { priority: e.target.value })} + placeholder="1" + /> +
+
+ GeoJSON +