enh
This commit is contained in:
parent
d9bc8352df
commit
6e5790e1fd
71 changed files with 4533 additions and 1374 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -91,10 +91,10 @@ export default function AllItemsOrder() {
|
|||
const [products, setProducts] = useState<Product[]>([]);
|
||||
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.');
|
||||
|
|
|
|||
|
|
@ -8,6 +8,20 @@ import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
|||
|
||||
type ConstantFormData = Record<string, any>
|
||||
|
||||
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<string, string> = {
|
||||
minRegularOrderValue: 'Minimum Regular Order Value',
|
||||
freeDeliveryThreshold: 'Free Delivery Threshold',
|
||||
|
|
@ -16,6 +30,7 @@ const CONST_LABELS: Record<string, string> = {
|
|||
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<string, string> = {
|
|||
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<string, string> = {
|
|||
welcomeMessage: 'Welcome Message',
|
||||
};
|
||||
|
||||
const CONST_VISIBILITY: Record<string, boolean> = {
|
||||
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<string, BoundValueType> = {
|
||||
const KEY_TYPES: Record<string, ConstValueType> = {
|
||||
minRegularOrderValue: 'number',
|
||||
freeDeliveryThreshold: 'number',
|
||||
deliveryCharge: 'number',
|
||||
|
|
@ -68,17 +58,27 @@ const BOUND_KEY_TYPES: Record<string, BoundValueType> = {
|
|||
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<ConstantInputProps> = ({
|
|||
|
||||
export default function CustomizeApp() {
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<'bounds' | 'global'>('bounds');
|
||||
const [tab, setTab] = useState<ConstTab>('bound');
|
||||
const [selectedBoundId, setSelectedBoundId] = useState<number | null>(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<string, any> = useMemo(() => {
|
||||
const values: Record<string, any> = {};
|
||||
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<string, string | null> = {};
|
||||
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 (
|
||||
<View style={tw`py-12 items-center`}>
|
||||
|
|
@ -518,7 +526,7 @@ export default function CustomizeApp() {
|
|||
>
|
||||
{({ handleSubmit, values, setFieldValue }) => (
|
||||
<View>
|
||||
{REGIONAL_KEYS.map((key) => (
|
||||
{BOUND_KEYS.map((key) => (
|
||||
<View key={key} style={tw`mb-4`}>
|
||||
<ConstantInput
|
||||
constantKey={key}
|
||||
|
|
@ -549,54 +557,42 @@ export default function CustomizeApp() {
|
|||
);
|
||||
};
|
||||
|
||||
const renderGlobal = () => {
|
||||
if (isLoadingConstants) {
|
||||
const renderRegion = () => {
|
||||
if (isLoadingRegionConstants) {
|
||||
return (
|
||||
<View style={tw`py-12 items-center`}>
|
||||
<MyText style={tw`text-gray-500`}>Loading constants...</MyText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (!constants) {
|
||||
return (
|
||||
<View style={tw`py-12 items-center`}>
|
||||
<MyText style={tw`text-gray-500`}>Failed to load constants</MyText>
|
||||
<MyText style={tw`text-gray-500`}>Loading region settings...</MyText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Formik initialValues={globalInitialValues} onSubmit={handleGlobalSubmit}>
|
||||
<Formik initialValues={regionInitialValues} enableReinitialize onSubmit={handleRegionSubmit}>
|
||||
{({ handleSubmit, values, setFieldValue }) => (
|
||||
<View>
|
||||
<MyText style={tw`text-gray-500 text-sm mb-4`}>
|
||||
These global constants are not region-specific and still apply app-wide.
|
||||
Region settings apply to every bound in this region.
|
||||
</MyText>
|
||||
{constants.map((constant) => {
|
||||
if (!CONST_VISIBILITY[constant.key]) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<View key={constant.key} style={tw`mb-4`}>
|
||||
<ConstantInput
|
||||
constantKey={constant.key}
|
||||
value={values[constant.key]}
|
||||
setFieldValue={setFieldValue}
|
||||
router={router}
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
{REGION_KEYS.map((key) => (
|
||||
<View key={key} style={tw`mb-4`}>
|
||||
<ConstantInput
|
||||
constantKey={key}
|
||||
value={values[key]}
|
||||
setFieldValue={setFieldValue}
|
||||
router={router}
|
||||
/>
|
||||
</View>
|
||||
))}
|
||||
|
||||
<MyTouchableOpacity
|
||||
onPress={() => 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' : ''
|
||||
}`}
|
||||
>
|
||||
<MyText style={tw`text-white text-center font-semibold`}>
|
||||
{isUpdating ? 'Updating...' : 'Save Changes'}
|
||||
{updateRegionConstants.isPending ? 'Saving...' : 'Save Changes'}
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
|
|
@ -605,6 +601,11 @@ export default function CustomizeApp() {
|
|||
);
|
||||
};
|
||||
|
||||
const tabs: { id: ConstTab; label: string }[] = [
|
||||
{ id: 'region', label: 'Region' },
|
||||
{ id: 'bound', label: 'Bound' },
|
||||
];
|
||||
|
||||
return (
|
||||
<AppContainer>
|
||||
<MyText style={tw`text-xl font-bold`}>Customize App</MyText>
|
||||
|
|
@ -612,35 +613,27 @@ export default function CustomizeApp() {
|
|||
{region?.name ? `Region: ${region.name}` : 'Regional business settings'}
|
||||
</MyText>
|
||||
|
||||
{/* Top-level switch: per-bound regional settings vs. legacy global constants. */}
|
||||
{/* Top-level switch: region vs. per-bound settings. */}
|
||||
<View style={tw`flex-row bg-gray-100 rounded-lg p-1 mt-4 mb-4`}>
|
||||
<MyTouchableOpacity
|
||||
onPress={() => setMode('bounds')}
|
||||
style={tw`flex-1 py-2 rounded-md ${mode === 'bounds' ? 'bg-white' : ''}`}
|
||||
>
|
||||
<MyText
|
||||
style={tw`text-center ${
|
||||
mode === 'bounds' ? 'text-gray-900 font-semibold' : 'text-gray-500'
|
||||
}`}
|
||||
{tabs.map((t) => (
|
||||
<MyTouchableOpacity
|
||||
key={t.id}
|
||||
onPress={() => setTab(t.id)}
|
||||
style={tw`flex-1 py-2 rounded-md ${tab === t.id ? 'bg-white' : ''}`}
|
||||
>
|
||||
Regional Settings
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
<MyTouchableOpacity
|
||||
onPress={() => setMode('global')}
|
||||
style={tw`flex-1 py-2 rounded-md ${mode === 'global' ? 'bg-white' : ''}`}
|
||||
>
|
||||
<MyText
|
||||
style={tw`text-center ${
|
||||
mode === 'global' ? 'text-gray-900 font-semibold' : 'text-gray-500'
|
||||
}`}
|
||||
>
|
||||
Global Constants
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
<MyText
|
||||
style={tw`text-center ${
|
||||
tab === t.id ? 'text-gray-900 font-semibold' : 'text-gray-500'
|
||||
}`}
|
||||
>
|
||||
{t.label}
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
))}
|
||||
</View>
|
||||
|
||||
{mode === 'bounds' ? renderRegional() : renderGlobal()}
|
||||
{tab === 'region' && renderRegion()}
|
||||
{tab === 'bound' && renderBound()}
|
||||
</AppContainer>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -118,10 +118,10 @@ export default function CustomizePopularItems() {
|
|||
const [showAddDialog, setShowAddDialog] = useState(false);
|
||||
const [selectedProductIds, setSelectedProductIds] = useState<number[]>([]);
|
||||
|
||||
// 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.');
|
||||
|
|
|
|||
|
|
@ -82,10 +82,10 @@ export default function TagOrders() {
|
|||
const [tags, setTags] = useState<Tag[]>([]);
|
||||
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.');
|
||||
|
|
|
|||
|
|
@ -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 () => {
|
||||
|
|
|
|||
|
|
@ -94,9 +94,9 @@ function AllItemsOrder() {
|
|||
const [products, setProducts] = useState<Product[]>([])
|
||||
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.')
|
||||
|
|
|
|||
|
|
@ -107,9 +107,9 @@ function CustomizePopularItems() {
|
|||
const [showAddDialog, setShowAddDialog] = useState(false)
|
||||
const [selectedProductIds, setSelectedProductIds] = useState<number[]>([])
|
||||
|
||||
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.')
|
||||
|
|
|
|||
|
|
@ -11,6 +11,20 @@ export const Route = createFileRoute('/dashboard/customize-app')({
|
|||
|
||||
type ConstantFormData = Record<string, any>
|
||||
|
||||
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<string, string> = {
|
||||
minRegularOrderValue: 'Minimum Regular Order Value',
|
||||
freeDeliveryThreshold: 'Free Delivery Threshold',
|
||||
|
|
@ -19,6 +33,7 @@ const CONST_LABELS: Record<string, string> = {
|
|||
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<string, string> = {
|
|||
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<string, boolean> = {
|
||||
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<string, BoundValueType> = {
|
||||
const KEY_TYPES: Record<string, ConstValueType> = {
|
||||
minRegularOrderValue: 'number',
|
||||
freeDeliveryThreshold: 'number',
|
||||
deliveryCharge: 'number',
|
||||
|
|
@ -69,17 +61,27 @@ const BOUND_KEY_TYPES: Record<string, BoundValueType> = {
|
|||
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<ConstTab>('bound')
|
||||
const [selectedBoundId, setSelectedBoundId] = useState<number | null>(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<string, any> = useMemo(() => {
|
||||
const values: Record<string, any> = {}
|
||||
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<string, string | null> = {}
|
||||
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 (
|
||||
<div className="flex flex-1 items-center justify-center py-12">
|
||||
|
|
@ -497,7 +515,7 @@ function CustomizeApp() {
|
|||
>
|
||||
{({ handleSubmit, values, setFieldValue }) => (
|
||||
<div>
|
||||
{REGIONAL_KEYS.map((key) => (
|
||||
{BOUND_KEYS.map((key) => (
|
||||
<div key={key} className="mb-4">
|
||||
<ConstantInput
|
||||
constantKey={key}
|
||||
|
|
@ -526,59 +544,40 @@ function CustomizeApp() {
|
|||
)
|
||||
}
|
||||
|
||||
const renderGlobal = () => {
|
||||
if (isLoadingConstants) {
|
||||
const renderRegion = () => {
|
||||
if (isLoadingRegionConstants) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<MyText className="text-gray-500">Loading constants...</MyText>
|
||||
<div className="flex flex-1 items-center justify-center py-12">
|
||||
<MyText className="text-gray-500">Loading region settings...</MyText>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!constants) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<MyText className="text-gray-500">Failed to load constants</MyText>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const initialValues: ConstantFormData = constants.reduce((acc, constant) => {
|
||||
acc[constant.key] = constant.value ?? ''
|
||||
return acc
|
||||
}, {} as ConstantFormData)
|
||||
|
||||
return (
|
||||
<Formik initialValues={initialValues} onSubmit={handleGlobalSubmit}>
|
||||
<Formik initialValues={regionInitialValues} enableReinitialize onSubmit={handleRegionSubmit}>
|
||||
{({ handleSubmit, values, setFieldValue }) => (
|
||||
<div>
|
||||
<MyText className="mb-4 text-sm text-gray-500">
|
||||
These global constants are not region-specific and still apply app-wide.
|
||||
Region settings apply to every bound in this region.
|
||||
</MyText>
|
||||
{constants.map((constant) => {
|
||||
if (!CONST_VISIBILITY[constant.key]) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={constant.key} className="mb-4">
|
||||
<ConstantInput
|
||||
constantKey={constant.key}
|
||||
value={values[constant.key]}
|
||||
setFieldValue={setFieldValue}
|
||||
router={router}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{REGION_KEYS.map((key) => (
|
||||
<div key={key} className="mb-4">
|
||||
<ConstantInput
|
||||
constantKey={key}
|
||||
value={values[key]}
|
||||
setFieldValue={setFieldValue}
|
||||
router={router}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<button
|
||||
onClick={() => handleSubmit()}
|
||||
disabled={isUpdating}
|
||||
className={`mt-6 rounded-lg bg-blue-500 p-4 ${isUpdating ? 'opacity-50' : ''}`}
|
||||
disabled={isSavingRegion}
|
||||
className={`mt-6 rounded-lg bg-blue-500 p-4 ${isSavingRegion ? 'opacity-50' : ''}`}
|
||||
>
|
||||
<MyText className="text-center font-semibold text-white">
|
||||
{isUpdating ? 'Updating...' : 'Save Changes'}
|
||||
{isSavingRegion ? 'Saving...' : 'Save Changes'}
|
||||
</MyText>
|
||||
</button>
|
||||
</div>
|
||||
|
|
@ -587,6 +586,11 @@ function CustomizeApp() {
|
|||
)
|
||||
}
|
||||
|
||||
const tabs: { id: ConstTab; label: string }[] = [
|
||||
{ id: 'region', label: 'Region' },
|
||||
{ id: 'bound', label: 'Bound' },
|
||||
]
|
||||
|
||||
return (
|
||||
<AppContainer>
|
||||
<div className="flex-1 bg-gray-50 p-4">
|
||||
|
|
@ -598,27 +602,23 @@ function CustomizeApp() {
|
|||
Modify application settings. Changes will take effect immediately.
|
||||
</MyText>
|
||||
|
||||
{/* Top-level switch: per-bound regional settings vs. legacy global constants. */}
|
||||
{/* Top-level switch: region vs. per-bound settings. */}
|
||||
<div className="mb-4 flex flex-row rounded-lg bg-gray-100 p-1">
|
||||
<button
|
||||
onClick={() => setMode('bounds')}
|
||||
className={`flex-1 rounded-md py-2 ${mode === 'bounds' ? 'bg-white' : ''}`}
|
||||
>
|
||||
<MyText className={`text-center ${mode === 'bounds' ? 'font-semibold text-gray-900' : 'text-gray-500'}`}>
|
||||
Regional Settings
|
||||
</MyText>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setMode('global')}
|
||||
className={`flex-1 rounded-md py-2 ${mode === 'global' ? 'bg-white' : ''}`}
|
||||
>
|
||||
<MyText className={`text-center ${mode === 'global' ? 'font-semibold text-gray-900' : 'text-gray-500'}`}>
|
||||
Global Constants
|
||||
</MyText>
|
||||
</button>
|
||||
{tabs.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
onClick={() => setTab(t.id)}
|
||||
className={`flex-1 rounded-md py-2 ${tab === t.id ? 'bg-white' : ''}`}
|
||||
>
|
||||
<MyText className={`text-center ${tab === t.id ? 'font-semibold text-gray-900' : 'text-gray-500'}`}>
|
||||
{t.label}
|
||||
</MyText>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{mode === 'bounds' ? renderRegional() : renderGlobal()}
|
||||
{tab === 'region' && renderRegion()}
|
||||
{tab === 'bound' && renderBound()}
|
||||
</div>
|
||||
</AppContainer>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -87,9 +87,9 @@ function TagOrders() {
|
|||
const [tags, setTags] = useState<Tag[]>([])
|
||||
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.')
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
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
|
||||
|
|
@ -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<RegionCa
|
|||
console.log(`Cache files created successfully for region ${regionId}`)
|
||||
|
||||
// Single awaited mirror refresh for the region (all regional counters bumped above).
|
||||
await refreshGenKv(regionId)
|
||||
await refreshGenKvForRegion(regionId)
|
||||
|
||||
return {
|
||||
regionId,
|
||||
|
|
@ -158,13 +159,15 @@ export async function createAvailabilityCacheFile(regionId: number, refresh = tr
|
|||
filePath
|
||||
)
|
||||
|
||||
if (refresh) await refreshGenKv(regionId)
|
||||
if (refresh) await refreshGenKvForRegion(regionId)
|
||||
|
||||
return version
|
||||
}
|
||||
|
||||
async function createEssentialConstsFileInternal(regionId: number, version: number): Promise<string> {
|
||||
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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<ConstKey, string> = {
|
|||
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<ConstKey, ConstValueType> = {
|
|||
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<ConstKey, boolean> = {
|
|||
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<ConstKey, boolean> = {
|
|||
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<string, ConstScope> = {}
|
||||
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'
|
||||
|
|
|
|||
|
|
@ -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<void> => {
|
||||
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 <T = any>(key: string): Promise<T | null> => {
|
||||
// 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 <T = any>(keys: string[]): Promise<Record<string, T | null>> => {
|
||||
// const redisKeys = keys.map(key => `${CONST_REDIS_PREFIX}${key}`);
|
||||
// const values = await redisClient.MGET(redisKeys);
|
||||
//
|
||||
// const result: Record<string, T | null> = {};
|
||||
// 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<string, T | null> = {};
|
||||
const result: Record<string, T | null> = {}
|
||||
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<Record<string, any>> => {
|
||||
return getAllGlobalConsts()
|
||||
}
|
||||
|
||||
export const getAllConstValues = async (): Promise<Record<ConstKey, any>> => {
|
||||
// const result: Record<string, any> = {};
|
||||
//
|
||||
// for (const key of CONST_KEYS_ARRAY) {
|
||||
// result[key] = await getConstant(key);
|
||||
// }
|
||||
//
|
||||
// return result as Record<ConstKey, any>;
|
||||
export const getRegionConstValues = async (regionId: number): Promise<Record<string, any>> => {
|
||||
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<Record<string, any>> => {
|
||||
return getBoundConsts(boundId)
|
||||
}
|
||||
|
||||
const result: Record<string, any> = {};
|
||||
for (const key of CONST_KEYS_ARRAY) {
|
||||
result[key] = constantsMap.get(key) ?? null;
|
||||
}
|
||||
|
||||
return result as Record<ConstKey, any>;
|
||||
};
|
||||
|
||||
export { CONST_KEYS, CONST_KEYS_ARRAY };
|
||||
export { CONST_KEYS, CONST_KEYS_ARRAY }
|
||||
export type { ConstKey }
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<ReturnType<typeof scaffoldEssentialConsts>>
|
||||
|
||||
// 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<EssentialConstsPayload> {
|
||||
async function buildEssentialConsts(boundId: number): Promise<EssentialConstsPayload> {
|
||||
const { scaffoldEssentialConsts } = await import(
|
||||
'../trpc/apis/common-apis/common-trpc-index'
|
||||
)
|
||||
return scaffoldEssentialConsts(regionId)
|
||||
return scaffoldEssentialConsts(boundId)
|
||||
}
|
||||
|
||||
async function allBoundIds(): Promise<number[]> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
export async function refreshGenKv(boundId?: number): Promise<void> {
|
||||
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<void> {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<EssentialConstsPayload> {
|
||||
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<void> {
|
||||
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<EssentialConstsPayload> {
|
||||
const key = genKvKeyForBound(boundId)
|
||||
|
||||
try {
|
||||
const kv = getGenKvNamespace()
|
||||
|
|
@ -68,13 +92,13 @@ export async function readEssentialConstsFromKv(regionId?: number): Promise<Esse
|
|||
console.error('readEssentialConstsFromKv failed:', error)
|
||||
}
|
||||
|
||||
const payload = await buildEssentialConsts(regionId)
|
||||
const payload = await buildEssentialConsts(boundId)
|
||||
|
||||
try {
|
||||
const kv = getGenKvNamespace()
|
||||
if (kv) await kv.put(key, JSON.stringify(payload))
|
||||
} catch (error) {
|
||||
console.error('backfill essential_consts failed:', error)
|
||||
console.error('backfill essentialConsts failed:', error)
|
||||
}
|
||||
|
||||
return payload
|
||||
|
|
|
|||
|
|
@ -4,13 +4,13 @@ import {
|
|||
seedStaffPermissions,
|
||||
seedRolePermissions,
|
||||
seedKeyValStore,
|
||||
seedGlobalConsts,
|
||||
type UnitSeedData,
|
||||
type RolePermissionAssignment,
|
||||
type KeyValSeedData,
|
||||
type StaffRoleName,
|
||||
type StaffPermissionName,
|
||||
} from '@/src/dbService'
|
||||
import { getMinOrderValue, getDeliveryCharge } from '@/src/lib/env-exporter'
|
||||
import { CONST_KEYS } from '@/src/lib/const-keys'
|
||||
import { refreshGenKv } from '@/src/lib/gen-store'
|
||||
|
||||
|
|
@ -48,25 +48,20 @@ export async function seed() {
|
|||
];
|
||||
await seedRolePermissions(rolePermissionAssignments);
|
||||
|
||||
// Seed key-val store constants
|
||||
const constantsToSeed: KeyValSeedData[] = [
|
||||
{ key: CONST_KEYS.readableOrderId, value: 0 },
|
||||
{ key: CONST_KEYS.minRegularOrderValue, value: getMinOrderValue() },
|
||||
{ key: CONST_KEYS.freeDeliveryThreshold, value: getMinOrderValue() },
|
||||
{ key: CONST_KEYS.deliveryCharge, value: getDeliveryCharge() },
|
||||
{ key: CONST_KEYS.flashFreeDeliveryThreshold, value: 500 },
|
||||
{ key: CONST_KEYS.flashDeliveryCharge, value: 69 },
|
||||
{ key: CONST_KEYS.popularItems, value: [] },
|
||||
{ key: CONST_KEYS.allItemsOrder, value: [] },
|
||||
// Seed global consts (global_consts table).
|
||||
const globalConstantsToSeed: KeyValSeedData[] = [
|
||||
{ key: CONST_KEYS.versionNum, value: '1.1.0' },
|
||||
{ key: CONST_KEYS.playStoreUrl, value: 'https://play.google.com/store/apps/details?id=in.freshyo.app' },
|
||||
{ key: CONST_KEYS.appStoreUrl, value: 'https://apps.apple.com/in/app/freshyo/id6756889077' },
|
||||
{ key: CONST_KEYS.isFlashDeliveryEnabled, value: false },
|
||||
{ key: CONST_KEYS.supportMobile, value: '8688182552' },
|
||||
{ key: CONST_KEYS.supportEmail, value: 'qushammohd@gmail.com' },
|
||||
{ key: CONST_KEYS.welcomeMessage, value: "Hi! Thank you for your first order at Freshyo. We're glad to have you." },
|
||||
{ key: CONST_KEYS.internalAppVersion, value: 1 },
|
||||
];
|
||||
await seedKeyValStore(constantsToSeed);
|
||||
await seedGlobalConsts(globalConstantsToSeed);
|
||||
|
||||
// Seed legacy leftover consts (key_val_store table).
|
||||
const legacyConstantsToSeed: KeyValSeedData[] = [
|
||||
{ key: CONST_KEYS.readableOrderId, value: 0 },
|
||||
];
|
||||
await seedKeyValStore(legacyConstantsToSeed);
|
||||
|
||||
// Mirror the seeded constants into KV for client reads.
|
||||
await refreshGenKv();
|
||||
|
|
|
|||
74
apps/backend/src/map-assets/jcl.geojson
Normal file
74
apps/backend/src/map-assets/jcl.geojson
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
{
|
||||
"type": "FeatureCollection",
|
||||
"features": [
|
||||
{
|
||||
"type": "Feature",
|
||||
"properties": {
|
||||
"name": "Jadcherla"
|
||||
},
|
||||
"geometry": {
|
||||
"type": "Polygon",
|
||||
"coordinates": [
|
||||
[
|
||||
[
|
||||
78.1403916,
|
||||
16.744066
|
||||
],
|
||||
[
|
||||
78.1548681,
|
||||
16.7415277
|
||||
],
|
||||
[
|
||||
78.1593669,
|
||||
16.7523755
|
||||
],
|
||||
[
|
||||
78.1621315,
|
||||
16.7630654
|
||||
],
|
||||
[
|
||||
78.1620705,
|
||||
16.7692272
|
||||
],
|
||||
[
|
||||
78.1564687,
|
||||
16.7758419
|
||||
],
|
||||
[
|
||||
78.1513873,
|
||||
16.7783785
|
||||
],
|
||||
[
|
||||
78.1455877,
|
||||
16.7796921
|
||||
],
|
||||
[
|
||||
78.1326433,
|
||||
16.781202
|
||||
],
|
||||
[
|
||||
78.123043,
|
||||
16.7805196
|
||||
],
|
||||
[
|
||||
78.118775,
|
||||
16.7757046
|
||||
],
|
||||
[
|
||||
78.1173809,
|
||||
16.7685992
|
||||
],
|
||||
[
|
||||
78.1205895,
|
||||
16.7633171
|
||||
],
|
||||
[
|
||||
78.1403916,
|
||||
16.744066
|
||||
]
|
||||
]
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,59 +1,60 @@
|
|||
import { router, protectedProcedure } from '@/src/trpc/trpc-index'
|
||||
import { z } from 'zod';
|
||||
import { computeConstants } from '@/src/lib/const-store'
|
||||
import { refreshGenKv } from '@/src/lib/gen-store'
|
||||
import { CONST_KEYS } from '@/src/lib/const-keys'
|
||||
import { refreshGenKv, refreshGenKvForRegion } from '@/src/lib/gen-store'
|
||||
import { CONST_SCOPE } from '@/src/lib/const-keys'
|
||||
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
|
||||
import { getAllConstants as getAllConstantsFromDb, upsertConstants as upsertConstantsInDb } from '@/src/dbService'
|
||||
import {
|
||||
getAllConstants as getAllConstantsFromDb,
|
||||
upsertConstants as upsertConstantsInDb,
|
||||
getAllGlobalConsts,
|
||||
upsertGlobalConsts,
|
||||
getLegacyConsts,
|
||||
upsertLegacyConsts,
|
||||
} from '@/src/dbService'
|
||||
import type { Constant, ConstantUpdateResult } from '@packages/shared'
|
||||
|
||||
// Constants that are baked into the versioned cache files (products.json etc.)
|
||||
// — changing them requires regenerating the cache so the user app picks it up.
|
||||
const CACHE_AFFECTING_KEYS: string[] = [
|
||||
CONST_KEYS.tagsOrder,
|
||||
]
|
||||
const CACHE_AFFECTING_KEYS: string[] = ['tagsOrder']
|
||||
|
||||
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 constRouter = router({
|
||||
// Backward-compat: merged global + legacy view. Writes route by key scope.
|
||||
getConstants: protectedProcedure
|
||||
.query(async (): Promise<Constant[]> => {
|
||||
// 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<ConstantUpdateResult> => {
|
||||
.input(constantsInput)
|
||||
.mutation(async ({ input, ctx }): Promise<ConstantUpdateResult> => {
|
||||
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<Constant[]> => {
|
||||
const values = await getAllGlobalConsts()
|
||||
return Object.entries(values).map(([key, value]) => ({ key, value }))
|
||||
}),
|
||||
|
||||
updateGlobalConstants: protectedProcedure
|
||||
.input(constantsInput)
|
||||
.mutation(async ({ input }): Promise<ConstantUpdateResult> => {
|
||||
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<Constant[]> => {
|
||||
const values = await getLegacyConsts()
|
||||
return Object.entries(values).map(([key, value]) => ({ key, value }))
|
||||
}),
|
||||
|
||||
updateLegacyConstants: protectedProcedure
|
||||
.input(constantsInput)
|
||||
.mutation(async ({ input }): Promise<ConstantUpdateResult> => {
|
||||
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),
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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 }
|
||||
}),
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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<typeof turfPolygon>
|
||||
|
||||
// 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<StoresSummaryResponse> => {
|
||||
// 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<StoresSummaryResponse> => {
|
||||
// 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<ResolvedRegion | null> => {
|
||||
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 = `<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%;">
|
||||
<h1 style="font-size: 72px">You're using an old version of app. please restart to update. Just close and open</h1>
|
||||
<h1 style="font-size: 36px; margin-top: 48px">With love, from Freshyo</h5>
|
||||
</div>`
|
||||
|
||||
const response = await readEssentialConstsFromKv(input.regionId);
|
||||
<h1 style="font-size: 72px">You're using an old version of app. please restart to update. Just close and open</h1>
|
||||
<h1 style="font-size: 36px; margin-top: 48px">With love, from Freshyo</h5>
|
||||
</div>`
|
||||
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -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<number, (typeof perRegion[number]['tags'])[number]>()
|
||||
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 }
|
||||
}),
|
||||
|
||||
|
|
|
|||
52
apps/backend/src/trpc/apis/superadmin-apis/apis/const.ts
Normal file
52
apps/backend/src/trpc/apis/superadmin-apis/apis/const.ts
Normal file
|
|
@ -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<Constant[]> => {
|
||||
const values = await getAllGlobalConsts()
|
||||
return Object.entries(values).map(([key, value]) => ({ key, value }))
|
||||
}),
|
||||
|
||||
updateGlobalConstants: superadminProcedure
|
||||
.input(constantsInput)
|
||||
.mutation(async ({ input }): Promise<ConstantUpdateResult> => {
|
||||
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<Constant[]> => {
|
||||
const values = await getLegacyConsts()
|
||||
return Object.entries(values).map(([key, value]) => ({ key, value }))
|
||||
}),
|
||||
|
||||
updateLegacyConstants: superadminProcedure
|
||||
.input(constantsInput)
|
||||
.mutation(async ({ input }): Promise<ConstantUpdateResult> => {
|
||||
await upsertLegacyConsts(toRows(input.constants))
|
||||
return {
|
||||
success: true,
|
||||
updatedCount: input.constants.length,
|
||||
keys: input.constants.map((c) => c.key),
|
||||
}
|
||||
}),
|
||||
})
|
||||
|
|
@ -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 }) => {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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<string, any>
|
||||
|
||||
// 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<string, string> = {
|
||||
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<string, string> = {
|
|||
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<string, boolean> = {
|
||||
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<string, ConstValueType> = {
|
||||
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<ConstantInputProps> = ({ constantKey, value, setFieldValue }) => {
|
||||
const fieldName = constantKey
|
||||
|
||||
if (constantKey === 'popularItems') {
|
||||
return (
|
||||
<div>
|
||||
<MyText className="mb-2 block text-sm font-medium text-gray-700">
|
||||
{CONST_LABELS[constantKey] || constantKey}
|
||||
</MyText>
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
className="flex w-full cursor-not-allowed items-center justify-center rounded-lg border-2 border-dashed border-blue-200 bg-blue-50 p-4 opacity-70"
|
||||
>
|
||||
<Pencil className="mr-2 h-5 w-5 text-blue-500" />
|
||||
<span className="font-medium text-blue-700">
|
||||
Manage Popular Items ({Array.isArray(value) ? value.length : 0} items)
|
||||
</span>
|
||||
<ChevronRight className="ml-2 h-5 w-5 text-blue-500" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (constantKey === 'allItemsOrder') {
|
||||
return (
|
||||
<div>
|
||||
<MyText className="mb-2 block text-sm font-medium text-gray-700">
|
||||
{CONST_LABELS[constantKey] || constantKey}
|
||||
</MyText>
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
className="flex w-full cursor-not-allowed items-center justify-center rounded-lg border-2 border-dashed border-green-200 bg-green-50 p-4 opacity-70"
|
||||
>
|
||||
<ListOrdered className="mr-2 h-5 w-5 text-green-600" />
|
||||
<span className="font-medium text-green-700">
|
||||
Manage All Visible Items ({Array.isArray(value) ? value.length : 0} items)
|
||||
</span>
|
||||
<ChevronRight className="ml-2 h-5 w-5 text-green-600" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (typeof value === 'boolean') {
|
||||
return (
|
||||
<div>
|
||||
|
|
@ -140,23 +115,6 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
|
|||
)
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return (
|
||||
<PInput
|
||||
topLabel={CONST_LABELS[constantKey] || constantKey}
|
||||
value={value.join(', ')}
|
||||
onChange={(e) => {
|
||||
const arrayValue = e.target.value
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length > 0)
|
||||
setFieldValue(fieldName, arrayValue)
|
||||
}}
|
||||
placeholder="Enter comma separated values"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<PInput
|
||||
topLabel={CONST_LABELS[constantKey] || constantKey}
|
||||
|
|
@ -168,41 +126,93 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ 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<string, any> = {}
|
||||
for (const row of globalConstants ?? []) map[row.key] = row.value
|
||||
return map
|
||||
}, [globalConstants])
|
||||
|
||||
if (changedConstants.length === 0) {
|
||||
const legacyValueByKey = useMemo(() => {
|
||||
const map: Record<string, any> = {}
|
||||
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 (
|
||||
<div className="flex flex-1 items-center justify-center p-8">
|
||||
<MyText className="text-gray-500">Loading constants...</MyText>
|
||||
|
|
@ -210,19 +220,6 @@ function CustomizeApp() {
|
|||
)
|
||||
}
|
||||
|
||||
if (!constants) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center p-8">
|
||||
<MyText className="text-gray-500">Failed to load constants</MyText>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const initialValues: ConstantFormData = constants.reduce((acc, constant) => {
|
||||
acc[constant.key] = constant.value ?? ''
|
||||
return acc
|
||||
}, {} as ConstantFormData)
|
||||
|
||||
return (
|
||||
<AppContainer>
|
||||
<div className="bg-gray-50 p-4">
|
||||
|
|
@ -230,39 +227,55 @@ function CustomizeApp() {
|
|||
Customize App Constants
|
||||
</MyText>
|
||||
<MyText className="mb-6 block text-gray-600">
|
||||
Modify application constants. Changes will take effect immediately.
|
||||
Global constants apply app-wide. Region and per-bound settings are managed from the
|
||||
Regions page.
|
||||
</MyText>
|
||||
|
||||
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
|
||||
{({ handleSubmit, values, setFieldValue }) => (
|
||||
<form onSubmit={handleSubmit}>
|
||||
{constants.map((constant) => {
|
||||
if (!CONST_VISIBILITY[constant.key]) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={constant.key} className="mb-4">
|
||||
<ConstantInput
|
||||
constantKey={constant.key}
|
||||
value={values[constant.key]}
|
||||
setFieldValue={setFieldValue}
|
||||
/>
|
||||
<div className="mb-6 rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
|
||||
<MyText className="mb-4 block font-semibold text-gray-900">Global</MyText>
|
||||
<Formik initialValues={globalInitialValues} enableReinitialize onSubmit={handleGlobalSubmit}>
|
||||
{({ handleSubmit, values, setFieldValue }) => (
|
||||
<form onSubmit={handleSubmit}>
|
||||
{globalKeys.map((key) => (
|
||||
<div key={key} className="mb-4">
|
||||
<ConstantInput constantKey={key} value={values[key]} setFieldValue={setFieldValue} />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
))}
|
||||
<MyButton
|
||||
type="submit"
|
||||
disabled={isUpdatingGlobals}
|
||||
fullWidth
|
||||
className={`mt-6 rounded-lg bg-blue-500 p-4 text-base text-white ${isUpdatingGlobals ? 'opacity-50' : ''}`}
|
||||
>
|
||||
{isUpdatingGlobals ? 'Updating...' : 'Save global changes'}
|
||||
</MyButton>
|
||||
</form>
|
||||
)}
|
||||
</Formik>
|
||||
</div>
|
||||
|
||||
<MyButton
|
||||
type="submit"
|
||||
disabled={isUpdating}
|
||||
fullWidth
|
||||
className={`mt-6 rounded-lg bg-blue-500 p-4 text-base text-white ${isUpdating ? 'opacity-50' : ''}`}
|
||||
>
|
||||
{isUpdating ? 'Updating...' : 'Save Changes'}
|
||||
</MyButton>
|
||||
</form>
|
||||
)}
|
||||
</Formik>
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
|
||||
<MyText className="mb-4 block font-semibold text-gray-900">Legacy</MyText>
|
||||
<Formik initialValues={legacyInitialValues} enableReinitialize onSubmit={handleLegacySubmit}>
|
||||
{({ handleSubmit, values, setFieldValue }) => (
|
||||
<form onSubmit={handleSubmit}>
|
||||
{legacyKeys.map((key) => (
|
||||
<div key={key} className="mb-4">
|
||||
<ConstantInput constantKey={key} value={values[key]} setFieldValue={setFieldValue} />
|
||||
</div>
|
||||
))}
|
||||
<MyButton
|
||||
type="submit"
|
||||
disabled={isUpdatingLegacy}
|
||||
fullWidth
|
||||
className={`mt-6 rounded-lg bg-blue-500 p-4 text-base text-white ${isUpdatingLegacy ? 'opacity-50' : ''}`}
|
||||
>
|
||||
{isUpdatingLegacy ? 'Updating...' : 'Save legacy changes'}
|
||||
</MyButton>
|
||||
</form>
|
||||
)}
|
||||
</Formik>
|
||||
</div>
|
||||
</div>
|
||||
</AppContainer>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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<string, string> = {
|
|||
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<number | null>(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.
|
||||
</MyText>
|
||||
|
||||
<div className="mb-6 rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
|
||||
<MyText className="mb-3 block font-semibold text-gray-900">Add a region</MyText>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<PInput
|
||||
topLabel="Name"
|
||||
value={newRegionName}
|
||||
onChange={(e) => setNewRegionName(e.target.value)}
|
||||
placeholder="e.g. Mahabubnagar"
|
||||
/>
|
||||
<PInput
|
||||
topLabel="Description"
|
||||
value={newRegionDescription}
|
||||
onChange={(e) => setNewRegionDescription(e.target.value)}
|
||||
placeholder="Optional"
|
||||
/>
|
||||
</div>
|
||||
<MyButton
|
||||
disabled={!newRegionName.trim() || createRegion.isPending}
|
||||
onClick={async () => {
|
||||
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'}
|
||||
</MyButton>
|
||||
</div>
|
||||
<CreateRegionForm onCreated={(regionId) => setSelectedRegionId(regionId)} />
|
||||
|
||||
{regionsQuery.isLoading && <MyText className="text-gray-500">Loading regions...</MyText>}
|
||||
|
||||
|
|
@ -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<BoundDraft[]>([emptyBound()])
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const creating = createRegion.isPending
|
||||
|
||||
const updateBound = (index: number, patch: Partial<BoundDraft>) =>
|
||||
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 (
|
||||
<div className="mb-6 rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
|
||||
<MyText className="mb-1 block font-semibold text-gray-900">Add a region</MyText>
|
||||
<MyText className="mb-3 block text-gray-600">
|
||||
A region must be created with at least one delivery bound.
|
||||
</MyText>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<PInput
|
||||
topLabel="Name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="e.g. Mahabubnagar"
|
||||
/>
|
||||
<PInput
|
||||
topLabel="Description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Optional"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-5 rounded-lg border border-gray-200 bg-gray-50 p-4">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<MyText className="block text-sm font-semibold text-gray-700">
|
||||
Bounds ({bounds.length})
|
||||
</MyText>
|
||||
<MyButton
|
||||
onClick={() => setBounds((prev) => [...prev, emptyBound()])}
|
||||
className="rounded-lg border border-gray-300 px-3 py-1.5 text-xs text-gray-700"
|
||||
>
|
||||
+ Add another bound
|
||||
</MyButton>
|
||||
</div>
|
||||
|
||||
{bounds.map((bound, index) => (
|
||||
<div key={index} className="mb-4 rounded-lg bg-white p-3">
|
||||
<div className="mb-1 flex items-center justify-between">
|
||||
<MyText className="block text-xs font-bold uppercase tracking-wide text-gray-500">
|
||||
Bound {index + 1}
|
||||
</MyText>
|
||||
{bounds.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeBound(index)}
|
||||
className="text-xs text-red-500 hover:underline"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<PInput
|
||||
topLabel="Description (optional)"
|
||||
value={bound.description}
|
||||
onChange={(e) => updateBound(index, { description: e.target.value })}
|
||||
placeholder="e.g. Mbnr-1"
|
||||
/>
|
||||
<PInput
|
||||
topLabel="Priority (lower = higher precedence)"
|
||||
value={bound.priority}
|
||||
onChange={(e) => updateBound(index, { priority: e.target.value })}
|
||||
placeholder="1"
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<MyText className="mb-1 block text-sm font-medium text-gray-700">GeoJSON</MyText>
|
||||
<textarea
|
||||
value={bound.geojson}
|
||||
onChange={(e) => updateBound(index, { geojson: e.target.value })}
|
||||
rows={6}
|
||||
placeholder='{"type":"FeatureCollection","features":[...]}'
|
||||
className="w-full rounded-lg border border-gray-300 p-3 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{error && <MyText className="mt-2 block text-sm text-red-600">{error}</MyText>}
|
||||
<MyButton
|
||||
disabled={!canSubmit}
|
||||
onClick={handleSubmit}
|
||||
className="mt-4 rounded-lg bg-blue-500 px-4 py-2 text-white disabled:opacity-50"
|
||||
>
|
||||
{creating ? 'Creating...' : 'Create region'}
|
||||
</MyButton>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RegionDetail({ regionId }: { regionId: number }) {
|
||||
const regionQuery = trpc.superadmin.regions.get.useQuery({ id: regionId })
|
||||
const [activeBoundId, setActiveBoundId] = useState<number | null>(null)
|
||||
|
|
@ -159,6 +287,10 @@ function RegionDetail({ regionId }: { regionId: number }) {
|
|||
/>
|
||||
)}
|
||||
|
||||
<RegionConstantsEditor regionId={regionId} />
|
||||
|
||||
<div className="my-5 border-t border-gray-200" />
|
||||
|
||||
{bounds.length === 0 && !showAddBound && (
|
||||
<MyText className="block text-gray-500">
|
||||
No bounds yet. Add at least one bound so this region can take orders.
|
||||
|
|
@ -262,6 +394,76 @@ function AddBoundForm({ regionId, onCreated }: { regionId: number; onCreated: (i
|
|||
)
|
||||
}
|
||||
|
||||
function RegionConstantsEditor({ regionId }: { regionId: number }) {
|
||||
const constantsQuery = trpc.superadmin.regions.getRegionConstants.useQuery({ regionId })
|
||||
const updateConstants = trpc.superadmin.regions.updateRegionConstants.useMutation({
|
||||
onSuccess: () => constantsQuery.refetch(),
|
||||
})
|
||||
|
||||
const [draft, setDraft] = useState<Record<string, string>>({})
|
||||
const [initialised, setInitialised] = useState<number | null>(null)
|
||||
|
||||
const valueByKey: Record<string, string | null> = {}
|
||||
for (const row of constantsQuery.data ?? []) valueByKey[row.key] = row.value as string | null
|
||||
|
||||
// Re-initialise the draft whenever the selected region changes.
|
||||
if (initialised !== regionId && constantsQuery.isSuccess) {
|
||||
const next: Record<string, string> = {}
|
||||
for (const key of REGION_SETTING_KEYS) next[key] = valueByKey[key] ?? ''
|
||||
setDraft(next)
|
||||
setInitialised(regionId)
|
||||
}
|
||||
|
||||
if (constantsQuery.isLoading) {
|
||||
return <MyText className="block text-gray-500">Loading region settings...</MyText>
|
||||
}
|
||||
|
||||
const handleSave = () => {
|
||||
updateConstants.mutate({
|
||||
regionId,
|
||||
constants: REGION_SETTING_KEYS.map((key) => ({ key, value: draft[key] ?? '' })),
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mb-4">
|
||||
<MyText className="mb-1 block font-semibold text-gray-900">Region settings</MyText>
|
||||
<MyText className="mb-3 block text-sm text-gray-500">
|
||||
These apply to every bound in this region.
|
||||
</MyText>
|
||||
{REGION_SETTING_KEYS.map((key) => (
|
||||
<div key={key} className="mb-3">
|
||||
{isBooleanSetting(key) ? (
|
||||
<label className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(draft[key] ?? '') === 'true'}
|
||||
onChange={(e) => setDraft((prev) => ({ ...prev, [key]: e.target.checked ? 'true' : 'false' }))}
|
||||
/>
|
||||
<MyText className="block text-sm font-medium text-gray-700">
|
||||
{SETTING_LABELS[key] || key}
|
||||
</MyText>
|
||||
</label>
|
||||
) : (
|
||||
<PInput
|
||||
topLabel={SETTING_LABELS[key] || key}
|
||||
value={draft[key] ?? ''}
|
||||
onChange={(e) => setDraft((prev) => ({ ...prev, [key]: e.target.value }))}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<MyButton
|
||||
onClick={handleSave}
|
||||
disabled={updateConstants.isPending}
|
||||
className="mt-2 rounded-lg bg-blue-500 px-4 py-2 text-white disabled:opacity-50"
|
||||
>
|
||||
{updateConstants.isPending ? 'Saving...' : 'Save region settings'}
|
||||
</MyButton>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function BoundSettingsEditor({ boundId }: { boundId: number }) {
|
||||
const settingsQuery = trpc.superadmin.regions.boundSettings.useQuery({ boundId })
|
||||
const updateSettings = trpc.superadmin.regions.updateBoundSettings.useMutation({
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import React, { useState, useCallback, useMemo, memo, useRef, useEffect } from "react";
|
||||
import { View, Dimensions, Image, RefreshControl } from "react-native";
|
||||
import { View, Dimensions, Image, RefreshControl, SectionList } from "react-native";
|
||||
import { ScrollView } from "react-native-gesture-handler";
|
||||
import { useRouter } from "expo-router";
|
||||
import {
|
||||
|
|
@ -28,6 +28,7 @@ import { useCentralProductStore } from "@/src/store/centralProductStore";
|
|||
import FloatingCartBar from "@/components/floating-cart-bar";
|
||||
import { useUserDetails } from "@/src/contexts/AuthContext";
|
||||
import TabLayoutWrapper from "@/components/TabLayoutWrapper";
|
||||
import LocationBar from "@/src/components/LocationBar";
|
||||
import { useNavigationStore } from "@/src/store/navigationStore";
|
||||
import NextOrderGlimpse from "@/components/NextOrderGlimpse";
|
||||
dayjs.extend(relativeTime);
|
||||
|
|
@ -640,6 +641,17 @@ export default function Dashboard() {
|
|||
// <Image style={{ width: 150, height: 235 }} source={{ uri: item.images[0]}} />
|
||||
), [handleProductPress]);
|
||||
|
||||
const pageTint = activeTagId == null ? '#FFFFFF' : getTagColor(activeTagId).pageBg;
|
||||
const pageTintStyle = useMemo(() => [
|
||||
tw`flex-1`,
|
||||
{ backgroundColor: '#FFFFFF' }
|
||||
], [pageTint]);
|
||||
|
||||
const searchBarContainerStyle = useMemo(() => [
|
||||
tw`w-full px-4 pt-4 pb-0`,
|
||||
{ backgroundColor: '#FFFFFF' }
|
||||
], [pageTint]);
|
||||
|
||||
const listHeader = useMemo(() => (
|
||||
<ListHeader
|
||||
dashboardTags={dashboardTags}
|
||||
|
|
@ -654,17 +666,6 @@ export default function Dashboard() {
|
|||
/>
|
||||
), [dashboardTags, activeTagId, productsByTagId, expandedByTagId, handleToggleExpand, handleProductPress, storesData, sortedSlots]);
|
||||
|
||||
const pageTint = activeTagId == null ? '#FFFFFF' : getTagColor(activeTagId).pageBg;
|
||||
const pageTintStyle = useMemo(() => [
|
||||
tw`flex-1`,
|
||||
{ backgroundColor: '#FFFFFF' }
|
||||
], [pageTint]);
|
||||
|
||||
const searchBarContainerStyle = useMemo(() => [
|
||||
tw`w-full px-4 pt-4 pb-0`,
|
||||
{ backgroundColor: '#FFFFFF' }
|
||||
], [pageTint]);
|
||||
|
||||
const listContentContainerStyle = useMemo(() => [
|
||||
tw`pb-24`,
|
||||
staticStyles.flatListContent
|
||||
|
|
@ -694,34 +695,52 @@ export default function Dashboard() {
|
|||
return (
|
||||
<TabLayoutWrapper style={{ backgroundColor: '#FFFFFF' }}>
|
||||
<View style={pageTintStyle}>
|
||||
<View
|
||||
style={searchBarContainerStyle}
|
||||
>
|
||||
<SearchBar
|
||||
testID="home-search"
|
||||
value={""}
|
||||
onChangeText={() => { }}
|
||||
onPress={handleSearchPress}
|
||||
editable={false}
|
||||
containerStyle={tw`bg-white`}
|
||||
onSubmitEditing={() => {
|
||||
if (inputQuery.trim()) {
|
||||
router.push(`/(drawer)/(tabs)/home/search-results?q=${encodeURIComponent(inputQuery.trim())}`);
|
||||
}
|
||||
}}
|
||||
returnKeyType="search"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<MyFlatList
|
||||
data={displayedProducts.slice(0, visibleCount)}
|
||||
keyExtractor={(item) => item.id.toString()}
|
||||
numColumns={3}
|
||||
<SectionList
|
||||
sections={[{ data: [[], ...Array.from(
|
||||
{ length: Math.ceil(Math.min(displayedProducts.length, visibleCount) / 3) },
|
||||
(_, index) => displayedProducts.slice(index * 3, Math.min(index * 3 + 3, visibleCount))
|
||||
)] }]}
|
||||
keyExtractor={(row, index) => row.length ? row.map((item) => item.id).join('-') : 'catalog-header'}
|
||||
stickySectionHeadersEnabled
|
||||
style={{ backgroundColor: '#FFFFFF' }}
|
||||
contentContainerStyle={listContentContainerStyle}
|
||||
columnWrapperStyle={staticStyles.columnWrapper}
|
||||
renderItem={renderProductItem}
|
||||
ListHeaderComponent={listHeader}
|
||||
ListHeaderComponent={<LocationBar />}
|
||||
renderSectionHeader={() => (
|
||||
<View style={searchBarContainerStyle}>
|
||||
<SearchBar
|
||||
testID="home-search"
|
||||
value={""}
|
||||
onChangeText={() => { }}
|
||||
onPress={handleSearchPress}
|
||||
editable={false}
|
||||
containerStyle={tw`bg-white`}
|
||||
onSubmitEditing={() => {
|
||||
if (inputQuery.trim()) {
|
||||
router.push(`/(drawer)/(tabs)/home/search-results?q=${encodeURIComponent(inputQuery.trim())}`);
|
||||
}
|
||||
}}
|
||||
returnKeyType="search"
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
renderItem={({ item: row, index }) => index === 0 ? (
|
||||
<>
|
||||
{listHeader}
|
||||
{displayedProducts.length === 0 && (
|
||||
<View style={tw`items-center py-8`}>
|
||||
<MyText style={tw`text-gray-500`}>No products available</MyText>
|
||||
</View>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<View style={[staticStyles.columnWrapper, { flexDirection: 'row' }]}>
|
||||
{row.map((item) => (
|
||||
<React.Fragment key={item.id}>
|
||||
{renderProductItem({ item })}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
ListFooterComponent={
|
||||
hasMore ? (
|
||||
<View style={tw`items-center py-4`}>
|
||||
|
|
@ -744,11 +763,6 @@ export default function Dashboard() {
|
|||
colors={[theme.colors.brand500]}
|
||||
/>
|
||||
}
|
||||
ListEmptyComponent={
|
||||
<View style={tw`items-center py-8`}>
|
||||
<MyText style={tw`text-gray-500`}>No products available</MyText>
|
||||
</View>
|
||||
}
|
||||
// NOTE: do not add removeClippedSubviews here - it breaks touch
|
||||
// delivery to the nested horizontal scrollables in ListHeaderComponent
|
||||
// (tag tabs / slots) on Android.
|
||||
|
|
|
|||
|
|
@ -4,11 +4,12 @@ import { useRouter } from 'expo-router';
|
|||
import { useFocusEffect } from '@react-navigation/native';
|
||||
import { AppContainer, BottomDialog, MyText, tw, MyTouchableOpacity, ProfileImage, colors } from 'common-ui';
|
||||
import TabLayoutWrapper from '@/components/TabLayoutWrapper';
|
||||
import LocationBar from '@/src/components/LocationBar';
|
||||
import { LinearGradient } from 'expo-linear-gradient';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import NextOrderGlimpse from '@/components/NextOrderGlimpse';
|
||||
import RegionSelector from '@/src/components/RegionSelector';
|
||||
import { useRegionStore } from '@/src/store/regionStore';
|
||||
import { useRegion } from '@/src/hooks/useRegion';
|
||||
import { useAuth } from '@/src/contexts/AuthContext';
|
||||
import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget';
|
||||
|
||||
|
|
@ -17,8 +18,7 @@ export default function Me() {
|
|||
const { logout } = useAuth();
|
||||
const { getNavigationTarget } = useNavigationTarget();
|
||||
const [regionDialogOpen, setRegionDialogOpen] = useState(false);
|
||||
const selectedRegion = useRegionStore((state) => state.selectedRegion);
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId);
|
||||
const { region: selectedRegion, regionId } = useRegion();
|
||||
|
||||
useFocusEffect(() => {
|
||||
const target = getNavigationTarget();
|
||||
|
|
@ -110,6 +110,7 @@ export default function Me() {
|
|||
showsVerticalScrollIndicator={false}
|
||||
contentContainerStyle={tw`pb-8`}
|
||||
>
|
||||
<LocationBar />
|
||||
{/* Minimal Header Section */}
|
||||
<View style={tw`px-6 pt-8 pb-10 flex-row items-center justify-between`}>
|
||||
<View>
|
||||
|
|
@ -180,7 +181,7 @@ export default function Me() {
|
|||
<View style={tw`h-96`}>
|
||||
<RegionSelector
|
||||
mode="switch"
|
||||
selectedRegionId={selectedRegionId}
|
||||
selectedRegionId={regionId}
|
||||
onComplete={() => setRegionDialogOpen(false)}
|
||||
onCancel={() => setRegionDialogOpen(false)}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import ProductCard from "@/components/ProductCard";
|
|||
import { useAllProducts } from "@/src/hooks/prominent-api-hooks";
|
||||
import FloatingCartBar from "@/components/floating-cart-bar";
|
||||
import TabLayoutWrapper from "@/components/TabLayoutWrapper";
|
||||
import LocationBar from "@/src/components/LocationBar";
|
||||
|
||||
const { width: screenWidth } = Dimensions.get("window");
|
||||
// Same 3-column hero card sizing used on the home page.
|
||||
|
|
@ -137,6 +138,7 @@ export default function Offers() {
|
|||
return (
|
||||
<TabLayoutWrapper>
|
||||
<ScrollView style={tw`flex-1`} contentContainerStyle={tw`pb-20`}>
|
||||
<LocationBar />
|
||||
<OffersSection
|
||||
title="Offers"
|
||||
subtitle="Great prices on select items"
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import { Ionicons } from "@expo/vector-icons";
|
|||
import { useStores } from "@/src/hooks/prominent-api-hooks";
|
||||
import { LinearGradient } from "expo-linear-gradient";
|
||||
import TabLayoutWrapper from "@/components/TabLayoutWrapper";
|
||||
import LocationBar from "@/src/components/LocationBar";
|
||||
import FloatingCartBar from "@/components/floating-cart-bar";
|
||||
import { useFocusEffect } from "expo-router";
|
||||
import { useNavigationStore } from "@/src/store/navigationStore";
|
||||
|
|
@ -216,7 +217,8 @@ export default function Stores() {
|
|||
showsVerticalScrollIndicator={false}
|
||||
ListHeaderComponent={
|
||||
<View style={tw`pt-6 pb-4`}>
|
||||
<View style={tw`flex-row items-center mb-2`}>
|
||||
<LocationBar />
|
||||
<View style={tw`flex-row items-center mb-2 mt-3`}>
|
||||
<LinearGradient
|
||||
colors={[theme.colors.brand500, theme.colors.brand700]}
|
||||
start={{ x: 0, y: 0 }}
|
||||
|
|
|
|||
|
|
@ -18,9 +18,8 @@ import { Provider as PaperProvider } from "react-native-paper";
|
|||
import { AuthProvider } from "@/src/contexts/AuthContext";
|
||||
import { trpc, trpcClient } from "@/src/trpc-client";
|
||||
import { SafeAreaView, SafeAreaProvider } from "react-native-safe-area-context";
|
||||
import LocationTestWrapper from "@/components/LocationTestWrapper";
|
||||
import HealthTestWrapper from "@/components/HealthTestWrapper";
|
||||
import FirstUserWrapper from "@/components/FirstUserWrapper";
|
||||
import HealthTestWrapper from "@/components/HealthTestWrapper";
|
||||
import UpdateChecker from "@/components/UpdateChecker";
|
||||
import CentralStoreInitializer from "@/src/components/CentralStoreInitializer";
|
||||
import { RefreshProvider } from "../../../packages/ui/src/lib/refresh-context";
|
||||
|
|
@ -74,15 +73,13 @@ export default function RootLayout() {
|
|||
<NotificationProvider>
|
||||
<NotifChecker />
|
||||
<PaperProvider>
|
||||
<LocationTestWrapper>
|
||||
<RefreshProvider queryClient={queryClient}>
|
||||
<RefreshProvider queryClient={queryClient}>
|
||||
<CentralStoreInitializer>
|
||||
<BackHandlerWrapper />
|
||||
<Stack screenOptions={{ headerShown: false }} />
|
||||
<AddToCartDialog />
|
||||
</CentralStoreInitializer>
|
||||
</RefreshProvider>
|
||||
</LocationTestWrapper>
|
||||
</PaperProvider>
|
||||
</NotificationProvider>
|
||||
</AuthProvider>
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import LocationAttacher from '@/src/components/LocationAttacher';
|
|||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||
import { trpc } from '@/src/trpc-client';
|
||||
import { useAuth } from '@/src/contexts/AuthContext';
|
||||
import { useRegionStore } from '@/src/store/regionStore';
|
||||
import { useRegion } from '@/src/hooks/useRegion';
|
||||
import { confirmRegionSwitch } from '@/src/lib/region-switch';
|
||||
import * as Location from 'expo-location';
|
||||
|
||||
|
|
@ -32,7 +32,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
const router = useRouter();
|
||||
const scrollViewRef = useRef<ScrollView>(null);
|
||||
const { isAuthenticated } = useAuth();
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId);
|
||||
const { regionId: selectedRegionId } = useRegion();
|
||||
const { data: addresses } = trpc.user.address.getUserAddresses.useQuery(
|
||||
undefined,
|
||||
{ enabled: isAuthenticated }
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import React, { useState, useEffect } from 'react'
|
|||
import { View } from 'react-native'
|
||||
import { MyButton, StorageServiceCasual, tw, MyText } from 'common-ui'
|
||||
import type { ReactParentComponent } from '@packages/shared'
|
||||
import RegionGate from '@/src/components/RegionGate'
|
||||
import LocationTestWrapper from '@/components/LocationTestWrapper'
|
||||
|
||||
const FirstUserWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
||||
const [isFirstTime, setIsFirstTime] = useState<boolean | null>(null)
|
||||
|
|
@ -35,7 +35,7 @@ const FirstUserWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
|||
)
|
||||
}
|
||||
|
||||
return <RegionGate>{children}</RegionGate>
|
||||
return <LocationTestWrapper>{children}</LocationTestWrapper>
|
||||
}
|
||||
|
||||
export default FirstUserWrapper
|
||||
|
|
@ -1,108 +1,70 @@
|
|||
import React, { useState, useEffect } from 'react';
|
||||
import * as Location from 'expo-location';
|
||||
import { BackHandler, Platform } from 'react-native';
|
||||
import { ConfirmationDialog } from 'common-ui';
|
||||
import type { ReactParentComponent } from '@packages/shared';
|
||||
import { trpc } from '../src/trpc-client';
|
||||
import React, { useEffect } from 'react'
|
||||
import { ActivityIndicator, View } from 'react-native'
|
||||
import { MyText, theme, tw } from 'common-ui'
|
||||
import type { ReactParentComponent } from '@packages/shared'
|
||||
import { trpc } from '../src/trpc-client'
|
||||
import { useRegion } from '@/src/hooks/useRegion'
|
||||
import RegionSelector from '@/src/components/RegionSelector'
|
||||
import { isEmulator } from '@/src/lib/is-emulator'
|
||||
|
||||
// Emulator detection utility
|
||||
const isEmulator = (): boolean => {
|
||||
try {
|
||||
// Check for common emulator indicators
|
||||
const brand = (Platform.constants as any)?.Brand?.toLowerCase();
|
||||
const model = (Platform.constants as any)?.Model?.toLowerCase();
|
||||
const manufacturer = (Platform.constants as any)?.Manufacturer?.toLowerCase();
|
||||
|
||||
// Android emulator detection
|
||||
if (Platform.OS === 'android') {
|
||||
return (
|
||||
brand?.includes('generic') ||
|
||||
brand?.includes('unknown') ||
|
||||
model?.includes('emulator') ||
|
||||
model?.includes('sdk') ||
|
||||
model?.includes('android sdk') ||
|
||||
manufacturer?.includes('genymotion') ||
|
||||
manufacturer?.includes('unknown')
|
||||
);
|
||||
}
|
||||
|
||||
// iOS simulator detection
|
||||
if (Platform.OS === 'ios') {
|
||||
return (
|
||||
(Platform.constants as any)?.systemName?.includes('Simulator') ||
|
||||
!(Platform.constants as any)?.isDevice || // iOS simulator
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch (error) {
|
||||
// If detection fails, assume it's a real device to be safe
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Feature flag to enable/disable location warning dialogs
|
||||
const ENABLE_LOCATION_WARNINGS = false;
|
||||
const LoadingScreen: React.FC<{ label?: string }> = ({ label }) => (
|
||||
<View style={tw`flex-1 justify-center items-center bg-white`}>
|
||||
<ActivityIndicator size="large" color={theme.colors.brand500} />
|
||||
{label ? <MyText style={tw`text-gray-500 mt-4`}>{label}</MyText> : null}
|
||||
</View>
|
||||
)
|
||||
|
||||
/**
|
||||
* Region gate + location fallback.
|
||||
*
|
||||
* The browsing region is derived from the device location (see `useRegion`).
|
||||
* While that is in flight we show a spinner; once a region exists the app
|
||||
* renders. When the location is unusable — device location switched off,
|
||||
* permission denied, a simulator, or coordinates outside every region bound —
|
||||
* the user is asked to choose a region manually.
|
||||
*/
|
||||
const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
||||
// Skip location checks entirely for emulators
|
||||
if (isEmulator()) {
|
||||
return <>{children}</>;
|
||||
const {
|
||||
regionId,
|
||||
clearRegion,
|
||||
hydrated,
|
||||
isResolvingRegion,
|
||||
} = useRegion()
|
||||
|
||||
const { data: regions } = trpc.common.listRegions.useQuery()
|
||||
|
||||
// Validate the saved region against the live list. A stale/unknown id must
|
||||
// lead to selection, never a silent checkout fallback. Membership-only: no
|
||||
// setRegion here, so this effect can never re-trigger itself.
|
||||
useEffect(() => {
|
||||
if (!hydrated || !regions || regionId == null) return
|
||||
if (!regions.some((region) => region.id === regionId)) {
|
||||
clearRegion()
|
||||
}
|
||||
}, [hydrated, regions, regionId, clearRegion])
|
||||
|
||||
// A known region short-circuits every check below.
|
||||
if (regionId != null) {
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
// Enable location functionality for real devices
|
||||
const [locationDialogOpen, setLocationDialogOpen] = useState(false);
|
||||
const [locationErrorDialogOpen, setLocationErrorDialogOpen] = useState(false);
|
||||
const [userLocation, setUserLocation] = useState<Location.LocationObject | null>(null);
|
||||
|
||||
const { data: locationCheck } = trpc.common.checkLocationInPolygon.useQuery(
|
||||
{ lat: userLocation?.coords.latitude || 0, lng: userLocation?.coords.longitude || 0 },
|
||||
{ enabled: !!userLocation }
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (ENABLE_LOCATION_WARNINGS && locationCheck && !locationCheck.isInside) {
|
||||
setLocationErrorDialogOpen(true);
|
||||
}
|
||||
}, [locationCheck]);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const { status } = await Location.requestForegroundPermissionsAsync();
|
||||
if (status === 'granted') {
|
||||
const location = await Location.getCurrentPositionAsync({});
|
||||
setUserLocation(location);
|
||||
} else if (ENABLE_LOCATION_WARNINGS) {
|
||||
setLocationDialogOpen(true);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
// Wait for the persisted region to load before deciding: location tracking
|
||||
// must not start while a stored choice may still appear.
|
||||
if (!hydrated) {
|
||||
return <LoadingScreen />
|
||||
}
|
||||
|
||||
// Still deriving the region from device location.
|
||||
if (!isEmulator() && isResolvingRegion) {
|
||||
return <LoadingScreen label="Finding your region..." />
|
||||
}
|
||||
|
||||
// Location unavailable / denied / out of area -> choose a region manually.
|
||||
return (
|
||||
<>
|
||||
{children}
|
||||
<ConfirmationDialog
|
||||
open={locationDialogOpen}
|
||||
title="Location Permission Disabled"
|
||||
message="Your location may not be supported. We currently operate only in Mahabubnagar town."
|
||||
confirmText="Yes, Proceed"
|
||||
cancelText="Exit"
|
||||
positiveAction={() => setLocationDialogOpen(false)}
|
||||
negativeAction={() => BackHandler.exitApp()}
|
||||
/>
|
||||
<ConfirmationDialog
|
||||
open={locationErrorDialogOpen}
|
||||
title="Location Outside Service Area"
|
||||
message="Your current location is outside our supported area. We currently operate only in Mahabubnagar town. You can still proceed to browse our services."
|
||||
confirmText="Proceed Anyway"
|
||||
cancelText="Exit"
|
||||
positiveAction={() => setLocationErrorDialogOpen(false)}
|
||||
negativeAction={() => BackHandler.exitApp()}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
<View style={tw`flex-1 bg-white`}>
|
||||
<RegionSelector mode="gate" selectedRegionId={regionId} />
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
export default LocationTestWrapper;
|
||||
export default LocationTestWrapper
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
|||
import { trpc } from '@/src/trpc-client';
|
||||
import { useCentralProductStore } from '@/src/store/centralProductStore';
|
||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
||||
import { useRegionStore } from '@/src/store/regionStore';
|
||||
import { useRegion } from '@/src/hooks/useRegion';
|
||||
import { clearLocalCart } from '@/hooks/cart-query-hooks';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { FontAwesome5, FontAwesome6 } from '@expo/vector-icons';
|
||||
|
|
@ -61,7 +61,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
|||
const products = useCentralProductStore((state) => state.products);
|
||||
const productsById = useCentralProductStore((state) => state.productsById);
|
||||
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId);
|
||||
const { regionId: selectedRegionId } = useRegion();
|
||||
|
||||
// Memoized flash-eligible product IDs
|
||||
const flashEligibleProductIds = useMemo(() => {
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { BottomDialog, MyTouchableOpacity, MyText, tw, theme } from 'common-ui';
|
|||
import { useAuth } from '@/src/contexts/AuthContext';
|
||||
import { trpc } from '@/src/trpc-client';
|
||||
import { useAddressStore } from '@/src/store/addressStore';
|
||||
import { useRegionStore } from '@/src/store/regionStore';
|
||||
import { useRegion } from '@/src/hooks/useRegion';
|
||||
import { confirmRegionSwitch } from '@/src/lib/region-switch';
|
||||
import { useSlots } from '@/src/hooks/prominent-api-hooks';
|
||||
import dayjs from 'dayjs';
|
||||
|
|
@ -41,7 +41,7 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
|
|||
const addresses = addressesData?.data || [];
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId);
|
||||
const { regionId: selectedRegionId } = useRegion();
|
||||
const { data: regions } = trpc.common.listRegions.useQuery();
|
||||
|
||||
// An address (selected or default) that belongs to another region than the
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { useRouter, usePathname } from 'expo-router';
|
|||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||
import { tw, theme, MyText, MyTouchableOpacity, MyFlatList, AppContainer, MiniQuantifier, SearchBar } from 'common-ui';
|
||||
import { trpc } from '@/src/trpc-client';
|
||||
import LocationBar from '@/src/components/LocationBar';
|
||||
import { useAllProducts, useStores, useSlots } from '@/src/hooks/prominent-api-hooks';
|
||||
import { AllProductsApiType } from '@backend/trpc/router';
|
||||
import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore';
|
||||
|
|
@ -519,6 +520,7 @@ export function FlashDeliveryProducts({ storeId:storeIdParent, baseUrl, onProduc
|
|||
numColumns={2}
|
||||
ListHeaderComponent={
|
||||
<View style={tw`px-4 pt-2`}>
|
||||
<LocationBar />
|
||||
<SearchBar
|
||||
value={searchQuery}
|
||||
onChangeText={setSearchQuery}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import { trpc } from '../trpc-client';
|
|||
import LocationAttacher from './LocationAttacher';
|
||||
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
|
||||
import type { AddressFormProps } from '@packages/shared';
|
||||
import { useRegionStore } from '@/src/store/regionStore';
|
||||
import { useRegion } from '@/src/hooks/useRegion';
|
||||
|
||||
const AddressForm: React.FC<AddressFormProps> = ({ onSuccess, initialValues, isEdit = false }) => {
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
|
@ -22,7 +22,7 @@ const AddressForm: React.FC<AddressFormProps> = ({ onSuccess, initialValues, isE
|
|||
: null
|
||||
);
|
||||
|
||||
const browsingRegionId = useRegionStore((state) => state.selectedRegionId);
|
||||
const { regionId: browsingRegionId } = useRegion();
|
||||
const { data: regions } = trpc.common.listRegions.useQuery();
|
||||
|
||||
// Edits keep the stored region unless the user explicitly changes it; new
|
||||
|
|
|
|||
54
apps/user-ui/src/components/LocationBar.tsx
Normal file
54
apps/user-ui/src/components/LocationBar.tsx
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import React, { useState } from 'react'
|
||||
import { View } from 'react-native'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
import { tw, theme, MyText, MyTouchableOpacity, BottomDialog } from 'common-ui'
|
||||
import { useRegion } from '@/src/hooks/useRegion'
|
||||
import RegionSelector from '@/src/components/RegionSelector'
|
||||
|
||||
/**
|
||||
* Location bar shown at the top of every top-level tab screen.
|
||||
* Rendered INSIDE the scroll content (first item / ListHeaderComponent) so it
|
||||
* scrolls out with the page instead of sticking. Tapping opens a bottom
|
||||
* sheet with the region list; switching is confirmed inside RegionSelector.
|
||||
*/
|
||||
const LocationBar: React.FC = () => {
|
||||
const [sheetOpen, setSheetOpen] = useState(false)
|
||||
const { region, regionId } = useRegion()
|
||||
|
||||
return (
|
||||
<View style={tw`px-4 pt-3 pb-1`}>
|
||||
<MyTouchableOpacity
|
||||
testID="location-bar"
|
||||
activeOpacity={0.85}
|
||||
onPress={() => setSheetOpen(true)}
|
||||
style={tw`flex-row items-center bg-white border border-gray-100 rounded-2xl px-4 py-3 shadow-sm`}
|
||||
>
|
||||
<View style={tw`w-9 h-9 rounded-full bg-blue-50 items-center justify-center mr-3`}>
|
||||
<MaterialIcons name="location-on" size={20} color={theme.colors.brand500} />
|
||||
</View>
|
||||
<View style={tw`flex-1`}>
|
||||
<MyText style={tw`text-gray-400 text-[11px] font-semibold uppercase tracking-wider`}>
|
||||
Deliver to
|
||||
</MyText>
|
||||
<MyText style={tw`text-gray-900 text-base font-bold`} numberOfLines={1}>
|
||||
{region?.name ?? 'Choose your region'}
|
||||
</MyText>
|
||||
</View>
|
||||
<MaterialIcons name="keyboard-arrow-down" size={24} color="#9CA3AF" />
|
||||
</MyTouchableOpacity>
|
||||
|
||||
{sheetOpen && (
|
||||
<BottomDialog open={sheetOpen} onClose={() => setSheetOpen(false)}>
|
||||
<RegionSelector
|
||||
mode="switch"
|
||||
selectedRegionId={regionId}
|
||||
onComplete={() => setSheetOpen(false)}
|
||||
onCancel={() => setSheetOpen(false)}
|
||||
/>
|
||||
</BottomDialog>
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
export default LocationBar
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
import React, { useEffect, useState } from 'react'
|
||||
import { ActivityIndicator, View } from 'react-native'
|
||||
import { tw, theme } from 'common-ui'
|
||||
import type { ReactParentComponent } from '@packages/shared'
|
||||
import { trpc } from '@/src/trpc-client'
|
||||
import { useRegionStore } from '@/src/store/regionStore'
|
||||
import RegionSelector from './RegionSelector'
|
||||
|
||||
/**
|
||||
* Blocks the app until a valid browsing region exists. On first launch (or when
|
||||
* the saved region no longer exists) it shows the full-screen RegionSelector.
|
||||
* Once a region is saved, children render untouched.
|
||||
*/
|
||||
const RegionGate: React.FC<ReactParentComponent> = ({ children }) => {
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const selectedRegion = useRegionStore((state) => state.selectedRegion)
|
||||
const setRegion = useRegionStore((state) => state.setRegion)
|
||||
const clearRegion = useRegionStore((state) => state.clearRegion)
|
||||
|
||||
const [hasHydrated, setHasHydrated] = useState<boolean>(
|
||||
() => useRegionStore.persist.hasHydrated()
|
||||
)
|
||||
const { data: regions } = trpc.common.listRegions.useQuery()
|
||||
|
||||
// Wait for the persisted region to load before deciding whether to prompt.
|
||||
useEffect(() => {
|
||||
if (useRegionStore.persist.hasHydrated()) {
|
||||
setHasHydrated(true)
|
||||
return
|
||||
}
|
||||
const unsubscribe = useRegionStore.persist.onFinishHydration(() => setHasHydrated(true))
|
||||
return unsubscribe
|
||||
}, [])
|
||||
|
||||
// Validate the saved region against the live list. A stale/unknown id must
|
||||
// lead to selection, never a silent checkout fallback.
|
||||
useEffect(() => {
|
||||
if (!hasHydrated || !regions || selectedRegionId == null) return
|
||||
|
||||
const match = regions.find((region) => region.id === selectedRegionId)
|
||||
if (!match) {
|
||||
clearRegion()
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
selectedRegion?.id !== match.id ||
|
||||
selectedRegion?.name !== match.name ||
|
||||
selectedRegion?.description !== match.description
|
||||
) {
|
||||
setRegion(match)
|
||||
}
|
||||
}, [hasHydrated, regions, selectedRegionId, selectedRegion, setRegion, clearRegion])
|
||||
|
||||
if (!hasHydrated) {
|
||||
return (
|
||||
<View style={tw`flex-1 justify-center items-center bg-white`}>
|
||||
<ActivityIndicator size="large" color={theme.colors.brand500} />
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
if (selectedRegionId == null) {
|
||||
return <RegionSelector mode="gate" />
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default RegionGate
|
||||
|
|
@ -13,6 +13,8 @@ interface RegionSelectorProps {
|
|||
* 'switch' — content for a caller-owned dialog; shows a cart-clear confirmation.
|
||||
*/
|
||||
mode?: 'gate' | 'switch'
|
||||
/** Current browsing region id, for highlighting. Supplied by the caller so
|
||||
* this presentational picker never triggers location tracking itself. */
|
||||
selectedRegionId?: number | null
|
||||
onComplete?: (region: RegionSummary) => void
|
||||
onCancel?: () => void
|
||||
|
|
@ -31,7 +33,7 @@ const RegionSelector: React.FC<RegionSelectorProps> = ({
|
|||
const applySwitch = async (region: RegionSummary) => {
|
||||
setIsSwitching(true)
|
||||
try {
|
||||
await confirmRegionSwitch(region, queryClient)
|
||||
await confirmRegionSwitch(region, queryClient, region.effectiveBoundId ?? null)
|
||||
onComplete?.(region)
|
||||
} finally {
|
||||
setIsSwitching(false)
|
||||
|
|
|
|||
|
|
@ -2,39 +2,35 @@ import React, { useEffect, useState } from 'react'
|
|||
import { useQuery } from '@tanstack/react-query'
|
||||
import axios from 'axios'
|
||||
import { trpc } from '@/src/trpc-client'
|
||||
import type { ProductPriceFlags, EffectiveRegionSettings } from '@packages/shared'
|
||||
import type { ProductPriceFlags } from '@packages/shared'
|
||||
import { AllProductsApiType, StoresApiType, SlotsApiType, EssentialConstsApiType, StoreWithProductsApiType, AvailabilityApiType } from "@backend/trpc/router";
|
||||
import { CACHE_FILENAMES } from "@packages/shared";
|
||||
import { StorageServiceCasual } from 'common-ui';
|
||||
import { useRegionStore } from '@/src/store/regionStore'
|
||||
import { useRegion } from '@/src/hooks/useRegion'
|
||||
|
||||
// Discovery payload under the FIXED regional contract: the existing
|
||||
// essential-consts fields plus the browsing region's effective settings.
|
||||
// Declared locally from existing contracts so this file typechecks before
|
||||
// and after the backend adds the new fields.
|
||||
export type DiscoveryData = EssentialConstsApiType & {
|
||||
effectiveSettings?: EffectiveRegionSettings | null
|
||||
}
|
||||
// Discovery payload: the flat per-bound consts object (global + region + bound
|
||||
// merged by the backend) plus identity/env fields.
|
||||
export type DiscoveryData = EssentialConstsApiType
|
||||
|
||||
// The only persisted payload: the small essential-consts config object.
|
||||
// Keyed per browsing region so regions never share snapshots.
|
||||
const essentialConstsKey = (regionId: number) => `essential_consts_r${regionId}`
|
||||
// Keyed per bound so regions/bounds never share snapshots.
|
||||
const essentialConstsKey = (boundId: number) => `essential_consts_b${boundId}`
|
||||
|
||||
export const useGetEssentialConsts = () => {
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const { boundId } = useRegion()
|
||||
const [initialData, setInitialData] = useState<DiscoveryData | undefined>(undefined)
|
||||
const [isReady, setIsReady] = useState(false)
|
||||
|
||||
// Load the last persisted response for THIS region so config is available immediately.
|
||||
// Load the last persisted response for THIS bound so config is available immediately.
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setIsReady(false)
|
||||
setInitialData(undefined)
|
||||
if (selectedRegionId == null) {
|
||||
if (boundId == null) {
|
||||
setIsReady(true)
|
||||
return
|
||||
}
|
||||
StorageServiceCasual.getItem(essentialConstsKey(selectedRegionId)).then((raw) => {
|
||||
StorageServiceCasual.getItem(essentialConstsKey(boundId)).then((raw) => {
|
||||
if (cancelled) return
|
||||
if (raw) {
|
||||
try {
|
||||
|
|
@ -46,52 +42,33 @@ export const useGetEssentialConsts = () => {
|
|||
setIsReady(true)
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [selectedRegionId])
|
||||
}, [boundId])
|
||||
|
||||
// FIXED CONTRACT: essentialConsts REQUIRES {regionId}. The input is cast so
|
||||
// this typechecks against the current backend (which takes no input and
|
||||
// ignores the extra field at runtime) and the future one. tRPC includes the
|
||||
// input in the query key, so switching regions refetches discovery.
|
||||
const query = trpc.common.essentialConsts.useQuery({ regionId: selectedRegionId ?? 0 } as any, {
|
||||
// The backend resolves the flat payload for a single bound. tRPC includes the
|
||||
// input in the query key, so switching bounds refetches discovery.
|
||||
const query = trpc.common.essentialConsts.useQuery({ boundId: boundId ?? 0 }, {
|
||||
refetchInterval: 60000,
|
||||
enabled: isReady && selectedRegionId != null,
|
||||
enabled: isReady && boundId != null,
|
||||
placeholderData: initialData as any,
|
||||
})
|
||||
|
||||
// Persist the latest response under this region's key.
|
||||
// Persist the latest response under this bound's key.
|
||||
useEffect(() => {
|
||||
if (query.data && selectedRegionId != null) {
|
||||
StorageServiceCasual.setItem(essentialConstsKey(selectedRegionId), JSON.stringify(query.data))
|
||||
if (query.data && boundId != null) {
|
||||
StorageServiceCasual.setItem(essentialConstsKey(boundId), JSON.stringify(query.data))
|
||||
}
|
||||
}, [query.data, selectedRegionId])
|
||||
}, [query.data, boundId])
|
||||
|
||||
return { ...query, refetch: query.refetch }
|
||||
}
|
||||
|
||||
// Discovery data with the delivery/minimum display fields overridden from the
|
||||
// region's effective settings (numeric parse, global fallback). Display-only;
|
||||
// the backend remains authoritative for the actual charge.
|
||||
export function useRegionalConsts() {
|
||||
// The flat payload already carries the effective delivery/minimum values, so
|
||||
// this is a thin passthrough kept for the existing consumers. Typed loosely
|
||||
// (the previous override returned `any` for these fields) so cart/checkout need
|
||||
// no edits.
|
||||
export function useRegionalConsts(): any {
|
||||
const { data } = useGetEssentialConsts()
|
||||
return React.useMemo(() => {
|
||||
const discovery = data as DiscoveryData | undefined
|
||||
const settings = discovery?.effectiveSettings?.settings
|
||||
if (!settings) return data
|
||||
const pickNumber = (key: string, fallback: unknown): number | undefined => {
|
||||
const raw = settings[key]
|
||||
if (raw == null || raw === '') return typeof fallback === 'number' ? fallback : undefined
|
||||
const parsed = Number(raw)
|
||||
return Number.isFinite(parsed) ? parsed : (typeof fallback === 'number' ? fallback : undefined)
|
||||
}
|
||||
return {
|
||||
...data,
|
||||
deliveryCharge: pickNumber('deliveryCharge', (data as any)?.deliveryCharge),
|
||||
freeDeliveryThreshold: pickNumber('freeDeliveryThreshold', (data as any)?.freeDeliveryThreshold),
|
||||
flashDeliveryCharge: pickNumber('flashDeliveryCharge', (data as any)?.flashDeliveryCharge),
|
||||
flashFreeDeliveryThreshold: pickNumber('flashFreeDeliveryThreshold', (data as any)?.flashFreeDeliveryThreshold),
|
||||
minRegularOrderValue: pickNumber('minRegularOrderValue', (data as any)?.minRegularOrderValue),
|
||||
}
|
||||
}, [data])
|
||||
return data
|
||||
}
|
||||
|
||||
type ProductsResponse = AllProductsApiType;
|
||||
|
|
@ -108,9 +85,9 @@ export type MergedProduct = BaseProduct & ProductPriceFlags & {
|
|||
}
|
||||
|
||||
function useDiscoveryRegionId(essentialConsts: unknown): number | null {
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const effectiveRegionId = (essentialConsts as DiscoveryData | undefined)?.effectiveSettings?.regionId
|
||||
return effectiveRegionId ?? selectedRegionId
|
||||
const { regionId: selectedRegionId } = useRegion()
|
||||
const discovery = essentialConsts as DiscoveryData | undefined
|
||||
return discovery?.regionId ?? selectedRegionId
|
||||
}
|
||||
|
||||
function useCacheUrl(filename: string): string | null {
|
||||
|
|
@ -119,13 +96,13 @@ function useCacheUrl(filename: string): string | null {
|
|||
|
||||
const assetsDomain = essentialConsts?.assetsDomain
|
||||
const apiCacheKey = essentialConsts?.apiCacheKey
|
||||
const cacheVersion = essentialConsts?.cacheVersion
|
||||
const productsVersionNum = essentialConsts?.products_version_num
|
||||
|
||||
if (!assetsDomain || !apiCacheKey || cacheVersion === undefined || cacheVersion === null || regionId == null) {
|
||||
if (!assetsDomain || !apiCacheKey || productsVersionNum === undefined || productsVersionNum === null || regionId == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
return `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${cacheVersion}/${filename}`
|
||||
return `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${productsVersionNum}/${filename}`
|
||||
}
|
||||
|
||||
function useAvailabilityCacheUrl(): string | null {
|
||||
|
|
@ -133,7 +110,7 @@ function useAvailabilityCacheUrl(): string | null {
|
|||
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||
|
||||
const assetsDomain = essentialConsts?.assetsDomain
|
||||
const availabilityVersionNum = essentialConsts?.availabilityVersionNum
|
||||
const availabilityVersionNum = essentialConsts?.availability_version_num
|
||||
|
||||
if (!assetsDomain || availabilityVersionNum === undefined || availabilityVersionNum === null || regionId == null) {
|
||||
return null
|
||||
|
|
@ -147,7 +124,7 @@ function useSlotsCacheUrl(): string | null {
|
|||
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||
|
||||
const assetsDomain = essentialConsts?.assetsDomain
|
||||
const slotsVersionNum = essentialConsts?.slotsVersionNum
|
||||
const slotsVersionNum = essentialConsts?.slots_version_num
|
||||
|
||||
if (!assetsDomain || slotsVersionNum === undefined || slotsVersionNum === null || regionId == null) {
|
||||
return null
|
||||
|
|
@ -272,7 +249,7 @@ export function useStoreWithProducts(storeId: number) {
|
|||
|
||||
const assetsDomain = essentialConsts?.assetsDomain
|
||||
const apiCacheKey = essentialConsts?.apiCacheKey
|
||||
const cacheVersion = essentialConsts?.cacheVersion;
|
||||
const cacheVersion = essentialConsts?.products_version_num;
|
||||
|
||||
const cacheUrl = assetsDomain && apiCacheKey && regionId != null
|
||||
? `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${cacheVersion}/stores/${storeId}.json`
|
||||
|
|
|
|||
201
apps/user-ui/src/hooks/useRegion.ts
Normal file
201
apps/user-ui/src/hooks/useRegion.ts
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import type { RegionSummary, RegionBoundSummary } from '@packages/shared'
|
||||
import { useRegionStore } from '@/src/store/regionStore'
|
||||
import { useLocationStore } from '@/src/store/locationStore'
|
||||
import { trpc } from '@/src/trpc-client'
|
||||
import { confirmRegionSwitch } from '@/src/lib/region-switch'
|
||||
|
||||
// Give up on the backend resolve and fall back to the saved region / chooser.
|
||||
const RESOLVE_TIMEOUT_MS = 8000
|
||||
|
||||
// The startup location check runs ONCE per app launch, no matter how many
|
||||
// components consume `useRegion`. `startupCheckDone` is the single-flight guard
|
||||
// for the switch itself; `startupLaunchRegionId` records the region at launch so
|
||||
// a manual pick made before the fix lands is respected.
|
||||
let startupCheckDone = false
|
||||
let startupLaunchRegionId: number | null | undefined
|
||||
|
||||
/**
|
||||
* The single source of truth for the browsing region ("location").
|
||||
*
|
||||
* EVERY component/hook that needs to read or change the current region must go
|
||||
* through this hook instead of touching `useRegionStore` / `useLocationStore`
|
||||
* directly, so the location bar, the region gate, checkout and the regional API
|
||||
* hooks can never drift out of sync.
|
||||
*
|
||||
* On every launch the hook takes ONE device fix (no movement tracking) and
|
||||
* resolves it to a region + bound. If the resolved region equals the saved one
|
||||
* nothing happens; if it differs, the region is switched (which clears carts and
|
||||
* refreshes region-scoped data). When the location is unusable — permission
|
||||
* denied, services off, a simulator, or coordinates outside every bound — the
|
||||
* saved region is kept, or the chooser is shown when there is none.
|
||||
*/
|
||||
export interface UseRegionResult {
|
||||
/** The region the user is currently browsing. `null` until one is chosen. */
|
||||
region: RegionSummary | null
|
||||
/** Convenience alias for `region?.id`. `null` until a region is chosen. */
|
||||
regionId: number | null
|
||||
/** The bound whose consts the client reads for this region. `null` until known. */
|
||||
boundId: number | null
|
||||
/** The bound the launch location fell inside, when it resolved the region. */
|
||||
bound: RegionBoundSummary | null
|
||||
/** Monotonic marker bumped on every region change; use it to ignore stale responses. */
|
||||
regionGeneration: number
|
||||
/** True once the persisted region has finished loading from storage. */
|
||||
hydrated: boolean
|
||||
/** Latest device coordinates, if the launch fix succeeded. */
|
||||
coords: { latitude: number; longitude: number } | null
|
||||
/** Current state of the launch location read. */
|
||||
locationStatus: 'idle' | 'locating' | 'granted' | 'denied' | 'unavailable' | 'error'
|
||||
/**
|
||||
* True while the launch location check is still determining a region AND no
|
||||
* region is known yet. The UI should show a spinner rather than the chooser
|
||||
* while this is true. It never becomes true again after the check settles.
|
||||
*/
|
||||
isResolvingRegion: boolean
|
||||
/** Persist a new browsing region. For user-facing switches prefer `confirmRegionSwitch`. */
|
||||
setRegion: (region: RegionSummary, boundId?: number | null) => void
|
||||
/** Forget the browsing region (forces the region gate to prompt again). */
|
||||
clearRegion: () => void
|
||||
/** Re-check permission and take a fresh fix (e.g. a "use my location" button). */
|
||||
refreshLocation: () => void
|
||||
}
|
||||
|
||||
export function useRegion(): UseRegionResult {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const region = useRegionStore((state) => state.selectedRegion)
|
||||
const regionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const storedBoundId = useRegionStore((state) => state.selectedBoundId)
|
||||
const regionGeneration = useRegionStore((state) => state.regionGeneration)
|
||||
const setRegion = useRegionStore((state) => state.setRegion)
|
||||
const clearRegion = useRegionStore((state) => state.clearRegion)
|
||||
|
||||
const coords = useLocationStore((state) => state.coords)
|
||||
const locationStatus = useLocationStore((state) => state.status)
|
||||
const startTracking = useLocationStore((state) => state.start)
|
||||
const refreshTracking = useLocationStore((state) => state.refresh)
|
||||
|
||||
const [hydrated, setHydrated] = useState<boolean>(() =>
|
||||
useRegionStore.persist.hasHydrated()
|
||||
)
|
||||
// True once the launch location check has a definitive outcome.
|
||||
const [startupResolved, setStartupResolved] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (useRegionStore.persist.hasHydrated()) {
|
||||
setHydrated(true)
|
||||
return
|
||||
}
|
||||
return useRegionStore.persist.onFinishHydration(() => setHydrated(true))
|
||||
}, [])
|
||||
|
||||
// The bound whose consts the client reads. Falls back to the region's
|
||||
// effective bound so a region persisted before boundId existed still resolves.
|
||||
const boundId = storedBoundId ?? region?.effectiveBoundId ?? null
|
||||
|
||||
// Backfill a missing bound from the region list (also covers a manual pick
|
||||
// whose stored region summary lacked effectiveBoundId).
|
||||
const regionsQuery = trpc.common.listRegions.useQuery(undefined, {
|
||||
enabled: hydrated && regionId != null && boundId == null,
|
||||
staleTime: Infinity,
|
||||
})
|
||||
useEffect(() => {
|
||||
if (regionId == null || boundId != null) return
|
||||
const match = regionsQuery.data?.find((r) => r.id === regionId)
|
||||
if (match && match.effectiveBoundId != null) {
|
||||
setRegion(match, match.effectiveBoundId)
|
||||
}
|
||||
}, [regionId, boundId, regionsQuery.data, setRegion])
|
||||
|
||||
// Take the single launch fix — even when a region is already saved, so a
|
||||
// device that has moved to another region is detected on startup.
|
||||
useEffect(() => {
|
||||
if (!hydrated) return
|
||||
if (startupLaunchRegionId === undefined) startupLaunchRegionId = regionId
|
||||
startTracking()
|
||||
}, [hydrated, regionId, startTracking])
|
||||
|
||||
// Stable, rounded input so GPS jitter doesn't churn the query key.
|
||||
const lat = coords ? Math.round(coords.latitude * 1e5) / 1e5 : 0
|
||||
const lng = coords ? Math.round(coords.longitude * 1e5) / 1e5 : 0
|
||||
const queryInput = useMemo(() => ({ lat, lng }), [lat, lng])
|
||||
|
||||
const shouldResolve = hydrated && coords != null && !startupResolved
|
||||
const resolution = trpc.common.resolveRegionByLocation.useQuery(queryInput, {
|
||||
enabled: shouldResolve,
|
||||
staleTime: Infinity,
|
||||
retry: false,
|
||||
refetchOnWindowFocus: false,
|
||||
})
|
||||
|
||||
// Apply the launch outcome once: same region -> no-op, different -> switch.
|
||||
useEffect(() => {
|
||||
if (!hydrated || startupResolved) return
|
||||
const resolved = resolution.data
|
||||
const terminal =
|
||||
resolved != null ||
|
||||
resolution.isFetched ||
|
||||
resolution.isError ||
|
||||
locationStatus === 'denied' ||
|
||||
locationStatus === 'unavailable' ||
|
||||
locationStatus === 'error'
|
||||
if (!terminal) return
|
||||
|
||||
setStartupResolved(true)
|
||||
|
||||
// Only one consumer performs the switch; the rest just settle their spinner.
|
||||
if (startupCheckDone) return
|
||||
startupCheckDone = true
|
||||
|
||||
// Respect a manual pick made before the fix resolved.
|
||||
const userChangedRegion =
|
||||
startupLaunchRegionId !== undefined && startupLaunchRegionId !== regionId
|
||||
if (resolved?.region && !userChangedRegion && resolved.region.id !== regionId) {
|
||||
void confirmRegionSwitch(resolved.region, queryClient, resolved.bound?.id ?? null)
|
||||
}
|
||||
}, [
|
||||
hydrated,
|
||||
startupResolved,
|
||||
resolution.data,
|
||||
resolution.isFetched,
|
||||
resolution.isError,
|
||||
locationStatus,
|
||||
regionId,
|
||||
queryClient,
|
||||
])
|
||||
|
||||
// Safety net: a hanging resolve must not strand the first-run spinner.
|
||||
useEffect(() => {
|
||||
if (!hydrated || startupResolved || !shouldResolve) return
|
||||
const timer = setTimeout(() => {
|
||||
startupCheckDone = true
|
||||
setStartupResolved(true)
|
||||
}, RESOLVE_TIMEOUT_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}, [hydrated, startupResolved, shouldResolve])
|
||||
|
||||
const isResolvingRegion = regionId == null && !startupResolved
|
||||
|
||||
return {
|
||||
region,
|
||||
regionId,
|
||||
boundId,
|
||||
bound: resolution.data?.bound ?? null,
|
||||
regionGeneration,
|
||||
hydrated,
|
||||
coords,
|
||||
locationStatus,
|
||||
isResolvingRegion,
|
||||
setRegion,
|
||||
clearRegion,
|
||||
refreshLocation: () => {
|
||||
// Manual re-check: re-arm the launch check so a differing region switches.
|
||||
startupCheckDone = false
|
||||
startupLaunchRegionId = regionId
|
||||
setStartupResolved(false)
|
||||
void refreshTracking()
|
||||
},
|
||||
}
|
||||
}
|
||||
41
apps/user-ui/src/lib/is-emulator.ts
Normal file
41
apps/user-ui/src/lib/is-emulator.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { Platform } from 'react-native'
|
||||
|
||||
/**
|
||||
* Emulator/simulator detection. Emulators rarely expose a meaningful device
|
||||
* location, so callers treat them as "location unavailable" and let the user
|
||||
* pick a region manually.
|
||||
*
|
||||
* On Android, generic/unknown hardware or an "emulator"/"sdk" model gives it
|
||||
* away. On iOS, anything that is not a physical device is a simulator. If
|
||||
* detection itself fails we assume a real device (the safe default).
|
||||
*/
|
||||
export const isEmulator = (): boolean => {
|
||||
try {
|
||||
const brand = (Platform.constants as any)?.Brand?.toLowerCase()
|
||||
const model = (Platform.constants as any)?.Model?.toLowerCase()
|
||||
const manufacturer = (Platform.constants as any)?.Manufacturer?.toLowerCase()
|
||||
|
||||
if (Platform.OS === 'android') {
|
||||
return (
|
||||
brand?.includes('generic') ||
|
||||
brand?.includes('unknown') ||
|
||||
model?.includes('emulator') ||
|
||||
model?.includes('sdk') ||
|
||||
model?.includes('android sdk') ||
|
||||
manufacturer?.includes('genymotion') ||
|
||||
manufacturer?.includes('unknown')
|
||||
)
|
||||
}
|
||||
|
||||
if (Platform.OS === 'ios') {
|
||||
return (
|
||||
(Platform.constants as any)?.systemName?.includes('Simulator') ||
|
||||
!(Platform.constants as any)?.isDevice
|
||||
)
|
||||
}
|
||||
|
||||
return false
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
@ -24,6 +24,7 @@ import { useFlashNavigationStore } from '@/components/stores/flashNavigationStor
|
|||
export async function confirmRegionSwitch(
|
||||
region: RegionSummary,
|
||||
queryClient: QueryClient,
|
||||
boundId?: number | null,
|
||||
): Promise<void> {
|
||||
// 1. Clear the persisted local carts (regular + flash).
|
||||
await Promise.all([clearLocalCart('regular'), clearLocalCart('flash')])
|
||||
|
|
@ -52,8 +53,8 @@ export async function confirmRegionSwitch(
|
|||
queryClient.removeQueries({ queryKey: ['availability'] })
|
||||
queryClient.removeQueries({ queryKey: ['store-with-products'] })
|
||||
|
||||
// 4. Persist the new browsing region.
|
||||
useRegionStore.getState().setRegion(region)
|
||||
// 4. Persist the new browsing region (and its bound).
|
||||
useRegionStore.getState().setRegion(region, boundId ?? region.effectiveBoundId ?? null)
|
||||
|
||||
// 5. Refetch everything now scoped to the new region.
|
||||
await queryClient.invalidateQueries()
|
||||
|
|
|
|||
136
apps/user-ui/src/store/locationStore.ts
Normal file
136
apps/user-ui/src/store/locationStore.ts
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import { create } from 'zustand'
|
||||
import * as Location from 'expo-location'
|
||||
import { isEmulator } from '@/src/lib/is-emulator'
|
||||
|
||||
/**
|
||||
* Device-location reading, owned by the app (not by individual screens).
|
||||
*
|
||||
* A single one-shot fix is taken per app launch. The store is a singleton and
|
||||
* `start()` is idempotent, so any number of `useRegion()` consumers share one
|
||||
* permission request and one position read. No movement is tracked afterwards —
|
||||
* there is deliberately no position subscription.
|
||||
*/
|
||||
export type LocationStatus =
|
||||
| 'idle' // not started
|
||||
| 'locating' // permission requested / waiting for the fix
|
||||
| 'granted' // coordinates available
|
||||
| 'denied' // foreground permission refused
|
||||
| 'unavailable' // services off, emulator, or no fix could be read
|
||||
| 'error'
|
||||
|
||||
export interface Coords {
|
||||
latitude: number
|
||||
longitude: number
|
||||
}
|
||||
|
||||
interface LocationStoreState {
|
||||
coords: Coords | null
|
||||
status: LocationStatus
|
||||
error: string | null
|
||||
/** Take the launch fix (no-op if already taken this launch). */
|
||||
start: () => void
|
||||
/** Clear the fix and allow a later `start()` to run again. */
|
||||
stop: () => void
|
||||
/** Force a fresh permission check + fix (used by a manual "use my location"). */
|
||||
refresh: () => Promise<void>
|
||||
}
|
||||
|
||||
// Abort the fix read if the GPS never answers, so the UI can fall back to
|
||||
// manual region selection instead of spinning forever.
|
||||
const FIRST_FIX_TIMEOUT_MS = 8000
|
||||
|
||||
// Bumped on every refresh/stop so a stale in-flight read can be ignored.
|
||||
let activeToken = 0
|
||||
// One fix per app launch.
|
||||
let started = false
|
||||
|
||||
const COORD_PRECISION = 1e5
|
||||
|
||||
function toCoords(position: Location.LocationObject): Coords {
|
||||
// Round to ~1m so the resolved payload is stable.
|
||||
return {
|
||||
latitude: Math.round(position.coords.latitude * COORD_PRECISION) / COORD_PRECISION,
|
||||
longitude: Math.round(position.coords.longitude * COORD_PRECISION) / COORD_PRECISION,
|
||||
}
|
||||
}
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error('Location request timed out')), ms)
|
||||
promise.then(
|
||||
(value) => {
|
||||
clearTimeout(timer)
|
||||
resolve(value)
|
||||
},
|
||||
(error) => {
|
||||
clearTimeout(timer)
|
||||
reject(error)
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export const useLocationStore = create<LocationStoreState>((set, get) => ({
|
||||
coords: null,
|
||||
status: 'idle',
|
||||
error: null,
|
||||
|
||||
start: () => {
|
||||
if (started) return
|
||||
started = true
|
||||
void get().refresh()
|
||||
},
|
||||
|
||||
stop: () => {
|
||||
activeToken += 1
|
||||
started = false
|
||||
set({ status: 'idle', coords: null, error: null })
|
||||
},
|
||||
|
||||
refresh: async () => {
|
||||
const token = ++activeToken
|
||||
set({ status: 'locating', error: null })
|
||||
|
||||
try {
|
||||
// Simulators have no meaningful fix; let the caller ask the user instead.
|
||||
if (isEmulator()) {
|
||||
set({ status: 'unavailable', coords: null, error: null })
|
||||
return
|
||||
}
|
||||
|
||||
const { status } = await Location.requestForegroundPermissionsAsync()
|
||||
if (token !== activeToken) return
|
||||
|
||||
if (status !== 'granted') {
|
||||
set({ status: 'denied', coords: null, error: null })
|
||||
return
|
||||
}
|
||||
|
||||
// Device location services (GPS) may be switched off independently of the
|
||||
// app permission.
|
||||
const servicesEnabled =
|
||||
typeof Location.hasServicesEnabledAsync === 'function'
|
||||
? await Location.hasServicesEnabledAsync()
|
||||
: true
|
||||
if (token !== activeToken) return
|
||||
if (!servicesEnabled) {
|
||||
set({ status: 'unavailable', coords: null, error: null })
|
||||
return
|
||||
}
|
||||
|
||||
const position = await withTimeout(
|
||||
Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Balanced }),
|
||||
FIRST_FIX_TIMEOUT_MS
|
||||
)
|
||||
if (token !== activeToken) return
|
||||
set({ status: 'granted', coords: toCoords(position), error: null })
|
||||
} catch (err) {
|
||||
if (token !== activeToken) return
|
||||
set({
|
||||
status: 'unavailable',
|
||||
coords: null,
|
||||
error: err instanceof Error ? err.message : 'Location unavailable',
|
||||
})
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
|
@ -10,8 +10,14 @@ import type { RegionSummary } from '@packages/shared'
|
|||
interface RegionStore {
|
||||
selectedRegionId: number | null
|
||||
selectedRegion: RegionSummary | null
|
||||
/**
|
||||
* The bound whose consts the client should read for this region. Resolved
|
||||
* from device location (the containing bound) or from the region's effective
|
||||
* bound on a manual pick. `null` until known.
|
||||
*/
|
||||
selectedBoundId: number | null
|
||||
regionGeneration: number
|
||||
setRegion: (region: RegionSummary) => void
|
||||
setRegion: (region: RegionSummary, boundId?: number | null) => void
|
||||
clearRegion: () => void
|
||||
}
|
||||
|
||||
|
|
@ -20,19 +26,43 @@ export const useRegionStore = create<RegionStore>()(
|
|||
(set) => ({
|
||||
selectedRegionId: null,
|
||||
selectedRegion: null,
|
||||
selectedBoundId: null,
|
||||
regionGeneration: 0,
|
||||
setRegion: (region) =>
|
||||
set((state) => ({
|
||||
selectedRegionId: region.id,
|
||||
selectedRegion: region,
|
||||
regionGeneration: state.regionGeneration + 1,
|
||||
})),
|
||||
setRegion: (region, boundId = null) =>
|
||||
set((state) => {
|
||||
// No-op when nothing actually changed: keeps regionGeneration stable
|
||||
// and prevents effect loops that re-apply the same region.
|
||||
if (
|
||||
state.selectedRegionId === region.id &&
|
||||
state.selectedBoundId === boundId &&
|
||||
state.selectedRegion?.name === region.name &&
|
||||
state.selectedRegion?.description === region.description
|
||||
) {
|
||||
return state
|
||||
}
|
||||
return {
|
||||
selectedRegionId: region.id,
|
||||
selectedRegion: region,
|
||||
selectedBoundId: boundId,
|
||||
regionGeneration: state.regionGeneration + 1,
|
||||
}
|
||||
}),
|
||||
clearRegion: () =>
|
||||
set((state) => ({
|
||||
selectedRegionId: null,
|
||||
selectedRegion: null,
|
||||
regionGeneration: state.regionGeneration + 1,
|
||||
})),
|
||||
set((state) => {
|
||||
if (
|
||||
state.selectedRegionId == null &&
|
||||
state.selectedRegion == null &&
|
||||
state.selectedBoundId == null
|
||||
) {
|
||||
return state
|
||||
}
|
||||
return {
|
||||
selectedRegionId: null,
|
||||
selectedRegion: null,
|
||||
selectedBoundId: null,
|
||||
regionGeneration: state.regionGeneration + 1,
|
||||
}
|
||||
}),
|
||||
}),
|
||||
{
|
||||
name: 'freshyo-region',
|
||||
|
|
@ -41,6 +71,7 @@ export const useRegionStore = create<RegionStore>()(
|
|||
partialize: (state) => ({
|
||||
selectedRegionId: state.selectedRegionId,
|
||||
selectedRegion: state.selectedRegion,
|
||||
selectedBoundId: state.selectedBoundId,
|
||||
regionGeneration: state.regionGeneration,
|
||||
// Functions are dropped from the persisted payload.
|
||||
setRegion: state.setRegion,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
/**
|
||||
* LocationTestWrapper (components/LocationTestWrapper.tsx).
|
||||
* Under jest the platform constants read as an emulator, so the wrapper is a
|
||||
* passthrough; this locks that behaviour in.
|
||||
*
|
||||
* It is now the region gate: once a region is selected it is a passthrough,
|
||||
* otherwise it derives the region from location and falls back to the chooser.
|
||||
* Under jest the platform constants read as a simulator, so with no region the
|
||||
* chooser would show; this locks in the passthrough path with a region set.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
|
|
@ -9,14 +12,19 @@ import { Text } from 'react-native'
|
|||
import { screen } from '@testing-library/react-native'
|
||||
|
||||
import LocationTestWrapper from '@/components/LocationTestWrapper'
|
||||
import { useRegionStore } from '@/src/store/regionStore'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
describe('LocationTestWrapper', () => {
|
||||
it('renders its children on an emulator', async () => {
|
||||
it('renders its children once a region is selected', async () => {
|
||||
setupApiMocks()
|
||||
await resetStorage()
|
||||
|
||||
useRegionStore
|
||||
.getState()
|
||||
.setRegion({ id: 1, name: 'Test Region', description: null })
|
||||
|
||||
renderWithProviders(
|
||||
<LocationTestWrapper>
|
||||
<Text>app content</Text>
|
||||
|
|
|
|||
|
|
@ -35,8 +35,16 @@ export const useGetEssentialConsts = () => {
|
|||
// and after the backend adds the new fields.
|
||||
export type DiscoveryData = EssentialConstsApiType & {
|
||||
effectiveSettings?: EffectiveRegionSettings | null
|
||||
/** Pre-rename alias the backend still sends; read as fallback. */
|
||||
regionSettings?: EffectiveRegionSettings | null
|
||||
}
|
||||
|
||||
// Backend sends `effectiveSettings` (canonical) plus a `regionSettings` alias
|
||||
// for payloads cached in KV before the rename. Accept either so stale KV
|
||||
// entries still resolve to the right region's values.
|
||||
const discoverySettings = (discovery: DiscoveryData | undefined) =>
|
||||
discovery?.effectiveSettings ?? discovery?.regionSettings ?? null
|
||||
|
||||
// Discovery data with the delivery/minimum display fields overridden from the
|
||||
// region's effective settings (numeric parse, global fallback). Display-only;
|
||||
// the backend remains authoritative for the actual charge.
|
||||
|
|
@ -44,7 +52,7 @@ export function useRegionalConsts() {
|
|||
const { data } = useGetEssentialConsts()
|
||||
return useMemo(() => {
|
||||
const discovery = data as DiscoveryData | undefined
|
||||
const settings = discovery?.effectiveSettings?.settings
|
||||
const settings = discoverySettings(discovery)?.settings
|
||||
if (!settings) return data
|
||||
const pickNumber = (key: string, fallback: unknown): number | undefined => {
|
||||
const raw = settings[key]
|
||||
|
|
@ -139,7 +147,8 @@ export type MergedProduct = BaseProduct & ProductPriceFlags
|
|||
|
||||
function useDiscoveryRegionId(essentialConsts: unknown): number | null {
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const effectiveRegionId = (essentialConsts as DiscoveryData | undefined)?.effectiveSettings?.regionId
|
||||
const discovery = essentialConsts as DiscoveryData | undefined
|
||||
const effectiveRegionId = discoverySettings(discovery)?.regionId
|
||||
return effectiveRegionId ?? selectedRegionId
|
||||
}
|
||||
|
||||
|
|
|
|||
420
change-log.txt
420
change-log.txt
|
|
@ -765,3 +765,423 @@ apps/web-ui/tsconfig.json. No tests, no git, no migrations.
|
|||
Mahabubnagar shows ISOTagR1, no R2 leaks. (ISOProdR1 below render window;
|
||||
present in-file; its tag mapping empty by fixture design.)
|
||||
- Cross-region tag mapping rejected: 'Product 152 belongs to a different region'.
|
||||
|
||||
[2026-10-07 13:39:44] Closed loop: region-1 product verified rendered in UI.
|
||||
- web-ui search 'ISOProdR1' while browsing Mahabubnagar: 1 result (ISOProdR1,
|
||||
Rs 100, 500g), no ISOProdR2. Screenshot verified then removed.
|
||||
- Earlier home-page absence explained: new SKU shows Out of Stock (no
|
||||
availability/stock row), so it never surfaces in the purchasable list.
|
||||
Not a region issue.
|
||||
|
||||
[2026-10-07 13:45:12] user-ui location bar on all top-level tabs.
|
||||
- src/components/LocationBar.tsx (new): pin + region name row; tap opens
|
||||
BottomDialog with RegionSelector mode=switch (lazily mounted; sheet handles
|
||||
its own cart-clear confirmation). Rendered inside scroll content so it
|
||||
scrolls out instead of sticking.
|
||||
- Insert at top of scroll content: home listHeader, order-again ScrollView,
|
||||
FlashDeliveryProducts ListHeader, stores ListHeader, me ScrollView.
|
||||
|
||||
[2026-10-07 13:49:26] home: LocationBar vertically first — moved static SearchBar into
|
||||
the FlatList header below LocationBar so both scroll out together.
|
||||
|
||||
[2026-10-07T14:07:48+05:30] Home: scroll location away and stick the second (search) section header.
|
||||
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
|
||||
+++ apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useCallback, useMemo, memo, useRef, useEffect } from "react";
|
||||
-import { View, Dimensions, Image, RefreshControl } from "react-native";
|
||||
+import { View, Dimensions, Image, RefreshControl, SectionList } from "react-native";
|
||||
import { ScrollView } from "react-native-gesture-handler";
|
||||
import { useRouter } from "expo-router";
|
||||
import {
|
||||
@@ -653,8 +653,6 @@
|
||||
], [pageTint]);
|
||||
|
||||
const listHeader = useMemo(() => (
|
||||
- <>
|
||||
- <LocationBar />
|
||||
<ListHeader
|
||||
dashboardTags={dashboardTags}
|
||||
activeTagId={activeTagId}
|
||||
@@ -666,7 +664,6 @@
|
||||
storesData={storesData}
|
||||
sortedSlots={sortedSlots}
|
||||
/>
|
||||
- </>
|
||||
), [dashboardTags, activeTagId, productsByTagId, expandedByTagId, handleToggleExpand, handleProductPress, storesData, sortedSlots]);
|
||||
|
||||
const listContentContainerStyle = useMemo(() => [
|
||||
@@ -698,34 +695,52 @@
|
||||
return (
|
||||
<TabLayoutWrapper style={{ backgroundColor: '#FFFFFF' }}>
|
||||
<View style={pageTintStyle}>
|
||||
- <View
|
||||
- style={searchBarContainerStyle}
|
||||
- >
|
||||
- <SearchBar
|
||||
- testID="home-search"
|
||||
- value={""}
|
||||
- onChangeText={() => { }}
|
||||
- onPress={handleSearchPress}
|
||||
- editable={false}
|
||||
- containerStyle={tw`bg-white`}
|
||||
- onSubmitEditing={() => {
|
||||
- if (inputQuery.trim()) {
|
||||
- router.push(`/(drawer)/(tabs)/home/search-results?q=${encodeURIComponent(inputQuery.trim())}`);
|
||||
- }
|
||||
- }}
|
||||
- returnKeyType="search"
|
||||
- />
|
||||
- </View>
|
||||
-
|
||||
- <MyFlatList
|
||||
- data={displayedProducts.slice(0, visibleCount)}
|
||||
- keyExtractor={(item) => item.id.toString()}
|
||||
- numColumns={3}
|
||||
+ <SectionList
|
||||
+ sections={[{ data: [[], ...Array.from(
|
||||
+ { length: Math.ceil(Math.min(displayedProducts.length, visibleCount) / 3) },
|
||||
+ (_, index) => displayedProducts.slice(index * 3, Math.min(index * 3 + 3, visibleCount))
|
||||
+ )] }]}
|
||||
+ keyExtractor={(row, index) => row.length ? row.map((item) => item.id).join('-') : 'catalog-header'}
|
||||
+ stickySectionHeadersEnabled
|
||||
style={{ backgroundColor: '#FFFFFF' }}
|
||||
contentContainerStyle={listContentContainerStyle}
|
||||
- columnWrapperStyle={staticStyles.columnWrapper}
|
||||
- renderItem={renderProductItem}
|
||||
- ListHeaderComponent={listHeader}
|
||||
+ ListHeaderComponent={<LocationBar />}
|
||||
+ renderSectionHeader={() => (
|
||||
+ <View style={searchBarContainerStyle}>
|
||||
+ <SearchBar
|
||||
+ testID="home-search"
|
||||
+ value={""}
|
||||
+ onChangeText={() => { }}
|
||||
+ onPress={handleSearchPress}
|
||||
+ editable={false}
|
||||
+ containerStyle={tw`bg-white`}
|
||||
+ onSubmitEditing={() => {
|
||||
+ if (inputQuery.trim()) {
|
||||
+ router.push(`/(drawer)/(tabs)/home/search-results?q=${encodeURIComponent(inputQuery.trim())}`);
|
||||
+ }
|
||||
+ }}
|
||||
+ returnKeyType="search"
|
||||
+ />
|
||||
+ </View>
|
||||
+ )}
|
||||
+ renderItem={({ item: row, index }) => index === 0 ? (
|
||||
+ <>
|
||||
+ {listHeader}
|
||||
+ {displayedProducts.length === 0 && (
|
||||
+ <View style={tw`items-center py-8`}>
|
||||
+ <MyText style={tw`text-gray-500`}>No products available</MyText>
|
||||
+ </View>
|
||||
+ )}
|
||||
+ </>
|
||||
+ ) : (
|
||||
+ <View style={[staticStyles.columnWrapper, { flexDirection: 'row' }]}>
|
||||
+ {row.map((item) => (
|
||||
+ <React.Fragment key={item.id}>
|
||||
+ {renderProductItem({ item })}
|
||||
+ </React.Fragment>
|
||||
+ ))}
|
||||
+ </View>
|
||||
+ )}
|
||||
ListFooterComponent={
|
||||
hasMore ? (
|
||||
<View style={tw`items-center py-4`}>
|
||||
@@ -748,11 +763,6 @@
|
||||
colors={[theme.colors.brand500]}
|
||||
/>
|
||||
}
|
||||
- ListEmptyComponent={
|
||||
- <View style={tw`items-center py-8`}>
|
||||
- <MyText style={tw`text-gray-500`}>No products available</MyText>
|
||||
- </View>
|
||||
- }
|
||||
// NOTE: do not add removeClippedSubviews here - it breaks touch
|
||||
// delivery to the nested horizontal scrollables in ListHeaderComponent
|
||||
// (tag tabs / slots) on Android.
|
||||
|
||||
[2026-10-07 14:13:37] user-ui: single region source-of-truth hook.
|
||||
- NEW src/hooks/useRegion.ts: useRegion() returns { region, regionId,
|
||||
regionGeneration, hydrated, setRegion, clearRegion }. Wraps useRegionStore;
|
||||
owns the persist-hydration subscription so consumers no longer touch the store.
|
||||
- Routed all region/location reads through useRegion: LocationBar, RegionGate,
|
||||
RegionSelector (dropped selectedRegionId prop, reads hook), AddressForm,
|
||||
QuickDeliveryAddressSelector, PaymentAndOrderComponent, CheckoutAddressSelector,
|
||||
me/index.tsx, prominent-api-hooks (useGetEssentialConsts, useDiscoveryRegionId).
|
||||
- region-switch.ts keeps useRegionStore.getState() (non-hook lib, cannot call hooks).
|
||||
|
||||
[2026-10-07 14:26:08] location-based region resolution (backend + user-ui).
|
||||
Backend:
|
||||
- shared: add RegionBoundSummary + ResolvedRegion types (region.types.ts).
|
||||
- db_helper_sqlite: add getAllRegionsWithBounds() (regions ordered by id,
|
||||
each region's bounds ordered by ascending numeric priority); export it.
|
||||
- common tRPC: add public resolveRegionByLocation({lat,lng}) -> { region,
|
||||
bound } | null. Iterates every region, and within each region checks bounds
|
||||
least-priority-first; first containing bound wins. GeoJSON features
|
||||
(Polygon/MultiPolygon) converted with @turf.
|
||||
user-ui:
|
||||
- NEW src/store/locationStore.ts: zustand singleton that owns expo-location
|
||||
permission + watchPosition fixes (coords/status/error), start/stop/refresh.
|
||||
- src/hooks/useRegion.ts: now the location-aware single source of truth. While
|
||||
no region is chosen it starts tracking + calls resolveRegionByLocation and
|
||||
auto-sets the region; exposes coords/status/bound/isResolvingRegion. Stops
|
||||
tracking once a region exists.
|
||||
- RegionGate: shows spinner while resolving; only falls back to the chooser
|
||||
when location is unavailable/denied/no match.
|
||||
|
||||
[2026-10-07 15:02:02] user-ui: LocationTestWrapper owns the region chooser fallback.
|
||||
- NEW src/lib/is-emulator.ts: extracted emulator/simulator detection.
|
||||
- store/locationStore.ts: skip requesting location on emulators (status
|
||||
'unavailable'); check Location.hasServicesEnabledAsync(); race the first fix
|
||||
against a timeout so a missing GPS fix can no longer hang 'locating'.
|
||||
- LocationTestWrapper: rewritten as the region gate. Renders app once a region
|
||||
exists; spinner while deriving it from location; full-screen RegionSelector
|
||||
when location services are off, permission denied, on a simulator, or no
|
||||
bound contains the coordinates. Keeps the stale-region validation.
|
||||
- Moved LocationTestWrapper up (FirstUserWrapper) so the gate sits above
|
||||
Auth/Notification providers; removed it from app/_layout.tsx.
|
||||
- Removed src/components/RegionGate.tsx (superseded by LocationTestWrapper).
|
||||
|
||||
[2026-10-07 15:20:00] fix: region spinner stuck / infinite re-render.
|
||||
- regionStore: setRegion/clearRegion are now no-ops when nothing changes,
|
||||
so they no longer bump regionGeneration (and re-render) on every call.
|
||||
- useRegion: add resolvedAttempt flag -> isResolvingRegion flips false after
|
||||
the first definitive answer and never latches back on 'idle'; stop location
|
||||
tracking once settled; memoize/round the resolve query input; 8s resolve
|
||||
timeout fallback.
|
||||
- locationStore: round coords to ~1m and skip store updates when unchanged,
|
||||
so GPS jitter no longer churns a new query key every watch callback.
|
||||
- LocationTestWrapper: validation is membership-only (no setRegion in the
|
||||
effect), removing a possible self-triggering loop.
|
||||
|
||||
[2026-10-07 15:24:00] RegionSelector is controlled again (selectedRegionId prop) so
|
||||
the chooser no longer calls useRegion / starts location tracking; callers
|
||||
(LocationTestWrapper, LocationBar, me) pass the id from their useRegion.
|
||||
|
||||
[2026-10-07 15:42:21] regions cannot be created without bounds.
|
||||
- shared: add RegionBoundSeedInput + CreateRegionWithBoundsInput.
|
||||
- db_helper_sqlite: add createRegionWithBounds() (region + bounds inserted
|
||||
atomically in one transaction); export it.
|
||||
- superadmin regions.create: now requires bounds (min 1, valid GeoJSON +
|
||||
numeric priority) and returns { region, bounds }; duplicate priority -> 409.
|
||||
- superadmin-ui Regions page: create form now collects at least one bound
|
||||
(description/priority/GeoJSON supports multiple rows); legacy empty create
|
||||
removed.
|
||||
|
||||
[2026-10-07 15:58:00] admin-ui logout debug logging added temporarily.
|
||||
- (drawer)/_layout.tsx: log on drawer Logout item tap.
|
||||
- staff-auth-context.tsx: log on logout() entry and after deleteJWT resolves.
|
||||
|
||||
[2026-10-07 16:03:00] admin-ui logout: removed the temporary debug console.logs
|
||||
(drawer Logout handler and staff-auth-context logout()).
|
||||
|
||||
[2026-10-07 16:40:00] admin pickers leak cross-region data: fixed.
|
||||
- Root cause: three admin-only pickers used public, unscoped common endpoints.
|
||||
- common.getStoresSummary: public PROCEDURE aggregating ALL regions -> now
|
||||
protectedProcedure returning only the caller staff region's stores.
|
||||
- common.product.getAllProductsSummary: aggregated ALL regions -> now
|
||||
protectedProcedure returning scaffolledProducts(ctx.staffUser.regionId) only.
|
||||
- common.product.getAllSkusSummary: returned ALL SKUs -> protectedProcedure +
|
||||
new regionId arg on getAllSkusSummary (default null keeps old signature).
|
||||
- Affects admin-ui AND admin-web (both attach the staff JWT). The customer apps
|
||||
never call these (they use regional CDN cache files), so no public surface lost.
|
||||
|
||||
[2026-10-07 17:10:00] fix: essentialConsts returned region-1 values for region 3.
|
||||
Root cause: backend scaffold sent per-region settings as `regionSettings`
|
||||
but user-ui/web-ui read `effectiveSettings` -> override never applied, so the
|
||||
global (region-1-authored) top-level consts showed for every region.
|
||||
- backend scaffoldEssentialConsts now returns `effectiveSettings` (canonical)
|
||||
plus `regionSettings` alias for KV-cached payloads.
|
||||
- user-ui + web-ui read effectiveSettings ?? regionSettings, so even stale KV
|
||||
entries resolve correctly without waiting for a KV refresh.
|
||||
- After deploy, refresh KV (any const update / cache regen / seed calls
|
||||
refreshGenKv) so new payloads carry the canonical field.
|
||||
|
||||
[2026-10-07 17:25:00] fix: bound mutations now refresh KV.
|
||||
- updateBoundSettings wrote D1 only; KV mirror kept stale values.
|
||||
Now looks up the bound's region and awaits refreshGenKv(regionId).
|
||||
- Same staleness class fixed for createBound and updateBound (a new/changed
|
||||
bound can become the effective lowest-priority one).
|
||||
|
||||
[2026-10-07 17:40:00] fix: essentialConsts top-level fields now carry effective regional values.
|
||||
- scaffoldEssentialConsts resolved each business field as bound setting ??
|
||||
global const ?? default (numbers parsed, booleans coerced, raw passthrough
|
||||
otherwise), instead of storing globals flat next to the nested block.
|
||||
- Also exposes minRegularOrderValue/allItemsOrder/welcomeMessage top-level
|
||||
(previously nested-only). Helper return types stay `any` so the client
|
||||
contract is unchanged; only values changed.
|
||||
- Nested effectiveSettings (+regionSettings alias) retained for provenance
|
||||
and the client override path. Requires KV refresh post-deploy (any const
|
||||
save / cache regen / seed) to rewrite stored payloads.
|
||||
|
||||
[2026-10-07 17:55:00] essentialConsts payload is now flat: removed the nested
|
||||
effectiveSettings/regionSettings block. Top-level fields are the region's
|
||||
effective values (bound setting ?? global), so there is nothing nested left
|
||||
to re-appear. Clients keep reading the optional nested block only as a
|
||||
backward-compat fallback for payloads already cached in KV.
|
||||
|
||||
[2026-10-08 00:10:10] Part 1/2 - split consts model into three tables (global_consts / region_consts / region_bound_consts) + per-bound flat JSON in KV.
|
||||
|
||||
Planned diffs (backend + db_helper + admin-ui + admin-web + superadmin-ui; NO migration run; NO tests; NO git):
|
||||
|
||||
packages/db_helper_sqlite/src/db/schema.ts
|
||||
- Add globalConsts(key PK, value), regionConsts(region_id,key PK), regionBoundConsts(bound_id,key PK) tables.
|
||||
- Remove regionCacheVersions + regionBoundSettings tables and relations.
|
||||
packages/db_helper_sqlite/drizzle/0009_three_const_tables.sql (new, NOT run) + meta/_journal.json idx 9.
|
||||
- CREATE 3 tables; copy global / region (versions + region-level keys incl allItemsOrder from effective bound) / bound rows;
|
||||
DELETE migrated keys from key_val_store (keep leftovers); DROP region_bound_settings + region_cache_versions.
|
||||
packages/db_helper_sqlite/src/lib/const-keys.ts
|
||||
- Add GLOBAL_CONST_KEYS / REGION_CONST_KEYS / BOUND_CONST_KEYS / LEGACY_CONST_KEYS; rename cacheVersion -> products_version_num; keep merged CONST_KEYS.
|
||||
packages/db_helper_sqlite/src/admin-apis/const.ts
|
||||
- Add getAllGlobalConsts/upsertGlobalConsts, getRegionConsts/upsertRegionConsts, getBoundConsts/upsertBoundConsts, getLegacyConsts/upsertLegacyConsts;
|
||||
getAllConstants/upsertConstants route by scope. Remove dead global version counters.
|
||||
packages/db_helper_sqlite/src/lib/region-cache-versions.ts
|
||||
- Back get/incrementRegion* with region_consts rows (products_version_num / availability_version_num / slots_version_num).
|
||||
packages/db_helper_sqlite/src/superadmin-apis/regions.ts
|
||||
- getBoundSettings/upsertBoundSettings -> region_bound_consts; add getRegionConstants/upsertRegionConstants;
|
||||
getEffectiveRegionSettings merged region+bound; add getEffectiveBoundId; getAllRegions + effectiveBoundId; seed defaults on create.
|
||||
packages/db_helper_sqlite/src/db/seed.ts + seed.sql, index.ts exports.
|
||||
packages/shared/types/region.types.ts - RegionSummary.effectiveBoundId.
|
||||
apps/backend/src/lib/const-keys.ts, lib/const-store.ts, lib/gen-store.ts (essentialConsts_{boundId}),
|
||||
trpc/apis/common-apis/common-trpc-index.ts (scaffoldEssentialConsts(boundId), essentialConsts {boundId}, listRegions effectiveBoundId, regionSettings merged),
|
||||
lib/cloud_cache.ts, lib/flash-delivery-cron.ts, lib/seed.ts, sqliteImporter.ts,
|
||||
trpc/apis/admin-apis/apis/const.ts (global/legacy procedures + compat alias), admin-apis/apis/region.ts (region + bound constants),
|
||||
superadmin-apis/apis/regions.ts, new superadmin-apis/apis/const.ts router.
|
||||
apps/admin-ui + apps/admin-web: customize-app 3 tabs (Global/Region/Bound); popular-items/all-items-order region-scoped; tagsOrder via legacy.
|
||||
apps/superadmin-ui: constants.tsx -> superadmin.const.*; regions.tsx region + bound editors.
|
||||
Typecheck: db_helper_sqlite, backend, admin-ui, superadmin-ui, admin-web.
|
||||
|
||||
[2026-10-08 00:29:40] Part 1/2 follow-up — finish the admin UIs (admin-ui, admin-web, superadmin-ui) + move tagsOrder into region_consts.
|
||||
|
||||
Backend/db (tagsOrder is now region-scoped, per user decision; overrides the plan which kept it legacy):
|
||||
packages/db_helper_sqlite/src/lib/const-keys.ts
|
||||
- CONST_KEYS/LABELS/TYPES/VISIBILITY/DEFAULTS: add tagsOrder (string, hidden, default '[]').
|
||||
- REGION_CONST_KEYS: add 'tagsOrder'; LEGACY_CONST_KEYS: remove 'tagsOrder'.
|
||||
apps/backend/src/lib/const-keys.ts
|
||||
- REGION_CONST_KEYS: add 'tagsOrder'; LEGACY_CONST_KEYS: remove 'tagsOrder'.
|
||||
packages/db_helper_sqlite/drizzle/0009_three_const_tables.sql (NOT run)
|
||||
- Copy tagsOrder from key_val_store into region_consts per region; delete it from key_val_store.
|
||||
packages/db_helper_sqlite/src/db/seed.ts
|
||||
- Remove tagsOrder from legacy seed list (region_defaults now seeds it).
|
||||
apps/backend/src/lib/seed.ts
|
||||
- Remove tagsOrder from legacy seed list.
|
||||
apps/backend/src/trpc/apis/admin-apis/apis/region.ts
|
||||
- updateRegionConstants: trigger scheduleStoreInitialization when tagsOrder changes; ignore version-counter keys.
|
||||
apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts
|
||||
- updateRegionConstants: ignore version-counter keys (read-only).
|
||||
apps/backend/src/trpc/apis/common-apis/common.ts
|
||||
- scaffoldProducts: read tagsOrder from region_consts (region-scoped) instead of the global key_val_store.
|
||||
|
||||
Admin UIs (3 tabs Global/Region/Bound; Global holds legacy keys, globals hidden; Region hides version counters; Bound = 5 keys):
|
||||
apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
|
||||
- Replace 2-way switch with 3 tabs; global uses admin.const.getGlobalConstants/getLegacyConstants, region uses admin.region.getRegionConstants/updateRegionConstants, bound keeps per-bound Formik; hide tab if no visible keys.
|
||||
apps/admin-ui/app/(drawer)/dashboard/customize-app/popular-items.tsx
|
||||
apps/admin-ui/app/(drawer)/dashboard/customize-app/all-items-order.tsx
|
||||
- Read/write popularItems/allItemsOrder via admin.region.getRegionConstants/updateRegionConstants.
|
||||
apps/admin-ui/app/(drawer)/dashboard/product-tags/order.tsx
|
||||
- Read/write tagsOrder via admin.region.getRegionConstants/updateRegionConstants.
|
||||
apps/admin-ui/components/OrderOptionsMenu.tsx
|
||||
- welcomeMessage read via admin.region.getRegionConstants.
|
||||
apps/admin-web/src/routes/dashboard.customize-app.tsx
|
||||
- 3 tabs as above.
|
||||
apps/admin-web/src/routes/dashboard.customize-app.popular.tsx
|
||||
apps/admin-web/src/routes/dashboard.customize-app.ordering.tsx
|
||||
- Region-scoped popularItems/allItemsOrder.
|
||||
apps/admin-web/src/routes/dashboard.product-tags.order.tsx
|
||||
- Region-scoped tagsOrder.
|
||||
apps/superadmin-ui/src/routes/constants.tsx
|
||||
- Use superadmin.const.getGlobalConstants/updateGlobalConstants + getLegacyConstants/updateLegacyConstants; drop region/bound keys.
|
||||
apps/superadmin-ui/src/routes/regions.tsx
|
||||
- Split into RegionConstantsEditor (superadmin.regions.getRegionConstants/updateRegionConstants, version counters hidden) and BoundSettingsEditor (5 bound keys).
|
||||
|
||||
web-ui and user-ui untouched. No migrations run. No tests run.
|
||||
|
||||
[2026-10-08 00:41:00] Part 1/2 follow-up completed. Backend/db_helper/admin-ui/admin-web/superadmin-ui typecheck clean (tsc --noEmit). Migration 0009 NOT run (user runs it). web-ui + user-ui untouched.
|
||||
Notes/decisions:
|
||||
- Global tab in admin-ui/admin-web shows the legacy leftovers (platformFeePercent,
|
||||
minOrderAmountForCoupon, flashDeliverySlotId); the 4 global keys stay hidden there and are
|
||||
managed in superadmin-ui. Tab is hidden entirely if it would render no visible keys.
|
||||
- Region tab hides the 3 version counters; tagsOrder is edited on the Tag Orders screen
|
||||
(admin apps) and in the superadmin Region settings editor (no dedicated tags screen there).
|
||||
- List screens send comma-joined ids to the region endpoint (input is a strict scalar union).
|
||||
- Stale: apps/admin-ui/tests/** still mock admin.const.getConstants/updateConstants (tests not run).
|
||||
|
||||
[2026-10-08 00:44:05] Part 2/2 — apps/user-ui consumes the per-bound flat JSON.
|
||||
|
||||
apps/user-ui/src/store/regionStore.ts
|
||||
- Add selectedBoundId (persisted); setRegion(region, boundId?) compares+stores it; clearRegion resets it.
|
||||
apps/user-ui/src/hooks/useRegion.ts
|
||||
- Expose boundId from the store; on resolve persist setRegion(resolved.region, resolved.bound.id); setRegion signature gains boundId.
|
||||
apps/user-ui/src/lib/region-switch.ts
|
||||
- confirmRegionSwitch(region, queryClient, boundId?) forwards boundId to setRegion.
|
||||
apps/user-ui/src/components/RegionSelector.tsx
|
||||
apps/user-ui/components/CheckoutAddressSelector.tsx
|
||||
apps/user-ui/components/QuickDeliveryAddressSelector.tsx
|
||||
- Pass region.effectiveBoundId to confirmRegionSwitch.
|
||||
apps/user-ui/src/hooks/prominent-api-hooks.ts
|
||||
- useGetEssentialConsts reads boundId from useRegion, queries { boundId }, persists under essential_consts_b{boundId}.
|
||||
- useDiscoveryRegionId reads flat data.regionId (fallback useRegion().regionId).
|
||||
- Cache URLs use products_version_num / availability_version_num / slots_version_num.
|
||||
- useRegionalConsts is a thin passthrough of the flat payload.
|
||||
- Drop DiscoveryData extension + discoverySettings + EffectiveRegionSettings import.
|
||||
No tests run. web-ui untouched.
|
||||
|
||||
[2026-10-08 00:49:00] Part 2/2 completed. apps/user-ui typechecks clean; backend/db/admin apps still clean.
|
||||
Deviations/notes:
|
||||
- confirmRegionSwitch(region, queryClient, boundId?) defaults boundId to region.effectiveBoundId,
|
||||
so the address-selector call sites needed no change; RegionSelector passes it explicitly.
|
||||
- useRegion derives boundId = stored ?? region.effectiveBoundId ?? null and backfills a missing
|
||||
bound via common.listRegions (covers region state persisted before selectedBoundId existed).
|
||||
- useRegionalConsts keeps a loose (any) return so cart/checkout/floating-cart need no edits.
|
||||
|
||||
[2026-10-08 00:57:00] Globals are superadmin-only: removed the Global tab from the admin apps.
|
||||
apps/admin-ui/.../customize-app/index.tsx and apps/admin-web/.../dashboard.customize-app.tsx
|
||||
- Drop the Global tab, renderGlobal, global/legacy queries+mutations, GLOBAL_KEYS/LEGACY_KEYS,
|
||||
CONST_VISIBILITY; tab switcher is now Region | Bound only. tsc clean.
|
||||
- Global + legacy constants remain editable in apps/superadmin-ui/src/routes/constants.tsx.
|
||||
Backend note: staff `admin.const.*` (compat getConstants/updateConstants + the new
|
||||
getGlobalConstants/updateGlobalConstants/getLegacyConstants/updateLegacyConstants) still exist and
|
||||
are pinned by apps/backend/tests; not changed (no production UI caller remains).
|
||||
|
||||
[2026-10-08 01:12:47] Added packages/db_helper_sqlite/drizzle/merged_regions.sql — one squashed migration replacing 0006_regions_and_superadmins + 0007_region_columns_backfill + 0008_region_cache_versions + 0009_three_const_tables.
|
||||
- Drops the two throwaway staging tables (region_bound_settings, region_cache_versions) that the originals created only to copy from and then drop; global_consts / region_consts / region_bound_consts are seeded directly instead.
|
||||
- Phase order preserved: (1) regions/region_bounds/superadmins + seeds (from 0006), (2) 0007 region_id rebuild verbatim, (3) const tables + direct seeds (from 0008+0009).
|
||||
- Verification: rebuilt SQLite from apps/backend/dumps/latest.sql; applied 0006..0009 -> expected; applied merged_regions.sql -> merged. Python comparison: schema objects 86/86, tables 55/55, rows 21795/21795, IDENTICAL apart from CURRENT_TIMESTAMP seeds (regions.created_at, superadmins.created_at). Also validated D1-style splitting on the statement-breakpoint marker: 187 chunks, 0 failures, integrity ok, same-result. No migrations run against any real DB. No tests run.
|
||||
- Follow-up (exact-data check): re-ran 0006..0009 vs merged_regions.sql back-to-back in the same second and compared every row of the 6 new tables + 31 rebuilt tables + key_val_store with no masking -> EXACTLY IDENTICAL (rows: regions 1, region_bounds 2, superadmins 1, global_consts 3, region_consts 10, region_bound_consts 10; all 31 rebuilt tables match row-for-row, e.g. delivery_slot_info 1569, orders 2283, order_items 7959, order_status 2277, reserved_coupons 739; key_val_store 7 leftovers).
|
||||
- Squash applied: removed migrations 0006/0007/0008/0009 and replaced them with one file.
|
||||
* Backed up the pre-removal contents of 0006_regions_and_superadmins.sql,
|
||||
0007_region_columns_backfill.sql, 0008_region_cache_versions.sql and
|
||||
0009_three_const_tables.sql into
|
||||
packages/db_helper_sqlite/drizzle/stale/removed_region_migrations.txt
|
||||
(single txt, one section per file, verbatim).
|
||||
* Deleted those four .sql files.
|
||||
* Renamed packages/db_helper_sqlite/drizzle/merged_regions.sql ->
|
||||
packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql (same
|
||||
verified squashed content; staging tables removed).
|
||||
* drizzle/meta/_journal.json still lists tags 0007_region_columns_backfill,
|
||||
0008_region_cache_versions and 0009_three_const_tables; left untouched
|
||||
(user handles migrations) but needs those entries removed to stay consistent.
|
||||
* docs/consts-three-tables-part1-backend-admin.md still references
|
||||
`0009_three_const_tables`; left as-is.
|
||||
No migrations run. No tests run.
|
||||
|
||||
[2026-10-08 19:28:11] user-ui: startup-only location check (no movement tracking).
|
||||
apps/user-ui/src/store/locationStore.ts
|
||||
- Remove watchPositionAsync subscription (movement tracking) and coordsEqual; keep a single
|
||||
getCurrentPositionAsync (8s timeout). start() idempotent via a per-launch `started` flag.
|
||||
apps/user-ui/src/hooks/useRegion.ts
|
||||
- Run the location check once on hydration EVEN when a region is saved; never stop/start on regionId.
|
||||
- Apply outcome once per launch: same region -> no-op; different -> confirmRegionSwitch(resolved.region,
|
||||
queryClient, resolved.bound.id) (clears carts, invalidates region queries); null/denied/unavailable
|
||||
-> keep saved region. Single-flight switch guard (module flag) + manual-pick race guard.
|
||||
- Rename resolvedAttempt -> startupResolved; isResolvingRegion only for the true first run.
|
||||
No backend changes. No tests run.
|
||||
|
||||
[2026-10-08 19:34:00] startup-only location check implemented. user-ui typecheck clean.
|
||||
- locationStore: single getCurrentPositionAsync per launch, no watchPositionAsync.
|
||||
- useRegion: check runs on every launch (saved region included); same -> no-op,
|
||||
different -> confirmRegionSwitch (option a: clears carts, refreshes screens);
|
||||
unusable/null -> keep saved region (or chooser when none). Single-flight switch + manual-pick race guard.
|
||||
|
|
|
|||
254
docs/consts-three-tables-part1-backend-admin.md
Normal file
254
docs/consts-three-tables-part1-backend-admin.md
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
# Plan — Part 1/2: Backend + Admin UIs (three-table consts model)
|
||||
|
||||
Part 1 of 2. Covers the DB model, KV, migration, backend, and the **admin UIs**
|
||||
(`apps/admin-ui`, `apps/admin-web`, `apps/superadmin-ui`). Part 2 covers `apps/user-ui`
|
||||
(see `consts-three-tables-part2-user-ui.md`). Supersedes `three-table-consts-model.md`.
|
||||
|
||||
## 0. Decisions
|
||||
|
||||
- Scope Part 1: backend + admin-ui + admin-web + superadmin-ui.
|
||||
- `allItemsOrder` is **region-scoped** (one row per region in `region_consts`), grouped with
|
||||
`popularItems`.
|
||||
- Leftover keys stay in `key_val_store`: `platformFeePercent`, `taxRate`, `tester`,
|
||||
`minOrderAmountForCoupon`, `maxCouponDiscount`, `flashDeliverySlotId`, `readableOrderId`,
|
||||
`tagsOrder`.
|
||||
- `region_cache_versions` + `region_bound_settings` are dropped after data copy.
|
||||
- Precomputed flat JSON per bound in the KV gen namespace (§2) — consumed by user-ui (Part 2).
|
||||
- AGENTS.md: do NOT run migrations (user runs), do NOT run the test suite, do NOT use git.
|
||||
Append planned diffs + timestamp to `change-log.txt` before editing non-`.md`/`.txt` files.
|
||||
|
||||
## 1. Data model
|
||||
|
||||
New tables (`packages/db_helper_sqlite/src/db/schema.ts`):
|
||||
|
||||
```
|
||||
global_consts (key TEXT PRIMARY KEY, value TEXT)
|
||||
region_consts (region_id INTEGER FK->regions.id, key TEXT, value TEXT, PK(region_id,key))
|
||||
region_bound_consts (bound_id INTEGER FK->region_bounds.id, region_id INTEGER FK->regions.id,
|
||||
key TEXT, value TEXT, PK(bound_id,key))
|
||||
```
|
||||
|
||||
| Table | Keys |
|
||||
|---|---|
|
||||
| `global_consts` | `versionNum`, `playStoreUrl`, `appStoreUrl`, `internalAppVersion` |
|
||||
| `region_consts` | `products_version_num` (was `cache_version`), `availability_version_num`, `slots_version_num`, `popularItems`, `allItemsOrder`, `isFlashDeliveryEnabled`, `supportMobile`, `supportEmail`, `welcomeMessage` |
|
||||
| `region_bound_consts` | `minRegularOrderValue`, `freeDeliveryThreshold`, `deliveryCharge`, `flashFreeDeliveryThreshold`, `flashDeliveryCharge` |
|
||||
| `key_val_store` (kept) | `platformFeePercent`, `taxRate`, `tester`, `minOrderAmountForCoupon`, `maxCouponDiscount`, `flashDeliverySlotId`, `readableOrderId`, `tagsOrder` |
|
||||
|
||||
- Region-level keys are one row per region (no bound precedence). Bound-level keys stay per bound.
|
||||
- Version counters (`products_version_num`/`availability_version_num`/`slots_version_num`) live in
|
||||
`region_consts`, auto-created default 1.
|
||||
- `allItemsOrder`: exactly one row per region; identical for every bound in that region.
|
||||
|
||||
## 2. KV model
|
||||
|
||||
- Key `essentialConsts_{boundId}` in `freshyo_gen`/`freshyo_gen_dev`. Flat value =
|
||||
`{ ...global, ...region, ...bound, assetsDomain, apiCacheKey, regionId, boundId, webviewHtml, isWebviewClosable }`.
|
||||
- Numbers/booleans coerced (`Number()` / boolean) at build time; other values raw strings.
|
||||
|
||||
## 3. Migration (author only — user runs)
|
||||
|
||||
`packages/db_helper_sqlite/drizzle/0009_three_const_tables.sql` + journal idx 9
|
||||
(`0009_three_const_tables`). Steps: CREATE the 3 tables; copy `global_consts` (4 keys) from
|
||||
`key_val_store`; copy `region_consts` version counters from `region_cache_versions` and region
|
||||
business keys (incl. `allItemsOrder`) from each region's lowest-priority bound's
|
||||
`region_bound_settings`; copy the 5 bound keys into `region_bound_consts`; DELETE the migrated keys
|
||||
from `key_val_store` (keep the 8 leftovers); DROP `region_bound_settings` + `region_cache_versions`.
|
||||
(full SQL is in `docs/consts-three-tables-changes.md` §2.2 — reuse it verbatim.)
|
||||
|
||||
## 4. Backend
|
||||
|
||||
### 4.1 `packages/db_helper_sqlite`
|
||||
|
||||
- **`src/db/schema.ts`**: add `globalConsts`, `regionConsts`, `regionBoundConsts`; remove
|
||||
`regionCacheVersions` + `regionBoundSettings` and their relations.
|
||||
- **`src/lib/const-keys.ts`**: add `GLOBAL_CONST_KEYS`, `REGION_CONST_KEYS`, `BOUND_CONST_KEYS`,
|
||||
`LEGACY_CONST_KEYS`; keep merged `CONST_KEYS` + labels/types/visibility/defaults; add
|
||||
`products_version_num`; add `CONST_SCOPE` (`global|region|bound|legacy`).
|
||||
- **`src/admin-apis/const.ts`**:
|
||||
- add `getAllGlobalConsts()`, `upsertGlobalConsts(rows)`, `getRegionConsts(regionId)`,
|
||||
`upsertRegionConsts(regionId, rows)`, `getBoundConsts(boundId)`,
|
||||
`upsertBoundConsts(boundId, regionId, rows)`, `getLegacyConsts()`, `upsertLegacyConsts(rows)`.
|
||||
- keep `getAllConstants`/`upsertConstants` working: `getAllConstants()` = merged
|
||||
global+legacy (+ `CONST_DEFAULTS`); `upsertConstants(rows, regionId?)` routes by `CONST_SCOPE`.
|
||||
- remove the dead global counters (`get/incrementCacheVersion`, availability, slots).
|
||||
- **`src/lib/region-cache-versions.ts`**: back it with `region_consts`
|
||||
(`products_version_num`/`availability_version_num`/`slots_version_num`), auto-create rows;
|
||||
public signatures/return type unchanged (`cloud_cache.ts` untouched).
|
||||
- **`src/superadmin-apis/regions.ts`**:
|
||||
- `getBoundSettings(boundId)` → `region_bound_consts` only (5 keys), `Record<string,string|null>`.
|
||||
- `upsertBoundSettings(boundId, settings)` → `region_bound_consts` (look up regionId from bound).
|
||||
- add `getRegionConstants(regionId)` / `upsertRegionConstants(regionId, rows)`.
|
||||
- `getEffectiveRegionSettings(regionId)` → merged region + effective bound (shape unchanged).
|
||||
- add `getEffectiveBoundId(regionId)`; `getAllRegions()` → add `effectiveBoundId`.
|
||||
- `createRegionWithBounds`/`createRegionBound` → seed default rows + version counters (1/1/1).
|
||||
- **`src/db/seed.ts` + `src/db/seed.sql`**: seed the 3 tables (incl. per-region `allItemsOrder`);
|
||||
leftovers keep going to `key_val_store`.
|
||||
- **`index.ts`**: export the new helpers; drop removed ones.
|
||||
|
||||
### 4.2 `packages/shared`
|
||||
|
||||
- **`types/region.types.ts`**: `RegionSummary.effectiveBoundId?: number | null`.
|
||||
- **`types/const.types.ts`**: unchanged (`Constant`, `ConstantUpdateResult`); optional add
|
||||
`GlobalConstKey`/`RegionConstKey`/`BoundConstKey` union types if useful to the UIs.
|
||||
|
||||
### 4.3 `apps/backend` core
|
||||
|
||||
- **`src/lib/const-keys.ts`**: mirror the four key groups (`allItemsOrder` in `REGION_CONST_KEYS`).
|
||||
- **`src/lib/const-store.ts`**: `getGlobalConstValues()`, `getRegionConstValues(regionId)`,
|
||||
`getBoundConstValues(boundId)`; `getConstant(key)` (tagsOrder) stays on `key_val_store`.
|
||||
- **`src/lib/gen-store.ts`**: `GEN_KV_KEY='essentialConsts'`, `genKvKeyForBound(boundId)`,
|
||||
`refreshGenKv(boundId?)`, `refreshGenKvForRegion(regionId)`, `readEssentialConstsFromKv(boundId)`.
|
||||
- **`src/trpc/apis/common-apis/common-trpc-index.ts`**: `scaffoldEssentialConsts(boundId)`;
|
||||
`essentialConsts` input `{ boundId }`; `listRegions` returns `effectiveBoundId`; `regionSettings`
|
||||
merged.
|
||||
- **`src/lib/cloud_cache.ts`**: `refreshGenKvForRegion(regionId)`; essential-consts CDN file uses the
|
||||
effective bound.
|
||||
- **`src/lib/flash-delivery-cron.ts`**: `isFlashDeliveryEnabled` now region-level → write
|
||||
`region_consts` for all regions, then `refreshGenKv()`.
|
||||
- **`src/lib/seed.ts`**: new db seeds + `refreshGenKv()`.
|
||||
- **`src/sqliteImporter.ts`**: re-export new helpers.
|
||||
|
||||
### 4.4 tRPC endpoint surface (new / repointed)
|
||||
|
||||
Keep old `admin.const.getConstants`/`updateConstants` as **backward-compat aliases** (tests at
|
||||
`apps/backend/tests/helpers/consts.ts` + any stragglers). Add clean, scoped endpoints:
|
||||
|
||||
| Endpoint | Kind | Scope | Notes |
|
||||
|---|---|---|---|
|
||||
| `admin.const.getGlobalConstants` / `updateGlobalConstants` | query/mutation | staff | `global_consts` (4 keys) |
|
||||
| `admin.const.getLegacyConstants` / `updateLegacyConstants` | query/mutation | staff | `key_val_store` leftovers (`tagsOrder`, coupons, etc.) |
|
||||
| `admin.const.getConstants` / `updateConstants` | query/mutation | staff | **alias**: merged global+legacy; update routes by scope |
|
||||
| `admin.region.getRegionConstants` / `updateRegionConstants` | query/mutation | staff region | `region_consts` for `ctx.staffUser.regionId` |
|
||||
| `admin.region.getBoundSettings` / `updateBoundSettings` | query/mutation | staff region | `region_bound_consts` (5 keys); add `refreshGenKvForRegion` after write |
|
||||
| `superadmin.const.getGlobalConstants` / `updateGlobalConstants` | query/mutation | superadmin | NEW router (fixes the current `admin.const` guard mismatch) |
|
||||
| `superadmin.const.getLegacyConstants` / `updateLegacyConstants` | query/mutation | superadmin | leftovers |
|
||||
| `superadmin.regions.getRegionConstants` / `updateRegionConstants` | query/mutation | superadmin | `{ regionId }` + constants |
|
||||
| `superadmin.regions.boundSettings` / `updateBoundSettings` | query/mutation | superadmin | repointed to `region_bound_consts`; `refreshGenKvForRegion` |
|
||||
|
||||
- `update*` handlers validate keys against their group (`GLOBAL_CONST_KEYS` / `REGION_CONST_KEYS` /
|
||||
`BOUND_CONST_KEYS` / `LEGACY_CONST_KEYS`) and refresh KV for the affected scope.
|
||||
- `admin.region.updateRegionConstants` and `superadmin.regions.updateRegionConstants` taking
|
||||
`isFlashDeliveryEnabled`/etc. must `refreshGenKvForRegion(regionId)`.
|
||||
- Version-counter keys (`products_version_num`, etc.) are **not** editable via these endpoints
|
||||
(read-only in `getRegionConstants`, ignored on write).
|
||||
|
||||
### 4.5 `apps/backend` routers to edit
|
||||
|
||||
- `src/trpc/apis/admin-apis/apis/const.ts` — new global/legacy procedures + alias.
|
||||
- `src/trpc/apis/admin-apis/apis/region.ts` — `getRegionConstants`/`updateRegionConstants`;
|
||||
`getBoundSettings`/`updateBoundSettings` → bound table + KV refresh.
|
||||
- `src/trpc/apis/superadmin-apis/apis/regions.ts` — bound settings repoint + region constants +
|
||||
`refreshGenKvForRegion`.
|
||||
- new `src/trpc/apis/superadmin-apis/apis/const.ts` (`superadminConstRouter`) +
|
||||
register in `superadmin-apis/superadmin-trpc-index.ts`.
|
||||
- `src/trpc/apis/admin-apis/apis/admin-trpc-index.ts` — const router still mounted; nothing new
|
||||
needed beyond procedure additions.
|
||||
|
||||
## 5. Admin UI — `apps/admin-ui`
|
||||
|
||||
All key maps are **local** in `app/(drawer)/dashboard/customize-app/index.tsx`
|
||||
(`CONST_LABELS` 11–33, `CONST_VISIBILITY` 35–58, `BOUND_KEY_TYPES` 61–75, `REGIONAL_KEYS` 77,
|
||||
`parseBoundValue` 80–102, `serializeBoundValue` 105–120, local `ConstantInput` 122–261).
|
||||
|
||||
### 5.1 `customize-app/index.tsx`
|
||||
- Replace the 2-way switch (`mode: 'bounds' | 'global'`, line 265) with **3 tabs**:
|
||||
**Global** / **Region** / **Bound**.
|
||||
- **Global tab** → `admin.const.getGlobalConstants`/`updateGlobalConstants`; rows = the 4
|
||||
`GLOBAL_CONST_KEYS` (visibility-controlled) + a "Legacy" subsection for
|
||||
`admin.const.getLegacyConstants` (only if you want `tagsOrder`/coupon keys exposed; otherwise omit).
|
||||
- **Region tab** → `admin.region.getRegionConstants`/`updateRegionConstants`; rows =
|
||||
`REGION_CONST_KEYS` minus the 3 version counters (display-only). `popularItems` / `allItemsOrder`
|
||||
keep `allowSectionNavigation` links to their editors (§5.2).
|
||||
- **Bound tab** → keep the existing per-bound tabs + Formik, but `REGIONAL_KEYS` shrinks to the 5
|
||||
`BOUND_CONST_KEYS` (`minRegularOrderValue`, `freeDeliveryThreshold`, `deliveryCharge`,
|
||||
`flashFreeDeliveryThreshold`, `flashDeliveryCharge`) via
|
||||
`admin.region.getBoundSettings`/`updateBoundSettings`. Remove the 6 region-level keys from
|
||||
`BOUND_KEY_TYPES`.
|
||||
- Rebuild `CONST_LABELS`/`CONST_VISIBILITY`/type maps from the key groups (or import a small shared
|
||||
keys module — see §5.5); keep the local `ConstantInput` (incl. `allowSectionNavigation`).
|
||||
|
||||
### 5.2 `customize-app/popular-items.tsx` + `all-items-order.tsx`
|
||||
- These are now **region-scoped** (`region_consts`): switch reads/writes from `admin.const.*` to
|
||||
`admin.region.getRegionConstants`/`updateRegionConstants` (same `{ key, value:number[] }` payload;
|
||||
keep the array-or-CSV parse). Invalidate `region.getRegionConstants`.
|
||||
|
||||
### 5.3 `product-tags/order.tsx`
|
||||
- `tagsOrder` stays a **global leftover** in `key_val_store` → switch to
|
||||
`admin.const.getLegacyConstants`/`updateLegacyConstants` (payload unchanged; still triggers
|
||||
`scheduleStoreInitialization()` server-side).
|
||||
|
||||
### 5.4 `components/OrderOptionsMenu.tsx`
|
||||
- `welcomeMessage` is now in `region_consts` → read it from `admin.region.getRegionConstants`
|
||||
instead of `admin.const.getConstants`.
|
||||
|
||||
### 5.5 (optional) shared keys module
|
||||
- Consider extracting the key groups + labels into a small `apps/admin-ui/src/constants/const-keys.ts`
|
||||
to stop the label/visibility drift; not required.
|
||||
|
||||
## 6. Admin UI — `apps/admin-web`
|
||||
|
||||
Mirror of admin-ui (single file `src/routes/dashboard.customize-app.tsx`: `CONST_LABELS` 14–35,
|
||||
`CONST_VISIBILITY` 37–59, `BOUND_KEY_TYPES` 64–76, `REGIONAL_KEYS` 78, local `ConstantInput` 123–256).
|
||||
|
||||
- `dashboard.customize-app.tsx`: 3 tabs (Global/Region/Bound) as §5.1; `handleBoundSubmit`
|
||||
(323–354) writes the 5 bound keys; `handleGlobalSubmit` (356–383) writes global (+ legacy).
|
||||
- `dashboard.customize-app.popular.tsx` (110–204) and `.ordering.tsx` (97–183): switch to
|
||||
`admin.region.getRegionConstants`/`updateRegionConstants`; invalidate that key.
|
||||
- `dashboard.product-tags.order.tsx` (90–174): switch to `admin.const.getLegacyConstants`/
|
||||
`updateLegacyConstants`.
|
||||
- Keep the local `ConstantInput` + `allowSectionNavigation`.
|
||||
|
||||
## 7. Admin UI — `apps/superadmin-ui`
|
||||
|
||||
- **`src/routes/constants.tsx`**: currently calls `admin.const.*` under a **superadmin** token,
|
||||
which is `protectedProcedure` → UNAUTHORIZED. Switch to the new `superadmin.const.*`
|
||||
(`getGlobalConstants`/`updateGlobalConstants` + `getLegacyConstants`/`updateLegacyConstants`).
|
||||
Split the single form into Global (+ Legacy) sections; drop the region/bound keys from this screen
|
||||
(they move to the Regions page).
|
||||
- **`src/routes/regions.tsx`**: `SETTING_KEYS` (18–30) currently mixes region keys + bound keys.
|
||||
Split into:
|
||||
- **Region constants** editor (new `RegionConstantsEditor`) using
|
||||
`superadmin.regions.getRegionConstants`/`updateRegionConstants({ regionId })` for the region
|
||||
keys (popularItems, allItemsOrder, isFlashDeliveryEnabled, supportMobile, supportEmail,
|
||||
welcomeMessage).
|
||||
- **Bound constants** editor (`BoundSettingsEditor`, 383–436) uses `SETTING_KEYS` reduced to the
|
||||
5 bound keys via `superadmin.regions.boundSettings`/`updateBoundSettings`.
|
||||
- Keep the `EFFECTIVE` badge logic (bounds sorted by priority; effective = first).
|
||||
|
||||
## 8. Out of scope (Part 1)
|
||||
|
||||
- `apps/user-ui` — Part 2.
|
||||
- `apps/web-ui` storefront — still calls `common.essentialConsts({ regionId })` and will fail input
|
||||
validation once the input becomes `{ boundId }`. Not migrated here; flagged. (Optional follow-up:
|
||||
accept `{ regionId }` and map via `getEffectiveBoundId(regionId)`.)
|
||||
|
||||
## 9. Verification
|
||||
|
||||
0. Append planned diffs + timestamp to `change-log.txt` first.
|
||||
1. Typecheck: `npx tsc --noEmit --project packages/db_helper_sqlite/tsconfig.json`,
|
||||
`... apps/backend/tsconfig.json`, `... apps/admin-ui/tsconfig.json`,
|
||||
`... apps/superadmin-ui/tsconfig.json`, `... apps/admin-web/tsconfig.json`
|
||||
(admin-web package has its own `typecheck` script).
|
||||
2. After migration 0009: verify the three tables populated, `key_val_store` keeps the 8 leftovers,
|
||||
exactly one `allItemsOrder` per region.
|
||||
3. Endpoints: `admin.const.getGlobalConstants` (4 keys), `admin.region.getRegionConstants` (9 keys,
|
||||
versions read-only), `admin.region.getBoundSettings` (5 keys); `superadmin.const.*` works with a
|
||||
superadmin token; writes refresh KV (`essentialConsts_{boundId}` in `freshyo_gen`).
|
||||
4. Admin smoke: Global/Region/Bound tabs save to the correct tables; popular/all-items edits hit
|
||||
`region_consts`; tagsOrder edit still triggers cache regeneration.
|
||||
|
||||
## 10. Checklist
|
||||
|
||||
1. `change-log.txt` — append planned diffs.
|
||||
2. `packages/db_helper_sqlite`: schema, `0009` migration + journal, const-keys, admin-apis/const,
|
||||
region-cache-versions, superadmin-apis/regions, seed, index exports.
|
||||
3. `packages/shared`: `region.types.ts` (`effectiveBoundId`).
|
||||
4. `apps/backend`: const-keys, const-store, gen-store, common-trpc-index, cloud_cache,
|
||||
flash-delivery-cron, seed, sqliteImporter, admin const/region routers, superadmin regions router,
|
||||
new superadmin const router.
|
||||
5. `apps/admin-ui`: customize-app (3 tabs), popular-items, all-items-order, product-tags/order,
|
||||
OrderOptionsMenu.
|
||||
6. `apps/admin-web`: customize-app (3 tabs), popular, ordering, product-tags/order.
|
||||
7. `apps/superadmin-ui`: constants.tsx (superadmin.const.*), regions.tsx (region + bound editors).
|
||||
8. Typecheck all five projects; fix self-introduced errors.
|
||||
122
docs/consts-three-tables-part2-user-ui.md
Normal file
122
docs/consts-three-tables-part2-user-ui.md
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
# Plan — Part 2/2: user-ui (consume the per-bound flat JSON)
|
||||
|
||||
Part 2 of 2. Adapts **`apps/user-ui`** to request the precomputed flat JSON by `boundId` and read
|
||||
the flat shape. Backend + admin UIs are Part 1
|
||||
(`consts-three-tables-part1-backend-admin.md`) and must land first (the client depends on
|
||||
`{ boundId }` input, `listRegions.effectiveBoundId`, and the flat payload).
|
||||
|
||||
## 0. Decisions
|
||||
|
||||
- user-ui **sends `boundId`** (persisted client-side) and reads the flat JSON.
|
||||
- Scope: `apps/user-ui` only. `apps/web-ui` stays on the old contract (breaks; see §4).
|
||||
- AGENTS.md: no test runs, no migrations, no git; log planned diffs to `change-log.txt` before
|
||||
editing non-`.md`/`.txt` files.
|
||||
|
||||
## 1. Flat JSON contract (from Part 1)
|
||||
|
||||
`common.essentialConsts({ boundId })` returns the union of global + region + bound rows plus
|
||||
identity/env:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"versionNum": "1.1.0", "playStoreUrl": "...", "appStoreUrl": "...", "internalAppVersion": 1,
|
||||
"products_version_num": 2, "availability_version_num": 2, "slots_version_num": 2,
|
||||
"popularItems": "[]", "allItemsOrder": "[]", "isFlashDeliveryEnabled": true,
|
||||
"supportMobile": "...", "supportEmail": "...", "welcomeMessage": "...",
|
||||
"minRegularOrderValue": 300, "freeDeliveryThreshold": 300, "deliveryCharge": 20,
|
||||
"flashFreeDeliveryThreshold": 500, "flashDeliveryCharge": 69,
|
||||
"assetsDomain": "...", "apiCacheKey": "...", "regionId": 1, "boundId": 7,
|
||||
"webviewHtml": null, "isWebviewClosable": true
|
||||
}
|
||||
```
|
||||
|
||||
- `allItemsOrder` is the region's value (identical across bounds of the same region).
|
||||
- The nested `effectiveSettings`/`regionSettings` block is gone.
|
||||
- `EssentialConstsApiType` (`@backend/trpc/router`) already reflects this (derived from
|
||||
`scaffoldEssentialConsts`).
|
||||
|
||||
## 2. Region-bound state (client must know its boundId)
|
||||
|
||||
Today the client knows only `regionId` (persisted in `regionStore`); the resolved bound is
|
||||
transient. Changes:
|
||||
|
||||
### 2.1 `src/store/regionStore.ts`
|
||||
- Add `selectedBoundId: number | null`.
|
||||
- `setRegion(region: RegionSummary, boundId?: number | null)` persists both; include
|
||||
`selectedBoundId` in `partialize`; extend the no-op guard to compare boundId.
|
||||
|
||||
### 2.2 `src/hooks/useRegion.ts`
|
||||
- Expose `boundId` (from the store) on `UseRegionResult`.
|
||||
- On a successful `resolveRegionByLocation`, persist
|
||||
`setRegion(resolved.region, resolved.bound.id)` (instead of region-only).
|
||||
|
||||
### 2.3 `src/lib/region-switch.ts`
|
||||
- `confirmRegionSwitch(region, queryClient, boundId?)` forwards the boundId to
|
||||
`regionStore.setRegion` (manual picks get the region's effective bound id).
|
||||
|
||||
### 2.4 `src/components/RegionSelector.tsx`
|
||||
- `listRegions` now returns `effectiveBoundId` per region → pass it through
|
||||
`confirmRegionSwitch` so a manually chosen region still has a `boundId`.
|
||||
|
||||
## 3. Consuming the flat JSON
|
||||
|
||||
### 3.1 `src/hooks/prominent-api-hooks.ts`
|
||||
- **`useGetEssentialConsts`**
|
||||
- read `boundId` from `useRegion()` (not `regionId`);
|
||||
- `trpc.common.essentialConsts.useQuery({ boundId }, { refetchInterval: 60000, enabled: isReady && boundId != null, placeholderData: initialData })`;
|
||||
- persist under `` `essential_consts_b${boundId}` `` (was `essential_consts_r{regionId}`).
|
||||
- **URL builders** (rename to the new keys):
|
||||
- `useCacheUrl` / `useStoreWithProducts` → `products_version_num` (was `cacheVersion`);
|
||||
- `useAvailabilityCacheUrl` → `availability_version_num`;
|
||||
- `useSlotsCacheUrl` → `slots_version_num`;
|
||||
- region id in URLs → `data.regionId` (via `useDiscoveryRegionId`, now reading the flat
|
||||
`regionId` with `useRegion().regionId` fallback).
|
||||
- **`useRegionalConsts`** → thin passthrough of the flat data (delivery values are already
|
||||
top-level). Keep the exported function so `cart-page`, `checkout-page`, `floating-cart-bar`, and
|
||||
`PaymentAndOrderComponent` need no edits.
|
||||
- Remove the `effectiveSettings`/`regionSettings` fallback fields from `DiscoveryData` and the now
|
||||
unused `discoverySettings` helper.
|
||||
|
||||
### 3.2 Unchanged (verify only)
|
||||
- `cart-page.tsx`, `checkout-page.tsx`, `floating-cart-bar.tsx`, `PaymentAndOrderComponent.tsx`
|
||||
keep reading `deliveryCharge` / `flashDeliveryCharge` / `freeDeliveryThreshold` /
|
||||
`flashFreeDeliveryThreshold` / `minRegularOrderValue` (now flat).
|
||||
- `AddToCartDialog.tsx` (`isFlashDeliveryEnabled`), `flash-delivery/_layout.tsx`
|
||||
(`isFlashDeliveryEnabled`), `NextOrderGlimpse.tsx` (`supportMobile`),
|
||||
`me/complaints/index.tsx` (`supportMobile`/`supportEmail`), `UpdateChecker.tsx`
|
||||
(`internalAppVersion`), `HealthTestWrapper.tsx` (`versionNum`/`playStoreUrl`/`appStoreUrl`),
|
||||
`WebViewWrapper.tsx` (`webviewHtml`/`isWebviewClosable`) — field names unchanged in the flat JSON.
|
||||
- `LocationBar.tsx`, `LocationTestWrapper.tsx`, `FirstUserWrapper.tsx` — region-only; unaffected.
|
||||
|
||||
## 4. Out of scope / consequences
|
||||
|
||||
- **`apps/web-ui`** (`src/hooks/prominent-api-hooks.ts`) still calls
|
||||
`common.essentialConsts({ regionId })` and reads `cacheVersion`/`availabilityVersionNum`/
|
||||
`slotsVersionNum` → will fail input validation and show no data until migrated. Not in this plan.
|
||||
- If the hard break must be avoided, Part 1 can add a `regionId` fallback (server maps to
|
||||
`getEffectiveBoundId(regionId)`); then web-ui keeps working read-only. Decide before shipping.
|
||||
|
||||
## 5. Verification
|
||||
|
||||
0. Append planned diffs + timestamp to `change-log.txt` first.
|
||||
1. Typecheck: `npx tsc --noEmit --project apps/user-ui/tsconfig.json`.
|
||||
2. Smoke (after Part 1 is deployed + migration 0009 applied):
|
||||
- Pick/auto-resolve a region → `boundId` persisted in `freshyo-region`.
|
||||
- `common.essentialConsts` called with `{ boundId }`; payload cached under
|
||||
`essential_consts_b{boundId}`.
|
||||
- Catalog URLs contain `products_version_num` / `availability_version_num` /
|
||||
`slots_version_num` and the correct `regionId`.
|
||||
- Cart/checkout show the selected bound's delivery values; switching region updates them.
|
||||
- Flash gate (`isFlashDeliveryEnabled`), update gate (`internalAppVersion`/`versionNum`),
|
||||
support links, and webview notice all still work.
|
||||
|
||||
## 6. Checklist
|
||||
|
||||
1. `change-log.txt` — append planned diffs.
|
||||
2. `src/store/regionStore.ts` — `selectedBoundId` + persist.
|
||||
3. `src/hooks/useRegion.ts` — expose `boundId`; persist on resolve.
|
||||
4. `src/lib/region-switch.ts` — forward boundId.
|
||||
5. `src/components/RegionSelector.tsx` — use `effectiveBoundId`.
|
||||
6. `src/hooks/prominent-api-hooks.ts` — `{ boundId }` input, per-bound cache key, renamed
|
||||
version fields, simplified `useRegionalConsts`, drop `effectiveSettings` fallbacks.
|
||||
7. Typecheck `apps/user-ui`; fix self-introduced errors.
|
||||
|
|
@ -1,13 +1,33 @@
|
|||
-- Migration: regions, region bounds, per-bound settings, and superadmin identities.
|
||||
-- Migration: merged replacement for the interim regionalization migrations
|
||||
-- 0006_regions_and_superadmins, 0007_region_columns_backfill,
|
||||
-- 0008_region_cache_versions, and 0009_three_const_tables.
|
||||
--
|
||||
-- Region "Mahabubnagar" is created and all current data will be backfilled to it
|
||||
-- in a later migration (backend phase). This migration only creates the new
|
||||
-- tables and seeds the region, its two bounds, per-bound settings, and the
|
||||
-- bootstrap superadmin account.
|
||||
-- The originals created two throwaway staging tables purely to copy from and
|
||||
-- then drop them:
|
||||
-- * `region_bound_settings` (created + seeded in 0006, dropped in 0009)
|
||||
-- * `region_cache_versions` (created + seeded in 0008, dropped in 0009)
|
||||
-- This script creates neither. The final tables are seeded directly:
|
||||
-- * global keys + per-region version counters + region-level business keys
|
||||
-- -> `region_consts` (global ones -> `global_consts`)
|
||||
-- * per-bound business keys -> `region_bound_consts`
|
||||
--
|
||||
-- NOTE: SQLite has no `ADD COLUMN IF NOT EXISTS`; tables use IF NOT EXISTS so the
|
||||
-- file is safe if re-applied, but rely on the migration journal to run it once.
|
||||
-- Phases, kept in the original dependency order:
|
||||
-- 1. regions / region_bounds / superadmins + seeds (from 0006)
|
||||
-- 2. region_id backfill + 31-table rebuild (from 0007)
|
||||
-- 3. global_consts / region_consts / region_bound_consts (from 0008+0009)
|
||||
--
|
||||
-- Verified: applying this file to apps/backend/dumps/latest.sql yields the same
|
||||
-- schema and the same rows as applying 0006..0009 in order.
|
||||
--
|
||||
-- NOTE: SQLite has no `ADD COLUMN IF NOT EXISTS`; the CREATEs use IF NOT EXISTS
|
||||
-- so the file is partially re-runnable, but rely on the migration journal to run
|
||||
-- it once. As in 0007, re-running without resetting the database will fail.
|
||||
|
||||
-- =====================================================================
|
||||
-- Phase 1 (from 0006): regions, region bounds, and the bootstrap superadmin.
|
||||
-- `region_bound_settings` is not created here; its rows are seeded straight
|
||||
-- into `region_bound_consts` in Phase 3.
|
||||
-- =====================================================================
|
||||
CREATE TABLE IF NOT EXISTS `regions` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
|
|
@ -26,18 +46,6 @@ CREATE TABLE IF NOT EXISTS `region_bounds` (
|
|||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS `unique_region_bound_priority` ON `region_bounds` (`region_id`, `priority`);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS `region_bound_settings` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
`bound_id` integer NOT NULL,
|
||||
`key` text NOT NULL,
|
||||
`value` text,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`bound_id`) REFERENCES `region_bounds`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS `unique_region_bound_setting_key` ON `region_bound_settings` (`bound_id`, `key`);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS `superadmins` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`username` text NOT NULL,
|
||||
|
|
@ -63,41 +71,851 @@ SELECT id, 'Mbnr-2', '{"type":"FeatureCollection","features":[{"type":"Feature",
|
|||
FROM `regions` WHERE `name` = 'Mahabubnagar'
|
||||
AND NOT EXISTS (SELECT 1 FROM `region_bounds` WHERE `priority` = '2' AND `region_id` = (SELECT id FROM `regions` WHERE `name` = 'Mahabubnagar'));
|
||||
--> statement-breakpoint
|
||||
-- Seed per-bound business settings (same values as the former global constants) for every bound.
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'minRegularOrderValue', '300' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'freeDeliveryThreshold', '300' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'deliveryCharge', '20' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'flashFreeDeliveryThreshold', '500' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'flashDeliveryCharge', '69' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'popularItems', '[]' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'allItemsOrder', '[]' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'isFlashDeliveryEnabled', 'false' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'supportMobile', '8688182552' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'supportEmail', 'qushammohd@gmail.com' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'welcomeMessage', 'Hi! Thank you for your first order at Freshyo. We''re glad to have you.' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
-- Bootstrap superadmin (password hash supplied by the product owner; stored as-is, never re-hashed).
|
||||
INSERT INTO `superadmins` (`username`, `password_hash`)
|
||||
SELECT 'superadmin', '$2a$12$pDL1ooXdvmdpCFpeXgEnB.7eRot4ygtL/Z9lSmW8ApjRLAhTiuOCu'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `superadmins` WHERE `username` = 'superadmin');
|
||||
|
||||
--> statement-breakpoint
|
||||
-- Migration: rebuild the region-ownership FK subgraph with `region_id NOT NULL`
|
||||
-- pointing at the Mahabubnagar region created in 0006, and repair legacy orphan
|
||||
-- rows that were written before FK enforcement (they would fail the copy).
|
||||
--
|
||||
-- Single pass — no ALTER ADD COLUMN phase. `region_id` is added by the rebuild
|
||||
-- itself and its value is computed at DB level in each copy SELECT
|
||||
-- ((SELECT id FROM regions WHERE name='Mahabubnagar')), never by app defaults.
|
||||
--
|
||||
-- Follows docs/recreate-referenced-tables.md: create/copy parent-first, drop
|
||||
-- leaf-first, rename parent-first, recreate indexes last. D1 enforces FKs and
|
||||
-- ignores both FK pragmas, so the whole connected subgraph is rebuilt.
|
||||
--
|
||||
-- NOTE: re-running without resetting the database will fail (tables already
|
||||
-- exist / columns already added). Reset the local D1 state and re-apply 0006
|
||||
-- first when starting over.
|
||||
|
||||
-- =====================================================================
|
||||
-- Repair legacy orphan rows (must run before any copy: the rebuilt tables
|
||||
-- declare FKs, and inserting live orphan rows into them is a constraint
|
||||
-- violation).
|
||||
--
|
||||
-- Live-DB findings this is sized for:
|
||||
-- * 11 payments rows whose order no longer exists (all payment rows).
|
||||
-- * 5 orders whose address no longer exists (their dependents deleted too,
|
||||
-- per product-owner decision; purchase history for these is dropped).
|
||||
-- =====================================================================
|
||||
|
||||
-- Orphan payments first (also removes payments of the orphan orders below).
|
||||
DELETE FROM `payments` WHERE `order_id` NOT IN (SELECT `id` FROM `orders`);
|
||||
--> statement-breakpoint
|
||||
-- Detach coupon usage / complaints / incidents from the orphan orders before
|
||||
-- removing the orders themselves (columns are nullable; deleting usage rows
|
||||
-- entirely would also lose coupon history tied to surviving behavior).
|
||||
UPDATE `coupon_usage` SET `order_item_id` = NULL
|
||||
WHERE `order_item_id` IN (SELECT `oi`.`id` FROM `order_items` `oi` JOIN `orders` `o` ON `o`.`id` = `oi`.`order_id` WHERE `o`.`address_id` NOT IN (SELECT `id` FROM `addresses`));
|
||||
--> statement-breakpoint
|
||||
UPDATE `coupon_usage` SET `order_id` = NULL
|
||||
WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
|
||||
--> statement-breakpoint
|
||||
UPDATE `complaints` SET `order_id` = NULL
|
||||
WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
|
||||
--> statement-breakpoint
|
||||
UPDATE `user_incidents` SET `order_id` = NULL
|
||||
WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
|
||||
--> statement-breakpoint
|
||||
-- Delete the orphan orders' remaining hard dependents (order_status / refunds
|
||||
-- included — their copies into the rebuilt tables would otherwise fail first).
|
||||
DELETE FROM `refunds` WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
|
||||
--> statement-breakpoint
|
||||
DELETE FROM `order_status` WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
|
||||
--> statement-breakpoint
|
||||
DELETE FROM `order_items` WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
|
||||
--> statement-breakpoint
|
||||
DELETE FROM `orders`
|
||||
WHERE `id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`))
|
||||
AND `address_id` NOT IN (SELECT `id` FROM `addresses`);
|
||||
--> statement-breakpoint
|
||||
-- Sanity: no more orphan rows against the tables we keep.
|
||||
-- (Not verifiable in plain SQL execution; validated post-migration with
|
||||
-- PRAGMA foreign_key_check and row counts.)
|
||||
|
||||
-- =====================================================================
|
||||
-- Rebuild phase. 31 tables: create `__new_*` (parents first), copy all
|
||||
-- columns, drop originals leaf-first, rename parents first, recreate indexes.
|
||||
-- =====================================================================
|
||||
|
||||
CREATE TABLE `__new_staff_users` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`password` text NOT NULL,
|
||||
`staff_role_id` integer,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
FOREIGN KEY (`staff_role_id`) REFERENCES `staff_roles`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_staff_users` (`id`,`name`,`password`,`staff_role_id`,`created_at`,`region_id`)
|
||||
SELECT `id`,`name`,`password`,`staff_role_id`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `staff_users`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_staff_notif_creds` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`token` text NOT NULL,
|
||||
`added_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`staff_user_id` integer NOT NULL,
|
||||
`last_verified` text,
|
||||
FOREIGN KEY (`staff_user_id`) REFERENCES `__new_staff_users`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_staff_notif_creds` (`id`,`token`,`added_at`,`staff_user_id`,`last_verified`)
|
||||
SELECT `id`,`token`,`added_at`,`staff_user_id`,`last_verified` FROM `staff_notif_creds`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_store_info` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`description` text,
|
||||
`image_url` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`owner` integer NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
FOREIGN KEY (`owner`) REFERENCES `__new_staff_users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_store_info` (`id`,`name`,`description`,`image_url`,`created_at`,`owner`,`region_id`)
|
||||
SELECT `id`,`name`,`description`,`image_url`,`created_at`,`owner`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `store_info`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_product_info` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`short_description` text,
|
||||
`long_description` text,
|
||||
`store_id` integer,
|
||||
`increment_step` real DEFAULT 1 NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`product_type` text DEFAULT 'item' NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
FOREIGN KEY (`store_id`) REFERENCES `__new_store_info`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_product_info` (`id`,`name`,`short_description`,`long_description`,`store_id`,`increment_step`,`created_at`,`product_type`,`region_id`)
|
||||
SELECT `id`,`name`,`short_description`,`long_description`,`store_id`,`increment_step`,`created_at`,`product_type`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `product_info`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_product_tag_info` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`tag_name` text NOT NULL,
|
||||
`tag_description` text,
|
||||
`image_url` text,
|
||||
`is_dashboard_tag` integer DEFAULT false NOT NULL,
|
||||
`related_stores` text,
|
||||
`sort_order` text DEFAULT '[]',
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_product_tag_info` (`id`,`tag_name`,`tag_description`,`image_url`,`is_dashboard_tag`,`related_stores`,`sort_order`,`created_at`,`region_id`)
|
||||
SELECT `id`,`tag_name`,`tag_description`,`image_url`,`is_dashboard_tag`,`related_stores`,`sort_order`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `product_tag_info`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_product_group_info` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`group_name` text NOT NULL,
|
||||
`description` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_product_group_info` (`id`,`group_name`,`description`,`created_at`,`region_id`)
|
||||
SELECT `id`,`group_name`,`description`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `product_group_info`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_delivery_slot_info` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`delivery_time` text NOT NULL,
|
||||
`freeze_time` text NOT NULL,
|
||||
`is_active` integer DEFAULT true NOT NULL,
|
||||
`is_flash` integer DEFAULT false NOT NULL,
|
||||
`is_capacity_full` integer DEFAULT false NOT NULL,
|
||||
`delivery_sequence` text,
|
||||
`group_ids` text,
|
||||
`sku_ids` text,
|
||||
`region_id` integer NOT NULL,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_delivery_slot_info` (`id`,`delivery_time`,`freeze_time`,`is_active`,`is_flash`,`is_capacity_full`,`delivery_sequence`,`group_ids`,`sku_ids`,`region_id`)
|
||||
SELECT `id`,`delivery_time`,`freeze_time`,`is_active`,`is_flash`,`is_capacity_full`,`delivery_sequence`,`group_ids`,`sku_ids`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `delivery_slot_info`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_vendor_snippets` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`snippet_code` text NOT NULL,
|
||||
`slot_id` integer,
|
||||
`is_permanent` integer DEFAULT false NOT NULL,
|
||||
`sku_ids` text NOT NULL,
|
||||
`valid_till` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
FOREIGN KEY (`slot_id`) REFERENCES `__new_delivery_slot_info`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_vendor_snippets` (`id`,`snippet_code`,`slot_id`,`is_permanent`,`sku_ids`,`valid_till`,`created_at`,`region_id`)
|
||||
SELECT `id`,`snippet_code`,`slot_id`,`is_permanent`,`sku_ids`,`valid_till`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `vendor_snippets`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_home_banners` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`image_url` text NOT NULL,
|
||||
`description` text,
|
||||
`sku_ids` text,
|
||||
`redirect_url` text,
|
||||
`serial_num` integer,
|
||||
`is_active` integer DEFAULT false NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`last_updated` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_home_banners` (`id`,`name`,`image_url`,`description`,`sku_ids`,`redirect_url`,`serial_num`,`is_active`,`created_at`,`last_updated`,`region_id`)
|
||||
SELECT `id`,`name`,`image_url`,`description`,`sku_ids`,`redirect_url`,`serial_num`,`is_active`,`created_at`,`last_updated`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `home_banners`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_addresses` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`phone` text NOT NULL,
|
||||
`address_line1` text NOT NULL,
|
||||
`address_line2` text,
|
||||
`city` text NOT NULL,
|
||||
`state` text NOT NULL,
|
||||
`pincode` text NOT NULL,
|
||||
`is_default` integer DEFAULT false NOT NULL,
|
||||
`latitude` real,
|
||||
`longitude` real,
|
||||
`google_maps_url` text,
|
||||
`admin_latitude` real,
|
||||
`admin_longitude` real,
|
||||
`zone_id` integer,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_addresses` (`id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`pincode`,`is_default`,`latitude`,`longitude`,`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,`region_id`)
|
||||
SELECT `id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`pincode`,`is_default`,`latitude`,`longitude`,`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `addresses`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_coupons` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`coupon_code` text NOT NULL,
|
||||
`is_user_based` integer DEFAULT false NOT NULL,
|
||||
`discount_percent` text,
|
||||
`flat_discount` text,
|
||||
`min_order` text,
|
||||
`sku_ids` text,
|
||||
`created_by` integer NOT NULL,
|
||||
`max_value` text,
|
||||
`is_apply_for_all` integer DEFAULT false NOT NULL,
|
||||
`valid_till` text,
|
||||
`max_limit_for_user` integer,
|
||||
`is_invalidated` integer DEFAULT false NOT NULL,
|
||||
`exclusive_apply` integer DEFAULT false NOT NULL,
|
||||
`is_first_order_only` integer DEFAULT false NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
FOREIGN KEY (`created_by`) REFERENCES `__new_staff_users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_coupons` (`id`,`coupon_code`,`is_user_based`,`discount_percent`,`flat_discount`,`min_order`,`sku_ids`,`created_by`,`max_value`,`is_apply_for_all`,`valid_till`,`max_limit_for_user`,`is_invalidated`,`exclusive_apply`,`is_first_order_only`,`created_at`,`region_id`)
|
||||
SELECT `id`,`coupon_code`,`is_user_based`,`discount_percent`,`flat_discount`,`min_order`,`sku_ids`,`created_by`,`max_value`,`is_apply_for_all`,`valid_till`,`max_limit_for_user`,`is_invalidated`,`exclusive_apply`,`is_first_order_only`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `coupons`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_product_skus` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`product_id` integer NOT NULL,
|
||||
`name` text,
|
||||
`images` text,
|
||||
`is_offer` integer DEFAULT false NOT NULL,
|
||||
`is_combo_only` integer DEFAULT false NOT NULL,
|
||||
`is_deleted` integer DEFAULT false NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`product_id`) REFERENCES `__new_product_info`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_product_skus` (`id`,`product_id`,`name`,`images`,`is_offer`,`is_combo_only`,`is_deleted`,`created_at`)
|
||||
SELECT `id`,`product_id`,`name`,`images`,`is_offer`,`is_combo_only`,`is_deleted`,`created_at` FROM `product_skus`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_product_market_stats` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`sku_id` integer NOT NULL,
|
||||
`market_price` text,
|
||||
`our_price` text NOT NULL,
|
||||
`is_flash_available` integer DEFAULT false NOT NULL,
|
||||
`flash_price` text,
|
||||
`is_out_of_stock` integer DEFAULT false NOT NULL,
|
||||
`is_suspended` integer DEFAULT false NOT NULL,
|
||||
FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_product_market_stats` (`id`,`sku_id`,`market_price`,`our_price`,`is_flash_available`,`flash_price`,`is_out_of_stock`,`is_suspended`)
|
||||
SELECT `id`,`sku_id`,`market_price`,`our_price`,`is_flash_available`,`flash_price`,`is_out_of_stock`,`is_suspended` FROM `product_market_stats`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_sku_features` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`sku_id` integer NOT NULL,
|
||||
`feature_name` text,
|
||||
`feature_value` text NOT NULL,
|
||||
FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_sku_features` (`id`,`sku_id`,`feature_name`,`feature_value`)
|
||||
SELECT `id`,`sku_id`,`feature_name`,`feature_value` FROM `sku_features`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_product_combos` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`combo_sku_id` integer NOT NULL,
|
||||
`sku_id` integer NOT NULL,
|
||||
FOREIGN KEY (`combo_sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_product_combos` (`id`,`combo_sku_id`,`sku_id`)
|
||||
SELECT `id`,`combo_sku_id`,`sku_id` FROM `product_combos`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_special_deals` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`sku_id` integer NOT NULL,
|
||||
`quantity` text NOT NULL,
|
||||
`price` text NOT NULL,
|
||||
`valid_till` text NOT NULL,
|
||||
FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_special_deals` (`id`,`sku_id`,`quantity`,`price`,`valid_till`)
|
||||
SELECT `id`,`sku_id`,`quantity`,`price`,`valid_till` FROM `special_deals`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_product_reviews` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
`product_id` integer NOT NULL,
|
||||
`review_body` text NOT NULL,
|
||||
`image_urls` text,
|
||||
`review_time` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`ratings` real NOT NULL,
|
||||
`admin_response` text,
|
||||
`admin_response_images` text,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`product_id`) REFERENCES `__new_product_info`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
CONSTRAINT "rating_check" CHECK(`ratings` >= 1 AND `ratings` <= 5)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_product_reviews` (`id`,`user_id`,`product_id`,`review_body`,`image_urls`,`review_time`,`ratings`,`admin_response`,`admin_response_images`)
|
||||
SELECT `id`,`user_id`,`product_id`,`review_body`,`image_urls`,`review_time`,`ratings`,`admin_response`,`admin_response_images` FROM `product_reviews`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_product_tags` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`product_id` integer NOT NULL,
|
||||
`tag_id` integer NOT NULL,
|
||||
`assigned_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`product_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`tag_id`) REFERENCES `__new_product_tag_info`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_product_tags` (`id`,`product_id`,`tag_id`,`assigned_at`)
|
||||
SELECT `id`,`product_id`,`tag_id`,`assigned_at` FROM `product_tags`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_product_group_membership` (
|
||||
`product_id` integer NOT NULL,
|
||||
`group_id` integer NOT NULL,
|
||||
`added_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
PRIMARY KEY (`product_id`,`group_id`),
|
||||
FOREIGN KEY (`product_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`group_id`) REFERENCES `__new_product_group_info`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_product_group_membership` (`product_id`,`group_id`,`added_at`)
|
||||
SELECT `product_id`,`group_id`,`added_at` FROM `product_group_membership`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_orders` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
`address_id` integer NOT NULL,
|
||||
`slot_id` integer,
|
||||
`is_cod` integer DEFAULT false NOT NULL,
|
||||
`is_online_payment` integer DEFAULT false NOT NULL,
|
||||
`payment_info_id` integer,
|
||||
`total_amount` text NOT NULL,
|
||||
`delivery_charge` text DEFAULT '0' NOT NULL,
|
||||
`readable_id` integer NOT NULL,
|
||||
`admin_notes` text,
|
||||
`user_notes` text,
|
||||
`order_group_id` text,
|
||||
`order_group_proportion` text,
|
||||
`is_flash_delivery` integer DEFAULT false NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`delivered_at` text,
|
||||
`region_id` integer NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`address_id`) REFERENCES `__new_addresses`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`slot_id`) REFERENCES `__new_delivery_slot_info`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`payment_info_id`) REFERENCES `payment_info`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_orders` (`id`,`user_id`,`address_id`,`slot_id`,`is_cod`,`is_online_payment`,`payment_info_id`,`total_amount`,`delivery_charge`,`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,`region_id`)
|
||||
SELECT `id`,`user_id`,`address_id`,`slot_id`,`is_cod`,`is_online_payment`,`payment_info_id`,`total_amount`,`delivery_charge`,`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `orders`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_order_items` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`order_id` integer NOT NULL,
|
||||
`sku_id` integer NOT NULL,
|
||||
`quantity` text NOT NULL,
|
||||
`price` text NOT NULL,
|
||||
`discounted_price` text,
|
||||
`is_packaged` integer DEFAULT false NOT NULL,
|
||||
`is_package_verified` integer DEFAULT false NOT NULL,
|
||||
`packaged_at` text,
|
||||
FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_order_items` (`id`,`order_id`,`sku_id`,`quantity`,`price`,`discounted_price`,`is_packaged`,`is_package_verified`,`packaged_at`)
|
||||
SELECT `id`,`order_id`,`sku_id`,`quantity`,`price`,`discounted_price`,`is_packaged`,`is_package_verified`,`packaged_at` FROM `order_items`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_order_status` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`order_time` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
`order_id` integer NOT NULL,
|
||||
`is_packaged` integer DEFAULT false NOT NULL,
|
||||
`is_delivered` integer DEFAULT false NOT NULL,
|
||||
`is_cancelled` integer DEFAULT false NOT NULL,
|
||||
`cancel_reason` text,
|
||||
`is_cancelled_by_admin` integer,
|
||||
`payment_state` text DEFAULT 'pending' NOT NULL,
|
||||
`cancellation_user_notes` text,
|
||||
`cancellation_admin_notes` text,
|
||||
`cancellation_reviewed` integer DEFAULT false NOT NULL,
|
||||
`cancellation_reviewed_at` text,
|
||||
`refund_coupon_id` integer,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`refund_coupon_id`) REFERENCES `__new_coupons`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_order_status` (`id`,`order_time`,`user_id`,`order_id`,`is_packaged`,`is_delivered`,`is_cancelled`,`cancel_reason`,`is_cancelled_by_admin`,`payment_state`,`cancellation_user_notes`,`cancellation_admin_notes`,`cancellation_reviewed`,`cancellation_reviewed_at`,`refund_coupon_id`)
|
||||
SELECT `id`,`order_time`,`user_id`,`order_id`,`is_packaged`,`is_delivered`,`is_cancelled`,`cancel_reason`,`is_cancelled_by_admin`,`payment_state`,`cancellation_user_notes`,`cancellation_admin_notes`,`cancellation_reviewed`,`cancellation_reviewed_at`,`refund_coupon_id` FROM `order_status`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_refunds` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`order_id` integer NOT NULL,
|
||||
`refund_amount` text,
|
||||
`refund_status` text DEFAULT 'none',
|
||||
`merchant_refund_id` text,
|
||||
`refund_processed_at` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_refunds` (`id`,`order_id`,`refund_amount`,`refund_status`,`merchant_refund_id`,`refund_processed_at`,`created_at`)
|
||||
SELECT `id`,`order_id`,`refund_amount`,`refund_status`,`merchant_refund_id`,`refund_processed_at`,`created_at` FROM `refunds`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_payments` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`status` text NOT NULL,
|
||||
`gateway` text NOT NULL,
|
||||
`order_id` integer NOT NULL,
|
||||
`token` text,
|
||||
`merchant_order_id` text NOT NULL,
|
||||
`payload` text,
|
||||
FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_payments` (`id`,`status`,`gateway`,`order_id`,`token`,`merchant_order_id`,`payload`)
|
||||
SELECT `id`,`status`,`gateway`,`order_id`,`token`,`merchant_order_id`,`payload` FROM `payments`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_coupon_usage` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
`coupon_id` integer NOT NULL,
|
||||
`order_id` integer,
|
||||
`order_item_id` integer,
|
||||
`used_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`coupon_id`) REFERENCES `__new_coupons`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`order_item_id`) REFERENCES `__new_order_items`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_coupon_usage` (`id`,`user_id`,`coupon_id`,`order_id`,`order_item_id`,`used_at`)
|
||||
SELECT `id`,`user_id`,`coupon_id`,`order_id`,`order_item_id`,`used_at` FROM `coupon_usage`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_coupon_applicable_users` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`coupon_id` integer NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
FOREIGN KEY (`coupon_id`) REFERENCES `__new_coupons`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_coupon_applicable_users` (`id`,`coupon_id`,`user_id`)
|
||||
SELECT `id`,`coupon_id`,`user_id` FROM `coupon_applicable_users`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_coupon_applicable_products` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`coupon_id` integer NOT NULL,
|
||||
`sku_id` integer NOT NULL,
|
||||
FOREIGN KEY (`coupon_id`) REFERENCES `__new_coupons`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_coupon_applicable_products` (`id`,`coupon_id`,`sku_id`)
|
||||
SELECT `id`,`coupon_id`,`sku_id` FROM `coupon_applicable_products`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_reserved_coupons` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`secret_code` text NOT NULL,
|
||||
`coupon_code` text NOT NULL,
|
||||
`discount_percent` text,
|
||||
`flat_discount` text,
|
||||
`min_order` text,
|
||||
`sku_ids` text,
|
||||
`max_value` text,
|
||||
`valid_till` text,
|
||||
`max_limit_for_user` integer,
|
||||
`exclusive_apply` integer DEFAULT false NOT NULL,
|
||||
`is_first_order_only` integer DEFAULT false NOT NULL,
|
||||
`is_redeemed` integer DEFAULT false NOT NULL,
|
||||
`redeemed_by` integer,
|
||||
`redeemed_at` text,
|
||||
`created_by` integer NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
FOREIGN KEY (`redeemed_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`created_by`) REFERENCES `__new_staff_users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_reserved_coupons` (`id`,`secret_code`,`coupon_code`,`discount_percent`,`flat_discount`,`min_order`,`sku_ids`,`max_value`,`valid_till`,`max_limit_for_user`,`exclusive_apply`,`is_first_order_only`,`is_redeemed`,`redeemed_by`,`redeemed_at`,`created_by`,`created_at`,`region_id`)
|
||||
SELECT `id`,`secret_code`,`coupon_code`,`discount_percent`,`flat_discount`,`min_order`,`sku_ids`,`max_value`,`valid_till`,`max_limit_for_user`,`exclusive_apply`,`is_first_order_only`,`is_redeemed`,`redeemed_by`,`redeemed_at`,`created_by`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `reserved_coupons`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_cart_items` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
`sku_id` integer NOT NULL,
|
||||
`quantity` text NOT NULL,
|
||||
`added_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_cart_items` (`id`,`user_id`,`sku_id`,`quantity`,`added_at`)
|
||||
SELECT `id`,`user_id`,`sku_id`,`quantity`,`added_at` FROM `cart_items`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_complaints` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
`order_id` integer,
|
||||
`complaint_body` text NOT NULL,
|
||||
`images` text,
|
||||
`response` text,
|
||||
`is_resolved` integer DEFAULT false NOT NULL,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_complaints` (`id`,`user_id`,`order_id`,`complaint_body`,`images`,`response`,`is_resolved`,`created_at`)
|
||||
SELECT `id`,`user_id`,`order_id`,`complaint_body`,`images`,`response`,`is_resolved`,`created_at` FROM `complaints`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_user_incidents` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
`order_id` integer,
|
||||
`date_added` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`admin_comment` text,
|
||||
`added_by` integer,
|
||||
`negativity_score` integer,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`added_by`) REFERENCES `__new_staff_users`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_user_incidents` (`id`,`user_id`,`order_id`,`date_added`,`admin_comment`,`added_by`,`negativity_score`)
|
||||
SELECT `id`,`user_id`,`order_id`,`date_added`,`admin_comment`,`added_by`,`negativity_score` FROM `user_incidents`;
|
||||
--> statement-breakpoint
|
||||
-- Drop originals leaf-first (nothing references a table when it is dropped).
|
||||
DROP TABLE `user_incidents`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `complaints`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `cart_items`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `reserved_coupons`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `coupon_applicable_products`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `coupon_applicable_users`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `coupon_usage`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `payments`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `refunds`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `order_status`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `order_items`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `orders`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `product_group_membership`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `product_tags`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `product_reviews`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `special_deals`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `product_combos`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `sku_features`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `product_market_stats`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `product_skus`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `coupons`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `addresses`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `home_banners`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `vendor_snippets`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `delivery_slot_info`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `product_group_info`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `product_tag_info`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `product_info`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `store_info`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `staff_notif_creds`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `staff_users`;
|
||||
--> statement-breakpoint
|
||||
-- Promote replacements parent-first; SQLite rewrites child FK clauses on rename.
|
||||
ALTER TABLE `__new_staff_users` RENAME TO `staff_users`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_staff_notif_creds` RENAME TO `staff_notif_creds`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_store_info` RENAME TO `store_info`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_product_info` RENAME TO `product_info`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_product_tag_info` RENAME TO `product_tag_info`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_product_group_info` RENAME TO `product_group_info`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_delivery_slot_info` RENAME TO `delivery_slot_info`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_vendor_snippets` RENAME TO `vendor_snippets`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_home_banners` RENAME TO `home_banners`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_addresses` RENAME TO `addresses`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_coupons` RENAME TO `coupons`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_product_skus` RENAME TO `product_skus`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_product_market_stats` RENAME TO `product_market_stats`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_sku_features` RENAME TO `sku_features`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_product_combos` RENAME TO `product_combos`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_special_deals` RENAME TO `special_deals`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_product_reviews` RENAME TO `product_reviews`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_product_tags` RENAME TO `product_tags`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_product_group_membership` RENAME TO `product_group_membership`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_orders` RENAME TO `orders`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_order_items` RENAME TO `order_items`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_order_status` RENAME TO `order_status`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_refunds` RENAME TO `refunds`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_payments` RENAME TO `payments`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_coupon_usage` RENAME TO `coupon_usage`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_coupon_applicable_users` RENAME TO `coupon_applicable_users`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_coupon_applicable_products` RENAME TO `coupon_applicable_products`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_reserved_coupons` RENAME TO `reserved_coupons`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_cart_items` RENAME TO `cart_items`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_complaints` RENAME TO `complaints`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_user_incidents` RENAME TO `user_incidents`;
|
||||
--> statement-breakpoint
|
||||
-- Recreate indexes after original names are released.
|
||||
CREATE UNIQUE INDEX `staff_notif_creds_token_unique` ON `staff_notif_creds` (`token`);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `product_tag_info_tag_name_unique` ON `product_tag_info` (`tag_name`);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `vendor_snippets_snippet_code_unique` ON `vendor_snippets` (`snippet_code`);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `coupons_coupon_code_unique` ON `coupons` (`coupon_code`);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `product_market_stats_sku_id_unique` ON `product_market_stats` (`sku_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `unique_sku_feature_name` ON `sku_features` (`sku_id`,`feature_name`);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `unique_combo_sku_item` ON `product_combos` (`combo_sku_id`,`sku_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `unique_product_tag` ON `product_tags` (`product_id`,`tag_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `payments_merchant_order_id_unique` ON `payments` (`merchant_order_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `unique_coupon_user` ON `coupon_applicable_users` (`coupon_id`,`user_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `unique_coupon_sku` ON `coupon_applicable_products` (`coupon_id`,`sku_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `reserved_coupons_secret_code_unique` ON `reserved_coupons` (`secret_code`);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `unique_user_sku` ON `cart_items` (`user_id`,`sku_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_product_info_region` ON `product_info` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_staff_users_region` ON `staff_users` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_store_info_region` ON `store_info` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_vendor_snippets_region` ON `vendor_snippets` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_product_tag_info_region` ON `product_tag_info` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_product_group_info_region` ON `product_group_info` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_delivery_slot_info_region` ON `delivery_slot_info` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_coupons_region` ON `coupons` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_reserved_coupons_region` ON `reserved_coupons` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_home_banners_region` ON `home_banners` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_addresses_region` ON `addresses` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_orders_region` ON `orders` (`region_id`);
|
||||
|
||||
--> statement-breakpoint
|
||||
-- =====================================================================
|
||||
-- Phase 3 (from 0008 + 0009): the three const tables, seeded directly.
|
||||
-- `region_cache_versions` is not created; its 1/1/1 seed is folded into the
|
||||
-- region_consts version counters below. `region_bound_settings` is not created;
|
||||
-- its per-bound and region-level rows are seeded straight into the final tables.
|
||||
-- =====================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `global_consts` (
|
||||
`key` text PRIMARY KEY NOT NULL,
|
||||
`value` text
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS `region_consts` (
|
||||
`region_id` integer NOT NULL,
|
||||
`key` text NOT NULL,
|
||||
`value` text,
|
||||
PRIMARY KEY (`region_id`, `key`),
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS `region_bound_consts` (
|
||||
`bound_id` integer NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
`key` text NOT NULL,
|
||||
`value` text,
|
||||
PRIMARY KEY (`bound_id`, `key`),
|
||||
FOREIGN KEY (`bound_id`) REFERENCES `region_bounds`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
-- Global rows (from key_val_store, same key set as the former 0009).
|
||||
INSERT OR REPLACE INTO `global_consts` (`key`, `value`)
|
||||
SELECT `key`, `value` FROM `key_val_store`
|
||||
WHERE `key` IN ('versionNum','playStoreUrl','appStoreUrl','internalAppVersion');
|
||||
--> statement-breakpoint
|
||||
-- Per-region version counters (was region_cache_versions seeded with 1/1/1).
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT `id`, 'products_version_num', '1' FROM `regions`;
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT `id`, 'availability_version_num', '1' FROM `regions`;
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT `id`, 'slots_version_num', '1' FROM `regions`;
|
||||
--> statement-breakpoint
|
||||
-- Region-level business keys. 0006 seeded these per bound and 0009 lifted them
|
||||
-- from each region's lowest-priority bound; both seeded bounds share the same
|
||||
-- values, so seed them once per region with those values.
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT `id`, 'popularItems', '[]' FROM `regions` WHERE `name` = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT `id`, 'allItemsOrder', '[]' FROM `regions` WHERE `name` = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT `id`, 'isFlashDeliveryEnabled', 'false' FROM `regions` WHERE `name` = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT `id`, 'supportMobile', '8688182552' FROM `regions` WHERE `name` = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT `id`, 'supportEmail', 'qushammohd@gmail.com' FROM `regions` WHERE `name` = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT `id`, 'welcomeMessage', 'Hi! Thank you for your first order at Freshyo. We''re glad to have you.' FROM `regions` WHERE `name` = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
-- Fallback region-level values from the old global rows (same as 0009; only
|
||||
-- fills keys not already set above, e.g. tagsOrder).
|
||||
INSERT OR IGNORE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT r.`id`, kv.`key`, kv.`value`
|
||||
FROM `regions` r, `key_val_store` kv
|
||||
WHERE kv.`key` IN ('popularItems','allItemsOrder','tagsOrder','isFlashDeliveryEnabled','supportMobile','supportEmail','welcomeMessage');
|
||||
--> statement-breakpoint
|
||||
-- Per-bound business keys (formerly seeded into region_bound_settings in 0006).
|
||||
INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`)
|
||||
SELECT b.`id`, b.`region_id`, 'minRegularOrderValue', '300' FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`)
|
||||
SELECT b.`id`, b.`region_id`, 'freeDeliveryThreshold', '300' FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`)
|
||||
SELECT b.`id`, b.`region_id`, 'deliveryCharge', '20' FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`)
|
||||
SELECT b.`id`, b.`region_id`, 'flashFreeDeliveryThreshold', '500' FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`)
|
||||
SELECT b.`id`, b.`region_id`, 'flashDeliveryCharge', '69' FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
-- Keep only the leftover keys in key_val_store (same set 0009 keeps).
|
||||
DELETE FROM `key_val_store` WHERE `key` IN (
|
||||
'versionNum','playStoreUrl','appStoreUrl','internalAppVersion',
|
||||
'popularItems','allItemsOrder','tagsOrder','isFlashDeliveryEnabled','supportMobile','supportEmail','welcomeMessage',
|
||||
'cache_version','availability_version_num','slots_version_num'
|
||||
);
|
||||
--> statement-breakpoint
|
||||
|
|
|
|||
|
|
@ -1,24 +0,0 @@
|
|||
-- Migration: per-region storefront cache versions.
|
||||
--
|
||||
-- One row per region in `region_cache_versions` drives the versioned per-region
|
||||
-- cache files (products/stores/banners/essential-consts, availability, slots).
|
||||
-- Rows for regions created later are auto-created on first use
|
||||
-- (getRegionCacheVersions), so the seed below only covers existing regions.
|
||||
--
|
||||
-- NOTE: SQLite has no `ADD COLUMN IF NOT EXISTS`; tables use IF NOT EXISTS so the
|
||||
-- file is safe if re-applied, but rely on the migration journal to run it once.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `region_cache_versions` (
|
||||
`region_id` integer NOT NULL,
|
||||
`cache_version` integer NOT NULL DEFAULT 1,
|
||||
`availability_version_num` integer NOT NULL DEFAULT 1,
|
||||
`slots_version_num` integer NOT NULL DEFAULT 1,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS `unique_region_cache_version_region` ON `region_cache_versions` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
-- Seed one row per existing region.
|
||||
INSERT INTO `region_cache_versions` (`region_id`, `cache_version`, `availability_version_num`, `slots_version_num`)
|
||||
SELECT `id`, 1, 1, 1 FROM `regions`
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `region_cache_versions` WHERE `region_cache_versions`.`region_id` = `regions`.`id`);
|
||||
|
|
@ -64,6 +64,13 @@
|
|||
"when": 1791374400000,
|
||||
"tag": "0008_region_cache_versions",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 9,
|
||||
"version": "6",
|
||||
"when": 1792000000000,
|
||||
"tag": "0009_three_const_tables",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,119 @@
|
|||
======================================================================
|
||||
STALE REGIONALIZATION MIGRATIONS (removed 2026-10-08 19:13:57)
|
||||
Replaced by 0006_regions_and_superadmins.sql (squashed 0006-0009).
|
||||
Contents below are the verbatim pre-removal files.
|
||||
======================================================================
|
||||
|
||||
======================================================================
|
||||
FILE: 0006_regions_and_superadmins.sql
|
||||
======================================================================
|
||||
-- Migration: regions, region bounds, per-bound settings, and superadmin identities.
|
||||
--
|
||||
-- Region "Mahabubnagar" is created and all current data will be backfilled to it
|
||||
-- in a later migration (backend phase). This migration only creates the new
|
||||
-- tables and seeds the region, its two bounds, per-bound settings, and the
|
||||
-- bootstrap superadmin account.
|
||||
--
|
||||
-- NOTE: SQLite has no `ADD COLUMN IF NOT EXISTS`; tables use IF NOT EXISTS so the
|
||||
-- file is safe if re-applied, but rely on the migration journal to run it once.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `regions` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`description` text,
|
||||
`created_at` text DEFAULT (CURRENT_TIMESTAMP) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS `region_bounds` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
`description` text,
|
||||
`geojson` text NOT NULL,
|
||||
`priority` text NOT NULL,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS `unique_region_bound_priority` ON `region_bounds` (`region_id`, `priority`);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS `region_bound_settings` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
`bound_id` integer NOT NULL,
|
||||
`key` text NOT NULL,
|
||||
`value` text,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`bound_id`) REFERENCES `region_bounds`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS `unique_region_bound_setting_key` ON `region_bound_settings` (`bound_id`, `key`);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS `superadmins` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`username` text NOT NULL,
|
||||
`password_hash` text NOT NULL,
|
||||
`created_at` text DEFAULT (CURRENT_TIMESTAMP) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS `unique_superadmin_username` ON `superadmins` (`username`);
|
||||
--> statement-breakpoint
|
||||
-- Seed region.
|
||||
INSERT INTO `regions` (`name`, `description`)
|
||||
SELECT 'Mahabubnagar', 'Default region (all pre-existing data backfilled here)'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `regions` WHERE `name` = 'Mahabubnagar');
|
||||
--> statement-breakpoint
|
||||
-- Seed bounds (exact GeoJSON from apps/backend/src/map-assets/Mbnr-1.geojson / Mbnr-2.geojson).
|
||||
INSERT INTO `region_bounds` (`region_id`, `description`, `geojson`, `priority`)
|
||||
SELECT id, 'Mbnr-1', '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Polygon 4"},"geometry":{"type":"Polygon","coordinates":[[[77.9802307,16.7224827],[77.9832452,16.7186281],[77.9885003,16.7191643],[78.0027771,16.7184524],[78.0167635,16.717821],[78.0176657,16.7225884],[78.0245685,16.7301059],[78.0346065,16.7366045],[78.0483126,16.7469324],[78.0558892,16.7506815],[78.0533183,16.7547082],[78.0497798,16.7596596],[78.0456892,16.7640471],[78.0383339,16.7641426],[78.0343234,16.758687],[78.021375,16.7570244],[78.0163704,16.758279],[78.0128516,16.7590231],[78.0120219,16.7648881],[78.0095524,16.7664414],[77.99363,16.7660548],[77.9720422,16.7596124],[77.9679337,16.7449906],[77.9802307,16.7224827]]]}}]}', '1'
|
||||
FROM `regions` WHERE `name` = 'Mahabubnagar'
|
||||
AND NOT EXISTS (SELECT 1 FROM `region_bounds` WHERE `priority` = '1' AND `region_id` = (SELECT id FROM `regions` WHERE `name` = 'Mahabubnagar'));
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bounds` (`region_id`, `description`, `geojson`, `priority`)
|
||||
SELECT id, 'Mbnr-2', '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Mbnr-2"},"geometry":{"type":"Polygon","coordinates":[[[77.9773739,16.7127921],[77.9950359,16.7080928],[78.0187929,16.70999],[78.0289444,16.7211582],[78.0570875,16.7502883],[78.0662922,16.7519867],[78.0652719,16.7684088],[78.0204341,16.7689639],[78.0023161,16.770186],[77.9984809,16.7850848],[77.983305,16.782843],[77.971574,16.7646028],[77.9686551,16.7454905],[77.9773739,16.7127921]]]}}]}', '2'
|
||||
FROM `regions` WHERE `name` = 'Mahabubnagar'
|
||||
AND NOT EXISTS (SELECT 1 FROM `region_bounds` WHERE `priority` = '2' AND `region_id` = (SELECT id FROM `regions` WHERE `name` = 'Mahabubnagar'));
|
||||
--> statement-breakpoint
|
||||
-- Seed per-bound business settings (same values as the former global constants) for every bound.
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'minRegularOrderValue', '300' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'freeDeliveryThreshold', '300' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'deliveryCharge', '20' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'flashFreeDeliveryThreshold', '500' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'flashDeliveryCharge', '69' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'popularItems', '[]' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'allItemsOrder', '[]' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'isFlashDeliveryEnabled', 'false' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'supportMobile', '8688182552' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'supportEmail', 'qushammohd@gmail.com' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `region_bound_settings` (`region_id`, `bound_id`, `key`, `value`)
|
||||
SELECT r.id, b.id, 'welcomeMessage', 'Hi! Thank you for your first order at Freshyo. We''re glad to have you.' FROM `regions` r JOIN `region_bounds` b ON b.region_id = r.id WHERE r.name = 'Mahabubnagar';
|
||||
--> statement-breakpoint
|
||||
-- Bootstrap superadmin (password hash supplied by the product owner; stored as-is, never re-hashed).
|
||||
INSERT INTO `superadmins` (`username`, `password_hash`)
|
||||
SELECT 'superadmin', '$2a$12$pDL1ooXdvmdpCFpeXgEnB.7eRot4ygtL/Z9lSmW8ApjRLAhTiuOCu'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `superadmins` WHERE `username` = 'superadmin');
|
||||
|
||||
======================================================================
|
||||
FILE: 0007_region_columns_backfill.sql
|
||||
======================================================================
|
||||
-- Migration: rebuild the region-ownership FK subgraph with `region_id NOT NULL`
|
||||
-- pointing at the Mahabubnagar region created in 0006, and repair legacy orphan
|
||||
-- rows that were written before FK enforcement (they would fail the copy).
|
||||
|
|
@ -742,3 +858,116 @@ CREATE INDEX `idx_home_banners_region` ON `home_banners` (`region_id`);
|
|||
CREATE INDEX `idx_addresses_region` ON `addresses` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `idx_orders_region` ON `orders` (`region_id`);
|
||||
|
||||
======================================================================
|
||||
FILE: 0008_region_cache_versions.sql
|
||||
======================================================================
|
||||
-- Migration: per-region storefront cache versions.
|
||||
--
|
||||
-- One row per region in `region_cache_versions` drives the versioned per-region
|
||||
-- cache files (products/stores/banners/essential-consts, availability, slots).
|
||||
-- Rows for regions created later are auto-created on first use
|
||||
-- (getRegionCacheVersions), so the seed below only covers existing regions.
|
||||
--
|
||||
-- NOTE: SQLite has no `ADD COLUMN IF NOT EXISTS`; tables use IF NOT EXISTS so the
|
||||
-- file is safe if re-applied, but rely on the migration journal to run it once.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `region_cache_versions` (
|
||||
`region_id` integer NOT NULL,
|
||||
`cache_version` integer NOT NULL DEFAULT 1,
|
||||
`availability_version_num` integer NOT NULL DEFAULT 1,
|
||||
`slots_version_num` integer NOT NULL DEFAULT 1,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS `unique_region_cache_version_region` ON `region_cache_versions` (`region_id`);
|
||||
--> statement-breakpoint
|
||||
-- Seed one row per existing region.
|
||||
INSERT INTO `region_cache_versions` (`region_id`, `cache_version`, `availability_version_num`, `slots_version_num`)
|
||||
SELECT `id`, 1, 1, 1 FROM `regions`
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `region_cache_versions` WHERE `region_cache_versions`.`region_id` = `regions`.`id`);
|
||||
|
||||
======================================================================
|
||||
FILE: 0009_three_const_tables.sql
|
||||
======================================================================
|
||||
-- Migration: split the consts model into global_consts / region_consts / region_bound_consts.
|
||||
--
|
||||
-- Replaces the single key_val_store constants table (kept for the remaining
|
||||
-- leftover keys), the per-region region_cache_versions table, and the
|
||||
-- per-bound region_bound_settings table.
|
||||
--
|
||||
-- Data is copied first, then the superseded tables are dropped.
|
||||
-- NOTE: SQLite has no ADD COLUMN IF NOT EXISTS; the CREATEs use IF NOT EXISTS so the
|
||||
-- file is partially re-runnable, but rely on the migration journal to run it once.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `global_consts` (
|
||||
`key` text PRIMARY KEY NOT NULL,
|
||||
`value` text
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS `region_consts` (
|
||||
`region_id` integer NOT NULL,
|
||||
`key` text NOT NULL,
|
||||
`value` text,
|
||||
PRIMARY KEY (`region_id`, `key`),
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS `region_bound_consts` (
|
||||
`bound_id` integer NOT NULL,
|
||||
`region_id` integer NOT NULL,
|
||||
`key` text NOT NULL,
|
||||
`value` text,
|
||||
PRIMARY KEY (`bound_id`, `key`),
|
||||
FOREIGN KEY (`bound_id`) REFERENCES `region_bounds`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
-- Copy global rows.
|
||||
INSERT OR REPLACE INTO `global_consts` (`key`, `value`)
|
||||
SELECT `key`, `value` FROM `key_val_store`
|
||||
WHERE `key` IN ('versionNum','playStoreUrl','appStoreUrl','internalAppVersion');
|
||||
--> statement-breakpoint
|
||||
-- Copy per-region version counters.
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT `region_id`, 'products_version_num', CAST(`cache_version` AS TEXT) FROM `region_cache_versions`;
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT `region_id`, 'availability_version_num', CAST(`availability_version_num` AS TEXT) FROM `region_cache_versions`;
|
||||
--> statement-breakpoint
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT `region_id`, 'slots_version_num', CAST(`slots_version_num` AS TEXT) FROM `region_cache_versions`;
|
||||
--> statement-breakpoint
|
||||
-- Copy region-level business keys from each region's effective (lowest-priority) bound.
|
||||
INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT rbs.`region_id`, rbs.`key`, rbs.`value`
|
||||
FROM `region_bound_settings` rbs
|
||||
JOIN `region_bounds` rb ON rb.`id` = rbs.`bound_id`
|
||||
WHERE rbs.`key` IN ('popularItems','allItemsOrder','isFlashDeliveryEnabled','supportMobile','supportEmail','welcomeMessage')
|
||||
AND rb.`id` = (
|
||||
SELECT b2.`id` FROM `region_bounds` b2
|
||||
WHERE b2.`region_id` = rbs.`region_id`
|
||||
ORDER BY CAST(b2.`priority` AS REAL) ASC LIMIT 1
|
||||
);
|
||||
--> statement-breakpoint
|
||||
-- Fallback region-level values from the old global rows for regions with no bound rows.
|
||||
INSERT OR IGNORE INTO `region_consts` (`region_id`, `key`, `value`)
|
||||
SELECT r.`id`, kv.`key`, kv.`value`
|
||||
FROM `regions` r, `key_val_store` kv
|
||||
WHERE kv.`key` IN ('popularItems','allItemsOrder','tagsOrder','isFlashDeliveryEnabled','supportMobile','supportEmail','welcomeMessage');
|
||||
--> statement-breakpoint
|
||||
-- Copy per-bound rows.
|
||||
INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`)
|
||||
SELECT `bound_id`, `region_id`, `key`, `value` FROM `region_bound_settings`
|
||||
WHERE `key` IN ('minRegularOrderValue','freeDeliveryThreshold','deliveryCharge','flashFreeDeliveryThreshold','flashDeliveryCharge');
|
||||
--> statement-breakpoint
|
||||
-- Keep only the leftover keys in key_val_store.
|
||||
DELETE FROM `key_val_store` WHERE `key` IN (
|
||||
'versionNum','playStoreUrl','appStoreUrl','internalAppVersion',
|
||||
'popularItems','allItemsOrder','tagsOrder','isFlashDeliveryEnabled','supportMobile','supportEmail','welcomeMessage',
|
||||
'cache_version','availability_version_num','slots_version_num'
|
||||
);
|
||||
--> statement-breakpoint
|
||||
DROP TABLE IF EXISTS `region_bound_settings`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE IF EXISTS `region_cache_versions`;
|
||||
|
|
@ -27,12 +27,14 @@ export {
|
|||
// Constants
|
||||
getAllConstants,
|
||||
upsertConstants,
|
||||
getCacheVersion,
|
||||
incrementCacheVersion,
|
||||
getAvailabilityVersionNum,
|
||||
incrementAvailabilityVersionNum,
|
||||
getSlotsVersionNum,
|
||||
incrementSlotsVersionNum,
|
||||
getAllGlobalConsts,
|
||||
upsertGlobalConsts,
|
||||
getRegionConsts,
|
||||
upsertRegionConsts,
|
||||
getBoundConsts,
|
||||
upsertBoundConsts,
|
||||
getLegacyConsts,
|
||||
upsertLegacyConsts,
|
||||
} from './src/admin-apis/const'
|
||||
|
||||
export {
|
||||
|
|
@ -376,6 +378,7 @@ export {
|
|||
seedStaffPermissions,
|
||||
seedRolePermissions,
|
||||
seedKeyValStore,
|
||||
seedGlobalConsts,
|
||||
type UnitSeedData,
|
||||
type RolePermissionAssignment,
|
||||
type KeyValSeedData,
|
||||
|
|
@ -393,7 +396,9 @@ export {
|
|||
getAllRegions,
|
||||
getRegionById,
|
||||
getRegionWithBounds,
|
||||
getAllRegionsWithBounds,
|
||||
createRegion,
|
||||
createRegionWithBounds,
|
||||
updateRegion,
|
||||
getBoundsForRegion,
|
||||
getBoundById,
|
||||
|
|
@ -401,5 +406,8 @@ export {
|
|||
updateRegionBound,
|
||||
getBoundSettings,
|
||||
upsertBoundSettings,
|
||||
getRegionConstants,
|
||||
upsertRegionConstants,
|
||||
getEffectiveBoundId,
|
||||
getEffectiveRegionSettings,
|
||||
} from './src/superadmin-apis/regions'
|
||||
|
|
|
|||
|
|
@ -1,151 +1,153 @@
|
|||
import { db } from '../db/db_index'
|
||||
import { keyValStore } from '../db/schema'
|
||||
import { globalConsts, keyValStore, regionBoundConsts, regionConsts } from '../db/schema'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import type { Constant } from '@packages/shared'
|
||||
import { CONST_KEYS, CONST_KEYS_ARRAY, CONST_DEFAULTS, castConstValue } from '../lib/const-keys'
|
||||
import { CONST_KEYS_ARRAY, CONST_DEFAULTS, CONST_SCOPE, castConstValue } from '../lib/const-keys'
|
||||
|
||||
type ConstRow = { key: string; value: string | null }
|
||||
|
||||
const serializeValue = (value: unknown): string | null => {
|
||||
if (value === null || value === undefined) return null
|
||||
return typeof value === 'string' ? value : String(value)
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* global_consts
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
export async function getAllGlobalConsts(): Promise<Record<string, string | null>> {
|
||||
const rows = await db.select().from(globalConsts)
|
||||
const out: Record<string, string | null> = {}
|
||||
for (const row of rows) out[row.key] = row.value
|
||||
return out
|
||||
}
|
||||
|
||||
export async function upsertGlobalConsts(rows: ConstRow[]): Promise<void> {
|
||||
if (rows.length === 0) return
|
||||
await db.transaction(async (tx) => {
|
||||
for (const { key, value } of rows) {
|
||||
await tx
|
||||
.insert(globalConsts)
|
||||
.values({ key, value })
|
||||
.onConflictDoUpdate({ target: globalConsts.key, set: { value } })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* key_val_store (legacy leftovers)
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
export async function getLegacyConsts(): Promise<Record<string, string | null>> {
|
||||
const rows = await db.select().from(keyValStore)
|
||||
const out: Record<string, string | null> = {}
|
||||
for (const row of rows) out[row.key] = row.value
|
||||
return out
|
||||
}
|
||||
|
||||
export async function upsertLegacyConsts(rows: ConstRow[]): Promise<void> {
|
||||
if (rows.length === 0) return
|
||||
await db.transaction(async (tx) => {
|
||||
for (const { key, value } of rows) {
|
||||
await tx
|
||||
.insert(keyValStore)
|
||||
.values({ key, value })
|
||||
.onConflictDoUpdate({ target: keyValStore.key, set: { value } })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* region_consts
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
export async function getRegionConsts(regionId: number): Promise<Record<string, string | null>> {
|
||||
const rows = await db.select().from(regionConsts).where(eq(regionConsts.regionId, regionId))
|
||||
const out: Record<string, string | null> = {}
|
||||
for (const row of rows) out[row.key] = row.value
|
||||
return out
|
||||
}
|
||||
|
||||
export async function upsertRegionConsts(regionId: number, rows: ConstRow[]): Promise<void> {
|
||||
if (rows.length === 0) return
|
||||
await db.transaction(async (tx) => {
|
||||
for (const { key, value } of rows) {
|
||||
await tx
|
||||
.insert(regionConsts)
|
||||
.values({ regionId, key, value })
|
||||
.onConflictDoUpdate({
|
||||
target: [regionConsts.regionId, regionConsts.key],
|
||||
set: { value },
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* region_bound_consts
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
export async function getBoundConsts(boundId: number): Promise<Record<string, string | null>> {
|
||||
const rows = await db.select().from(regionBoundConsts).where(eq(regionBoundConsts.boundId, boundId))
|
||||
const out: Record<string, string | null> = {}
|
||||
for (const row of rows) out[row.key] = row.value
|
||||
return out
|
||||
}
|
||||
|
||||
export async function upsertBoundConsts(
|
||||
boundId: number,
|
||||
regionId: number,
|
||||
rows: ConstRow[]
|
||||
): Promise<void> {
|
||||
if (rows.length === 0) return
|
||||
await db.transaction(async (tx) => {
|
||||
for (const { key, value } of rows) {
|
||||
await tx
|
||||
.insert(regionBoundConsts)
|
||||
.values({ boundId, regionId, key, value })
|
||||
.onConflictDoUpdate({
|
||||
target: [regionBoundConsts.boundId, regionBoundConsts.key],
|
||||
set: { value, regionId },
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* Admin global editor (+ tests) — global + legacy, routed writes
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
export async function getAllConstants(): Promise<Constant[]> {
|
||||
const constants = await db.select().from(keyValStore)
|
||||
const present = new Set(constants.map((c) => c.key))
|
||||
const [globals, legacy] = await Promise.all([getAllGlobalConsts(), getLegacyConsts()])
|
||||
const merged = new Map<string, string | null>()
|
||||
for (const [k, v] of Object.entries(legacy)) merged.set(k, v)
|
||||
for (const [k, v] of Object.entries(globals)) merged.set(k, v)
|
||||
|
||||
const result: Constant[] = constants.map((c) => ({
|
||||
key: c.key,
|
||||
value: castConstValue(c.key, c.value),
|
||||
}))
|
||||
|
||||
// Surface known constants that have no row yet (e.g. a newly added one) with
|
||||
// their default, so they render in the admin form instead of being invisible.
|
||||
const result: Constant[] = []
|
||||
for (const key of CONST_KEYS_ARRAY) {
|
||||
if (!present.has(key)) {
|
||||
result.push({ key, value: castConstValue(key, CONST_DEFAULTS[key]) })
|
||||
}
|
||||
const scope = CONST_SCOPE[key]
|
||||
// Region/bound keys are edited through their own endpoints.
|
||||
if (scope === 'region' || scope === 'bound') continue
|
||||
const raw = merged.has(key) ? merged.get(key) : CONST_DEFAULTS[key as keyof typeof CONST_DEFAULTS]
|
||||
result.push({ key, value: castConstValue(key, raw) })
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
export async function upsertConstants(constants: Constant[]): Promise<void> {
|
||||
await db.transaction(async (tx) => {
|
||||
for (const { key, value } of constants) {
|
||||
// const castedValue = castConstValue(key, value)
|
||||
const castedValue = value+'';
|
||||
const existing = await tx.query.keyValStore.findFirst({
|
||||
where: eq(keyValStore.key, key),
|
||||
columns: { key: true },
|
||||
})
|
||||
export async function upsertConstants(constants: Constant[], regionId?: number): Promise<void> {
|
||||
const byScope: Record<string, ConstRow[]> = { global: [], region: [], bound: [], legacy: [] }
|
||||
for (const c of constants) {
|
||||
const scope = CONST_SCOPE[c.key] ?? 'legacy'
|
||||
byScope[scope].push({ key: c.key, value: serializeValue(c.value) })
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
await tx.update(keyValStore)
|
||||
.set({ value: castedValue })
|
||||
.where(eq(keyValStore.key, key))
|
||||
} else {
|
||||
await tx.insert(keyValStore)
|
||||
.values({ key, value: castedValue })
|
||||
}
|
||||
if (byScope.global.length) await upsertGlobalConsts(byScope.global)
|
||||
if (byScope.legacy.length) await upsertLegacyConsts(byScope.legacy)
|
||||
if (byScope.region.length) {
|
||||
if (regionId == null) {
|
||||
throw new Error('regionId is required to update region constants')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const CACHE_VERSION_KEY = CONST_KEYS.cacheVersion
|
||||
|
||||
const parseCacheVersion = (value: unknown) => {
|
||||
const parsed = Number(value)
|
||||
return Number.isFinite(parsed) ? parsed : 0
|
||||
}
|
||||
|
||||
export async function getCacheVersion(): Promise<number> {
|
||||
const record = await db.query.keyValStore.findFirst({
|
||||
where: eq(keyValStore.key, CACHE_VERSION_KEY),
|
||||
columns: { value: true },
|
||||
})
|
||||
|
||||
return record ? parseCacheVersion(record.value) : 0
|
||||
}
|
||||
|
||||
export async function incrementCacheVersion(): Promise<number> {
|
||||
return db.transaction(async (tx) => {
|
||||
const existing = await tx.query.keyValStore.findFirst({
|
||||
where: eq(keyValStore.key, CACHE_VERSION_KEY),
|
||||
columns: { value: true },
|
||||
})
|
||||
|
||||
const nextValue = parseCacheVersion(existing?.value) + 1
|
||||
|
||||
if (existing) {
|
||||
await tx.update(keyValStore)
|
||||
.set({ value: nextValue +'' })
|
||||
.where(eq(keyValStore.key, CACHE_VERSION_KEY))
|
||||
} else {
|
||||
await tx.insert(keyValStore)
|
||||
.values({ key: CACHE_VERSION_KEY, value: nextValue+'' })
|
||||
}
|
||||
|
||||
return nextValue
|
||||
})
|
||||
}
|
||||
|
||||
const AVAILABILITY_VERSION_KEY = CONST_KEYS.availabilityVersionNum
|
||||
|
||||
export async function getAvailabilityVersionNum(): Promise<number> {
|
||||
const record = await db.query.keyValStore.findFirst({
|
||||
where: eq(keyValStore.key, AVAILABILITY_VERSION_KEY),
|
||||
columns: { value: true },
|
||||
})
|
||||
|
||||
return record ? parseCacheVersion(record.value) : 0
|
||||
}
|
||||
|
||||
export async function incrementAvailabilityVersionNum(): Promise<number> {
|
||||
return db.transaction(async (tx) => {
|
||||
const existing = await tx.query.keyValStore.findFirst({
|
||||
where: eq(keyValStore.key, AVAILABILITY_VERSION_KEY),
|
||||
columns: { value: true },
|
||||
})
|
||||
|
||||
const nextValue = parseCacheVersion(existing?.value) + 1
|
||||
|
||||
if (existing) {
|
||||
await tx.update(keyValStore)
|
||||
.set({ value: nextValue +'' })
|
||||
.where(eq(keyValStore.key, AVAILABILITY_VERSION_KEY))
|
||||
} else {
|
||||
await tx.insert(keyValStore)
|
||||
.values({ key: AVAILABILITY_VERSION_KEY, value: nextValue+'' })
|
||||
}
|
||||
|
||||
return nextValue
|
||||
})
|
||||
}
|
||||
|
||||
const SLOTS_VERSION_KEY = CONST_KEYS.slotsVersionNum
|
||||
|
||||
export async function getSlotsVersionNum(): Promise<number> {
|
||||
const record = await db.query.keyValStore.findFirst({
|
||||
where: eq(keyValStore.key, SLOTS_VERSION_KEY),
|
||||
columns: { value: true },
|
||||
})
|
||||
|
||||
return record ? parseCacheVersion(record.value) : 0
|
||||
}
|
||||
|
||||
export async function incrementSlotsVersionNum(): Promise<number> {
|
||||
return db.transaction(async (tx) => {
|
||||
const existing = await tx.query.keyValStore.findFirst({
|
||||
where: eq(keyValStore.key, SLOTS_VERSION_KEY),
|
||||
columns: { value: true },
|
||||
})
|
||||
|
||||
const nextValue = parseCacheVersion(existing?.value) + 1
|
||||
|
||||
if (existing) {
|
||||
await tx.update(keyValStore)
|
||||
.set({ value: nextValue +'' })
|
||||
.where(eq(keyValStore.key, SLOTS_VERSION_KEY))
|
||||
} else {
|
||||
await tx.insert(keyValStore)
|
||||
.values({ key: SLOTS_VERSION_KEY, value: nextValue+'' })
|
||||
}
|
||||
|
||||
return nextValue
|
||||
})
|
||||
await upsertRegionConsts(regionId, byScope.region)
|
||||
}
|
||||
// Bound keys are updated via upsertBoundConsts(boundId, regionId, rows).
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ const queryLogger = {
|
|||
export function initDb(database: D1Database): void {
|
||||
const base = drizzle(database, {
|
||||
schema,
|
||||
logger: isQueryLoggingDisabled() ? undefined : queryLogger,
|
||||
// logger: isQueryLoggingDisabled() ? undefined : queryLogger,
|
||||
}) as DbClient
|
||||
dbInstance = Object.assign(base, {
|
||||
transaction: async <T>(handler: (tx: DbClient) => Promise<T>): Promise<T> => {
|
||||
|
|
|
|||
|
|
@ -417,6 +417,12 @@ export const keyValStore = sqliteTable('key_val_store', {
|
|||
value: text(),
|
||||
})
|
||||
|
||||
// App-wide consts (one row per key). Region/bound scoping lives in the two tables below.
|
||||
export const globalConsts = sqliteTable('global_consts', {
|
||||
key: text('key').primaryKey(),
|
||||
value: text(),
|
||||
})
|
||||
|
||||
// GeoJSON shape stored for a region bound (a FeatureCollection of polygons).
|
||||
export interface RegionGeoJson {
|
||||
type: 'FeatureCollection'
|
||||
|
|
@ -447,17 +453,25 @@ export const regionBounds = sqliteTable('region_bounds', {
|
|||
unq_region_priority: uniqueIndex('unique_region_bound_priority').on(t.regionId, t.priority),
|
||||
}))
|
||||
|
||||
// Per-bound business settings, stored as key/value rows so the customize screen
|
||||
// can add keys without a schema change. Effective values come from the region's
|
||||
// lowest-numbered-priority bound.
|
||||
export const regionBoundSettings = sqliteTable('region_bound_settings', {
|
||||
id: integer().primaryKey({ autoIncrement: true }),
|
||||
// Region-scoped consts (one row per key per region): region-level business
|
||||
// settings plus the per-region storefront version counters.
|
||||
export const regionConsts = sqliteTable('region_consts', {
|
||||
regionId: integer('region_id').notNull().references(() => regions.id),
|
||||
boundId: integer('bound_id').notNull().references(() => regionBounds.id),
|
||||
key: text('key').notNull(),
|
||||
value: text('value'),
|
||||
}, (t) => ({
|
||||
unq_bound_key: uniqueIndex('unique_region_bound_setting_key').on(t.boundId, t.key),
|
||||
pk: primaryKey({ columns: [t.regionId, t.key], name: 'region_consts_pk' }),
|
||||
}))
|
||||
|
||||
// Bound-scoped consts (one row per key per bound). A region's effective values
|
||||
// come from its lowest-numbered-priority bound.
|
||||
export const regionBoundConsts = sqliteTable('region_bound_consts', {
|
||||
boundId: integer('bound_id').notNull().references(() => regionBounds.id),
|
||||
regionId: integer('region_id').notNull().references(() => regions.id),
|
||||
key: text('key').notNull(),
|
||||
value: text('value'),
|
||||
}, (t) => ({
|
||||
pk: primaryKey({ columns: [t.boundId, t.key], name: 'region_bound_consts_pk' }),
|
||||
}))
|
||||
|
||||
export const superadmins = sqliteTable('superadmins', {
|
||||
|
|
@ -469,17 +483,6 @@ export const superadmins = sqliteTable('superadmins', {
|
|||
unq_username: uniqueIndex('unique_superadmin_username').on(t.username),
|
||||
}))
|
||||
|
||||
// Per-region storefront cache versions. One row per region; auto-created on
|
||||
// first use. Bumped by per-region cache generation (cloud_cache.ts).
|
||||
export const regionCacheVersions = sqliteTable('region_cache_versions', {
|
||||
regionId: integer('region_id').notNull().references(() => regions.id),
|
||||
cacheVersion: integer('cache_version').notNull().default(1),
|
||||
availabilityVersionNum: integer('availability_version_num').notNull().default(1),
|
||||
slotsVersionNum: integer('slots_version_num').notNull().default(1),
|
||||
}, (t) => ({
|
||||
unq_region: uniqueIndex('unique_region_cache_version_region').on(t.regionId),
|
||||
}))
|
||||
|
||||
export const notifications = sqliteTable('notifications', {
|
||||
id: integer().primaryKey({ autoIncrement: true }),
|
||||
userId: integer('user_id').notNull().references(() => users.id),
|
||||
|
|
@ -838,16 +841,11 @@ export const vendorSnippetsRelations = relations(vendorSnippets, ({ one }) => ({
|
|||
|
||||
export const regionsRelations = relations(regions, ({ many }) => ({
|
||||
bounds: many(regionBounds),
|
||||
boundSettings: many(regionBoundSettings),
|
||||
consts: many(regionConsts),
|
||||
}))
|
||||
|
||||
export const regionBoundsRelations = relations(regionBounds, ({ one, many }) => ({
|
||||
region: one(regions, { fields: [regionBounds.regionId], references: [regions.id] }),
|
||||
settings: many(regionBoundSettings),
|
||||
}))
|
||||
|
||||
export const regionBoundSettingsRelations = relations(regionBoundSettings, ({ one }) => ({
|
||||
region: one(regions, { fields: [regionBoundSettings.regionId], references: [regions.id] }),
|
||||
bound: one(regionBounds, { fields: [regionBoundSettings.boundId], references: [regionBounds.id] }),
|
||||
consts: many(regionBoundConsts),
|
||||
}))
|
||||
|
||||
|
|
|
|||
|
|
@ -4,12 +4,12 @@ import {
|
|||
productInfo,
|
||||
deliverySlotInfo,
|
||||
keyValStore,
|
||||
globalConsts,
|
||||
staffRoles,
|
||||
staffPermissions,
|
||||
staffRolePermissions,
|
||||
} from '@/src/db/schema'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { minOrderValue, deliveryCharge } from '@/src/lib/env-exporter'
|
||||
import { CONST_KEYS } from '@/src/lib/const-keys'
|
||||
|
||||
export async function seed() {
|
||||
|
|
@ -112,26 +112,32 @@ export async function seed() {
|
|||
}
|
||||
})
|
||||
|
||||
// Seed key-val store constants using CONST_KEYS
|
||||
const constantsToSeed = [
|
||||
{ key: CONST_KEYS.readableOrderId, value: 0 },
|
||||
{ key: CONST_KEYS.minRegularOrderValue, value: minOrderValue },
|
||||
{ key: CONST_KEYS.freeDeliveryThreshold, value: minOrderValue },
|
||||
{ key: CONST_KEYS.deliveryCharge, value: deliveryCharge },
|
||||
{ key: CONST_KEYS.flashFreeDeliveryThreshold, value: 500 },
|
||||
{ key: CONST_KEYS.flashDeliveryCharge, value: 69 },
|
||||
{ key: CONST_KEYS.popularItems, value: [] },
|
||||
{ key: CONST_KEYS.allItemsOrder, value: [] },
|
||||
// Seed global consts (global_consts table).
|
||||
const globalConstantsToSeed = [
|
||||
{ key: CONST_KEYS.versionNum, value: '1.1.0' },
|
||||
{ key: CONST_KEYS.playStoreUrl, value: 'https://info.freshyo.in/qr-based-download' },
|
||||
{ key: CONST_KEYS.appStoreUrl, value: 'https://info.freshyo.in/qr-based-download' },
|
||||
{ key: CONST_KEYS.isFlashDeliveryEnabled, value: false },
|
||||
{ key: CONST_KEYS.supportMobile, value: '8688182552' },
|
||||
{ key: CONST_KEYS.supportEmail, value: 'qushammohd@gmail.com' },
|
||||
{ key: CONST_KEYS.welcomeMessage, value: "Hi! Thank you for your first order at Freshyo. We're glad to have you." },
|
||||
{ key: CONST_KEYS.internalAppVersion, value: 1 },
|
||||
]
|
||||
|
||||
for (const constant of constantsToSeed) {
|
||||
for (const constant of globalConstantsToSeed) {
|
||||
const existing = await db.query.globalConsts.findFirst({
|
||||
where: eq(globalConsts.key, constant.key),
|
||||
})
|
||||
if (!existing) {
|
||||
await db.insert(globalConsts).values({
|
||||
key: constant.key,
|
||||
value: String(constant.value),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Seed legacy leftover consts (key_val_store table).
|
||||
const legacyConstantsToSeed = [
|
||||
{ key: CONST_KEYS.readableOrderId, value: 0 },
|
||||
]
|
||||
|
||||
for (const constant of legacyConstantsToSeed) {
|
||||
const existing = await db.query.keyValStore.findFirst({
|
||||
where: eq(keyValStore.key, constant.key),
|
||||
})
|
||||
|
|
|
|||
|
|
@ -14,13 +14,14 @@ export const CONST_KEYS = {
|
|||
flashDeliverySlotId: 'flashDeliverySlotId',
|
||||
readableOrderId: 'readableOrderId',
|
||||
versionNum: 'versionNum',
|
||||
cacheVersion: 'cache_version',
|
||||
productsVersionNum: 'products_version_num',
|
||||
availabilityVersionNum: 'availability_version_num',
|
||||
slotsVersionNum: 'slots_version_num',
|
||||
playStoreUrl: 'playStoreUrl',
|
||||
appStoreUrl: 'appStoreUrl',
|
||||
popularItems: 'popularItems',
|
||||
allItemsOrder: 'allItemsOrder',
|
||||
tagsOrder: 'tagsOrder',
|
||||
isFlashDeliveryEnabled: 'isFlashDeliveryEnabled',
|
||||
supportMobile: 'supportMobile',
|
||||
supportEmail: 'supportEmail',
|
||||
|
|
@ -42,13 +43,14 @@ export const CONST_LABELS: Record<ConstKey, string> = {
|
|||
flashDeliverySlotId: 'Flash Delivery Slot ID',
|
||||
readableOrderId: 'Readable Order ID',
|
||||
versionNum: 'Version Number',
|
||||
'cache_version': 'Cache Version',
|
||||
'products_version_num': 'Cache Version (products)',
|
||||
availability_version_num: 'Availability Cache Version',
|
||||
slots_version_num: 'Slots Cache Version',
|
||||
playStoreUrl: 'Play Store URL',
|
||||
appStoreUrl: 'App Store URL',
|
||||
popularItems: 'Popular Items',
|
||||
allItemsOrder: 'All Items Order',
|
||||
tagsOrder: 'Tags Order',
|
||||
isFlashDeliveryEnabled: 'Enable Flash Delivery',
|
||||
supportMobile: 'Support Mobile',
|
||||
supportEmail: 'Support Email',
|
||||
|
|
@ -74,13 +76,14 @@ export const CONST_TYPES: Record<ConstKey, ConstValueType> = {
|
|||
flashDeliverySlotId: 'number',
|
||||
readableOrderId: 'number',
|
||||
versionNum: 'string',
|
||||
'cache_version': 'number',
|
||||
'products_version_num': 'number',
|
||||
availability_version_num: 'number',
|
||||
slots_version_num: 'number',
|
||||
playStoreUrl: 'string',
|
||||
appStoreUrl: 'string',
|
||||
popularItems: 'string',
|
||||
allItemsOrder: 'string',
|
||||
tagsOrder: 'string',
|
||||
isFlashDeliveryEnabled: 'boolean',
|
||||
supportMobile: 'string',
|
||||
supportEmail: 'string',
|
||||
|
|
@ -102,13 +105,14 @@ export const CONST_VISIBILITY: Record<ConstKey, boolean> = {
|
|||
flashDeliverySlotId: true,
|
||||
readableOrderId: false,
|
||||
versionNum: true,
|
||||
'cache_version': false,
|
||||
'products_version_num': false,
|
||||
availability_version_num: false,
|
||||
slots_version_num: false,
|
||||
playStoreUrl: true,
|
||||
appStoreUrl: true,
|
||||
popularItems: true,
|
||||
allItemsOrder: true,
|
||||
tagsOrder: false,
|
||||
isFlashDeliveryEnabled: true,
|
||||
supportMobile: true,
|
||||
supportEmail: true,
|
||||
|
|
@ -135,13 +139,14 @@ export const CONST_DEFAULTS: Record<ConstKey, string | number | boolean> = {
|
|||
flashDeliverySlotId: 0,
|
||||
readableOrderId: 0,
|
||||
versionNum: '1.0.0',
|
||||
cache_version: 0,
|
||||
products_version_num: 0,
|
||||
availability_version_num: 0,
|
||||
slots_version_num: 0,
|
||||
playStoreUrl: 'https://info.freshyo.in/qr-based-download',
|
||||
appStoreUrl: 'https://info.freshyo.in/qr-based-download',
|
||||
popularItems: '[]',
|
||||
allItemsOrder: '[]',
|
||||
tagsOrder: '[]',
|
||||
isFlashDeliveryEnabled: false,
|
||||
supportMobile: '',
|
||||
supportEmail: '',
|
||||
|
|
@ -178,3 +183,36 @@ export const castConstValue = (key: string, value: unknown) => {
|
|||
|
||||
return String(value)
|
||||
}
|
||||
|
||||
/** 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<string, ConstScope> = {}
|
||||
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'
|
||||
|
|
|
|||
|
|
@ -1,81 +1,85 @@
|
|||
import { db } from '../db/db_index'
|
||||
import { regionCacheVersions } from '../db/schema'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { regionConsts } from '../db/schema'
|
||||
import { and, eq } from 'drizzle-orm'
|
||||
import type { RegionCacheVersions } from '@packages/shared'
|
||||
|
||||
const DEFAULT_VERSIONS = {
|
||||
cacheVersion: 1,
|
||||
availabilityVersionNum: 1,
|
||||
slotsVersionNum: 1,
|
||||
const PRODUCTS_VERSION_KEY = 'products_version_num'
|
||||
const AVAILABILITY_VERSION_KEY = 'availability_version_num'
|
||||
const SLOTS_VERSION_KEY = 'slots_version_num'
|
||||
|
||||
const DEFAULT_VERSION = 1
|
||||
|
||||
const parseVersion = (value: unknown) => {
|
||||
const parsed = Number(value)
|
||||
return Number.isFinite(parsed) ? parsed : 0
|
||||
}
|
||||
|
||||
function toVersions(row: typeof regionCacheVersions.$inferSelect): RegionCacheVersions {
|
||||
return {
|
||||
regionId: row.regionId,
|
||||
cacheVersion: row.cacheVersion ?? DEFAULT_VERSIONS.cacheVersion,
|
||||
availabilityVersionNum: row.availabilityVersionNum ?? DEFAULT_VERSIONS.availabilityVersionNum,
|
||||
slotsVersionNum: row.slotsVersionNum ?? DEFAULT_VERSIONS.slotsVersionNum,
|
||||
}
|
||||
async function readRegionVersion(regionId: number, key: string): Promise<number | null> {
|
||||
const rows = await db
|
||||
.select({ value: regionConsts.value })
|
||||
.from(regionConsts)
|
||||
.where(and(eq(regionConsts.regionId, regionId), eq(regionConsts.key, key)))
|
||||
.limit(1)
|
||||
const row = rows[0]
|
||||
return row ? parseVersion(row.value) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a region's cache versions, auto-creating the row (defaults 1/1/1) when
|
||||
* missing — e.g. regions created before migration 0008 or newly created regions
|
||||
* whose cache files have not been generated yet.
|
||||
*/
|
||||
export async function getRegionCacheVersions(regionId: number): Promise<RegionCacheVersions> {
|
||||
const existing = await db.query.regionCacheVersions.findFirst({
|
||||
where: eq(regionCacheVersions.regionId, regionId),
|
||||
})
|
||||
if (existing) return toVersions(existing)
|
||||
/** Read a region's version row, creating it (default 1) on first use. */
|
||||
async function ensureRegionVersion(regionId: number, key: string): Promise<number> {
|
||||
const existing = await readRegionVersion(regionId, key)
|
||||
if (existing !== null) return existing
|
||||
|
||||
const [row] = await db
|
||||
.insert(regionCacheVersions)
|
||||
.values({ regionId, ...DEFAULT_VERSIONS })
|
||||
.onConflictDoNothing({ target: regionCacheVersions.regionId })
|
||||
.returning()
|
||||
await db
|
||||
.insert(regionConsts)
|
||||
.values({ regionId, key, value: String(DEFAULT_VERSION) })
|
||||
.onConflictDoNothing({ target: [regionConsts.regionId, regionConsts.key] })
|
||||
|
||||
if (row) return toVersions(row)
|
||||
|
||||
const raced = await db.query.regionCacheVersions.findFirst({
|
||||
where: eq(regionCacheVersions.regionId, regionId),
|
||||
})
|
||||
if (!raced) throw new Error(`region_cache_versions row missing for region ${regionId}`)
|
||||
return toVersions(raced)
|
||||
return (await readRegionVersion(regionId, key)) ?? DEFAULT_VERSION
|
||||
}
|
||||
|
||||
async function incrementRegionVersionField(
|
||||
regionId: number,
|
||||
field: 'cacheVersion' | 'availabilityVersionNum' | 'slotsVersionNum'
|
||||
): Promise<number> {
|
||||
async function incrementRegionVersionField(regionId: number, key: string): Promise<number> {
|
||||
// Ensure the row exists first so increments never run on a missing row.
|
||||
await getRegionCacheVersions(regionId)
|
||||
await ensureRegionVersion(regionId, key)
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
const existing = await tx.query.regionCacheVersions.findFirst({
|
||||
where: eq(regionCacheVersions.regionId, regionId),
|
||||
columns: { [field]: true } as { [field]: true },
|
||||
})
|
||||
const rows = await tx
|
||||
.select({ value: regionConsts.value })
|
||||
.from(regionConsts)
|
||||
.where(and(eq(regionConsts.regionId, regionId), eq(regionConsts.key, key)))
|
||||
.limit(1)
|
||||
|
||||
const nextValue = Number((existing as Record<string, unknown> | undefined)?.[field] ?? 0) + 1
|
||||
const nextValue = parseVersion(rows[0]?.value) + 1
|
||||
|
||||
await tx
|
||||
.update(regionCacheVersions)
|
||||
.set({ [field]: nextValue } as Partial<typeof regionCacheVersions.$inferInsert>)
|
||||
.where(eq(regionCacheVersions.regionId, regionId))
|
||||
.update(regionConsts)
|
||||
.set({ value: String(nextValue) })
|
||||
.where(and(eq(regionConsts.regionId, regionId), eq(regionConsts.key, key)))
|
||||
|
||||
return nextValue
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a region's storefront cache versions (stored as region_consts rows;
|
||||
* auto-created with default 1 when missing).
|
||||
*/
|
||||
export async function getRegionCacheVersions(regionId: number): Promise<RegionCacheVersions> {
|
||||
const [cacheVersion, availabilityVersionNum, slotsVersionNum] = await Promise.all([
|
||||
ensureRegionVersion(regionId, PRODUCTS_VERSION_KEY),
|
||||
ensureRegionVersion(regionId, AVAILABILITY_VERSION_KEY),
|
||||
ensureRegionVersion(regionId, SLOTS_VERSION_KEY),
|
||||
])
|
||||
return { regionId, cacheVersion, availabilityVersionNum, slotsVersionNum }
|
||||
}
|
||||
|
||||
export async function incrementRegionCacheVersion(regionId: number): Promise<number> {
|
||||
return incrementRegionVersionField(regionId, 'cacheVersion')
|
||||
return incrementRegionVersionField(regionId, PRODUCTS_VERSION_KEY)
|
||||
}
|
||||
|
||||
export async function incrementRegionAvailabilityVersionNum(regionId: number): Promise<number> {
|
||||
return incrementRegionVersionField(regionId, 'availabilityVersionNum')
|
||||
return incrementRegionVersionField(regionId, AVAILABILITY_VERSION_KEY)
|
||||
}
|
||||
|
||||
export async function incrementRegionSlotsVersionNum(regionId: number): Promise<number> {
|
||||
return incrementRegionVersionField(regionId, 'slotsVersionNum')
|
||||
return incrementRegionVersionField(regionId, SLOTS_VERSION_KEY)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -109,3 +109,23 @@ export async function seedKeyValStore(constantsToSeed: KeyValSeedData[]): Promis
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ============================================================================
|
||||
// Global Consts Seed Helper (global_consts table)
|
||||
// ============================================================================
|
||||
|
||||
export async function seedGlobalConsts(constantsToSeed: KeyValSeedData[]): Promise<void> {
|
||||
for (const constant of constantsToSeed) {
|
||||
const { globalConsts } = await import('../db/schema')
|
||||
const existing = await db.query.globalConsts.findFirst({
|
||||
where: eq(globalConsts.key, constant.key),
|
||||
})
|
||||
if (!existing) {
|
||||
await db.insert(globalConsts).values({
|
||||
key: constant.key,
|
||||
value: String(constant.value),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
import { db } from '../db/db_index'
|
||||
import { regions, regionBounds, regionBoundSettings } from '../db/schema'
|
||||
import { and, eq, sql } from 'drizzle-orm'
|
||||
import { regions, regionBounds, regionConsts, regionBoundConsts } from '../db/schema'
|
||||
import { eq, sql } from 'drizzle-orm'
|
||||
import { BOUND_CONST_KEYS, CONST_DEFAULTS, REGION_CONST_KEYS } from '../lib/const-keys'
|
||||
import type {
|
||||
RegionSummary,
|
||||
RegionWithBounds,
|
||||
RegionBoundDto,
|
||||
CreateRegionInput,
|
||||
CreateRegionWithBoundsInput,
|
||||
UpdateRegionInput,
|
||||
CreateRegionBoundInput,
|
||||
UpdateRegionBoundInput,
|
||||
|
|
@ -15,6 +17,30 @@ import type {
|
|||
// Bounds are ordered by numeric priority ascending (lower number = higher precedence).
|
||||
const priorityOrder = sql`CAST(${regionBounds.priority} AS REAL) ASC`
|
||||
|
||||
const serializeDefault = (value: unknown): string | null => {
|
||||
if (value === null || value === undefined) return null
|
||||
return typeof value === 'string' ? value : String(value)
|
||||
}
|
||||
|
||||
const isVersionKey = (key: string) => key.includes('version')
|
||||
|
||||
function defaultRegionRows(regionId: number) {
|
||||
return REGION_CONST_KEYS.map((key) => ({
|
||||
regionId,
|
||||
key,
|
||||
value: isVersionKey(key) ? '1' : serializeDefault(CONST_DEFAULTS[key as keyof typeof CONST_DEFAULTS]),
|
||||
}))
|
||||
}
|
||||
|
||||
function defaultBoundRows(regionId: number, boundId: number) {
|
||||
return BOUND_CONST_KEYS.map((key) => ({
|
||||
regionId,
|
||||
boundId,
|
||||
key,
|
||||
value: serializeDefault(CONST_DEFAULTS[key as keyof typeof CONST_DEFAULTS]),
|
||||
}))
|
||||
}
|
||||
|
||||
function toSummary(region: typeof regions.$inferSelect): RegionSummary {
|
||||
return { id: region.id, name: region.name, description: region.description }
|
||||
}
|
||||
|
|
@ -31,7 +57,21 @@ function toBoundDto(bound: typeof regionBounds.$inferSelect): RegionBoundDto {
|
|||
|
||||
export async function getAllRegions(): Promise<RegionSummary[]> {
|
||||
const rows = await db.select().from(regions).orderBy(regions.name)
|
||||
return rows.map(toSummary)
|
||||
const boundRows = await db
|
||||
.select({ id: regionBounds.id, regionId: regionBounds.regionId })
|
||||
.from(regionBounds)
|
||||
.orderBy(regionBounds.regionId, priorityOrder)
|
||||
|
||||
// First (lowest-priority) bound per region is the effective one.
|
||||
const effective = new Map<number, number>()
|
||||
for (const bound of boundRows) {
|
||||
if (!effective.has(bound.regionId)) effective.set(bound.regionId, bound.id)
|
||||
}
|
||||
|
||||
return rows.map((region) => ({
|
||||
...toSummary(region),
|
||||
effectiveBoundId: effective.get(region.id) ?? null,
|
||||
}))
|
||||
}
|
||||
|
||||
export async function getRegionById(id: number): Promise<RegionSummary | null> {
|
||||
|
|
@ -50,6 +90,31 @@ export async function getRegionWithBounds(id: number): Promise<RegionWithBounds
|
|||
return { ...toSummary(region), bounds: bounds.map(toBoundDto) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Every region with its bounds, for coordinate-based region resolution.
|
||||
* Regions are ordered by id; each region's bounds by ascending numeric priority
|
||||
* (lowest number = highest precedence).
|
||||
*/
|
||||
export async function getAllRegionsWithBounds(): Promise<RegionWithBounds[]> {
|
||||
const regionRows = await db.select().from(regions).orderBy(regions.id)
|
||||
const boundRows = await db
|
||||
.select()
|
||||
.from(regionBounds)
|
||||
.orderBy(regionBounds.regionId, priorityOrder)
|
||||
|
||||
const byRegion = new Map<number, RegionBoundDto[]>()
|
||||
for (const bound of boundRows) {
|
||||
const list = byRegion.get(bound.regionId) ?? []
|
||||
list.push(toBoundDto(bound))
|
||||
byRegion.set(bound.regionId, list)
|
||||
}
|
||||
|
||||
return regionRows.map((region) => ({
|
||||
...toSummary(region),
|
||||
bounds: byRegion.get(region.id) ?? [],
|
||||
}))
|
||||
}
|
||||
|
||||
export async function createRegion(input: CreateRegionInput): Promise<RegionSummary> {
|
||||
const [row] = await db
|
||||
.insert(regions)
|
||||
|
|
@ -58,6 +123,43 @@ export async function createRegion(input: CreateRegionInput): Promise<RegionSumm
|
|||
return toSummary(row)
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a region together with at least one delivery bound, atomically.
|
||||
* Regions are unusable without bounds, so creation and seeding are one step.
|
||||
* Seeds default region_consts rows and per-bound region_bound_consts rows.
|
||||
*/
|
||||
export async function createRegionWithBounds(
|
||||
input: CreateRegionWithBoundsInput
|
||||
): Promise<{ region: RegionSummary; bounds: RegionBoundDto[] }> {
|
||||
return db.transaction(async (tx) => {
|
||||
const [region] = await tx
|
||||
.insert(regions)
|
||||
.values({ name: input.name, description: input.description ?? null })
|
||||
.returning()
|
||||
|
||||
const inserted = await tx
|
||||
.insert(regionBounds)
|
||||
.values(
|
||||
input.bounds.map((bound) => ({
|
||||
regionId: region.id,
|
||||
description: bound.description ?? null,
|
||||
geojson: bound.geojson,
|
||||
priority: String(bound.priority),
|
||||
}))
|
||||
)
|
||||
.returning()
|
||||
|
||||
await tx.insert(regionConsts).values(defaultRegionRows(region.id)).onConflictDoNothing()
|
||||
|
||||
const boundRows = inserted.flatMap((bound) => defaultBoundRows(region.id, bound.id))
|
||||
if (boundRows.length > 0) {
|
||||
await tx.insert(regionBoundConsts).values(boundRows).onConflictDoNothing()
|
||||
}
|
||||
|
||||
return { region: toSummary(region), bounds: inserted.map(toBoundDto) }
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateRegion(input: UpdateRegionInput): Promise<RegionSummary | null> {
|
||||
const [row] = await db
|
||||
.update(regions)
|
||||
|
|
@ -85,16 +187,24 @@ export async function getBoundById(id: number): Promise<RegionBoundDto | null> {
|
|||
}
|
||||
|
||||
export async function createRegionBound(input: CreateRegionBoundInput): Promise<RegionBoundDto> {
|
||||
const [row] = await db
|
||||
.insert(regionBounds)
|
||||
.values({
|
||||
regionId: input.regionId,
|
||||
description: input.description ?? null,
|
||||
geojson: input.geojson,
|
||||
priority: String(input.priority),
|
||||
})
|
||||
.returning()
|
||||
return toBoundDto(row)
|
||||
return db.transaction(async (tx) => {
|
||||
const [row] = await tx
|
||||
.insert(regionBounds)
|
||||
.values({
|
||||
regionId: input.regionId,
|
||||
description: input.description ?? null,
|
||||
geojson: input.geojson,
|
||||
priority: String(input.priority),
|
||||
})
|
||||
.returning()
|
||||
|
||||
await tx
|
||||
.insert(regionBoundConsts)
|
||||
.values(defaultBoundRows(input.regionId, row.id))
|
||||
.onConflictDoNothing()
|
||||
|
||||
return toBoundDto(row)
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateRegionBound(input: UpdateRegionBoundInput): Promise<RegionBoundDto | null> {
|
||||
|
|
@ -110,11 +220,12 @@ export async function updateRegionBound(input: UpdateRegionBoundInput): Promise<
|
|||
return row ? toBoundDto(row) : null
|
||||
}
|
||||
|
||||
/** Bound-scoped consts (region_bound_consts) for one bound. */
|
||||
export async function getBoundSettings(boundId: number): Promise<Record<string, string | null>> {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(regionBoundSettings)
|
||||
.where(eq(regionBoundSettings.boundId, boundId))
|
||||
.from(regionBoundConsts)
|
||||
.where(eq(regionBoundConsts.boundId, boundId))
|
||||
const result: Record<string, string | null> = {}
|
||||
for (const row of rows) result[row.key] = row.value
|
||||
return result
|
||||
|
|
@ -132,43 +243,72 @@ export async function upsertBoundSettings(
|
|||
|
||||
await db.transaction(async (tx) => {
|
||||
for (const { key, value } of settings) {
|
||||
const existing = await tx.query.regionBoundSettings.findFirst({
|
||||
where: and(
|
||||
eq(regionBoundSettings.boundId, boundId),
|
||||
eq(regionBoundSettings.key, key)
|
||||
),
|
||||
columns: { id: true },
|
||||
})
|
||||
|
||||
if (existing) {
|
||||
await tx
|
||||
.update(regionBoundSettings)
|
||||
.set({ value: value === null ? null : String(value) })
|
||||
.where(eq(regionBoundSettings.id, existing.id))
|
||||
} else {
|
||||
await tx.insert(regionBoundSettings).values({
|
||||
regionId: bound.regionId,
|
||||
boundId,
|
||||
key,
|
||||
value: value === null ? null : String(value),
|
||||
const nextValue = value === null ? null : String(value)
|
||||
await tx
|
||||
.insert(regionBoundConsts)
|
||||
.values({ regionId: bound.regionId, boundId, key, value: nextValue })
|
||||
.onConflictDoUpdate({
|
||||
target: [regionBoundConsts.boundId, regionBoundConsts.key],
|
||||
set: { value: nextValue, regionId: bound.regionId },
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** Effective region settings = settings of the region's lowest-numbered-priority bound. */
|
||||
/** Region-scoped consts (region_consts) for one region. */
|
||||
export async function getRegionConstants(regionId: number): Promise<Record<string, string | null>> {
|
||||
const rows = await db.select().from(regionConsts).where(eq(regionConsts.regionId, regionId))
|
||||
const result: Record<string, string | null> = {}
|
||||
for (const row of rows) result[row.key] = row.value
|
||||
return result
|
||||
}
|
||||
|
||||
export async function upsertRegionConstants(
|
||||
regionId: number,
|
||||
settings: Array<{ key: string; value: string | null }>
|
||||
): Promise<void> {
|
||||
await db.transaction(async (tx) => {
|
||||
for (const { key, value } of settings) {
|
||||
const nextValue = value === null ? null : String(value)
|
||||
await tx
|
||||
.insert(regionConsts)
|
||||
.values({ regionId, key, value: nextValue })
|
||||
.onConflictDoUpdate({
|
||||
target: [regionConsts.regionId, regionConsts.key],
|
||||
set: { value: nextValue },
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** The region's lowest-numbered-priority bound id, if any. */
|
||||
export async function getEffectiveBoundId(regionId: number): Promise<number | null> {
|
||||
const bound = await db.query.regionBounds.findFirst({
|
||||
where: eq(regionBounds.regionId, regionId),
|
||||
orderBy: priorityOrder,
|
||||
columns: { id: true },
|
||||
})
|
||||
return bound?.id ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Effective region settings = the region's region_consts merged with the
|
||||
* region_bound_consts of its lowest-numbered-priority bound (bound wins).
|
||||
*/
|
||||
export async function getEffectiveRegionSettings(regionId: number): Promise<EffectiveRegionSettings | null> {
|
||||
const bound = await db.query.regionBounds.findFirst({
|
||||
where: eq(regionBounds.regionId, regionId),
|
||||
orderBy: priorityOrder,
|
||||
})
|
||||
if (!bound) return null
|
||||
const settings = await getBoundSettings(bound.id)
|
||||
const [regionValues, boundValues] = await Promise.all([
|
||||
getRegionConstants(regionId),
|
||||
getBoundSettings(bound.id),
|
||||
])
|
||||
return {
|
||||
regionId,
|
||||
boundId: bound.id,
|
||||
priority: bound.priority ?? '',
|
||||
settings,
|
||||
settings: { ...regionValues, ...boundValues },
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -344,19 +344,20 @@ export async function getNextDeliveryDateWithCapacity(skuId: number): Promise<Da
|
|||
import type { SkuSummary } from '@packages/shared'
|
||||
export type { SkuSummary } from '@packages/shared'
|
||||
|
||||
export async function getAllSkusSummary(): Promise<SkuSummary[]> {
|
||||
export async function getAllSkusSummary(regionId: number | null = null): Promise<SkuSummary[]> {
|
||||
const skus = await db.query.productSkus.findMany({
|
||||
with: {
|
||||
features: true,
|
||||
marketStats: true,
|
||||
product: {
|
||||
columns: { name: true, storeId: true },
|
||||
columns: { name: true, storeId: true, regionId: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return skus
|
||||
.filter((sku) => !sku.marketStats?.isSuspended && !sku.isDeleted)
|
||||
.filter((sku) => regionId == null || sku.product?.regionId === regionId)
|
||||
.map((sku) => {
|
||||
const featureValues = (sku.features || []).map((f) => f.featureValue)
|
||||
const label = [sku.product?.name ?? 'Unknown', ...featureValues].join(' ')
|
||||
|
|
|
|||
|
|
@ -18,6 +18,12 @@ export interface RegionSummary {
|
|||
id: number
|
||||
name: string
|
||||
description: string | null
|
||||
/**
|
||||
* Id of the bound whose values are effective for this region (its
|
||||
* lowest-numbered-priority bound). Used by clients to request per-bound
|
||||
* consts. `null` when the region has no bounds.
|
||||
*/
|
||||
effectiveBoundId?: number | null
|
||||
}
|
||||
|
||||
export interface RegionBoundDto {
|
||||
|
|
@ -32,6 +38,18 @@ export interface RegionWithBounds extends RegionSummary {
|
|||
bounds: RegionBoundDto[]
|
||||
}
|
||||
|
||||
/** A bound reference without its (potentially large) geometry. */
|
||||
export type RegionBoundSummary = Omit<RegionBoundDto, 'geojson'>
|
||||
|
||||
/**
|
||||
* Result of resolving device coordinates to a region: the matched region plus the
|
||||
* specific bound that contained the point. `null` when no bound matches.
|
||||
*/
|
||||
export interface ResolvedRegion {
|
||||
region: RegionSummary
|
||||
bound: RegionBoundSummary
|
||||
}
|
||||
|
||||
export interface RegionBoundSettingDto {
|
||||
key: string
|
||||
value: string | null
|
||||
|
|
@ -50,6 +68,18 @@ export interface CreateRegionInput {
|
|||
description?: string | null
|
||||
}
|
||||
|
||||
/** A bound to create along with the region it belongs to. */
|
||||
export interface RegionBoundSeedInput {
|
||||
description?: string | null
|
||||
geojson: RegionGeoJson
|
||||
priority: string
|
||||
}
|
||||
|
||||
/** Every region must be created with at least one bound. */
|
||||
export interface CreateRegionWithBoundsInput extends CreateRegionInput {
|
||||
bounds: RegionBoundSeedInput[]
|
||||
}
|
||||
|
||||
export interface UpdateRegionInput {
|
||||
id: number
|
||||
name?: string
|
||||
|
|
|
|||
0
statement-breakpoint
Normal file
0
statement-breakpoint
Normal file
76
verify-regions.tmp.js
Normal file
76
verify-regions.tmp.js
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
const { chromium } = require('playwright');
|
||||
|
||||
(async () => {
|
||||
const browser = await chromium.launch({
|
||||
executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
||||
args: ['--no-sandbox'],
|
||||
});
|
||||
const results = [];
|
||||
const check = (name, ok, detail) => {
|
||||
results.push({ name, ok, detail });
|
||||
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ' — ' + detail : ''}`);
|
||||
};
|
||||
|
||||
// ---- web-ui: region gate ----
|
||||
{
|
||||
const page = await browser.newPage();
|
||||
await page.goto('http://localhost:4174/', { waitUntil: 'networkidle', timeout: 60000 }).catch(() => {});
|
||||
await page.waitForTimeout(4000);
|
||||
const body = await page.content();
|
||||
const hasGate = /select.*region|choose.*region|delivery region/i.test(body);
|
||||
const hasMbnr = /Mahabubnagar/i.test(body);
|
||||
check('web-ui region gate renders', hasGate, `gate=${hasGate}`);
|
||||
check('web-ui lists Mahabubnagar', hasMbnr, `listed=${hasMbnr}`);
|
||||
await page.screenshot({ path: '/tmp/verify-webui-gate.png' });
|
||||
// Try selecting the region if a matching button/option exists
|
||||
const clicked = await page.evaluate(() => {
|
||||
const els = Array.from(document.querySelectorAll('button, [role="option"], li, div'));
|
||||
const t = els.find((e) => /Mahabubnagar/i.test(e.textContent || '') && (e.textContent || '').length < 120);
|
||||
if (t) { t.click(); return true; }
|
||||
return false;
|
||||
});
|
||||
if (clicked) {
|
||||
await page.waitForTimeout(5000);
|
||||
const after = await page.content();
|
||||
check('web-ui region selectable, home loads after', !/select.*region/i.test(after) || /store|product|slot/i.test(after), `clicked=${clicked}`);
|
||||
await page.screenshot({ path: '/tmp/verify-webui-home.png' });
|
||||
} else {
|
||||
check('web-ui region selectable, home loads after', false, 'no clickable region row found');
|
||||
}
|
||||
await page.close();
|
||||
}
|
||||
|
||||
// ---- admin-web: login + customize bound tabs ----
|
||||
{
|
||||
const page = await browser.newPage();
|
||||
await page.goto('http://localhost:4175/login', { waitUntil: 'networkidle', timeout: 60000 }).catch(() => {});
|
||||
await page.waitForTimeout(3000);
|
||||
await page.screenshot({ path: '/tmp/verify-admin-login.png' });
|
||||
// Fill first text input + password input
|
||||
const inputs = await page.$$('input');
|
||||
if (inputs.length >= 2) {
|
||||
await inputs[0].fill('uitest');
|
||||
await inputs[inputs.length - 1].fill('test1234');
|
||||
const btn = await page.$('button[type="submit"], button:has-text("Login"), button:has-text("Sign in")');
|
||||
if (btn) await btn.click();
|
||||
await page.waitForTimeout(4000);
|
||||
const authed = page.url();
|
||||
check('admin-web staff login works', !/login/i.test(authed), `url=${authed}`);
|
||||
} else {
|
||||
check('admin-web staff login works', false, `found ${inputs.length} inputs`);
|
||||
}
|
||||
await page.goto('http://localhost:4175/dashboard/customize-app', { waitUntil: 'networkidle', timeout: 60000 }).catch(() => {});
|
||||
await page.waitForTimeout(5000);
|
||||
const body = await page.content();
|
||||
check('customize shows bound tabs', /Mbnr-1/i.test(body) && /Mbnr-2/i.test(body), 'Mbnr-1 & Mbnr-2');
|
||||
check('customize marks effective bound', /effective/i.test(body), 'EFFECTIVE badge/copy');
|
||||
check('customize loads bound settings', /delivery charge/i.test(body), 'settings rendered');
|
||||
await page.screenshot({ path: '/tmp/verify-admin-customize.png', fullPage: true });
|
||||
await page.close();
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
const failed = results.filter((r) => !r.ok);
|
||||
console.log(`\n${results.length - failed.length}/${results.length} checks passed`);
|
||||
process.exit(failed.length ? 1 : 0);
|
||||
})().catch((e) => { console.error('SCRIPT ERROR:', e.message); process.exit(2); });
|
||||
Loading…
Add table
Reference in a new issue