enhh
This commit is contained in:
parent
a09cb936c0
commit
d9bc8352df
123 changed files with 19398 additions and 10974 deletions
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -140,4 +140,6 @@ apps/user-ui/android/
|
|||
apps/admin-ui/android/
|
||||
.maestro-output/*
|
||||
|
||||
apps/admin-ui/.expo/cache/*
|
||||
apps/admin-ui/.expo/cache/*
|
||||
|
||||
.playwright-mcp
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import React from 'react';
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { View, ScrollView, Alert } from 'react-native';
|
||||
import { Formik } from 'formik';
|
||||
import { MyText, MyTextInput, MyTouchableOpacity, tw, AppContainer, Checkbox } from 'common-ui';
|
||||
import { trpc } from '../../../../src/trpc-client';
|
||||
import { trpc } from '@/src/trpc-client';
|
||||
import { useRouter } from 'expo-router';
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||
|
||||
|
|
@ -57,18 +57,88 @@ const CONST_VISIBILITY: Record<string, boolean> = {
|
|||
tester: false,
|
||||
};
|
||||
|
||||
// The 11 constants that are edited per region bound.
|
||||
type BoundValueType = 'number' | 'boolean' | 'array' | 'string'
|
||||
|
||||
const BOUND_KEY_TYPES: Record<string, BoundValueType> = {
|
||||
minRegularOrderValue: 'number',
|
||||
freeDeliveryThreshold: 'number',
|
||||
deliveryCharge: 'number',
|
||||
flashFreeDeliveryThreshold: 'number',
|
||||
flashDeliveryCharge: 'number',
|
||||
popularItems: 'array',
|
||||
allItemsOrder: 'array',
|
||||
isFlashDeliveryEnabled: 'boolean',
|
||||
supportMobile: 'string',
|
||||
supportEmail: 'string',
|
||||
welcomeMessage: 'string',
|
||||
};
|
||||
|
||||
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';
|
||||
|
||||
if (raw === null || raw === undefined || raw === '') {
|
||||
if (type === 'number') return 0;
|
||||
if (type === 'boolean') return false;
|
||||
if (type === 'array') return [];
|
||||
return '';
|
||||
}
|
||||
|
||||
switch (type) {
|
||||
case 'number': {
|
||||
const num = parseFloat(raw);
|
||||
return isNaN(num) ? 0 : num;
|
||||
}
|
||||
case 'boolean':
|
||||
return raw === 'true' || raw === '1' || raw === 'yes' || raw === 'on';
|
||||
case 'array':
|
||||
return raw.split(',').map((s) => s.trim()).filter((s) => s.length > 0);
|
||||
default:
|
||||
return raw;
|
||||
}
|
||||
};
|
||||
|
||||
/** 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';
|
||||
|
||||
switch (type) {
|
||||
case 'number': {
|
||||
const num = typeof value === 'number' ? value : parseFloat(value);
|
||||
return isNaN(num) ? '0' : String(num);
|
||||
}
|
||||
case 'boolean':
|
||||
return value ? 'true' : 'false';
|
||||
case 'array':
|
||||
return Array.isArray(value) ? value.join(',') : String(value ?? '');
|
||||
default:
|
||||
return value === null || value === undefined ? '' : String(value);
|
||||
}
|
||||
};
|
||||
|
||||
interface ConstantInputProps {
|
||||
constantKey: string;
|
||||
value: any;
|
||||
setFieldValue: (field: string, value: any) => void;
|
||||
router: any;
|
||||
/** When false, popularItems/allItemsOrder render as inline inputs instead of links. */
|
||||
allowSectionNavigation?: boolean;
|
||||
}
|
||||
|
||||
const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFieldValue, router }) => {
|
||||
const ConstantInput: React.FC<ConstantInputProps> = ({
|
||||
constantKey,
|
||||
value,
|
||||
setFieldValue,
|
||||
router,
|
||||
allowSectionNavigation = true,
|
||||
}) => {
|
||||
const fieldName = constantKey
|
||||
|
||||
// Special handling for popularItems - show navigation button instead of input
|
||||
if (constantKey === 'popularItems') {
|
||||
if (allowSectionNavigation && constantKey === 'popularItems') {
|
||||
return (
|
||||
<View>
|
||||
<MyText style={tw`text-sm font-medium text-gray-700 mb-2`}>
|
||||
|
|
@ -89,8 +159,7 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
|
|||
}
|
||||
|
||||
// Special handling for allItemsOrder - show navigation button instead of input
|
||||
if (constantKey === 'allItemsOrder') {
|
||||
|
||||
if (allowSectionNavigation && constantKey === 'allItemsOrder') {
|
||||
return (
|
||||
<View>
|
||||
<MyText style={tw`text-sm font-medium text-gray-700 mb-2`}>
|
||||
|
|
@ -182,7 +251,6 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
|
|||
return (
|
||||
<MyTextInput
|
||||
topLabel={CONST_LABELS[constantKey] || constantKey}
|
||||
// value={value === null || value === undefined ? '' : String(value)}
|
||||
value={value}
|
||||
onChangeText={(value) => {
|
||||
setFieldValue(fieldName, value)
|
||||
|
|
@ -194,11 +262,100 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
|
|||
|
||||
export default function CustomizeApp() {
|
||||
const router = useRouter();
|
||||
const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery();
|
||||
const [mode, setMode] = useState<'bounds' | 'global'>('bounds');
|
||||
const [selectedBoundId, setSelectedBoundId] = useState<number | null>(null);
|
||||
|
||||
const { data: region } = trpc.admin.region.current.useQuery();
|
||||
const {
|
||||
data: bounds,
|
||||
isLoading: isLoadingBounds,
|
||||
isError: isBoundsError,
|
||||
error: boundsError,
|
||||
refetch: refetchBounds,
|
||||
} = trpc.admin.region.bounds.useQuery();
|
||||
|
||||
// Only fetch the selected bound's settings (avoid requesting boundId 0).
|
||||
const {
|
||||
data: boundSettings,
|
||||
isLoading: isLoadingBoundSettings,
|
||||
isError: isBoundSettingsError,
|
||||
error: boundSettingsError,
|
||||
refetch: refetchBoundSettings,
|
||||
} = trpc.admin.region.getBoundSettings.useQuery(
|
||||
{ boundId: selectedBoundId ?? 0 },
|
||||
{ enabled: selectedBoundId !== null }
|
||||
);
|
||||
|
||||
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();
|
||||
|
||||
|
||||
const handleSubmit = (values: ConstantFormData) => {
|
||||
// Default-select the lowest-priority bound (first, ascending by priority).
|
||||
useEffect(() => {
|
||||
if (bounds && bounds.length > 0) {
|
||||
setSelectedBoundId((prev) => {
|
||||
if (prev !== null && bounds.some((b) => b.id === prev)) {
|
||||
return prev;
|
||||
}
|
||||
return bounds[0].id;
|
||||
});
|
||||
}
|
||||
}, [bounds]);
|
||||
|
||||
// The effective bound is the one with the lowest-numbered priority.
|
||||
const effectiveBoundId = useMemo(() => {
|
||||
if (!bounds || bounds.length === 0) return null;
|
||||
return bounds.reduce((min, bound) =>
|
||||
Number(bound.priority) < Number(min.priority) ? bound : min
|
||||
).id;
|
||||
}, [bounds]);
|
||||
|
||||
// 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);
|
||||
}
|
||||
return values;
|
||||
}, [boundSettings]);
|
||||
|
||||
const handleBoundSubmit = (values: ConstantFormData) => {
|
||||
if (selectedBoundId === null) return;
|
||||
|
||||
const original = boundSettings ?? {};
|
||||
const changed = REGIONAL_KEYS.filter((key) => {
|
||||
const next = serializeBoundValue(key, values[key]);
|
||||
const prev = original[key] ?? null;
|
||||
return next !== prev;
|
||||
}).map((key) => ({
|
||||
key,
|
||||
value: serializeBoundValue(key, values[key]),
|
||||
}));
|
||||
|
||||
if (changed.length === 0) {
|
||||
Alert.alert('No Changes', 'No settings were modified.');
|
||||
return;
|
||||
}
|
||||
|
||||
updateBoundSettings.mutate(
|
||||
{ boundId: selectedBoundId, settings: changed },
|
||||
{
|
||||
onSuccess: (response) => {
|
||||
Alert.alert('Success', `Updated ${response.updatedCount} settings successfully.`);
|
||||
refetchBoundSettings();
|
||||
},
|
||||
onError: (error) => {
|
||||
Alert.alert('Error', 'Failed to update settings. Please try again.');
|
||||
console.error('Update bound settings error:', error);
|
||||
},
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
const handleGlobalSubmit = (values: ConstantFormData) => {
|
||||
// Filter out constants that haven't changed
|
||||
const changedConstants = (constants || []).filter((constant) => {
|
||||
const nextValue = values[constant.key]
|
||||
|
|
@ -218,7 +375,7 @@ export default function CustomizeApp() {
|
|||
{
|
||||
onSuccess: (response) => {
|
||||
Alert.alert('Success', `Updated ${response.updatedCount} constants successfully.`);
|
||||
refetch();
|
||||
refetchConstants();
|
||||
},
|
||||
onError: (error) => {
|
||||
Alert.alert('Error', 'Failed to update constants. Please try again.');
|
||||
|
|
@ -228,70 +385,262 @@ export default function CustomizeApp() {
|
|||
);
|
||||
};
|
||||
|
||||
if (isLoadingConstants) {
|
||||
return (
|
||||
<View style={tw`flex-1 justify-center items-center`}>
|
||||
<MyText style={tw`text-gray-500`}>Loading constants...</MyText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (!constants) {
|
||||
return (
|
||||
<View style={tw`flex-1 justify-center items-center`}>
|
||||
<MyText style={tw`text-gray-500`}>Failed to load constants</MyText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const initialValues: ConstantFormData = constants.reduce((acc, constant) => {
|
||||
const globalInitialValues: ConstantFormData = (constants ?? []).reduce((acc, constant) => {
|
||||
acc[constant.key] = constant.value ?? ''
|
||||
return acc
|
||||
}, {} as ConstantFormData)
|
||||
|
||||
const renderRegional = () => {
|
||||
if (isLoadingBounds) {
|
||||
return (
|
||||
<View style={tw`py-12 items-center`}>
|
||||
<MyText style={tw`text-gray-500`}>Loading bounds...</MyText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (isBoundsError) {
|
||||
return (
|
||||
<View style={tw`py-12 items-center`}>
|
||||
<MaterialIcons name="error-outline" size={48} color="#ef4444" />
|
||||
<MyText style={tw`text-gray-700 mt-3 font-semibold`}>Failed to load bounds</MyText>
|
||||
<MyText style={tw`text-gray-500 mt-1 text-center`}>
|
||||
{boundsError?.message || 'Please try again.'}
|
||||
</MyText>
|
||||
<MyTouchableOpacity
|
||||
onPress={() => refetchBounds()}
|
||||
style={tw`mt-4 bg-blue-600 px-6 py-2 rounded-full`}
|
||||
>
|
||||
<MyText style={tw`text-white font-semibold`}>Retry</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (!bounds || bounds.length === 0) {
|
||||
return (
|
||||
<View style={tw`py-12 items-center`}>
|
||||
<MaterialIcons name="map" size={48} color="#d1d5db" />
|
||||
<MyText style={tw`text-gray-700 mt-3 font-semibold`}>No bounds configured</MyText>
|
||||
<MyText style={tw`text-gray-500 mt-1 text-center`}>
|
||||
This region has no bounds yet. Ask a superadmin to configure one.
|
||||
</MyText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const selectedBound = bounds.find((bound) => bound.id === selectedBoundId) ?? null;
|
||||
|
||||
return (
|
||||
<View>
|
||||
<MyText style={tw`text-gray-600 mb-4`}>
|
||||
Each bound stores its own business settings. The Effective bound (lowest
|
||||
priority) is the one whose settings apply to checkout.
|
||||
</MyText>
|
||||
|
||||
{/* One tab per bound, ordered ascending by priority. */}
|
||||
<ScrollView horizontal showsHorizontalScrollIndicator={false} style={tw`mb-4`}>
|
||||
{bounds.map((bound) => {
|
||||
const isSelected = bound.id === selectedBoundId;
|
||||
const isEffective = bound.id === effectiveBoundId;
|
||||
return (
|
||||
<MyTouchableOpacity
|
||||
key={bound.id}
|
||||
onPress={() => setSelectedBoundId(bound.id)}
|
||||
style={tw`mr-2 px-4 py-2 rounded-lg border ${
|
||||
isSelected ? 'bg-blue-600 border-blue-600' : 'bg-white border-gray-200'
|
||||
}`}
|
||||
>
|
||||
<MyText
|
||||
style={tw`${isSelected ? 'text-white' : 'text-gray-800'} font-semibold`}
|
||||
>
|
||||
{bound.description || `Bound #${bound.id}`}
|
||||
</MyText>
|
||||
<View style={tw`flex-row items-center mt-1`}>
|
||||
<MyText
|
||||
style={tw`${isSelected ? 'text-blue-100' : 'text-gray-400'} text-xs mr-2`}
|
||||
>
|
||||
Priority {bound.priority}
|
||||
</MyText>
|
||||
{isEffective && (
|
||||
<View
|
||||
style={tw`px-2 py-0.5 rounded-full ${
|
||||
isSelected ? 'bg-white' : 'bg-green-100'
|
||||
}`}
|
||||
>
|
||||
<MyText
|
||||
style={tw`${
|
||||
isSelected ? 'text-blue-700' : 'text-green-700'
|
||||
} text-[10px] font-bold uppercase`}
|
||||
>
|
||||
Effective
|
||||
</MyText>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</MyTouchableOpacity>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
|
||||
{selectedBound && (
|
||||
<MyText style={tw`text-gray-500 text-sm mb-4`}>
|
||||
Editing {selectedBound.description || `Bound #${selectedBound.id}`}
|
||||
{selectedBound.id === effectiveBoundId ? ' — settings apply to checkout' : ''}
|
||||
</MyText>
|
||||
)}
|
||||
|
||||
{selectedBoundId === null || isLoadingBoundSettings ? (
|
||||
<View style={tw`py-12 items-center`}>
|
||||
<MyText style={tw`text-gray-500`}>Loading settings...</MyText>
|
||||
</View>
|
||||
) : isBoundSettingsError ? (
|
||||
<View style={tw`py-12 items-center`}>
|
||||
<MaterialIcons name="error-outline" size={48} color="#ef4444" />
|
||||
<MyText style={tw`text-gray-700 mt-3 font-semibold`}>Failed to load settings</MyText>
|
||||
<MyText style={tw`text-gray-500 mt-1 text-center`}>
|
||||
{boundSettingsError?.message || 'Please try again.'}
|
||||
</MyText>
|
||||
<MyTouchableOpacity
|
||||
onPress={() => refetchBoundSettings()}
|
||||
style={tw`mt-4 bg-blue-600 px-6 py-2 rounded-full`}
|
||||
>
|
||||
<MyText style={tw`text-white font-semibold`}>Retry</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
) : (
|
||||
// key forces a fresh form per bound so drafts never leak between tabs.
|
||||
<Formik
|
||||
key={selectedBoundId}
|
||||
initialValues={boundInitialValues}
|
||||
enableReinitialize
|
||||
onSubmit={handleBoundSubmit}
|
||||
>
|
||||
{({ handleSubmit, values, setFieldValue }) => (
|
||||
<View>
|
||||
{REGIONAL_KEYS.map((key) => (
|
||||
<View key={key} style={tw`mb-4`}>
|
||||
<ConstantInput
|
||||
constantKey={key}
|
||||
value={values[key]}
|
||||
setFieldValue={setFieldValue}
|
||||
router={router}
|
||||
allowSectionNavigation={false}
|
||||
/>
|
||||
</View>
|
||||
))}
|
||||
|
||||
<MyTouchableOpacity
|
||||
onPress={() => handleSubmit()}
|
||||
disabled={updateBoundSettings.isPending}
|
||||
style={tw`bg-blue-500 p-4 rounded-lg mt-6 ${
|
||||
updateBoundSettings.isPending ? 'opacity-50' : ''
|
||||
}`}
|
||||
>
|
||||
<MyText style={tw`text-white text-center font-semibold`}>
|
||||
{updateBoundSettings.isPending ? 'Saving...' : 'Save Changes'}
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
</Formik>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
const renderGlobal = () => {
|
||||
if (isLoadingConstants) {
|
||||
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>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Formik initialValues={globalInitialValues} onSubmit={handleGlobalSubmit}>
|
||||
{({ 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.
|
||||
</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>
|
||||
)
|
||||
})}
|
||||
|
||||
<MyTouchableOpacity
|
||||
onPress={() => handleSubmit()}
|
||||
disabled={isUpdating}
|
||||
style={tw`bg-blue-500 p-4 rounded-lg mt-6 ${isUpdating ? 'opacity-50' : ''}`}
|
||||
>
|
||||
<MyText style={tw`text-white text-center font-semibold`}>
|
||||
{isUpdating ? 'Updating...' : 'Save Changes'}
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
</Formik>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<AppContainer>
|
||||
<View style={tw`flex-1 bg-gray-50 p-4`}>
|
||||
<MyText style={tw`text-xl font-bold mb-4`}>Customize App Constants</MyText>
|
||||
<MyText style={tw`text-gray-600 mb-6`}>
|
||||
Modify application constants. Changes will take effect immediately.
|
||||
</MyText>
|
||||
<MyText style={tw`text-xl font-bold`}>Customize App</MyText>
|
||||
<MyText style={tw`text-gray-500 mt-1`}>
|
||||
{region?.name ? `Region: ${region.name}` : 'Regional business settings'}
|
||||
</MyText>
|
||||
|
||||
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
|
||||
{({ handleSubmit, values, setFieldValue }) => (
|
||||
<View>
|
||||
{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>
|
||||
)
|
||||
})}
|
||||
|
||||
<MyTouchableOpacity
|
||||
onPress={() => handleSubmit()}
|
||||
disabled={isUpdating}
|
||||
style={tw`bg-blue-500 p-4 rounded-lg mt-6 ${isUpdating ? 'opacity-50' : ''}`}
|
||||
>
|
||||
<MyText style={tw`text-white text-center font-semibold`}>
|
||||
{isUpdating ? 'Updating...' : 'Save Changes'}
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
</Formik>
|
||||
{/* Top-level switch: per-bound regional settings vs. legacy global constants. */}
|
||||
<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'
|
||||
}`}
|
||||
>
|
||||
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>
|
||||
</View>
|
||||
|
||||
{mode === 'bounds' ? renderRegional() : renderGlobal()}
|
||||
</AppContainer>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,12 +7,15 @@ import { trpc } from "@/src/trpc-client";
|
|||
import { saveJWT, getJWT, deleteJWT } from "@/hooks/useJWT";
|
||||
import type { IdName } from '@packages/shared';
|
||||
|
||||
type Staff = IdName;
|
||||
interface Staff extends IdName {
|
||||
regionId?: number | null;
|
||||
}
|
||||
|
||||
interface StaffAuthContextType {
|
||||
isLoggedIn: boolean;
|
||||
isLoading: boolean;
|
||||
staff: Staff | null;
|
||||
regionId: number | null;
|
||||
login: (name: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
isLoggingIn: boolean;
|
||||
|
|
@ -94,6 +97,7 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
|
|||
isLoggedIn,
|
||||
isLoading,
|
||||
staff,
|
||||
regionId: staff?.regionId ?? null,
|
||||
login,
|
||||
logout,
|
||||
isLoggingIn: loginMutation.isPending,
|
||||
|
|
|
|||
|
|
@ -6,12 +6,15 @@ import { trpc } from '../../lib/trpc-client'
|
|||
import { saveJWT, getJWT, deleteJWT } from '../../hooks/useJWT'
|
||||
import type { IdName } from '@packages/shared'
|
||||
|
||||
type Staff = IdName
|
||||
type Staff = IdName & {
|
||||
regionId?: number | null
|
||||
}
|
||||
|
||||
interface StaffAuthContextType {
|
||||
isLoggedIn: boolean
|
||||
isLoading: boolean
|
||||
staff: Staff | null
|
||||
regionId: number | null
|
||||
login: (name: string, password: string) => Promise<void>
|
||||
logout: () => void
|
||||
isLoggingIn: boolean
|
||||
|
|
@ -92,6 +95,7 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
|
|||
isLoggedIn,
|
||||
isLoading,
|
||||
staff,
|
||||
regionId: staff?.regionId ?? null,
|
||||
login,
|
||||
logout,
|
||||
isLoggingIn: loginMutation.isPending,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import React from 'react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { Formik } from 'formik'
|
||||
import { Pencil, ChevronRight, ArrowDownUp } from 'lucide-react'
|
||||
|
|
@ -58,17 +58,87 @@ const CONST_VISIBILITY: Record<string, boolean> = {
|
|||
tester: false,
|
||||
}
|
||||
|
||||
// The 11 constants that are edited per region bound.
|
||||
type BoundValueType = 'number' | 'boolean' | 'array' | 'string'
|
||||
|
||||
const BOUND_KEY_TYPES: Record<string, BoundValueType> = {
|
||||
minRegularOrderValue: 'number',
|
||||
freeDeliveryThreshold: 'number',
|
||||
deliveryCharge: 'number',
|
||||
flashFreeDeliveryThreshold: 'number',
|
||||
flashDeliveryCharge: 'number',
|
||||
popularItems: 'array',
|
||||
allItemsOrder: 'array',
|
||||
isFlashDeliveryEnabled: 'boolean',
|
||||
supportMobile: 'string',
|
||||
supportEmail: 'string',
|
||||
welcomeMessage: 'string',
|
||||
}
|
||||
|
||||
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'
|
||||
|
||||
if (raw === null || raw === undefined || raw === '') {
|
||||
if (type === 'number') return 0
|
||||
if (type === 'boolean') return false
|
||||
if (type === 'array') return []
|
||||
return ''
|
||||
}
|
||||
|
||||
switch (type) {
|
||||
case 'number': {
|
||||
const num = parseFloat(raw)
|
||||
return isNaN(num) ? 0 : num
|
||||
}
|
||||
case 'boolean':
|
||||
return raw === 'true' || raw === '1' || raw === 'yes' || raw === 'on'
|
||||
case 'array':
|
||||
return raw.split(',').map((s) => s.trim()).filter((s) => s.length > 0)
|
||||
default:
|
||||
return raw
|
||||
}
|
||||
}
|
||||
|
||||
/** 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'
|
||||
|
||||
switch (type) {
|
||||
case 'number': {
|
||||
const num = typeof value === 'number' ? value : parseFloat(value)
|
||||
return isNaN(num) ? '0' : String(num)
|
||||
}
|
||||
case 'boolean':
|
||||
return value ? 'true' : 'false'
|
||||
case 'array':
|
||||
return Array.isArray(value) ? value.join(',') : String(value ?? '')
|
||||
default:
|
||||
return value === null || value === undefined ? '' : String(value)
|
||||
}
|
||||
}
|
||||
|
||||
interface ConstantInputProps {
|
||||
constantKey: string
|
||||
value: any
|
||||
setFieldValue: (field: string, value: any) => void
|
||||
router: any
|
||||
/** When false, popularItems/allItemsOrder render as inline inputs instead of links. */
|
||||
allowSectionNavigation?: boolean
|
||||
}
|
||||
|
||||
const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFieldValue, router }) => {
|
||||
const ConstantInput: React.FC<ConstantInputProps> = ({
|
||||
constantKey,
|
||||
value,
|
||||
setFieldValue,
|
||||
router,
|
||||
allowSectionNavigation = true,
|
||||
}) => {
|
||||
const fieldName = constantKey
|
||||
|
||||
if (constantKey === 'popularItems') {
|
||||
if (allowSectionNavigation && constantKey === 'popularItems') {
|
||||
return (
|
||||
<div>
|
||||
<MyText className="mb-2 text-sm font-medium text-gray-700">
|
||||
|
|
@ -88,7 +158,7 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
|
|||
)
|
||||
}
|
||||
|
||||
if (constantKey === 'allItemsOrder') {
|
||||
if (allowSectionNavigation && constantKey === 'allItemsOrder') {
|
||||
return (
|
||||
<div>
|
||||
<MyText className="mb-2 text-sm font-medium text-gray-700">
|
||||
|
|
@ -190,10 +260,100 @@ function CustomizeApp() {
|
|||
const router = {
|
||||
push: (to: string) => navigate({ to: to as any }),
|
||||
}
|
||||
const [mode, setMode] = useState<'bounds' | 'global'>('bounds')
|
||||
const [selectedBoundId, setSelectedBoundId] = useState<number | null>(null)
|
||||
|
||||
const { data: region } = trpc.admin.region.current.useQuery()
|
||||
const {
|
||||
data: bounds,
|
||||
isLoading: isLoadingBounds,
|
||||
isError: isBoundsError,
|
||||
error: boundsError,
|
||||
refetch: refetchBounds,
|
||||
} = trpc.admin.region.bounds.useQuery()
|
||||
|
||||
// Only fetch the selected bound's settings (avoid requesting boundId 0).
|
||||
const {
|
||||
data: boundSettings,
|
||||
isLoading: isLoadingBoundSettings,
|
||||
isError: isBoundSettingsError,
|
||||
error: boundSettingsError,
|
||||
refetch: refetchBoundSettings,
|
||||
} = trpc.admin.region.getBoundSettings.useQuery(
|
||||
{ boundId: selectedBoundId ?? 0 },
|
||||
{ enabled: selectedBoundId !== null },
|
||||
)
|
||||
|
||||
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()
|
||||
|
||||
const handleSubmit = (values: ConstantFormData) => {
|
||||
// Default-select the lowest-priority bound (first, ascending by priority).
|
||||
useEffect(() => {
|
||||
if (bounds && bounds.length > 0) {
|
||||
setSelectedBoundId((prev) => {
|
||||
if (prev !== null && bounds.some((b) => b.id === prev)) {
|
||||
return prev
|
||||
}
|
||||
return bounds[0].id
|
||||
})
|
||||
}
|
||||
}, [bounds])
|
||||
|
||||
// The effective bound is the one with the lowest-numbered priority.
|
||||
const effectiveBoundId = useMemo(() => {
|
||||
if (!bounds || bounds.length === 0) return null
|
||||
return bounds.reduce((min, bound) =>
|
||||
Number(bound.priority) < Number(min.priority) ? bound : min,
|
||||
).id
|
||||
}, [bounds])
|
||||
|
||||
// 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)
|
||||
}
|
||||
return values
|
||||
}, [boundSettings])
|
||||
|
||||
const handleBoundSubmit = (values: ConstantFormData) => {
|
||||
if (selectedBoundId === null) return
|
||||
|
||||
const original = boundSettings ?? {}
|
||||
const changed = REGIONAL_KEYS.filter((key) => {
|
||||
const next = serializeBoundValue(key, values[key])
|
||||
const prev = original[key] ?? null
|
||||
return next !== prev
|
||||
}).map((key) => ({
|
||||
key,
|
||||
value: serializeBoundValue(key, values[key]),
|
||||
}))
|
||||
|
||||
if (changed.length === 0) {
|
||||
window.alert('No settings were modified.')
|
||||
return
|
||||
}
|
||||
|
||||
updateBoundSettings(
|
||||
{ boundId: selectedBoundId, settings: changed },
|
||||
{
|
||||
onSuccess: (response) => {
|
||||
window.alert(`Updated ${response.updatedCount} settings successfully.`)
|
||||
refetchBoundSettings()
|
||||
},
|
||||
onError: (error) => {
|
||||
window.alert('Failed to update settings. Please try again.')
|
||||
console.error('Update bound settings error:', error)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const handleGlobalSubmit = (values: ConstantFormData) => {
|
||||
const changedConstants = (constants || []).filter((constant) => {
|
||||
const nextValue = values[constant.key]
|
||||
return JSON.stringify(nextValue) !== JSON.stringify(constant.value)
|
||||
|
|
@ -218,71 +378,247 @@ function CustomizeApp() {
|
|||
window.alert('Failed to update constants. Please try again.')
|
||||
console.error('Update constants error:', error)
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (isLoadingConstants) {
|
||||
const renderRegional = () => {
|
||||
if (isLoadingBounds) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center py-12">
|
||||
<MyText className="text-gray-500">Loading bounds...</MyText>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isBoundsError) {
|
||||
return (
|
||||
<div className="flex flex-col items-center py-12">
|
||||
<MyText className="font-semibold text-gray-700">Failed to load bounds</MyText>
|
||||
<MyText className="mt-1 text-center text-gray-500">
|
||||
{boundsError?.message || 'Please try again.'}
|
||||
</MyText>
|
||||
<button
|
||||
onClick={() => refetchBounds()}
|
||||
className="mt-4 rounded-full bg-blue-600 px-6 py-2"
|
||||
>
|
||||
<MyText className="font-semibold text-white">Retry</MyText>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!bounds || bounds.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center py-12">
|
||||
<MyText className="font-semibold text-gray-700">No bounds configured</MyText>
|
||||
<MyText className="mt-1 text-center text-gray-500">
|
||||
This region has no bounds yet. Ask a superadmin to configure one.
|
||||
</MyText>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const selectedBound = bounds.find((bound) => bound.id === selectedBoundId) ?? null
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<MyText className="text-gray-500">Loading constants...</MyText>
|
||||
<div>
|
||||
<MyText className="mb-4 text-gray-600">
|
||||
Each bound stores its own business settings. Only the effective bound (lowest priority)
|
||||
settings apply to checkout.
|
||||
</MyText>
|
||||
|
||||
{/* One tab per bound, ordered ascending by priority. */}
|
||||
<div className="mb-4 flex flex-row gap-2 overflow-x-auto pb-1">
|
||||
{bounds.map((bound) => {
|
||||
const isSelected = bound.id === selectedBoundId
|
||||
const isEffective = bound.id === effectiveBoundId
|
||||
return (
|
||||
<button
|
||||
key={bound.id}
|
||||
onClick={() => setSelectedBoundId(bound.id)}
|
||||
className={`rounded-lg border px-4 py-2 text-left ${
|
||||
isSelected ? 'border-blue-600 bg-blue-600' : 'border-gray-200 bg-white'
|
||||
}`}
|
||||
>
|
||||
<MyText className={`font-semibold ${isSelected ? 'text-white' : 'text-gray-800'}`}>
|
||||
{bound.description || `Bound #${bound.id}`}
|
||||
</MyText>
|
||||
<div className="mt-1 flex flex-row items-center">
|
||||
<MyText className={`mr-2 text-xs ${isSelected ? 'text-blue-100' : 'text-gray-400'}`}>
|
||||
Priority {bound.priority}
|
||||
</MyText>
|
||||
{isEffective && (
|
||||
<span
|
||||
className={`rounded-full px-2 py-0.5 text-[10px] font-bold uppercase ${
|
||||
isSelected ? 'bg-white text-blue-700' : 'bg-green-100 text-green-700'
|
||||
}`}
|
||||
>
|
||||
Effective
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{selectedBound && (
|
||||
<MyText className="mb-4 text-sm text-gray-500">
|
||||
Editing {selectedBound.description || `Bound #${selectedBound.id}`}
|
||||
{selectedBound.id === effectiveBoundId ? ' — settings apply to checkout' : ''}
|
||||
</MyText>
|
||||
)}
|
||||
|
||||
{selectedBoundId === null || isLoadingBoundSettings ? (
|
||||
<div className="flex flex-1 items-center justify-center py-12">
|
||||
<MyText className="text-gray-500">Loading settings...</MyText>
|
||||
</div>
|
||||
) : isBoundSettingsError ? (
|
||||
<div className="flex flex-col items-center py-12">
|
||||
<MyText className="font-semibold text-gray-700">Failed to load settings</MyText>
|
||||
<MyText className="mt-1 text-center text-gray-500">
|
||||
{boundSettingsError?.message || 'Please try again.'}
|
||||
</MyText>
|
||||
<button
|
||||
onClick={() => refetchBoundSettings()}
|
||||
className="mt-4 rounded-full bg-blue-600 px-6 py-2"
|
||||
>
|
||||
<MyText className="font-semibold text-white">Retry</MyText>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
// key forces a fresh form per bound so drafts never leak between tabs.
|
||||
<Formik
|
||||
key={selectedBoundId}
|
||||
initialValues={boundInitialValues}
|
||||
enableReinitialize
|
||||
onSubmit={handleBoundSubmit}
|
||||
>
|
||||
{({ handleSubmit, values, setFieldValue }) => (
|
||||
<div>
|
||||
{REGIONAL_KEYS.map((key) => (
|
||||
<div key={key} className="mb-4">
|
||||
<ConstantInput
|
||||
constantKey={key}
|
||||
value={values[key]}
|
||||
setFieldValue={setFieldValue}
|
||||
router={router}
|
||||
allowSectionNavigation={false}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<button
|
||||
onClick={() => handleSubmit()}
|
||||
disabled={isSavingBound}
|
||||
className={`mt-6 rounded-lg bg-blue-500 p-4 ${isSavingBound ? 'opacity-50' : ''}`}
|
||||
>
|
||||
<MyText className="text-center font-semibold text-white">
|
||||
{isSavingBound ? 'Saving...' : 'Save Changes'}
|
||||
</MyText>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</Formik>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!constants) {
|
||||
const renderGlobal = () => {
|
||||
if (isLoadingConstants) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<MyText className="text-gray-500">Loading constants...</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 (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<MyText className="text-gray-500">Failed to load constants</MyText>
|
||||
</div>
|
||||
<Formik initialValues={initialValues} onSubmit={handleGlobalSubmit}>
|
||||
{({ 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.
|
||||
</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>
|
||||
)
|
||||
})}
|
||||
|
||||
<button
|
||||
onClick={() => handleSubmit()}
|
||||
disabled={isUpdating}
|
||||
className={`mt-6 rounded-lg bg-blue-500 p-4 ${isUpdating ? 'opacity-50' : ''}`}
|
||||
>
|
||||
<MyText className="text-center font-semibold text-white">
|
||||
{isUpdating ? 'Updating...' : 'Save Changes'}
|
||||
</MyText>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</Formik>
|
||||
)
|
||||
}
|
||||
|
||||
const initialValues: ConstantFormData = constants.reduce((acc, constant) => {
|
||||
acc[constant.key] = constant.value ?? ''
|
||||
return acc
|
||||
}, {} as ConstantFormData)
|
||||
|
||||
return (
|
||||
<AppContainer>
|
||||
<div className="flex-1 bg-gray-50 p-4">
|
||||
<MyText className="mb-4 text-xl font-bold">Customize App Constants</MyText>
|
||||
<MyText className="mb-6 text-gray-600">
|
||||
Modify application constants. Changes will take effect immediately.
|
||||
<MyText className="mb-1 text-xl font-bold">Customize App</MyText>
|
||||
<MyText className="mb-2 text-gray-600">
|
||||
{region?.name ? `Region: ${region.name}` : 'Regional business settings'}
|
||||
</MyText>
|
||||
<MyText className="mb-4 text-gray-600">
|
||||
Modify application settings. Changes will take effect immediately.
|
||||
</MyText>
|
||||
|
||||
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
|
||||
{({ handleSubmit, values, setFieldValue }) => (
|
||||
<div>
|
||||
{constants.map((constant) => {
|
||||
if (!CONST_VISIBILITY[constant.key]) {
|
||||
return null
|
||||
}
|
||||
{/* Top-level switch: per-bound regional settings vs. legacy global constants. */}
|
||||
<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>
|
||||
</div>
|
||||
|
||||
return (
|
||||
<div key={constant.key} className="mb-4">
|
||||
<ConstantInput
|
||||
constantKey={constant.key}
|
||||
value={values[constant.key]}
|
||||
setFieldValue={setFieldValue}
|
||||
router={router}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
<button
|
||||
onClick={() => handleSubmit()}
|
||||
disabled={isUpdating}
|
||||
className={`mt-6 rounded-lg bg-blue-500 p-4 ${isUpdating ? 'opacity-50' : ''}`}
|
||||
>
|
||||
<MyText className="text-center font-semibold text-white">
|
||||
{isUpdating ? 'Updating...' : 'Save Changes'}
|
||||
</MyText>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</Formik>
|
||||
{mode === 'bounds' ? renderRegional() : renderGlobal()}
|
||||
</div>
|
||||
</AppContainer>
|
||||
)
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -3,7 +3,7 @@ import type { Context } from 'hono'
|
|||
import { cors } from 'hono/cors'
|
||||
import { logger } from 'hono/logger'
|
||||
import { trpcServer } from '@hono/trpc-server'
|
||||
import { getStaffUserById, isUserSuspended } from '@/src/dbService'
|
||||
import { getStaffUserById, isUserSuspended, getSuperadminById } from '@/src/dbService'
|
||||
import mainRouter from '@/src/main-router'
|
||||
import { appRouter } from '@/src/trpc/router'
|
||||
import { TRPCError } from '@trpc/server'
|
||||
|
|
@ -15,7 +15,7 @@ export const createApp = () => {
|
|||
|
||||
// CORS middleware
|
||||
app.use(cors({
|
||||
origin: ['http://localhost:5174', 'http://localhost:4174', 'http://localhost:4175', 'https://ui.freshyo.in', 'https://www.freshyo.in', 'https://webui.freshyo.in', 'https://app.freshyo.in', 'https://admin.freshyo.in', 'https://superadmin.freshyo.in'],
|
||||
origin: ['http://localhost:5174', 'http://localhost:4174', 'http://localhost:4176', 'http://localhost:4175', 'https://ui.freshyo.in', 'https://www.freshyo.in', 'https://webui.freshyo.in', 'https://app.freshyo.in', 'https://admin.freshyo.in', 'https://superadmin.freshyo.in'],
|
||||
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
||||
allowHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'Caller-Interface'],
|
||||
credentials: true,
|
||||
|
|
@ -30,6 +30,7 @@ export const createApp = () => {
|
|||
createContext: async ({ req }, c) => {
|
||||
let user = null
|
||||
let staffUser = null
|
||||
let superadmin = null
|
||||
const authHeader = req.headers.get('authorization')
|
||||
const callerInterface = req.headers.get('caller-interface')
|
||||
|
||||
|
|
@ -56,8 +57,13 @@ export const createApp = () => {
|
|||
const { payload } = await jwtVerify(token, getEncodedJwtSecret())
|
||||
const decoded = payload as any
|
||||
|
||||
// Check if this is a staff token (has staffId)
|
||||
if (decoded.staffId) {
|
||||
if (decoded.identityType === 'superadmin' || decoded.superadminId) {
|
||||
// Superadmin token — resolve from the dedicated superadmins table.
|
||||
const superadminRow = await getSuperadminById(decoded.superadminId)
|
||||
if (superadminRow) {
|
||||
superadmin = { id: superadminRow.id, username: superadminRow.username }
|
||||
}
|
||||
} else if (decoded.staffId) {
|
||||
// This is a staff token, verify staff exists
|
||||
const staff = await getStaffUserById(decoded.staffId)
|
||||
|
||||
|
|
@ -66,6 +72,7 @@ export const createApp = () => {
|
|||
staffUser = {
|
||||
id: staff.id,
|
||||
name: staff.name,
|
||||
regionId: (staff as any).regionId ?? 0,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
|
@ -86,7 +93,7 @@ export const createApp = () => {
|
|||
// Invalid token, both user and staffUser remain null
|
||||
}
|
||||
}
|
||||
return { req, c, user, staffUser, callerInterface }
|
||||
return { req, c, user, staffUser, superadmin, callerInterface }
|
||||
},
|
||||
onError({ error, path, type, ctx }) {
|
||||
console.error('🚨 tRPC Error :', {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { initializeAllStores } from '@/src/stores/store-initializer'
|
|||
import { ensureWorkerInit } from '@/src/lib/worker-init'
|
||||
|
||||
const LAST_TRIGGER_KEY = 'lastTrigger'
|
||||
const PENDING_REGIONS_KEY = 'pendingRegions'
|
||||
const ALARM_DELAY_MINUTES = 0.5
|
||||
// const ALARM_DELAY_MINUTES = 0.1
|
||||
|
||||
|
|
@ -16,31 +17,32 @@ export class CacheCreator {
|
|||
ensureWorkerInit(env)
|
||||
}
|
||||
|
||||
async schedule(): Promise<void> {
|
||||
console.log( 'from the fetch method of durable object')
|
||||
// if (request.method === 'POST' && url.pathname === '/schedule') {
|
||||
const now = Date.now()
|
||||
await this.state.storage.put(LAST_TRIGGER_KEY, now)
|
||||
const alarmAt = dayjs(now).add(ALARM_DELAY_MINUTES, 'minute').valueOf()
|
||||
await this.state.storage.setAlarm(alarmAt)
|
||||
// return new Response('OK')
|
||||
// }
|
||||
// if (request.method === 'POST' && url.pathname === '/clear') {
|
||||
await this.state.storage.deleteAll()
|
||||
// return new Response('OK')
|
||||
// }
|
||||
async schedule(regionId?: number): Promise<void> {
|
||||
console.log('from the fetch method of durable object')
|
||||
const now = Date.now()
|
||||
await this.state.storage.put(LAST_TRIGGER_KEY, now)
|
||||
|
||||
// return new Response('CacheCreator ready', { status: 200 })
|
||||
// Accumulate per-region regeneration requests. Empty = all regions.
|
||||
// No global mutable current-region: pending ids are drained by the alarm.
|
||||
if (regionId != null && Number.isFinite(regionId)) {
|
||||
const pending = ((await this.state.storage.get(PENDING_REGIONS_KEY)) as number[] | undefined) ?? []
|
||||
if (!pending.includes(regionId)) {
|
||||
pending.push(regionId)
|
||||
await this.state.storage.put(PENDING_REGIONS_KEY, pending)
|
||||
}
|
||||
}
|
||||
|
||||
const alarmAt = dayjs(now).add(ALARM_DELAY_MINUTES, 'minute').valueOf()
|
||||
await this.state.storage.setAlarm(alarmAt)
|
||||
}
|
||||
|
||||
|
||||
async fetch(request: Request): Promise<Response> {
|
||||
const url = new URL(request.url)
|
||||
if (request.method === 'POST' && url.pathname === '/schedule') {
|
||||
const now = Date.now()
|
||||
await this.state.storage.put(LAST_TRIGGER_KEY, now)
|
||||
const alarmAt = dayjs(now).add(ALARM_DELAY_MINUTES, 'minute').valueOf()
|
||||
await this.state.storage.setAlarm(alarmAt)
|
||||
const regionParam = url.searchParams.get('regionId')
|
||||
const regionId = regionParam != null ? parseInt(regionParam, 10) : undefined
|
||||
await this.schedule(Number.isFinite(regionId) ? regionId : undefined)
|
||||
return new Response('OK')
|
||||
}
|
||||
if (request.method === 'POST' && url.pathname === '/clear') {
|
||||
|
|
@ -60,10 +62,19 @@ export class CacheCreator {
|
|||
}
|
||||
|
||||
const threshold = dayjs().subtract(ALARM_DELAY_MINUTES, 'minute')
|
||||
const isQualify = dayjs(lastTrigger).isBefore(threshold);
|
||||
const isQualify = dayjs(lastTrigger).isBefore(threshold);
|
||||
console.log({isQualify, threshold, curr: dayjs(lastTrigger)})
|
||||
if (isQualify) {
|
||||
await initializeAllStores()
|
||||
const pending = ((await this.state.storage.get(PENDING_REGIONS_KEY)) as number[] | undefined) ?? []
|
||||
await this.state.storage.delete(PENDING_REGIONS_KEY)
|
||||
|
||||
if (pending.length === 0) {
|
||||
await initializeAllStores()
|
||||
} else {
|
||||
for (const regionId of pending) {
|
||||
await initializeAllStores(regionId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,32 +5,42 @@ import { scaffoldStores } from '@/src/trpc/apis/user-apis/apis/stores'
|
|||
import { scaffoldSlotsWithProducts } from '@/src/trpc/apis/user-apis/apis/slots'
|
||||
import { scaffoldBanners } from '@/src/trpc/apis/user-apis/apis/banners'
|
||||
import { scaffoldStoreWithProducts } from '@/src/trpc/apis/user-apis/apis/stores'
|
||||
import { getStoresSummary, incrementCacheVersion, incrementAvailabilityVersionNum, incrementSlotsVersionNum } from '@/src/dbService'
|
||||
import {
|
||||
getStoresSummary,
|
||||
getAllRegions,
|
||||
incrementRegionCacheVersion,
|
||||
incrementRegionAvailabilityVersionNum,
|
||||
incrementRegionSlotsVersionNum,
|
||||
} from '@/src/dbService'
|
||||
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'
|
||||
|
||||
const buildCachePath = (path: string, version: number) => `v-${version}/${path}`
|
||||
const buildRegionCachePath = (regionId: number, version: number, filename: string) =>
|
||||
`regions/${regionId}/v-${version}/${filename}`
|
||||
|
||||
const buildAvailabilityPath = (version: number) => `av-${version}/${CACHE_FILENAMES.availability}`
|
||||
const buildRegionAvailabilityPath = (regionId: number, version: number) =>
|
||||
`regions/${regionId}/av-${version}/${CACHE_FILENAMES.availability}`
|
||||
|
||||
const buildSlotsPath = (version: number) => `slots/v-${version}/${CACHE_FILENAMES.slots}`
|
||||
const buildRegionSlotsPath = (regionId: number, version: number) =>
|
||||
`regions/${regionId}/slots/v-${version}/${CACHE_FILENAMES.slots}`
|
||||
|
||||
function constructCacheUrl(path: string, version: number): string {
|
||||
return `${getAssetsDomain()}${getApiCacheKey()}/${buildCachePath(path, version)}`
|
||||
function constructRegionCacheUrl(regionId: number, filename: string, version: number): string {
|
||||
return `${getAssetsDomain()}${getApiCacheKey()}/${buildRegionCachePath(regionId, version, filename)}`
|
||||
}
|
||||
|
||||
function constructAvailabilityUrl(version: number): string {
|
||||
return `${getAssetsDomain()}${buildAvailabilityPath(version)}`
|
||||
function constructRegionAvailabilityUrl(regionId: number, version: number): string {
|
||||
return `${getAssetsDomain()}${buildRegionAvailabilityPath(regionId, version)}`
|
||||
}
|
||||
|
||||
function constructSlotsUrl(version: number): string {
|
||||
return `${getAssetsDomain()}${buildSlotsPath(version)}`
|
||||
function constructRegionSlotsUrl(regionId: number, version: number): string {
|
||||
return `${getAssetsDomain()}${buildRegionSlotsPath(regionId, version)}`
|
||||
}
|
||||
|
||||
export interface CreateAllCacheFilesResult {
|
||||
export interface RegionCacheFilesResult {
|
||||
regionId: number
|
||||
cacheVersion: number
|
||||
products: string
|
||||
essentialConsts: string
|
||||
|
|
@ -41,12 +51,12 @@ export interface CreateAllCacheFilesResult {
|
|||
individualStores: string[]
|
||||
}
|
||||
|
||||
export async function createAllCacheFiles(): Promise<CreateAllCacheFilesResult> {
|
||||
console.log('Starting creation of all cache files...')
|
||||
export async function createRegionCacheFiles(regionId: number): Promise<RegionCacheFilesResult> {
|
||||
console.log(`Starting creation of cache files for region ${regionId}...`)
|
||||
|
||||
const cacheVersion = await incrementCacheVersion()
|
||||
const cacheVersion = await incrementRegionCacheVersion(regionId)
|
||||
|
||||
// Create all global cache files in parallel
|
||||
// Create all per-region cache files in parallel
|
||||
const [
|
||||
productsKey,
|
||||
essentialConstsKey,
|
||||
|
|
@ -56,42 +66,43 @@ export async function createAllCacheFiles(): Promise<CreateAllCacheFilesResult>
|
|||
bannersKey,
|
||||
individualStoreKeys,
|
||||
] = await Promise.all([
|
||||
createProductsFileInternal(cacheVersion),
|
||||
createEssentialConstsFileInternal(cacheVersion),
|
||||
createStoresFileInternal(cacheVersion),
|
||||
createSlotsCacheFile(false),
|
||||
createAvailabilityCacheFile(false),
|
||||
createBannersFileInternal(cacheVersion),
|
||||
createAllStoresFilesInternal(cacheVersion),
|
||||
createProductsFileInternal(regionId, cacheVersion),
|
||||
createEssentialConstsFileInternal(regionId, cacheVersion),
|
||||
createStoresFileInternal(regionId, cacheVersion),
|
||||
createSlotsCacheFile(regionId, false),
|
||||
createAvailabilityCacheFile(regionId, false),
|
||||
createBannersFileInternal(regionId, cacheVersion),
|
||||
createAllStoresFilesInternal(regionId, cacheVersion),
|
||||
])
|
||||
|
||||
const stores = await getStoresSummary()
|
||||
const stores = await getStoresSummary(regionId)
|
||||
|
||||
// Collect all URLs for batch cache purge
|
||||
// Collect all per-region URLs for batch cache purge
|
||||
const urls = [
|
||||
constructCacheUrl(CACHE_FILENAMES.products, cacheVersion),
|
||||
constructCacheUrl(CACHE_FILENAMES.essentialConsts, cacheVersion),
|
||||
constructCacheUrl(CACHE_FILENAMES.stores, cacheVersion),
|
||||
constructSlotsUrl(slotsVersion),
|
||||
constructAvailabilityUrl(availabilityVersion),
|
||||
constructCacheUrl(CACHE_FILENAMES.banners, cacheVersion),
|
||||
...stores.map((store) => constructCacheUrl(`stores/${store.id}.json`, cacheVersion)),
|
||||
constructRegionCacheUrl(regionId, CACHE_FILENAMES.products, cacheVersion),
|
||||
constructRegionCacheUrl(regionId, CACHE_FILENAMES.essentialConsts, cacheVersion),
|
||||
constructRegionCacheUrl(regionId, CACHE_FILENAMES.stores, cacheVersion),
|
||||
constructRegionSlotsUrl(regionId, slotsVersion),
|
||||
constructRegionAvailabilityUrl(regionId, availabilityVersion),
|
||||
constructRegionCacheUrl(regionId, CACHE_FILENAMES.banners, cacheVersion),
|
||||
...stores.map((store) => constructRegionCacheUrl(regionId, `stores/${store.id}.json`, cacheVersion)),
|
||||
]
|
||||
|
||||
// Purge all caches in one batch with retry
|
||||
try {
|
||||
await retryWithExponentialBackoff(() => clearUrlCache(urls))
|
||||
console.log(`Cache purged for all ${urls.length} files`)
|
||||
console.log(`Cache purged for all ${urls.length} files of region ${regionId}`)
|
||||
} catch (error) {
|
||||
console.error(`Failed to purge cache for all files after 3 retries`, error)
|
||||
console.error(`Failed to purge cache for region ${regionId} files after 3 retries`, error)
|
||||
}
|
||||
|
||||
console.log('All cache files created successfully')
|
||||
console.log(`Cache files created successfully for region ${regionId}`)
|
||||
|
||||
// Single awaited mirror refresh for the whole cycle (all counters bumped above).
|
||||
await refreshGenKv()
|
||||
// Single awaited mirror refresh for the region (all regional counters bumped above).
|
||||
await refreshGenKv(regionId)
|
||||
|
||||
return {
|
||||
regionId,
|
||||
cacheVersion,
|
||||
products: productsKey,
|
||||
essentialConsts: essentialConstsKey,
|
||||
|
|
@ -103,12 +114,26 @@ export async function createAllCacheFiles(): Promise<CreateAllCacheFilesResult>
|
|||
}
|
||||
}
|
||||
|
||||
// With no regionId, generates cache files for EVERY region (sequentially to
|
||||
// avoid D1 version-counter races). Returns per-region results.
|
||||
export async function createAllCacheFiles(regionId?: number): Promise<RegionCacheFilesResult[]> {
|
||||
const regionIds = regionId != null
|
||||
? [regionId]
|
||||
: (await getAllRegions()).map((r) => r.id)
|
||||
|
||||
const results: RegionCacheFilesResult[] = []
|
||||
for (const id of regionIds) {
|
||||
results.push(await createRegionCacheFiles(id))
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
// Internal versions that skip cache purging (for batch operations)
|
||||
async function createProductsFileInternal(version: number): Promise<string> {
|
||||
const productsData = await scaffoldProducts()
|
||||
async function createProductsFileInternal(regionId: number, version: number): Promise<string> {
|
||||
const productsData = await scaffoldProducts(regionId)
|
||||
const jsonContent = JSON.stringify(productsData, null, 2)
|
||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||
const filePath = `${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.products, version)}`
|
||||
const filePath = `${getApiCacheKey()}/${buildRegionCachePath(regionId, version, CACHE_FILENAMES.products)}`
|
||||
|
||||
console.log(filePath)
|
||||
return await imageUploadS3(
|
||||
|
|
@ -119,12 +144,12 @@ async function createProductsFileInternal(version: number): Promise<string> {
|
|||
|
||||
}
|
||||
|
||||
export async function createAvailabilityCacheFile(refresh = true): Promise<number> {
|
||||
const version = await incrementAvailabilityVersionNum()
|
||||
const availabilityData = await scaffoldAvailability()
|
||||
export async function createAvailabilityCacheFile(regionId: number, refresh = true): Promise<number> {
|
||||
const version = await incrementRegionAvailabilityVersionNum(regionId)
|
||||
const availabilityData = await scaffoldAvailability(regionId)
|
||||
const jsonContent = JSON.stringify(availabilityData, null, 2)
|
||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||
const filePath = buildAvailabilityPath(version)
|
||||
const filePath = buildRegionAvailabilityPath(regionId, version)
|
||||
|
||||
console.log(filePath)
|
||||
await imageUploadS3(
|
||||
|
|
@ -133,39 +158,39 @@ export async function createAvailabilityCacheFile(refresh = true): Promise<numbe
|
|||
filePath
|
||||
)
|
||||
|
||||
if (refresh) await refreshGenKv()
|
||||
if (refresh) await refreshGenKv(regionId)
|
||||
|
||||
return version
|
||||
}
|
||||
|
||||
async function createEssentialConstsFileInternal(version: number): Promise<string> {
|
||||
const essentialConstsData = await scaffoldEssentialConsts()
|
||||
async function createEssentialConstsFileInternal(regionId: number, version: number): Promise<string> {
|
||||
const essentialConstsData = await scaffoldEssentialConsts(regionId)
|
||||
const jsonContent = JSON.stringify(essentialConstsData, null, 2)
|
||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||
return await imageUploadS3(
|
||||
buffer,
|
||||
'application/json',
|
||||
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.essentialConsts, version)}`
|
||||
`${getApiCacheKey()}/${buildRegionCachePath(regionId, version, CACHE_FILENAMES.essentialConsts)}`
|
||||
)
|
||||
}
|
||||
|
||||
async function createStoresFileInternal(version: number): Promise<string> {
|
||||
const storesData = await scaffoldStores()
|
||||
async function createStoresFileInternal(regionId: number, version: number): Promise<string> {
|
||||
const storesData = await scaffoldStores(regionId)
|
||||
const jsonContent = JSON.stringify(storesData, null, 2)
|
||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||
return await imageUploadS3(
|
||||
buffer,
|
||||
'application/json',
|
||||
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.stores, version)}`
|
||||
`${getApiCacheKey()}/${buildRegionCachePath(regionId, version, CACHE_FILENAMES.stores)}`
|
||||
)
|
||||
}
|
||||
|
||||
export async function createSlotsCacheFile(refresh = true): Promise<number> {
|
||||
const version = await incrementSlotsVersionNum()
|
||||
const slotsData = await scaffoldSlotsWithProducts()
|
||||
export async function createSlotsCacheFile(regionId: number, refresh = true): Promise<number> {
|
||||
const version = await incrementRegionSlotsVersionNum(regionId)
|
||||
const slotsData = await scaffoldSlotsWithProducts(regionId)
|
||||
const jsonContent = JSON.stringify(slotsData, null, 2)
|
||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||
const filePath = buildSlotsPath(version)
|
||||
const filePath = buildRegionSlotsPath(regionId, version)
|
||||
|
||||
console.log(filePath)
|
||||
await imageUploadS3(
|
||||
|
|
@ -174,40 +199,40 @@ export async function createSlotsCacheFile(refresh = true): Promise<number> {
|
|||
filePath
|
||||
)
|
||||
|
||||
if (refresh) await refreshGenKv()
|
||||
if (refresh) await refreshGenKv(regionId)
|
||||
|
||||
return version
|
||||
}
|
||||
|
||||
async function createBannersFileInternal(version: number): Promise<string> {
|
||||
const bannersData = await scaffoldBanners()
|
||||
async function createBannersFileInternal(regionId: number, version: number): Promise<string> {
|
||||
const bannersData = await scaffoldBanners(regionId)
|
||||
const jsonContent = JSON.stringify(bannersData, null, 2)
|
||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||
return await imageUploadS3(
|
||||
buffer,
|
||||
'application/json',
|
||||
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.banners, version)}`
|
||||
`${getApiCacheKey()}/${buildRegionCachePath(regionId, version, CACHE_FILENAMES.banners)}`
|
||||
)
|
||||
}
|
||||
|
||||
async function createAllStoresFilesInternal(version: number): Promise<string[]> {
|
||||
async function createAllStoresFilesInternal(regionId: number, version: number): Promise<string[]> {
|
||||
|
||||
const stores = await getStoresSummary()
|
||||
const stores = await getStoresSummary(regionId)
|
||||
const results: string[] = []
|
||||
|
||||
for (const store of stores) {
|
||||
const storeData = await scaffoldStoreWithProducts(store.id)
|
||||
const storeData = await scaffoldStoreWithProducts(regionId, store.id)
|
||||
const jsonContent = JSON.stringify(storeData, null, 2)
|
||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||
const s3Key = await imageUploadS3(
|
||||
buffer,
|
||||
'application/json',
|
||||
`${getApiCacheKey()}/${buildCachePath(`stores/${store.id}.json`, version)}`
|
||||
`${getApiCacheKey()}/${buildRegionCachePath(regionId, version, `stores/${store.id}.json`)}`
|
||||
)
|
||||
results.push(s3Key)
|
||||
}
|
||||
|
||||
console.log(`Created ${results.length} store cache files`)
|
||||
console.log(`Created ${results.length} store cache files for region ${regionId}`)
|
||||
return results
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,56 +1,78 @@
|
|||
import { getGenKvNamespace } from '@/src/lib/env-exporter'
|
||||
import { getAllRegions } from '@/src/dbService'
|
||||
import type { scaffoldEssentialConsts } from '@/src/trpc/apis/common-apis/common-trpc-index'
|
||||
|
||||
export const GEN_KV_KEY = 'essential_consts'
|
||||
|
||||
export const genKvKeyForRegion = (regionId: number): string => `${GEN_KV_KEY}:${regionId}`
|
||||
|
||||
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(): Promise<EssentialConstsPayload> {
|
||||
async function buildEssentialConsts(regionId: number): Promise<EssentialConstsPayload> {
|
||||
const { scaffoldEssentialConsts } = await import(
|
||||
'../trpc/apis/common-apis/common-trpc-index'
|
||||
)
|
||||
return scaffoldEssentialConsts()
|
||||
return scaffoldEssentialConsts(regionId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuilds the full essentialConsts response (constants + counters + env-derived
|
||||
* fields) from D1/env and mirrors it to KV. Call after a successful D1 write.
|
||||
* No-op when the KV binding is absent (local/tests).
|
||||
* 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.
|
||||
*/
|
||||
export async function refreshGenKv(): Promise<void> {
|
||||
export async function refreshGenKv(regionId?: number): Promise<void> {
|
||||
try {
|
||||
const kv = getGenKvNamespace()
|
||||
if (!kv) return
|
||||
|
||||
const payload = await buildEssentialConsts()
|
||||
await kv.put(GEN_KV_KEY, JSON.stringify(payload))
|
||||
const regionIds = regionId != null
|
||||
? [regionId]
|
||||
: (await getAllRegions()).map((r) => r.id)
|
||||
|
||||
for (const id of regionIds) {
|
||||
try {
|
||||
const payload = await buildEssentialConsts(id)
|
||||
await kv.put(genKvKeyForRegion(id), JSON.stringify(payload))
|
||||
} catch (error) {
|
||||
console.error(`refreshGenKv failed for region ${id}:`, error)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('refreshGenKv failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Client read path: serve the precomputed response from KV. On a miss, build it
|
||||
* from D1/env, backfill KV, and return.
|
||||
* 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(): Promise<EssentialConstsPayload> {
|
||||
export async function readEssentialConstsFromKv(regionId?: number): Promise<EssentialConstsPayload> {
|
||||
if (regionId == null) {
|
||||
throw new Error('readEssentialConstsFromKv requires a regionId')
|
||||
}
|
||||
|
||||
const key = genKvKeyForRegion(regionId)
|
||||
|
||||
try {
|
||||
const kv = getGenKvNamespace()
|
||||
if (kv) {
|
||||
const cached = (await kv.get(GEN_KV_KEY, 'json')) as EssentialConstsPayload | null
|
||||
const cached = (await kv.get(key, 'json')) as EssentialConstsPayload | null
|
||||
if (cached) return cached
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('readEssentialConstsFromKv failed:', error)
|
||||
}
|
||||
|
||||
const payload = await buildEssentialConsts()
|
||||
const payload = await buildEssentialConsts(regionId)
|
||||
|
||||
try {
|
||||
const kv = getGenKvNamespace()
|
||||
if (kv) await kv.put(GEN_KV_KEY, JSON.stringify(payload))
|
||||
if (kv) await kv.put(key, JSON.stringify(payload))
|
||||
} catch (error) {
|
||||
console.error('backfill essential_consts failed:', error)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -100,6 +100,9 @@ export {
|
|||
checkStaffUserExists,
|
||||
checkStaffRoleExists,
|
||||
createStaffUser,
|
||||
createStaffUserWithRegion,
|
||||
updateStaffUserRegion,
|
||||
deleteStaffUser,
|
||||
getAllRoles,
|
||||
// Admin - Store
|
||||
getAllStores,
|
||||
|
|
@ -243,12 +246,19 @@ export {
|
|||
// Automated Jobs
|
||||
toggleKeyVal,
|
||||
getAllKeyValStore,
|
||||
// Per-Region Cache Versions
|
||||
getRegionCacheVersions,
|
||||
incrementRegionCacheVersion,
|
||||
incrementRegionAvailabilityVersionNum,
|
||||
incrementRegionSlotsVersionNum,
|
||||
// Post-order handler helpers
|
||||
getOrdersByIdsWithFullData,
|
||||
getOrderByIdWithFullData,
|
||||
// Common API helpers
|
||||
getSuspendedSkuIds,
|
||||
getNextDeliveryDateWithCapacity,
|
||||
getSkuRegionId,
|
||||
getSkuRegionIds,
|
||||
getStoresSummary,
|
||||
healthCheck,
|
||||
// Delete orders helper
|
||||
|
|
@ -267,4 +277,19 @@ export {
|
|||
// Upload URL Helpers
|
||||
createUploadUrlStatus,
|
||||
claimUploadUrlStatus,
|
||||
// Superadmin / Region Helpers
|
||||
getSuperadminByUsername,
|
||||
getSuperadminById,
|
||||
getAllRegions,
|
||||
getRegionById,
|
||||
getRegionWithBounds,
|
||||
createRegion,
|
||||
updateRegion,
|
||||
getBoundsForRegion,
|
||||
getBoundById,
|
||||
createRegionBound,
|
||||
updateRegionBound,
|
||||
getBoundSettings,
|
||||
upsertBoundSettings,
|
||||
getEffectiveRegionSettings,
|
||||
} from '../../../packages/db_helper_sqlite'
|
||||
|
|
|
|||
|
|
@ -6,11 +6,11 @@ import {
|
|||
} from '@/src/dbService'
|
||||
import { scaffoldAssetUrl } from '@/src/lib/s3-client'
|
||||
|
||||
export async function initializeBannerStore(): Promise<void> {
|
||||
export async function initializeBannerStore(regionId: number): Promise<void> {
|
||||
try {
|
||||
console.log('Initializing banner store in Redis...')
|
||||
|
||||
const banners = await getAllBannersForCache()
|
||||
const banners = await getAllBannersForCache(regionId)
|
||||
|
||||
// Store each banner in Redis
|
||||
// for (const banner of banners) {
|
||||
|
|
@ -36,14 +36,14 @@ export async function initializeBannerStore(): Promise<void> {
|
|||
}
|
||||
}
|
||||
|
||||
export async function getBannerById(id: number): Promise<BannerData | null> {
|
||||
export async function getBannerById(regionId: number, id: number): Promise<BannerData | null> {
|
||||
try {
|
||||
// const key = `banner:${id}`
|
||||
// const data = await redisClient.get(key)
|
||||
// if (!data) return null
|
||||
// return JSON.parse(data) as Banner
|
||||
|
||||
const banner = await getBannerByIdFromDb(id)
|
||||
const banner = await getBannerByIdFromDb(regionId, id)
|
||||
if (!banner) return null
|
||||
|
||||
const signedImageUrl = banner.imageUrl
|
||||
|
|
|
|||
|
|
@ -37,19 +37,19 @@ interface Product extends ProductDetailCore {
|
|||
}>
|
||||
}
|
||||
|
||||
export async function initializeProducts(): Promise<void> {
|
||||
export async function initializeProducts(regionId: number): Promise<void> {
|
||||
try {
|
||||
console.log('Initializing product store in Redis...')
|
||||
|
||||
// Fetch all products with full details (similar to productMega logic)
|
||||
const productsData = await getAllProductsForCache()
|
||||
const productsData = await getAllProductsForCache(regionId)
|
||||
|
||||
// Fetch all stores
|
||||
const allStores = await getAllStoresForCache()
|
||||
const allStores = await getAllStoresForCache(regionId)
|
||||
const storeMap = new Map(allStores.map((s) => [s.id, s]))
|
||||
|
||||
// Fetch all delivery slots (excluding full capacity slots)
|
||||
const allDeliverySlots = await getAllDeliverySlotsForCache()
|
||||
const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
|
||||
const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
|
||||
for (const slot of allDeliverySlots) {
|
||||
if (!deliverySlotsMap.has(slot.skuId))
|
||||
|
|
@ -58,7 +58,7 @@ export async function initializeProducts(): Promise<void> {
|
|||
}
|
||||
|
||||
// Fetch all special deals
|
||||
const allSpecialDeals = await getAllSpecialDealsForCache()
|
||||
const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
|
||||
const specialDealsMap = new Map<number, SpecialDealData[]>()
|
||||
for (const deal of allSpecialDeals) {
|
||||
if (!specialDealsMap.has(deal.skuId))
|
||||
|
|
@ -67,7 +67,7 @@ export async function initializeProducts(): Promise<void> {
|
|||
}
|
||||
|
||||
// Fetch all product tags
|
||||
const allProductTags = await getAllProductTagsForCache()
|
||||
const allProductTags = await getAllProductTagsForCache(regionId)
|
||||
const productTagsMap = new Map<number, string[]>()
|
||||
for (const tag of allProductTags) {
|
||||
if (!productTagsMap.has(tag.productId))
|
||||
|
|
@ -127,9 +127,9 @@ export async function initializeProducts(): Promise<void> {
|
|||
}
|
||||
}
|
||||
|
||||
export async function getProductById(id: number): Promise<Product | null> {
|
||||
export async function getProductById(regionId: number, id: number): Promise<Product | null> {
|
||||
try {
|
||||
const allProducts = await getAllProducts()
|
||||
const allProducts = await getAllProducts(regionId)
|
||||
const product = allProducts.find(p => p.id === id)
|
||||
return product || null
|
||||
} catch (error) {
|
||||
|
|
@ -138,7 +138,7 @@ export async function getProductById(id: number): Promise<Product | null> {
|
|||
}
|
||||
}
|
||||
|
||||
export async function getAllProducts(): Promise<Product[]> {
|
||||
export async function getAllProducts(regionId: number): Promise<Product[]> {
|
||||
try {
|
||||
// Get all keys matching the pattern "product:*"
|
||||
// const keys = await redisClient.KEYS('product:*')
|
||||
|
|
@ -159,12 +159,12 @@ export async function getAllProducts(): Promise<Product[]> {
|
|||
//
|
||||
// return products
|
||||
|
||||
const productsData = await getAllProductsForCache()
|
||||
const productsData = await getAllProductsForCache(regionId)
|
||||
|
||||
const allStores = await getAllStoresForCache()
|
||||
const allStores = await getAllStoresForCache(regionId)
|
||||
const storeMap = new Map(allStores.map((s) => [s.id, s]))
|
||||
|
||||
const allDeliverySlots = await getAllDeliverySlotsForCache()
|
||||
const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
|
||||
const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
|
||||
for (const slot of allDeliverySlots) {
|
||||
if (!deliverySlotsMap.has(slot.skuId))
|
||||
|
|
@ -172,7 +172,7 @@ export async function getAllProducts(): Promise<Product[]> {
|
|||
deliverySlotsMap.get(slot.skuId)!.push(slot)
|
||||
}
|
||||
|
||||
const allSpecialDeals = await getAllSpecialDealsForCache()
|
||||
const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
|
||||
const specialDealsMap = new Map<number, SpecialDealData[]>()
|
||||
for (const deal of allSpecialDeals) {
|
||||
if (!specialDealsMap.has(deal.skuId))
|
||||
|
|
@ -180,7 +180,7 @@ export async function getAllProducts(): Promise<Product[]> {
|
|||
specialDealsMap.get(deal.skuId)!.push(deal)
|
||||
}
|
||||
|
||||
const allProductTags = await getAllProductTagsForCache()
|
||||
const allProductTags = await getAllProductTagsForCache(regionId)
|
||||
const productTagsMap = new Map<number, string[]>()
|
||||
for (const tag of allProductTags) {
|
||||
if (!productTagsMap.has(tag.productId))
|
||||
|
|
@ -189,7 +189,7 @@ export async function getAllProducts(): Promise<Product[]> {
|
|||
}
|
||||
|
||||
const products: Product[] = []
|
||||
const allProductCombos = await getAllProductCombosForCache()
|
||||
const allProductCombos = await getAllProductCombosForCache(regionId)
|
||||
const productCombosMap = new Map<number, ProductComboCacheData[]>()
|
||||
for (const comboItem of allProductCombos) {
|
||||
if (!productCombosMap.has(comboItem.comboSkuId))
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import {
|
|||
getAllTagsForCache,
|
||||
getAllTagProductMappings,
|
||||
getAllProductTags,
|
||||
db,
|
||||
} from '@/src/dbService'
|
||||
import { scaffoldAssetUrl } from '@/src/lib/s3-client'
|
||||
import type { ProductTagCore } from '@packages/shared'
|
||||
|
|
@ -41,15 +42,15 @@ async function transformTagToStoreTag(tag: {
|
|||
}
|
||||
}
|
||||
|
||||
export async function initializeProductTagStore(): Promise<void> {
|
||||
export async function initializeProductTagStore(regionId: number): Promise<void> {
|
||||
try {
|
||||
console.log('Initializing product tag store in Redis...')
|
||||
|
||||
// Fetch all tags
|
||||
const tagsData = await getAllTagsForCache()
|
||||
const tagsData = await getAllTagsForCache(regionId)
|
||||
|
||||
// Fetch product IDs for each tag
|
||||
const productTagsData = await getAllTagProductMappings()
|
||||
const productTagsData = await getAllTagProductMappings(regionId)
|
||||
|
||||
// Group product IDs by tag
|
||||
const productIdsByTag = new Map<number, number[]>()
|
||||
|
|
@ -109,7 +110,18 @@ export async function getTagsByStoreId(storeId: number): Promise<Tag[]> {
|
|||
//
|
||||
// return storeTags
|
||||
|
||||
const tags = await getAllProductTags()
|
||||
// Scope tags to the store's own region (user path has no staff region).
|
||||
// NOTE: callback-form `where` so operators come from the db's own
|
||||
// drizzle copy (backend must not import drizzle-orm directly: dual copy).
|
||||
const store = await db.query.storeInfo.findFirst({
|
||||
where: (f, { eq }) => eq(f.id, storeId),
|
||||
columns: { regionId: true },
|
||||
})
|
||||
if (store?.regionId == null) {
|
||||
return []
|
||||
}
|
||||
|
||||
const tags = await getAllProductTags(store.regionId)
|
||||
|
||||
const result: Tag[] = []
|
||||
for (const tag of tags) {
|
||||
|
|
|
|||
|
|
@ -63,17 +63,17 @@ function extractSlotInfo(slot: SlotWithProductsData): SlotInfo {
|
|||
}
|
||||
}
|
||||
|
||||
async function fetchAllTransformedSlots(): Promise<SlotWithProducts[]> {
|
||||
const slots = await getAllSlotsWithProductsForCache()
|
||||
async function fetchAllTransformedSlots(regionId: number): Promise<SlotWithProducts[]> {
|
||||
const slots = await getAllSlotsWithProductsForCache(regionId)
|
||||
return Promise.all(slots.map(transformSlotToStoreSlot))
|
||||
}
|
||||
|
||||
export async function initializeSlotStore(): Promise<void> {
|
||||
export async function initializeSlotStore(regionId: number): Promise<void> {
|
||||
try {
|
||||
console.log('Initializing slot store in Redis...')
|
||||
|
||||
// Fetch active delivery slots with future delivery times
|
||||
const slots = await getAllSlotsWithProductsForCache()
|
||||
const slots = await getAllSlotsWithProductsForCache(regionId)
|
||||
|
||||
// Transform data for storage
|
||||
const slotsWithProducts = await Promise.all(
|
||||
|
|
@ -140,14 +140,14 @@ export async function initializeSlotStore(): Promise<void> {
|
|||
}
|
||||
}
|
||||
|
||||
export async function getSlotById(slotId: number): Promise<SlotWithProducts | null> {
|
||||
export async function getSlotById(regionId: number, slotId: number): Promise<SlotWithProducts | null> {
|
||||
try {
|
||||
// const key = `slot:${slotId}`
|
||||
// const data = await redisClient.get(key)
|
||||
// if (!data) return null
|
||||
// return JSON.parse(data) as SlotWithProducts
|
||||
|
||||
const slots = await getAllSlotsWithProductsForCache()
|
||||
const slots = await getAllSlotsWithProductsForCache(regionId)
|
||||
const slot = slots.find(s => s.id === slotId)
|
||||
if (!slot) return null
|
||||
|
||||
|
|
@ -158,7 +158,7 @@ export async function getSlotById(slotId: number): Promise<SlotWithProducts | nu
|
|||
}
|
||||
}
|
||||
|
||||
export async function getAllSlots(): Promise<SlotWithProducts[]> {
|
||||
export async function getAllSlots(regionId: number): Promise<SlotWithProducts[]> {
|
||||
try {
|
||||
// Get all keys matching the pattern "slot:*"
|
||||
// const keys = await redisClient.KEYS('slot:*')
|
||||
|
|
@ -177,7 +177,7 @@ export async function getAllSlots(): Promise<SlotWithProducts[]> {
|
|||
//
|
||||
// return slots
|
||||
|
||||
return fetchAllTransformedSlots()
|
||||
return fetchAllTransformedSlots(regionId)
|
||||
} catch (error) {
|
||||
console.error('Error getting all slots:', error)
|
||||
return []
|
||||
|
|
@ -185,6 +185,7 @@ export async function getAllSlots(): Promise<SlotWithProducts[]> {
|
|||
}
|
||||
|
||||
export async function getMultipleProductsSlots(
|
||||
regionId: number,
|
||||
productIds: number[]
|
||||
): Promise<Record<number, SlotInfo[]>> {
|
||||
try {
|
||||
|
|
@ -208,7 +209,7 @@ export async function getMultipleProductsSlots(
|
|||
//
|
||||
// return result
|
||||
|
||||
const slots = await getAllSlotsWithProductsForCache()
|
||||
const slots = await getAllSlotsWithProductsForCache(regionId)
|
||||
const productIdSet = new Set(productIds)
|
||||
const result: Record<number, SlotInfo[]> = {}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { initializeProductTagStore } from '@/src/stores/product-tag-store'
|
|||
import { initializeSlotStore } from '@/src/stores/slot-store'
|
||||
import { initializeBannerStore } from '@/src/stores/banner-store'
|
||||
import { createAllCacheFiles } from '@/src/lib/cloud_cache'
|
||||
import { getAllRegions } from '@/src/dbService'
|
||||
import type { DurableObjectNamespace } from '@cloudflare/workers-types'
|
||||
|
||||
/**
|
||||
|
|
@ -16,24 +17,33 @@ import type { DurableObjectNamespace } from '@cloudflare/workers-types'
|
|||
* - Product Tag Store (caches all product tags in Redis)
|
||||
* - Slot Store (caches all delivery slots with products in Redis)
|
||||
* - Banner Store (caches all banners in Redis)
|
||||
*
|
||||
* With no regionId, initializes EVERY region. With a regionId, only that
|
||||
* region is regenerated.
|
||||
*/
|
||||
export const initializeAllStores = async (): Promise<void> => {
|
||||
export const initializeAllStores = async (regionId?: number): Promise<void> => {
|
||||
try {
|
||||
console.log('Starting application stores initialization...');
|
||||
|
||||
const targetRegionIds = regionId != null
|
||||
? [regionId]
|
||||
: (await getAllRegions()).map((r) => r.id)
|
||||
|
||||
await Promise.all([
|
||||
roleManager.fetchRoles(),
|
||||
computeConstants(),
|
||||
initializeProducts(),
|
||||
initializeProductTagStore(),
|
||||
initializeSlotStore(),
|
||||
initializeBannerStore(),
|
||||
...targetRegionIds.flatMap((id) => [
|
||||
initializeProducts(id),
|
||||
initializeProductTagStore(id),
|
||||
initializeSlotStore(id),
|
||||
initializeBannerStore(id),
|
||||
]),
|
||||
]);
|
||||
|
||||
console.log('All application stores initialized successfully');
|
||||
|
||||
// Regenerate all cache files (fire-and-forget)
|
||||
createAllCacheFiles().catch(error => {
|
||||
// Regenerate cache files for the target region(s) (fire-and-forget)
|
||||
createAllCacheFiles(regionId).catch(error => {
|
||||
console.error('Failed to regenerate cache files during store initialization:', error)
|
||||
})
|
||||
} catch (error) {
|
||||
|
|
@ -42,7 +52,7 @@ export const initializeAllStores = async (): Promise<void> => {
|
|||
}
|
||||
};
|
||||
|
||||
export const scheduleStoreInitialization = async (): Promise<void> => {
|
||||
export const scheduleStoreInitialization = async (regionId?: number): Promise<void> => {
|
||||
console.log("scheduling store initialization")
|
||||
const env = (globalThis as { ENV?: { CACHE_CREATOR?: DurableObjectNamespace } }).ENV
|
||||
if (!env?.CACHE_CREATOR) {
|
||||
|
|
@ -53,7 +63,10 @@ export const scheduleStoreInitialization = async (): Promise<void> => {
|
|||
const id = env.CACHE_CREATOR.idFromName('store-init')
|
||||
const stub = env.CACHE_CREATOR.get(id)
|
||||
try {
|
||||
await stub.fetch('https://cache-creator/schedule', { method: 'POST' })
|
||||
const path = regionId != null
|
||||
? `https://cache-creator/schedule?regionId=${regionId}`
|
||||
: 'https://cache-creator/schedule'
|
||||
await stub.fetch(path, { method: 'POST' })
|
||||
} catch (error) {
|
||||
console.error('Failed to schedule store initialization:', error)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import { adminPaymentsRouter } from '@/src/trpc/apis/admin-apis/apis/payments'
|
|||
import { bannerRouter } from '@/src/trpc/apis/admin-apis/apis/banner'
|
||||
import { userRouter } from '@/src/trpc/apis/admin-apis/apis/user'
|
||||
import { constRouter } from '@/src/trpc/apis/admin-apis/apis/const'
|
||||
import { regionRouter } from '@/src/trpc/apis/admin-apis/apis/region'
|
||||
|
||||
export const adminRouter = router({
|
||||
complaint: complaintRouter,
|
||||
|
|
@ -26,6 +27,7 @@ export const adminRouter = router({
|
|||
banner: bannerRouter,
|
||||
user: userRouter,
|
||||
const: constRouter,
|
||||
region: regionRouter,
|
||||
});
|
||||
|
||||
export type AdminRouter = typeof adminRouter;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { z } from 'zod';
|
||||
import { protectedProcedure, router } from '@/src/trpc/trpc-index'
|
||||
import { protectedProcedure, staffProcedure, router } from '@/src/trpc/trpc-index'
|
||||
import { extractKeyFromPresignedUrl, scaffoldAssetUrl } from '@/src/lib/s3-client'
|
||||
import { ApiError } from '@/src/lib/api-error';
|
||||
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
|
||||
|
|
@ -15,11 +15,11 @@ import type { Banner } from '@packages/shared'
|
|||
export const bannerRouter = router({
|
||||
// Get all banners
|
||||
getBanners: protectedProcedure
|
||||
.query(async (): Promise<{ banners: Banner[] }> => {
|
||||
.query(async ({ ctx }): Promise<{ banners: Banner[] }> => {
|
||||
try {
|
||||
|
||||
// Using dbService helper (new implementation)
|
||||
const banners = await getBannersFromDb();
|
||||
const banners = await getBannersFromDb(ctx.staffUser!.regionId);
|
||||
|
||||
// Convert S3 keys to signed URLs for client
|
||||
const bannersWithSignedUrls = await Promise.all(
|
||||
|
|
@ -57,9 +57,9 @@ export const bannerRouter = router({
|
|||
// Get single banner by ID
|
||||
getBanner: protectedProcedure
|
||||
.input(z.object({ id: z.number() }))
|
||||
.query(async ({ input }): Promise<Banner | null> => {
|
||||
.query(async ({ input, ctx }): Promise<Banner | null> => {
|
||||
// Using dbService helper (new implementation)
|
||||
const banner = await getBannerByIdFromDb(input.id);
|
||||
const banner = await getBannerByIdFromDb(ctx.staffUser!.regionId, input.id);
|
||||
|
||||
if (banner) {
|
||||
try {
|
||||
|
|
@ -82,7 +82,7 @@ export const bannerRouter = router({
|
|||
}),
|
||||
|
||||
// Create new banner
|
||||
createBanner: protectedProcedure
|
||||
createBanner: staffProcedure
|
||||
.input(z.object({
|
||||
name: z.string().min(1),
|
||||
imageUrl: z.string().url(),
|
||||
|
|
@ -91,7 +91,7 @@ export const bannerRouter = router({
|
|||
redirectUrl: z.string().url().optional(),
|
||||
// serialNum removed completely
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<Banner> => {
|
||||
.mutation(async ({ input, ctx }): Promise<Banner> => {
|
||||
try {
|
||||
// Using dbService helper (new implementation)
|
||||
const imageUrl = extractKeyFromPresignedUrl(input.imageUrl)
|
||||
|
|
@ -103,10 +103,10 @@ export const bannerRouter = router({
|
|||
redirectUrl: input.redirectUrl ?? null,
|
||||
serialNum: 999, // Default value, not used
|
||||
isActive: false, // Default to inactive
|
||||
});
|
||||
}, ctx.staffUser!.regionId);
|
||||
|
||||
// Reinitialize stores to reflect changes
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
return banner;
|
||||
} catch (error) {
|
||||
|
|
@ -127,7 +127,7 @@ export const bannerRouter = router({
|
|||
serialNum: z.number().nullable().optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<Banner> => {
|
||||
.mutation(async ({ input, ctx }): Promise<Banner> => {
|
||||
try {
|
||||
// Using dbService helper (new implementation)
|
||||
const { id, ...updateData } = input;
|
||||
|
|
@ -145,10 +145,14 @@ export const bannerRouter = router({
|
|||
processedData.serialNum = null;
|
||||
}
|
||||
|
||||
const banner = await updateBannerInDb(id, processedData);
|
||||
const banner = await updateBannerInDb(ctx.staffUser!.regionId, id, processedData);
|
||||
|
||||
if (!banner) {
|
||||
throw new ApiError('Banner not found', 404);
|
||||
}
|
||||
|
||||
// Reinitialize stores to reflect changes
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
return banner;
|
||||
} catch (error) {
|
||||
|
|
@ -160,12 +164,16 @@ export const bannerRouter = router({
|
|||
// Delete banner
|
||||
deleteBanner: protectedProcedure
|
||||
.input(z.object({ id: z.number() }))
|
||||
.mutation(async ({ input }): Promise<{ success: true }> => {
|
||||
.mutation(async ({ input, ctx }): Promise<{ success: true }> => {
|
||||
// Using dbService helper (new implementation)
|
||||
await deleteBannerFromDb(input.id);
|
||||
const deleted = await deleteBannerFromDb(ctx.staffUser!.regionId, input.id);
|
||||
|
||||
if (!deleted) {
|
||||
throw new ApiError('Banner not found', 404);
|
||||
}
|
||||
|
||||
// Reinitialize stores to reflect changes
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ export const complaintRouter = router({
|
|||
cursor: z.number().optional(),
|
||||
limit: z.number().default(20),
|
||||
}))
|
||||
.query(async ({ input }): Promise<{
|
||||
.query(async ({ input, ctx }): Promise<{
|
||||
complaints: Array<{
|
||||
id: number;
|
||||
text: string;
|
||||
|
|
@ -34,7 +34,7 @@ export const complaintRouter = router({
|
|||
const { cursor, limit } = input;
|
||||
|
||||
// Using dbService helper (new implementation)
|
||||
const { complaints: complaintsData, hasMore } = await getComplaintsFromDb(cursor, limit);
|
||||
const { complaints: complaintsData, hasMore } = await getComplaintsFromDb(ctx.staffUser!.regionId, cursor, limit);
|
||||
|
||||
const complaintsToReturn = hasMore ? complaintsData.slice(0, limit) : complaintsData;
|
||||
|
||||
|
|
@ -65,18 +65,22 @@ export const complaintRouter = router({
|
|||
|
||||
resolve: protectedProcedure
|
||||
.input(z.object({ id: z.string(), response: z.string().min(1) }))
|
||||
.mutation(async ({ input }): Promise<{ message: string }> => {
|
||||
.mutation(async ({ input, ctx }): Promise<{ message: string }> => {
|
||||
const complaintId = parseInt(input.id)
|
||||
const responseText = input.response.trim()
|
||||
|
||||
const complaint = await getComplaintById(complaintId)
|
||||
const complaint = await getComplaintById(ctx.staffUser!.regionId, complaintId)
|
||||
|
||||
if (!complaint) {
|
||||
throw new Error('Complaint not found')
|
||||
}
|
||||
|
||||
// Using dbService helper (new implementation)
|
||||
await resolveComplaintInDb(complaintId, responseText)
|
||||
const resolved = await resolveComplaintInDb(ctx.staffUser!.regionId, complaintId, responseText)
|
||||
|
||||
if (!resolved) {
|
||||
throw new Error('Complaint not found')
|
||||
}
|
||||
|
||||
const tokens = await getNotifTokensByUserIds([complaint.userId])
|
||||
for (const t of tokens) {
|
||||
|
|
|
|||
|
|
@ -113,7 +113,8 @@ export const couponRouter = router({
|
|||
isInvalidated: false,
|
||||
},
|
||||
applicableUsers,
|
||||
applicableProducts
|
||||
applicableProducts,
|
||||
ctx.staffUser!.regionId
|
||||
);
|
||||
|
||||
createdCoupons.push(coupon);
|
||||
|
|
@ -128,10 +129,10 @@ export const couponRouter = router({
|
|||
limit: z.number().default(50),
|
||||
search: z.string().optional(),
|
||||
}))
|
||||
.query(async ({ input }): Promise<{ coupons: any[]; nextCursor?: number }> => {
|
||||
.query(async ({ input, ctx }): Promise<{ coupons: any[]; nextCursor?: number }> => {
|
||||
const { cursor, limit, search } = input;
|
||||
|
||||
const { coupons: couponsList, hasMore } = await getAllCouponsFromDb(cursor, limit, search);
|
||||
|
||||
const { coupons: couponsList, hasMore } = await getAllCouponsFromDb(ctx.staffUser!.regionId, cursor, limit, search);
|
||||
|
||||
const nextCursor = hasMore ? couponsList[couponsList.length - 1].id : undefined;
|
||||
|
||||
|
|
@ -140,10 +141,10 @@ export const couponRouter = router({
|
|||
|
||||
getById: protectedProcedure
|
||||
.input(z.object({ id: z.number() }))
|
||||
.query(async ({ input }): Promise<any> => {
|
||||
.query(async ({ input, ctx }): Promise<any> => {
|
||||
const couponId = input.id;
|
||||
|
||||
const result = await getCouponByIdFromDb(couponId);
|
||||
const result = await getCouponByIdFromDb(ctx.staffUser!.regionId, couponId);
|
||||
|
||||
if (!result) {
|
||||
throw new Error("Coupon not found");
|
||||
|
|
@ -164,7 +165,7 @@ export const couponRouter = router({
|
|||
isInvalidated: z.boolean().optional(),
|
||||
}),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<Coupon> => {
|
||||
.mutation(async ({ input, ctx }): Promise<Coupon> => {
|
||||
const { id, updates } = input;
|
||||
|
||||
// Validation: ensure discount types are valid
|
||||
|
|
@ -177,7 +178,7 @@ export const couponRouter = router({
|
|||
// Prepare update data — always a COMPLETE CouponFormInput: fields present
|
||||
// in the payload win, everything else keeps its current value (the data
|
||||
// is still sent even where the caller doesn't need it).
|
||||
const existing = await getCouponByIdFromDb(id);
|
||||
const existing = await getCouponByIdFromDb(ctx.staffUser!.regionId, id);
|
||||
if (!existing) {
|
||||
throw new Error("Coupon not found");
|
||||
}
|
||||
|
|
@ -201,21 +202,30 @@ export const couponRouter = router({
|
|||
|
||||
// Using dbService helper (new implementation)
|
||||
const coupon = await updateCouponWithRelations(
|
||||
ctx.staffUser!.regionId,
|
||||
id,
|
||||
updateData,
|
||||
updates.applicableUsers,
|
||||
updates.applicableProducts
|
||||
);
|
||||
|
||||
if (!coupon) {
|
||||
throw new Error("Coupon not found");
|
||||
}
|
||||
|
||||
return coupon;
|
||||
}),
|
||||
|
||||
delete: protectedProcedure
|
||||
.input(z.object({ id: z.number() }))
|
||||
.mutation(async ({ input }): Promise<{ message: string }> => {
|
||||
.mutation(async ({ input, ctx }): Promise<{ message: string }> => {
|
||||
const { id } = input;
|
||||
|
||||
await invalidateCouponInDb(id);
|
||||
const coupon = await invalidateCouponInDb(ctx.staffUser!.regionId, id);
|
||||
|
||||
if (!coupon) {
|
||||
throw new Error("Coupon not found");
|
||||
}
|
||||
|
||||
return { message: "Coupon invalidated successfully" };
|
||||
}),
|
||||
|
|
@ -236,7 +246,7 @@ export const couponRouter = router({
|
|||
}
|
||||
|
||||
// Using dbService helper (new implementation)
|
||||
const order = await getOrderWithUser(orderId);
|
||||
const order = await getOrderWithUser(ctx.staffUser!.regionId, orderId);
|
||||
|
||||
if (!order) {
|
||||
throw new Error("Order not found");
|
||||
|
|
@ -264,7 +274,8 @@ export const couponRouter = router({
|
|||
staffUserId,
|
||||
order.userId,
|
||||
orderAmount,
|
||||
couponCode
|
||||
couponCode,
|
||||
order.regionId
|
||||
);
|
||||
|
||||
return coupon;
|
||||
|
|
@ -276,10 +287,10 @@ export const couponRouter = router({
|
|||
limit: z.number().default(50),
|
||||
search: z.string().optional(),
|
||||
}))
|
||||
.query(async ({ input }): Promise<{ coupons: any[]; nextCursor?: number }> => {
|
||||
.query(async ({ input, ctx }): Promise<{ coupons: any[]; nextCursor?: number }> => {
|
||||
const { cursor, limit, search } = input;
|
||||
|
||||
const { coupons: result, hasMore } = await getReservedCouponsFromDb(cursor, limit, search);
|
||||
const { coupons: result, hasMore } = await getReservedCouponsFromDb(ctx.staffUser!.regionId, cursor, limit, search);
|
||||
|
||||
const nextCursor = hasMore ? result[result.length - 1].id : undefined;
|
||||
|
||||
|
|
@ -339,7 +350,8 @@ export const couponRouter = router({
|
|||
isFirstOrderOnly: isFirstOrderOnly || false,
|
||||
createdBy: staffUserId,
|
||||
},
|
||||
applicableProducts
|
||||
applicableProducts,
|
||||
ctx.staffUser!.regionId
|
||||
);
|
||||
|
||||
createdCoupons.push(coupon);
|
||||
|
|
@ -354,10 +366,10 @@ export const couponRouter = router({
|
|||
limit: z.number().min(1).max(50).default(20),
|
||||
offset: z.number().min(0).default(0),
|
||||
}))
|
||||
.query(async ({ input }): Promise<{ users: UserMiniInfo[] }> => {
|
||||
.query(async ({ input, ctx }): Promise<{ users: UserMiniInfo[] }> => {
|
||||
const { search, limit, offset } = input;
|
||||
|
||||
const result = await getUsersForCouponFromDb(search, limit, offset);
|
||||
const result = await getUsersForCouponFromDb(ctx.staffUser!.regionId, search, limit, offset);
|
||||
|
||||
return result;
|
||||
}),
|
||||
|
|
@ -394,7 +406,7 @@ export const couponRouter = router({
|
|||
throw new Error("Generated coupon code already exists - please try again");
|
||||
}
|
||||
|
||||
const { coupon, user } = await createCouponForUser(cleanMobile, couponCode, staffUserId);
|
||||
const { coupon, user } = await createCouponForUser(cleanMobile, couponCode, staffUserId, ctx.staffUser!.regionId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
|
|
|
|||
|
|
@ -89,10 +89,10 @@ const getAllOrdersSchema = z.object({
|
|||
export const orderRouter = router({
|
||||
updateNotes: protectedProcedure
|
||||
.input(updateOrderNotesSchema)
|
||||
.mutation(async ({ input }): Promise<AdminOrderRow> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminOrderRow> => {
|
||||
const { orderId, adminNotes } = input;
|
||||
|
||||
const result = await updateOrderNotesInDb(orderId, adminNotes || null)
|
||||
const result = await updateOrderNotesInDb(ctx.staffUser!.regionId, orderId, adminNotes || null)
|
||||
|
||||
if (!result) {
|
||||
throw new Error("Order not found")
|
||||
|
|
@ -103,10 +103,10 @@ export const orderRouter = router({
|
|||
|
||||
getOrderDetails: protectedProcedure
|
||||
.input(getOrderDetailsSchema)
|
||||
.query(async ({ input }): Promise<AdminOrderDetails> => {
|
||||
.query(async ({ input, ctx }): Promise<AdminOrderDetails> => {
|
||||
const { orderId } = input;
|
||||
|
||||
const orderDetails = await getOrderDetailsInDb(orderId)
|
||||
const orderDetails = await getOrderDetailsInDb(ctx.staffUser!.regionId, orderId)
|
||||
|
||||
if (!orderDetails) {
|
||||
throw new Error('Order not found')
|
||||
|
|
@ -117,10 +117,14 @@ export const orderRouter = router({
|
|||
|
||||
updatePackaged: protectedProcedure
|
||||
.input(updatePackagedSchema)
|
||||
.mutation(async ({ input }): Promise<AdminOrderUpdateResult> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminOrderUpdateResult> => {
|
||||
const { orderId, isPackaged } = input;
|
||||
|
||||
const result = await updateOrderPackagedInDb(orderId, isPackaged)
|
||||
const result = await updateOrderPackagedInDb(ctx.staffUser!.regionId, orderId, isPackaged)
|
||||
|
||||
if (!result) {
|
||||
throw new ApiError('Order not found', 404)
|
||||
}
|
||||
|
||||
if (result.userId) await sendOrderPackagedNotification(result.userId, orderId)
|
||||
|
||||
|
|
@ -129,10 +133,14 @@ export const orderRouter = router({
|
|||
|
||||
updateDelivered: protectedProcedure
|
||||
.input(updateDeliveredSchema)
|
||||
.mutation(async ({ input }): Promise<AdminOrderUpdateResult> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminOrderUpdateResult> => {
|
||||
const { orderId, isDelivered } = input;
|
||||
|
||||
const result = await updateOrderDeliveredInDb(orderId, isDelivered)
|
||||
const result = await updateOrderDeliveredInDb(ctx.staffUser!.regionId, orderId, isDelivered)
|
||||
|
||||
if (!result) {
|
||||
throw new ApiError('Order not found', 404)
|
||||
}
|
||||
|
||||
if (result.userId) await sendOrderDeliveredNotification(result.userId, orderId)
|
||||
|
||||
|
|
@ -141,10 +149,10 @@ export const orderRouter = router({
|
|||
|
||||
updateOrderItemPackaging: protectedProcedure
|
||||
.input(updateOrderItemPackagingSchema)
|
||||
.mutation(async ({ input }): Promise<AdminOrderItemPackagingResult> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminOrderItemPackagingResult> => {
|
||||
const { orderItemId, isPackaged, isPackageVerified } = input;
|
||||
|
||||
const result = await updateOrderItemPackagingInDb(orderItemId, isPackaged, isPackageVerified)
|
||||
const result = await updateOrderItemPackagingInDb(ctx.staffUser!.regionId, orderItemId, isPackaged, isPackageVerified)
|
||||
|
||||
if (!result.updated) {
|
||||
throw new ApiError('Order item not found', 404)
|
||||
|
|
@ -155,10 +163,10 @@ export const orderRouter = router({
|
|||
|
||||
removeDeliveryCharge: protectedProcedure
|
||||
.input(z.object({ orderId: z.number() }))
|
||||
.mutation(async ({ input }): Promise<AdminOrderMessageResult> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminOrderMessageResult> => {
|
||||
const { orderId } = input;
|
||||
|
||||
const result = await removeDeliveryChargeInDb(orderId)
|
||||
const result = await removeDeliveryChargeInDb(ctx.staffUser!.regionId, orderId)
|
||||
|
||||
if (!result) {
|
||||
throw new Error('Order not found')
|
||||
|
|
@ -169,10 +177,10 @@ export const orderRouter = router({
|
|||
|
||||
getSlotOrders: protectedProcedure
|
||||
.input(getSlotOrdersSchema)
|
||||
.query(async ({ input }): Promise<AdminGetSlotOrdersResult> => {
|
||||
.query(async ({ input, ctx }): Promise<AdminGetSlotOrdersResult> => {
|
||||
const { slotId } = input;
|
||||
|
||||
const result = await getSlotOrdersInDb(slotId)
|
||||
const result = await getSlotOrdersInDb(ctx.staffUser!.regionId, slotId)
|
||||
|
||||
const userIds = [...new Set(result.data.map((order) => order.userId))]
|
||||
const firstOrderIdByUser = new Map<number, number | null>()
|
||||
|
|
@ -198,10 +206,10 @@ export const orderRouter = router({
|
|||
longitude: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }): Promise<AdminOrderBasicResult> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminOrderBasicResult> => {
|
||||
const { addressId, latitude, longitude } = input;
|
||||
|
||||
const result = await updateAddressCoordsInDb(addressId, latitude, longitude)
|
||||
const result = await updateAddressCoordsInDb(ctx.staffUser!.regionId, addressId, latitude, longitude)
|
||||
|
||||
if (!result.success) {
|
||||
throw new ApiError('Address not found', 404)
|
||||
|
|
@ -212,9 +220,9 @@ export const orderRouter = router({
|
|||
|
||||
getAll: protectedProcedure
|
||||
.input(getAllOrdersSchema)
|
||||
.query(async ({ input }): Promise<AdminGetAllOrdersResult | undefined> => {
|
||||
.query(async ({ input, ctx }): Promise<AdminGetAllOrdersResult | undefined> => {
|
||||
try {
|
||||
const result = await getAllOrdersInDb(input)
|
||||
const result = await getAllOrdersInDb(ctx.staffUser!.regionId, input)
|
||||
const userIds = [...new Set(result.orders.map((order) => order.userId))]
|
||||
const negativityScores = await getMultipleUserNegativityScores(userIds)
|
||||
|
||||
|
|
@ -245,10 +253,10 @@ export const orderRouter = router({
|
|||
|
||||
rebalanceSlots: protectedProcedure
|
||||
.input(z.object({ slotIds: z.array(z.number()).min(1).max(50) }))
|
||||
.mutation(async ({ input }): Promise<AdminRebalanceSlotsResult> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminRebalanceSlotsResult> => {
|
||||
const slotIds = input.slotIds;
|
||||
|
||||
const result = await rebalanceSlotsInDb(slotIds)
|
||||
const result = await rebalanceSlotsInDb(ctx.staffUser!.regionId, slotIds)
|
||||
|
||||
return result
|
||||
}),
|
||||
|
|
@ -258,10 +266,10 @@ export const orderRouter = router({
|
|||
orderId: z.number(),
|
||||
reason: z.string().min(1, "Cancellation reason is required"),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<AdminCancelOrderResult> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminCancelOrderResult> => {
|
||||
const { orderId, reason } = input;
|
||||
|
||||
const result = await cancelOrderInDb(orderId, reason)
|
||||
const result = await cancelOrderInDb(ctx.staffUser!.regionId, orderId, reason)
|
||||
|
||||
if (!result.success) {
|
||||
if (result.error === 'order_not_found') {
|
||||
|
|
@ -294,7 +302,6 @@ export const orderRouter = router({
|
|||
|
||||
// {"id": "order_Rhh00qJNdjUp8o", "notes": {"retry": "true", "customerOrderId": "14"}, "amount": 21000, "entity": "order", "status": "created", "receipt": "order_14_retry", "attempts": 0, "currency": "INR", "offer_id": null, "signature": "6df20655021f1d6841340f2a2ef2ef9378cb3d43495ab09e85f08aea1a851583", "amount_due": 21000, "created_at": 1763575791, "payment_id": "pay_Rhh15cLL28YM7j", "amount_paid": 0}
|
||||
|
||||
export async function deleteOrderById(orderId: number): Promise<void> {
|
||||
await deleteOrderByIdInDb(orderId)
|
||||
|
||||
export async function deleteOrderById(regionId: number, orderId: number): Promise<boolean> {
|
||||
return await deleteOrderByIdInDb(regionId, orderId)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { router, protectedProcedure } from '@/src/trpc/trpc-index'
|
||||
import { router, protectedProcedure, staffProcedure } from '@/src/trpc/trpc-index'
|
||||
import { z } from 'zod'
|
||||
import { ApiError } from '@/src/lib/api-error'
|
||||
import { scaffoldAssetUrl, claimUploadUrl, extractKeyFromPresignedUrl, deleteImageUtil } from '@/src/lib/s3-client'
|
||||
|
|
@ -43,8 +43,8 @@ import type {
|
|||
|
||||
export const productRouter = router({
|
||||
getProducts: protectedProcedure
|
||||
.query(async (): Promise<AdminProductListResponse> => {
|
||||
const products = await getAllProductsInDb()
|
||||
.query(async ({ ctx }): Promise<AdminProductListResponse> => {
|
||||
const products = await getAllProductsInDb(ctx.staffUser!.regionId)
|
||||
|
||||
const productsWithImageUrls = products.map((product) => ({
|
||||
...product,
|
||||
|
|
@ -64,10 +64,10 @@ export const productRouter = router({
|
|||
.input(z.object({
|
||||
id: z.number(),
|
||||
}))
|
||||
.query(async ({ input }): Promise<AdminProductResponse> => {
|
||||
.query(async ({ input, ctx }): Promise<AdminProductResponse> => {
|
||||
const { id } = input;
|
||||
|
||||
const product = await getProductByIdInDb(id)
|
||||
const product = await getProductByIdInDb(ctx.staffUser!.regionId, id)
|
||||
|
||||
if (!product) {
|
||||
throw new ApiError('Product not found', 404)
|
||||
|
|
@ -90,17 +90,17 @@ export const productRouter = router({
|
|||
.input(z.object({
|
||||
id: z.number(),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<AdminDeleteProductResult> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminDeleteProductResult> => {
|
||||
const { id } = input;
|
||||
|
||||
const deletedProduct = await deleteProductInDb(id)
|
||||
const deletedProduct = await deleteProductInDb(ctx.staffUser!.regionId, id)
|
||||
|
||||
if (!deletedProduct) {
|
||||
throw new ApiError('Product not found', 404)
|
||||
}
|
||||
|
||||
// Reinitialize stores to reflect changes
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
return {
|
||||
message: 'Product deleted successfully',
|
||||
|
|
@ -111,17 +111,17 @@ export const productRouter = router({
|
|||
.input(z.object({
|
||||
id: z.number(),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<AdminToggleOutOfStockResult> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminToggleOutOfStockResult> => {
|
||||
const { id } = input;
|
||||
|
||||
const result = await toggleProductOutOfStockInDb(id)
|
||||
const result = await toggleProductOutOfStockInDb(ctx.staffUser!.regionId, id)
|
||||
|
||||
if (!result) {
|
||||
throw new ApiError('Product not found', 404)
|
||||
}
|
||||
|
||||
// Only the availability cache needs regenerating for a stock flip.
|
||||
await createAvailabilityCacheFile().catch((err) => {
|
||||
await createAvailabilityCacheFile(ctx.staffUser!.regionId).catch((err) => {
|
||||
console.error('Failed to regenerate availability cache after stock update:', err)
|
||||
})
|
||||
|
||||
|
|
@ -132,7 +132,7 @@ export const productRouter = router({
|
|||
}
|
||||
}),
|
||||
|
||||
createProduct: protectedProcedure
|
||||
createProduct: staffProcedure
|
||||
.input(z.object({
|
||||
name: z.string().min(1, 'Name is required'),
|
||||
shortDescription: z.string().optional(),
|
||||
|
|
@ -161,7 +161,7 @@ export const productRouter = router({
|
|||
})).optional(),
|
||||
})).min(1, 'At least one SKU is required'),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
||||
.mutation(async ({ input, ctx }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
||||
const { name, shortDescription, longDescription, storeId, incrementStep, productType, skus } = input
|
||||
|
||||
const existingProduct = await checkProductExistsByName(name.trim())
|
||||
|
|
@ -198,13 +198,13 @@ export const productRouter = router({
|
|||
incrementStep,
|
||||
productType,
|
||||
skus: skuInputs,
|
||||
} as any)
|
||||
} as any, ctx.staffUser!.regionId)
|
||||
|
||||
if (allUploadUrls.length > 0) {
|
||||
await Promise.all(allUploadUrls.map((url) => claimUploadUrl(url)))
|
||||
}
|
||||
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
const productWithImageUrls = {
|
||||
...newProduct,
|
||||
|
|
@ -253,7 +253,7 @@ export const productRouter = router({
|
|||
deletedImageKeys: z.array(z.string()).optional().default([]),
|
||||
newImageUrls: z.array(z.string()).optional().default([]),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
||||
.mutation(async ({ input, ctx }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
||||
const { id, name, shortDescription, longDescription, storeId, incrementStep, productType, skus, deletedImageKeys, newImageUrls } = input
|
||||
|
||||
if (deletedImageKeys.length > 0) {
|
||||
|
|
@ -280,7 +280,7 @@ export const productRouter = router({
|
|||
comboItems: (sku.comboItems || []).map((ci) => ({ skuId: ci.skuId })),
|
||||
}))
|
||||
|
||||
const updatedProduct = await updateProductInDb(id, {
|
||||
const updatedProduct = await updateProductInDb(ctx.staffUser!.regionId, id, {
|
||||
name,
|
||||
shortDescription,
|
||||
longDescription,
|
||||
|
|
@ -298,7 +298,7 @@ export const productRouter = router({
|
|||
await Promise.all(newImageUrls.map((url) => claimUploadUrl(url)))
|
||||
}
|
||||
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
const productWithImageUrls = {
|
||||
...updatedProduct,
|
||||
|
|
@ -320,10 +320,10 @@ export const productRouter = router({
|
|||
limit: z.number().int().min(1).max(50).optional().default(10),
|
||||
offset: z.number().int().min(0).optional().default(0),
|
||||
}))
|
||||
.query(async ({ input }): Promise<AdminProductReviewsResult> => {
|
||||
.query(async ({ input, ctx }): Promise<AdminProductReviewsResult> => {
|
||||
const { productId, limit, offset } = input;
|
||||
|
||||
const { reviews, totalCount } = await getProductReviewsInDb(productId, limit, offset)
|
||||
const { reviews, totalCount } = await getProductReviewsInDb(ctx.staffUser!.regionId, productId, limit, offset)
|
||||
|
||||
const reviewsWithImageUrls = reviews.map((review) => ({
|
||||
...review,
|
||||
|
|
@ -343,10 +343,10 @@ export const productRouter = router({
|
|||
adminResponseImages: z.array(z.string()).optional().default([]),
|
||||
uploadUrls: z.array(z.string()).optional().default([]),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<AdminProductReviewResponse> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminProductReviewResponse> => {
|
||||
const { reviewId, adminResponse, adminResponseImages, uploadUrls } = input;
|
||||
|
||||
const updatedReview = await respondToReviewInDb(reviewId, adminResponse, adminResponseImages)
|
||||
const updatedReview = await respondToReviewInDb(ctx.staffUser!.regionId, reviewId, adminResponse, adminResponseImages)
|
||||
|
||||
if (!updatedReview) {
|
||||
throw new ApiError('Review not found', 404)
|
||||
|
|
@ -360,28 +360,28 @@ export const productRouter = router({
|
|||
}),
|
||||
|
||||
getGroups: protectedProcedure
|
||||
.query(async (): Promise<AdminProductGroupsResult> => {
|
||||
.query(async ({ ctx }): Promise<AdminProductGroupsResult> => {
|
||||
// getAllProductGroupsInDb already returns groups with products mapped
|
||||
// as AdminSku[] (SKU ids per the ProductsSelector).
|
||||
const groups = await getAllProductGroupsInDb()
|
||||
const groups = await getAllProductGroupsInDb(ctx.staffUser!.regionId)
|
||||
|
||||
return {
|
||||
groups,
|
||||
}
|
||||
}),
|
||||
|
||||
createGroup: protectedProcedure
|
||||
createGroup: staffProcedure
|
||||
.input(z.object({
|
||||
group_name: z.string().min(1),
|
||||
description: z.string().optional(),
|
||||
product_ids: z.array(z.number()).default([]),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<AdminProductGroupResponse> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminProductGroupResponse> => {
|
||||
const { group_name, description, product_ids } = input;
|
||||
|
||||
const newGroup = await createProductGroupInDb(group_name, description, product_ids)
|
||||
const newGroup = await createProductGroupInDb(group_name, description, product_ids, ctx.staffUser!.regionId)
|
||||
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
return {
|
||||
group: newGroup,
|
||||
|
|
@ -396,16 +396,16 @@ export const productRouter = router({
|
|||
description: z.string().optional(),
|
||||
product_ids: z.array(z.number()).optional(),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<AdminProductGroupResponse> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminProductGroupResponse> => {
|
||||
const { id, group_name, description, product_ids } = input;
|
||||
|
||||
const updatedGroup = await updateProductGroupInDb(id, group_name, description, product_ids)
|
||||
const updatedGroup = await updateProductGroupInDb(ctx.staffUser!.regionId, id, group_name, description, product_ids)
|
||||
|
||||
if (!updatedGroup) {
|
||||
throw new ApiError('Group not found', 404)
|
||||
}
|
||||
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
return {
|
||||
group: updatedGroup,
|
||||
|
|
@ -417,16 +417,16 @@ export const productRouter = router({
|
|||
.input(z.object({
|
||||
id: z.number(),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<AdminDeleteProductResult> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminDeleteProductResult> => {
|
||||
const { id } = input;
|
||||
|
||||
const deletedGroup = await deleteProductGroupInDb(id)
|
||||
const deletedGroup = await deleteProductGroupInDb(ctx.staffUser!.regionId, id)
|
||||
|
||||
if (!deletedGroup) {
|
||||
throw new ApiError('Group not found', 404)
|
||||
}
|
||||
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
return {
|
||||
message: 'Group deleted successfully',
|
||||
|
|
@ -443,20 +443,20 @@ export const productRouter = router({
|
|||
isFlashAvailable: z.boolean().optional(),
|
||||
})),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<AdminUpdateProductPricesResult> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminUpdateProductPricesResult> => {
|
||||
const { updates } = input;
|
||||
|
||||
if (updates.length === 0) {
|
||||
throw new ApiError('No updates provided', 400)
|
||||
}
|
||||
|
||||
const result = await updateProductPricesInDb(updates)
|
||||
const result = await updateProductPricesInDb(ctx.staffUser!.regionId, updates)
|
||||
|
||||
if (result.invalidIds.length > 0) {
|
||||
throw new ApiError(`Invalid product IDs: ${result.invalidIds.join(', ')}`, 400)
|
||||
}
|
||||
|
||||
await createAvailabilityCacheFile().catch((err) => {
|
||||
await createAvailabilityCacheFile(ctx.staffUser!.regionId).catch((err) => {
|
||||
console.error('Failed to regenerate availability cache after price update:', err)
|
||||
})
|
||||
|
||||
|
|
@ -467,8 +467,8 @@ export const productRouter = router({
|
|||
}),
|
||||
|
||||
getProductTags: protectedProcedure
|
||||
.query(async (): Promise<{ tags: Array<{ id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: number[] | null; createdAt: Date }>; message: string }> => {
|
||||
const tags = await getAllProductTagInfosInDb()
|
||||
.query(async ({ ctx }): Promise<{ tags: Array<{ id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: number[] | null; createdAt: Date }>; message: string }> => {
|
||||
const tags = await getAllProductTagInfosInDb(ctx.staffUser!.regionId)
|
||||
|
||||
const tagsWithImageUrls = tags.map((tag) => ({
|
||||
...tag,
|
||||
|
|
@ -483,8 +483,8 @@ export const productRouter = router({
|
|||
|
||||
getProductTagById: protectedProcedure
|
||||
.input(z.object({ id: z.number() }))
|
||||
.query(async ({ input }): Promise<{ tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[]; createdAt: Date; products: Array<{ productId: number; tagId: number; assignedAt: Date; product: any }>; productIds: number[] }; message: string }> => {
|
||||
const tag = await getProductTagByIdInDb(input.id)
|
||||
.query(async ({ input, ctx }): Promise<{ tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[]; createdAt: Date; products: Array<{ productId: number; tagId: number; assignedAt: Date; product: any }>; productIds: number[] }; message: string }> => {
|
||||
const tag = await getProductTagByIdInDb(ctx.staffUser!.regionId, input.id)
|
||||
|
||||
if (!tag) {
|
||||
throw new ApiError('Tag not found', 404)
|
||||
|
|
@ -501,7 +501,7 @@ export const productRouter = router({
|
|||
}
|
||||
}),
|
||||
|
||||
createProductTag: protectedProcedure
|
||||
createProductTag: staffProcedure
|
||||
.input(z.object({
|
||||
tagName: z.string().min(1, 'Tag name is required'),
|
||||
tagDescription: z.string().optional(),
|
||||
|
|
@ -511,7 +511,7 @@ export const productRouter = router({
|
|||
productIds: z.array(z.number()).optional().default([]),
|
||||
uploadUrls: z.array(z.string()).optional().default([]),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<{ tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[]; createdAt: Date }; message: string }> => {
|
||||
.mutation(async ({ input, ctx }): Promise<{ tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[]; createdAt: Date }; message: string }> => {
|
||||
const { tagName, tagDescription, imageUrl, isDashboardTag, relatedStores, productIds, uploadUrls } = input
|
||||
|
||||
const existingTag = await checkProductTagExistsByName(tagName.trim())
|
||||
|
|
@ -526,15 +526,15 @@ export const productRouter = router({
|
|||
isDashboardTag,
|
||||
relatedStores,
|
||||
sortOrder: productIds,
|
||||
})
|
||||
}, ctx.staffUser!.regionId)
|
||||
|
||||
await replaceTagProducts(createdTag.id, productIds)
|
||||
await replaceTagProducts(ctx.staffUser!.regionId, createdTag.id, productIds)
|
||||
|
||||
if (uploadUrls.length > 0) {
|
||||
await Promise.all(uploadUrls.map((url) => claimUploadUrl(url)))
|
||||
}
|
||||
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
const { products, ...createdTagInfo } = createdTag
|
||||
|
||||
|
|
@ -558,10 +558,10 @@ export const productRouter = router({
|
|||
productIds: z.array(z.number()).optional(),
|
||||
uploadUrls: z.array(z.string()).optional().default([]),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<{ tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[]; createdAt: Date }; message: string }> => {
|
||||
.mutation(async ({ input, ctx }): Promise<{ tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[]; createdAt: Date }; message: string }> => {
|
||||
const { id, tagName, tagDescription, imageUrl, isDashboardTag, relatedStores, productIds, uploadUrls } = input
|
||||
|
||||
const currentTag = await getProductTagInfoByIdInDb(id)
|
||||
const currentTag = await getProductTagInfoByIdInDb(ctx.staffUser!.regionId, id)
|
||||
|
||||
if (!currentTag) {
|
||||
throw new ApiError('Tag not found', 404)
|
||||
|
|
@ -573,7 +573,7 @@ export const productRouter = router({
|
|||
}
|
||||
}
|
||||
|
||||
const updatedTag = await updateProductTagInDb(id, {
|
||||
const updatedTag = await updateProductTagInDb(ctx.staffUser!.regionId, id, {
|
||||
tagName: tagName?.trim(),
|
||||
tagDescription: tagDescription ?? undefined,
|
||||
imageUrl: imageUrl ?? undefined,
|
||||
|
|
@ -582,15 +582,19 @@ export const productRouter = router({
|
|||
sortOrder: productIds,
|
||||
})
|
||||
|
||||
if (!updatedTag) {
|
||||
throw new ApiError('Tag not found', 404)
|
||||
}
|
||||
|
||||
if (productIds !== undefined) {
|
||||
await replaceTagProducts(id, productIds)
|
||||
await replaceTagProducts(ctx.staffUser!.regionId, id, productIds)
|
||||
}
|
||||
|
||||
if (uploadUrls.length > 0) {
|
||||
await Promise.all(uploadUrls.map((url) => claimUploadUrl(url)))
|
||||
}
|
||||
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
const { products, ...updatedTagInfo } = updatedTag
|
||||
|
||||
|
|
@ -605,8 +609,8 @@ export const productRouter = router({
|
|||
|
||||
deleteProductTag: protectedProcedure
|
||||
.input(z.object({ id: z.number() }))
|
||||
.mutation(async ({ input }): Promise<{ message: string }> => {
|
||||
const tag = await getProductTagInfoByIdInDb(input.id)
|
||||
.mutation(async ({ input, ctx }): Promise<{ message: string }> => {
|
||||
const tag = await getProductTagInfoByIdInDb(ctx.staffUser!.regionId, input.id)
|
||||
|
||||
if (!tag) {
|
||||
throw new ApiError('Tag not found', 404)
|
||||
|
|
@ -616,9 +620,13 @@ export const productRouter = router({
|
|||
await deleteImageUtil({ keys: [tag.imageUrl] })
|
||||
}
|
||||
|
||||
await deleteProductTagInDb(input.id)
|
||||
const deleted = await deleteProductTagInDb(ctx.staffUser!.regionId, input.id)
|
||||
|
||||
await scheduleStoreInitialization()
|
||||
if (!deleted) {
|
||||
throw new ApiError('Tag not found', 404)
|
||||
}
|
||||
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
return { message: 'Tag deleted successfully' }
|
||||
}),
|
||||
|
|
|
|||
58
apps/backend/src/trpc/apis/admin-apis/apis/region.ts
Normal file
58
apps/backend/src/trpc/apis/admin-apis/apis/region.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
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 {
|
||||
getBoundsForRegion,
|
||||
getBoundById,
|
||||
getBoundSettings,
|
||||
upsertBoundSettings,
|
||||
getEffectiveRegionSettings,
|
||||
getRegionById,
|
||||
} from '@/src/dbService'
|
||||
|
||||
/** Ensures a bound belongs to the authenticated staff member's region. */
|
||||
async function assertBoundInRegion(boundId: number, regionId: number) {
|
||||
const bound = await getBoundById(boundId)
|
||||
if (!bound || bound.regionId !== regionId) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND' })
|
||||
}
|
||||
return bound
|
||||
}
|
||||
|
||||
export const regionRouter = router({
|
||||
current: staffProcedure.query(async ({ ctx }) => {
|
||||
return getRegionById(ctx.staffUser!.regionId)
|
||||
}),
|
||||
|
||||
bounds: staffProcedure.query(async ({ ctx }) => {
|
||||
return getBoundsForRegion(ctx.staffUser!.regionId)
|
||||
}),
|
||||
|
||||
effective: staffProcedure.query(async ({ ctx }) => {
|
||||
const effective = await getEffectiveRegionSettings(ctx.staffUser!.regionId)
|
||||
if (!effective) throw new ApiError('Region has no configured bound', 422)
|
||||
return effective
|
||||
}),
|
||||
|
||||
getBoundSettings: staffProcedure
|
||||
.input(z.object({ boundId: z.number().int().positive() }))
|
||||
.query(async ({ input, ctx }) => {
|
||||
await assertBoundInRegion(input.boundId, ctx.staffUser!.regionId)
|
||||
return getBoundSettings(input.boundId)
|
||||
}),
|
||||
|
||||
updateBoundSettings: staffProcedure
|
||||
.input(z.object({
|
||||
boundId: z.number().int().positive(),
|
||||
settings: z.array(z.object({
|
||||
key: z.string(),
|
||||
value: z.string().nullable(),
|
||||
})),
|
||||
}))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
await assertBoundInRegion(input.boundId, ctx.staffUser!.regionId)
|
||||
await upsertBoundSettings(input.boundId, input.settings)
|
||||
return { success: true, updatedCount: input.settings.length }
|
||||
}),
|
||||
})
|
||||
|
|
@ -80,7 +80,7 @@ export const slotsRouter = router({
|
|||
throw new TRPCError({ code: "UNAUTHORIZED", message: "Access denied" });
|
||||
}
|
||||
|
||||
const slots = await getActiveSlotsWithProductsInDb(20)
|
||||
const slots = await getActiveSlotsWithProductsInDb(ctx.staffUser.regionId, 20)
|
||||
|
||||
return {
|
||||
slots,
|
||||
|
|
@ -117,10 +117,10 @@ export const slotsRouter = router({
|
|||
validTill: snippet.validTill ?? null,
|
||||
})),
|
||||
groupIds,
|
||||
})
|
||||
}, ctx.staffUser.regionId)
|
||||
|
||||
// Regenerate slots cache file (availability/products stay as-is)
|
||||
await createSlotsCacheFile().catch((error) => {
|
||||
await createSlotsCacheFile(ctx.staffUser!.regionId).catch((error) => {
|
||||
console.error('Failed to regenerate slots cache after slot create:', error)
|
||||
})
|
||||
|
||||
|
|
@ -141,7 +141,7 @@ export const slotsRouter = router({
|
|||
|
||||
const { id } = input;
|
||||
|
||||
const slot = await getSlotByIdWithRelationsInDb(id)
|
||||
const slot = await getSlotByIdWithRelationsInDb(ctx.staffUser.regionId, id)
|
||||
|
||||
if (!slot) {
|
||||
throw new ApiError('Slot not found', 404)
|
||||
|
|
@ -171,7 +171,7 @@ export const slotsRouter = router({
|
|||
throw new ApiError("Delivery time and orders close time are required", 400);
|
||||
}
|
||||
|
||||
const result = await updateSlotWithRelationsInDb({
|
||||
const result = await updateSlotWithRelationsInDb(ctx.staffUser!.regionId, {
|
||||
id,
|
||||
deliveryTime,
|
||||
freezeTime,
|
||||
|
|
@ -192,7 +192,7 @@ export const slotsRouter = router({
|
|||
}
|
||||
|
||||
// Regenerate slots cache file (availability/products stay as-is)
|
||||
await createSlotsCacheFile().catch((error) => {
|
||||
await createSlotsCacheFile(ctx.staffUser!.regionId).catch((error) => {
|
||||
console.error('Failed to regenerate slots cache after slot update:', error)
|
||||
})
|
||||
|
||||
|
|
@ -207,6 +207,9 @@ export const slotsRouter = router({
|
|||
getDeliverySequence: protectedProcedure
|
||||
.input(getDeliverySequenceSchema)
|
||||
.query(async ({ input, ctx }): Promise<AdminDeliverySequenceResult> => {
|
||||
if (!ctx.staffUser?.id) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED", message: "Access denied" });
|
||||
}
|
||||
|
||||
const { id } = input;
|
||||
const slotId = parseInt(id);
|
||||
|
|
@ -227,7 +230,7 @@ export const slotsRouter = router({
|
|||
// }
|
||||
|
||||
// Fallback to DB
|
||||
const slot = await getSlotDeliverySequenceInDb(slotId)
|
||||
const slot = await getSlotDeliverySequenceInDb(ctx.staffUser.regionId, slotId)
|
||||
|
||||
if (!slot) {
|
||||
throw new ApiError('Slot not found', 404)
|
||||
|
|
@ -255,7 +258,7 @@ export const slotsRouter = router({
|
|||
|
||||
const { id, deliverySequence } = input;
|
||||
|
||||
const updatedSlot = await updateSlotDeliverySequenceInDb(id, deliverySequence)
|
||||
const updatedSlot = await updateSlotDeliverySequenceInDb(ctx.staffUser!.regionId, id, deliverySequence)
|
||||
|
||||
if (!updatedSlot) {
|
||||
throw new ApiError('Slot not found', 404)
|
||||
|
|
@ -288,13 +291,13 @@ export const slotsRouter = router({
|
|||
|
||||
const { slotId, isCapacityFull } = input;
|
||||
|
||||
const result = await updateSlotCapacityInDb(slotId, isCapacityFull)
|
||||
const result = await updateSlotCapacityInDb(ctx.staffUser!.regionId, slotId, isCapacityFull)
|
||||
|
||||
if (!result) {
|
||||
throw new ApiError('Slot not found', 404)
|
||||
}
|
||||
|
||||
await createSlotsCacheFile().catch((error) => {
|
||||
await createSlotsCacheFile(ctx.staffUser!.regionId).catch((error) => {
|
||||
console.error('Failed to regenerate slots cache after capacity update:', error)
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ export const staffUserRouter = router({
|
|||
return {
|
||||
message: 'Login successful',
|
||||
token,
|
||||
staff: { id: staff.id, name: staff.name },
|
||||
staff: { id: staff.id, name: staff.name, regionId: (staff as any).regionId ?? null },
|
||||
};
|
||||
}),
|
||||
|
||||
|
|
@ -101,7 +101,7 @@ export const staffUserRouter = router({
|
|||
const hashedPassword = await bcrypt.hash(password, 12);
|
||||
|
||||
// Create staff user
|
||||
const newUser = await createStaffUser(name, hashedPassword, roleId);
|
||||
const newUser = await createStaffUser(name, hashedPassword, roleId, ctx.staffUser!.regionId);
|
||||
|
||||
return { success: true, user: { id: newUser.id, name: newUser.name } };
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { router, protectedProcedure } from '@/src/trpc/trpc-index'
|
||||
import { router, protectedProcedure, staffProcedure } from '@/src/trpc/trpc-index'
|
||||
import { z } from 'zod';
|
||||
import { ApiError } from '@/src/lib/api-error'
|
||||
import { extractKeyFromPresignedUrl, deleteImageUtil, scaffoldAssetUrl } from '@/src/lib/s3-client'
|
||||
|
|
@ -15,7 +15,7 @@ import type { Store } from '@packages/shared'
|
|||
export const storeRouter = router({
|
||||
getStores: protectedProcedure
|
||||
.query(async ({ ctx }): Promise<{ stores: any[]; count: number }> => {
|
||||
const stores = await getAllStoresFromDb();
|
||||
const stores = await getAllStoresFromDb(ctx.staffUser!.regionId);
|
||||
|
||||
await Promise.all(stores.map(async store => {
|
||||
if(store.imageUrl)
|
||||
|
|
@ -37,7 +37,7 @@ export const storeRouter = router({
|
|||
.query(async ({ input, ctx }): Promise<{ store: any }> => {
|
||||
const { id } = input;
|
||||
|
||||
const store = await getStoreByIdFromDb(id);
|
||||
const store = await getStoreByIdFromDb(ctx.staffUser!.regionId, id);
|
||||
|
||||
if (!store) {
|
||||
throw new ApiError("Store not found", 404);
|
||||
|
|
@ -48,7 +48,7 @@ export const storeRouter = router({
|
|||
};
|
||||
}),
|
||||
|
||||
createStore: protectedProcedure
|
||||
createStore: staffProcedure
|
||||
.input(z.object({
|
||||
name: z.string().min(1, "Name is required"),
|
||||
description: z.string().optional(),
|
||||
|
|
@ -68,11 +68,12 @@ export const storeRouter = router({
|
|||
imageUrl: imageKey,
|
||||
owner,
|
||||
},
|
||||
products
|
||||
products,
|
||||
ctx.staffUser!.regionId
|
||||
);
|
||||
|
||||
// Reinitialize stores to reflect changes
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
return {
|
||||
store: newStore,
|
||||
|
|
@ -92,7 +93,7 @@ export const storeRouter = router({
|
|||
.mutation(async ({ input, ctx }): Promise<{ store: Store; message: string }> => {
|
||||
const { id, name, description, imageUrl, owner, products } = input;
|
||||
|
||||
const existingStore = await getStoreByIdFromDb(id);
|
||||
const existingStore = await getStoreByIdFromDb(ctx.staffUser!.regionId, id);
|
||||
|
||||
if (!existingStore) {
|
||||
throw new ApiError("Store not found", 404);
|
||||
|
|
@ -117,6 +118,7 @@ export const storeRouter = router({
|
|||
}
|
||||
|
||||
const updatedStore = await updateStoreInDb(
|
||||
ctx.staffUser!.regionId,
|
||||
id,
|
||||
{
|
||||
name,
|
||||
|
|
@ -128,7 +130,7 @@ export const storeRouter = router({
|
|||
);
|
||||
|
||||
// Reinitialize stores to reflect changes
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
return {
|
||||
store: updatedStore,
|
||||
|
|
@ -143,10 +145,16 @@ export const storeRouter = router({
|
|||
.mutation(async ({ input, ctx }): Promise<{ message: string }> => {
|
||||
const { storeId } = input;
|
||||
|
||||
const result = await deleteStoreFromDb(storeId);
|
||||
const existingStore = await getStoreByIdFromDb(ctx.staffUser!.regionId, storeId);
|
||||
|
||||
if (!existingStore) {
|
||||
throw new ApiError("Store not found", 404);
|
||||
}
|
||||
|
||||
const result = await deleteStoreFromDb(ctx.staffUser!.regionId, storeId);
|
||||
|
||||
// Reinitialize stores to reflect changes (outside transaction)
|
||||
await scheduleStoreInitialization()
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
|
||||
return result;
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -28,8 +28,8 @@ const TOKENS_PER_QUEUE_MESSAGE = 5
|
|||
|
||||
export const userRouter = {
|
||||
getEssentials: protectedProcedure
|
||||
.query(async () => {
|
||||
const count = await getUnresolvedComplaintsCount();
|
||||
.query(async ({ ctx }) => {
|
||||
const count = await getUnresolvedComplaintsCount(ctx.staffUser!.regionId);
|
||||
|
||||
return {
|
||||
unresolvedComplaints: count,
|
||||
|
|
@ -42,17 +42,17 @@ export const userRouter = {
|
|||
cursor: z.number().optional(),
|
||||
search: z.string().optional(),
|
||||
}))
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
const { limit, cursor, search } = input;
|
||||
|
||||
const { users: usersToReturn, hasMore } = await getAllUsersWithFilters(limit, cursor, search);
|
||||
|
||||
const { users: usersToReturn, hasMore } = await getAllUsersWithFilters(ctx.staffUser!.regionId, limit, cursor, search);
|
||||
|
||||
// Get order stats for each user
|
||||
const userIds = usersToReturn.map((u: any) => u.id);
|
||||
|
||||
const orderCounts = await getOrderCountsByUserIds(userIds);
|
||||
const lastOrders = await getLastOrdersByUserIds(userIds);
|
||||
const suspensionStatuses = await getSuspensionStatusesByUserIds(userIds);
|
||||
|
||||
const orderCounts = await getOrderCountsByUserIds(ctx.staffUser!.regionId, userIds);
|
||||
const lastOrders = await getLastOrdersByUserIds(ctx.staffUser!.regionId, userIds);
|
||||
const suspensionStatuses = await getSuspensionStatusesByUserIds(ctx.staffUser!.regionId, userIds);
|
||||
|
||||
// Create lookup maps
|
||||
const orderCountMap = new Map(orderCounts.map(o => [o.userId, o.totalOrders]));
|
||||
|
|
@ -81,11 +81,11 @@ export const userRouter = {
|
|||
.input(z.object({
|
||||
userId: z.number(),
|
||||
}))
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
const { userId } = input;
|
||||
|
||||
// Get user info
|
||||
const user = await getUserBasicInfo(userId);
|
||||
const user = await getUserBasicInfo(ctx.staffUser!.regionId, userId);
|
||||
|
||||
if (!user) {
|
||||
throw new ApiError('User not found', 404);
|
||||
|
|
@ -95,14 +95,14 @@ export const userRouter = {
|
|||
const isSuspended = await getUserSuspensionStatus(userId);
|
||||
|
||||
// Get all orders for this user
|
||||
const userOrders = await getUserOrders(userId);
|
||||
const userOrders = await getUserOrders(ctx.staffUser!.regionId, userId);
|
||||
|
||||
// Get order status for each order
|
||||
const orderIds = userOrders.map((o: any) => o.id);
|
||||
const orderStatuses = await getOrderStatusesByOrderIds(orderIds);
|
||||
const orderStatuses = await getOrderStatusesByOrderIds(ctx.staffUser!.regionId, orderIds);
|
||||
|
||||
// Get item counts for each order
|
||||
const itemCounts = await getItemCountsByOrderIds(orderIds);
|
||||
const itemCounts = await getItemCountsByOrderIds(ctx.staffUser!.regionId, orderIds);
|
||||
|
||||
// Create lookup maps
|
||||
const statusMap = new Map(orderStatuses.map(s => [s.orderId, s]));
|
||||
|
|
@ -159,10 +159,10 @@ export const userRouter = {
|
|||
.input(z.object({
|
||||
search: z.string().optional(),
|
||||
}))
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
const { search } = input;
|
||||
|
||||
const usersList = await searchUsers(search);
|
||||
const usersList = await searchUsers(ctx.staffUser!.regionId, search);
|
||||
|
||||
// Get eligible users (have notif_creds entry)
|
||||
const eligibleUsers = await getAllNotifCreds();
|
||||
|
|
@ -245,10 +245,10 @@ export const userRouter = {
|
|||
.input(z.object({
|
||||
userId: z.number(),
|
||||
}))
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
const { userId } = input;
|
||||
|
||||
const incidents = await getUserIncidentsWithRelations(userId);
|
||||
const incidents = await getUserIncidentsWithRelations(ctx.staffUser!.regionId, userId);
|
||||
|
||||
return {
|
||||
incidents: incidents.map((incident: any) => ({
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { router, publicProcedure, protectedProcedure } from '@/src/trpc/trpc-index'
|
||||
import { router, publicProcedure, protectedProcedure, staffProcedure } from '@/src/trpc/trpc-index'
|
||||
import { z } from 'zod'
|
||||
import dayjs from 'dayjs'
|
||||
import { getAppUrl } from '@/src/lib/env-exporter'
|
||||
|
|
@ -46,7 +46,7 @@ const updateSnippetSchema = z.object({
|
|||
});
|
||||
|
||||
export const vendorSnippetsRouter = router({
|
||||
create: protectedProcedure
|
||||
create: staffProcedure
|
||||
.input(createSnippetSchema)
|
||||
.mutation(async ({ input, ctx }): Promise<AdminVendorSnippet> => {
|
||||
const { snippetCode, slotId, skuIds, validTill, isPermanent } = input;
|
||||
|
|
@ -58,13 +58,13 @@ export const vendorSnippetsRouter = router({
|
|||
}
|
||||
|
||||
if(slotId) {
|
||||
const slot = await getVendorSlotByIdInDb(slotId)
|
||||
const slot = await getVendorSlotByIdInDb(ctx.staffUser!.regionId, slotId)
|
||||
if (!slot) {
|
||||
throw new Error("Invalid slot ID")
|
||||
}
|
||||
}
|
||||
|
||||
const products = await getProductsByIdsInDb(skuIds)
|
||||
const products = await getProductsByIdsInDb(ctx.staffUser!.regionId, skuIds)
|
||||
if (products.length !== skuIds.length) {
|
||||
throw new Error("One or more invalid product IDs")
|
||||
}
|
||||
|
|
@ -80,21 +80,22 @@ export const vendorSnippetsRouter = router({
|
|||
skuIds,
|
||||
isPermanent,
|
||||
validTill: validTill ? new Date(validTill) : undefined,
|
||||
regionId: ctx.staffUser!.regionId,
|
||||
})
|
||||
|
||||
return result
|
||||
}),
|
||||
|
||||
getAll: protectedProcedure
|
||||
.query(async (): Promise<AdminVendorSnippetWithProducts[]> => {
|
||||
.query(async ({ ctx }): Promise<AdminVendorSnippetWithProducts[]> => {
|
||||
console.log('from the vendor snipptes methods')
|
||||
|
||||
try {
|
||||
const result = await getAllVendorSnippetsInDb()
|
||||
const result = await getAllVendorSnippetsInDb(ctx.staffUser!.regionId)
|
||||
|
||||
const snippetsWithProducts = await Promise.all(
|
||||
result.map(async (snippet) => {
|
||||
const products = await getProductsByIdsInDb(snippet.skuIds)
|
||||
const products = await getProductsByIdsInDb(ctx.staffUser!.regionId, snippet.skuIds)
|
||||
|
||||
return {
|
||||
...snippet,
|
||||
|
|
@ -114,23 +115,23 @@ export const vendorSnippetsRouter = router({
|
|||
|
||||
update: protectedProcedure
|
||||
.input(updateSnippetSchema)
|
||||
.mutation(async ({ input }): Promise<AdminVendorSnippet> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminVendorSnippet> => {
|
||||
const { id, updates } = input;
|
||||
|
||||
const existingSnippet = await getVendorSnippetByIdInDb(id)
|
||||
|
||||
const existingSnippet = await getVendorSnippetByIdInDb(ctx.staffUser!.regionId, id)
|
||||
if (!existingSnippet) {
|
||||
throw new Error('Vendor snippet not found')
|
||||
}
|
||||
|
||||
if (updates.slotId) {
|
||||
const slot = await getVendorSlotByIdInDb(updates.slotId)
|
||||
const slot = await getVendorSlotByIdInDb(ctx.staffUser!.regionId, updates.slotId)
|
||||
if (!slot) {
|
||||
throw new Error('Invalid slot ID')
|
||||
}
|
||||
}
|
||||
|
||||
if (updates.skuIds) {
|
||||
const products = await getProductsByIdsInDb(updates.skuIds)
|
||||
const products = await getProductsByIdsInDb(ctx.staffUser!.regionId, updates.skuIds)
|
||||
if (products.length !== updates.skuIds.length) {
|
||||
throw new Error('One or more invalid product IDs')
|
||||
}
|
||||
|
|
@ -150,7 +151,7 @@ export const vendorSnippetsRouter = router({
|
|||
: undefined,
|
||||
}
|
||||
|
||||
const result = await updateVendorSnippetInDb(id, updateData)
|
||||
const result = await updateVendorSnippetInDb(ctx.staffUser!.regionId, id, updateData)
|
||||
|
||||
if (!result) {
|
||||
throw new Error('Failed to update vendor snippet')
|
||||
|
|
@ -161,10 +162,10 @@ export const vendorSnippetsRouter = router({
|
|||
|
||||
delete: protectedProcedure
|
||||
.input(z.object({ id: z.number().int().positive() }))
|
||||
.mutation(async ({ input }): Promise<AdminVendorSnippetDeleteResult> => {
|
||||
.mutation(async ({ input, ctx }): Promise<AdminVendorSnippetDeleteResult> => {
|
||||
const { id } = input;
|
||||
|
||||
const result = await deleteVendorSnippetInDb(id)
|
||||
const result = await deleteVendorSnippetInDb(ctx.staffUser!.regionId, id)
|
||||
|
||||
if (!result) {
|
||||
throw new Error('Vendor snippet not found')
|
||||
|
|
@ -180,7 +181,8 @@ export const vendorSnippetsRouter = router({
|
|||
.query(async ({ input }): Promise<AdminVendorSnippetOrdersResult> => {
|
||||
const { snippetCode } = input;
|
||||
|
||||
const snippet = await getVendorSnippetByCodeInDb(snippetCode)
|
||||
// Public vendor link: no staff region available, lookup stays global.
|
||||
const snippet = await getVendorSnippetByCodeInDb(null, snippetCode)
|
||||
|
||||
if (!snippet) {
|
||||
throw new Error('Vendor snippet not found')
|
||||
|
|
@ -194,7 +196,7 @@ export const vendorSnippetsRouter = router({
|
|||
throw new Error('Vendor snippet not associated with a slot')
|
||||
}
|
||||
|
||||
const matchingOrders = await getVendorOrdersBySlotIdInDb(snippet.slotId)
|
||||
const matchingOrders = await getVendorOrdersBySlotIdInDb(null, snippet.slotId)
|
||||
|
||||
// Filter orders that contain at least one of the snippet's products
|
||||
const filteredOrders = matchingOrders.filter(order => {
|
||||
|
|
@ -259,7 +261,8 @@ export const vendorSnippetsRouter = router({
|
|||
getUpcomingSlots: publicProcedure
|
||||
.query(async (): Promise<AdminUpcomingSlotsResult> => {
|
||||
const threeHoursAgo = dayjs().subtract(3, 'hour').toDate();
|
||||
const slots = await getSlotsAfterDateInDb(threeHoursAgo)
|
||||
// Public vendor link: no staff region available, stays global.
|
||||
const slots = await getSlotsAfterDateInDb(null, threeHoursAgo)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
|
|
@ -280,8 +283,9 @@ export const vendorSnippetsRouter = router({
|
|||
.query(async ({ input }): Promise<AdminVendorSnippetOrdersWithSlotResult> => {
|
||||
const { snippetCode, slotId } = input;
|
||||
|
||||
const snippet = await getVendorSnippetByCodeInDb(snippetCode)
|
||||
const slot = await getVendorSlotByIdInDb(slotId)
|
||||
// Public vendor link: no staff region available, lookups stay global.
|
||||
const snippet = await getVendorSnippetByCodeInDb(null, snippetCode)
|
||||
const slot = await getVendorSlotByIdInDb(null, slotId)
|
||||
|
||||
if (!snippet) {
|
||||
throw new Error('Vendor snippet not found')
|
||||
|
|
@ -291,7 +295,7 @@ export const vendorSnippetsRouter = router({
|
|||
throw new Error('Slot not found')
|
||||
}
|
||||
|
||||
const matchingOrders = await getVendorOrdersBySlotIdInDb(slotId)
|
||||
const matchingOrders = await getVendorOrdersBySlotIdInDb(null, slotId)
|
||||
|
||||
// Filter orders that contain at least one of the snippet's products
|
||||
const filteredOrders = matchingOrders.filter(order => {
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@ import { commonRouter } from '@/src/trpc/apis/common-apis/common'
|
|||
import {
|
||||
getStoresSummary,
|
||||
healthCheck,
|
||||
getCacheVersion,
|
||||
getAvailabilityVersionNum,
|
||||
getSlotsVersionNum,
|
||||
getRegionCacheVersions,
|
||||
getAllRegions,
|
||||
getEffectiveRegionSettings,
|
||||
} from '@/src/dbService'
|
||||
import type { StoresSummaryResponse } from '@packages/shared'
|
||||
import { polygon as turfPolygon, point as turfPoint } from '@turf/helpers';
|
||||
|
|
@ -21,11 +21,10 @@ import { getAssetsDomain, getApiCacheKey } from '@/src/lib/env-exporter'
|
|||
|
||||
const polygon = turfPolygon(mbnrGeoJson.features[0].geometry.coordinates);
|
||||
|
||||
export async function scaffoldEssentialConsts() {
|
||||
export async function scaffoldEssentialConsts(regionId: number) {
|
||||
const consts = await getAllConstValues();
|
||||
const cacheVersion = await getCacheVersion()
|
||||
const availabilityVersionNum = await getAvailabilityVersionNum()
|
||||
const slotsVersionNum = await getSlotsVersionNum()
|
||||
const versions = await getRegionCacheVersions(regionId)
|
||||
const regionSettings = await getEffectiveRegionSettings(regionId)
|
||||
|
||||
return {
|
||||
freeDeliveryThreshold: consts[CONST_KEYS.freeDeliveryThreshold] ?? 200,
|
||||
|
|
@ -45,9 +44,11 @@ export async function scaffoldEssentialConsts() {
|
|||
internalAppVersion: consts[CONST_KEYS.internalAppVersion] ?? 1,
|
||||
assetsDomain: getAssetsDomain(),
|
||||
apiCacheKey: getApiCacheKey(),
|
||||
cacheVersion,
|
||||
availabilityVersionNum,
|
||||
slotsVersionNum,
|
||||
regionId,
|
||||
cacheVersion: versions.cacheVersion,
|
||||
availabilityVersionNum: versions.availabilityVersionNum,
|
||||
slotsVersionNum: versions.slotsVersionNum,
|
||||
regionSettings,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -56,11 +57,13 @@ export const commonApiRouter = router({
|
|||
|
||||
getStoresSummary: publicProcedure
|
||||
.query(async (): Promise<StoresSummaryResponse> => {
|
||||
|
||||
const stores = await getStoresSummary();
|
||||
// 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)));
|
||||
|
||||
return {
|
||||
stores,
|
||||
stores: perRegion.flat(),
|
||||
};
|
||||
}),
|
||||
|
||||
|
|
@ -137,8 +140,26 @@ export const commonApiRouter = router({
|
|||
return result;
|
||||
}),
|
||||
|
||||
// Public region discovery for the user app before a browsing region is chosen.
|
||||
listRegions: publicProcedure
|
||||
.query(async () => {
|
||||
return getAllRegions();
|
||||
}),
|
||||
|
||||
// Effective business settings (from the region's lowest-priority bound).
|
||||
regionSettings: publicProcedure
|
||||
.input(z.object({ regionId: z.number().int().positive() }))
|
||||
.query(async ({ input }) => {
|
||||
const effective = await getEffectiveRegionSettings(input.regionId)
|
||||
if (!effective) {
|
||||
throw new ApiError('Region has no configured bound', 422)
|
||||
}
|
||||
return effective
|
||||
}),
|
||||
|
||||
essentialConsts: publicProcedure
|
||||
.query(async ({ ctx }) => {
|
||||
.input(z.object({ regionId: z.number().int().positive() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const requestUrl = ctx.req.url
|
||||
const host = new URL(requestUrl).host
|
||||
console.log('essentialConsts request', { host, url: requestUrl })
|
||||
|
|
@ -147,7 +168,7 @@ export const commonApiRouter = router({
|
|||
<h1 style="font-size: 36px; margin-top: 48px">With love, from Freshyo</h5>
|
||||
</div>`
|
||||
|
||||
const response = await readEssentialConstsFromKv();
|
||||
const response = await readEssentialConstsFromKv(input.regionId);
|
||||
const shouldShowNotice = host.includes('raw') || host.includes('mf')
|
||||
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -2,62 +2,69 @@ import { router, publicProcedure } from '@/src/trpc/trpc-index'
|
|||
import {
|
||||
getSuspendedSkuIds,
|
||||
getNextDeliveryDateWithCapacity,
|
||||
getStoresSummary,
|
||||
getAllSkusSummary as getAllSkusSummaryInDb,
|
||||
getAllTagsForCache,
|
||||
getAllTagProductMappings,
|
||||
getAvailabilityForCache,
|
||||
getAllProductsForCache,
|
||||
getAllDeliverySlotsForCache,
|
||||
getAllRegions,
|
||||
} from '@/src/dbService'
|
||||
import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url, scaffoldAssetUrl } from '@/src/lib/s3-client'
|
||||
import { getAllProducts as getAllProductsFromCache } from '@/src/stores/product-store'
|
||||
import { getConstant } from '@/src/lib/const-store'
|
||||
import { CONST_KEYS } from '@/src/lib/const-keys'
|
||||
|
||||
// Re-export with original name for backwards compatibility
|
||||
export const getNextDeliveryDate = getNextDeliveryDateWithCapacity
|
||||
|
||||
export async function scaffoldProducts() {
|
||||
// Get all products from cache
|
||||
let products = await getAllProductsFromCache();
|
||||
products = products.filter(item => Boolean(item.id))
|
||||
export async function scaffoldProducts(regionId: number) {
|
||||
// Scoped DB reads directly (NOT the in-memory product-store) so the output
|
||||
// contains ONLY in-region SKUs/products/tags.
|
||||
const [productsData, suspendedSkuIds, allTags, tagMappings, deliveryRows] = await Promise.all([
|
||||
getAllProductsForCache(regionId),
|
||||
getSuspendedSkuIds(regionId),
|
||||
getAllTagsForCache(regionId),
|
||||
getAllTagProductMappings(regionId),
|
||||
getAllDeliverySlotsForCache(regionId),
|
||||
])
|
||||
|
||||
const suspendedSkuIds = new Set(await getSuspendedSkuIds());
|
||||
const suspended = new Set(suspendedSkuIds)
|
||||
const products = productsData.filter(item => Boolean(item.id) && !suspended.has(item.id))
|
||||
|
||||
// Filter out suspended products
|
||||
products = products.filter(product => !suspendedSkuIds.has(product.id));
|
||||
// Latest in-region delivery slot per SKU (matches the old DESC first-match
|
||||
// semantics of getNextDeliveryDateWithCapacity).
|
||||
const nextDeliveryBySku = new Map<number, Date>()
|
||||
for (const row of deliveryRows) {
|
||||
const prev = nextDeliveryBySku.get(row.skuId)
|
||||
if (!prev || row.deliveryTime > prev) {
|
||||
nextDeliveryBySku.set(row.skuId, row.deliveryTime)
|
||||
}
|
||||
}
|
||||
|
||||
// Format products to match the expected response structure
|
||||
const formattedProducts = await Promise.all(
|
||||
products.map(async (product) => {
|
||||
const nextDeliveryDate = await getNextDeliveryDateWithCapacity(product.id);
|
||||
return {
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
shortDescription: product.shortDescription,
|
||||
unit: product.unitNotation,
|
||||
unitNotation: product.unitNotation,
|
||||
incrementStep: product.incrementStep,
|
||||
productQuantity: product.productQuantity,
|
||||
storeId: product.store?.id || null,
|
||||
isOutOfStock: product.isOutOfStock,
|
||||
nextDeliveryDate: nextDeliveryDate ? nextDeliveryDate.toISOString() : null,
|
||||
images: product.images,
|
||||
productType: product.productType || 'item',
|
||||
isComboOnly: product.isComboOnly,
|
||||
isOffer: product.isOffer,
|
||||
price: Number(product.price ?? 0),
|
||||
marketPrice: product.marketPrice != null ? Number(product.marketPrice) : null,
|
||||
flashPrice: product.flashPrice != null ? Number(product.flashPrice) : null,
|
||||
isFlashAvailable: product.isFlashAvailable,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
// Fetch all product tags with their mapped product ids
|
||||
const [allTags, tagMappings] = await Promise.all([
|
||||
getAllTagsForCache(),
|
||||
getAllTagProductMappings(),
|
||||
])
|
||||
const formattedProducts = products.map((product) => {
|
||||
const nextDeliveryDate = nextDeliveryBySku.get(product.id) ?? null
|
||||
return {
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
shortDescription: product.shortDescription,
|
||||
unit: product.unitNotation,
|
||||
unitNotation: product.unitNotation,
|
||||
incrementStep: product.incrementStep,
|
||||
productQuantity: product.productQuantity,
|
||||
storeId: product.storeId ?? null,
|
||||
isOutOfStock: product.isOutOfStock,
|
||||
nextDeliveryDate: nextDeliveryDate ? nextDeliveryDate.toISOString() : null,
|
||||
images: scaffoldAssetUrl((product.images as string[]) || []),
|
||||
productType: product.productType || 'item',
|
||||
isComboOnly: product.isComboOnly,
|
||||
isOffer: product.isOffer,
|
||||
price: Number(product.price ?? 0),
|
||||
marketPrice: product.marketPrice != null ? Number(product.marketPrice) : null,
|
||||
flashPrice: product.flashPrice != null ? Number(product.flashPrice) : null,
|
||||
isFlashAvailable: product.isFlashAvailable,
|
||||
};
|
||||
})
|
||||
|
||||
// Order tags by the admin-defined tagsOrder (unknown tags go to the end).
|
||||
const tagsOrderRaw = await getConstant(CONST_KEYS.tagsOrder)
|
||||
|
|
@ -117,8 +124,8 @@ export async function scaffoldProducts() {
|
|||
};
|
||||
}
|
||||
|
||||
export async function scaffoldAvailability() {
|
||||
const availability = await getAvailabilityForCache()
|
||||
export async function scaffoldAvailability(regionId: number) {
|
||||
const availability = await getAvailabilityForCache(regionId)
|
||||
|
||||
return {
|
||||
availability,
|
||||
|
|
@ -129,8 +136,23 @@ export async function scaffoldAvailability() {
|
|||
export const commonRouter = router({
|
||||
getAllProductsSummary: publicProcedure
|
||||
.query(async () => {
|
||||
const response = await scaffoldProducts();
|
||||
return response;
|
||||
// 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()),
|
||||
};
|
||||
}),
|
||||
|
||||
getAllSkusSummary: publicProcedure
|
||||
|
|
|
|||
52
apps/backend/src/trpc/apis/superadmin-apis/apis/auth.ts
Normal file
52
apps/backend/src/trpc/apis/superadmin-apis/apis/auth.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { router, publicProcedure, superadminProcedure } from '@/src/trpc/trpc-index'
|
||||
import { z } from 'zod'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import { SignJWT } from 'jose'
|
||||
import { getEncodedJwtSecret } from '@/src/lib/env-exporter'
|
||||
import { ApiError } from '@/src/lib/api-error'
|
||||
import { getSuperadminByUsername } from '@/src/dbService'
|
||||
|
||||
export const superadminAuthRouter = router({
|
||||
login: publicProcedure
|
||||
.input(z.object({
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
}))
|
||||
.mutation(async ({ input }) => {
|
||||
const { username, password } = input
|
||||
|
||||
if (!username || !password) {
|
||||
throw new ApiError('Username and password are required', 400)
|
||||
}
|
||||
|
||||
const superadmin = await getSuperadminByUsername(username)
|
||||
|
||||
if (!superadmin) {
|
||||
throw new ApiError('Invalid credentials', 401)
|
||||
}
|
||||
|
||||
const isPasswordValid = await bcrypt.compare(password, superadmin.passwordHash)
|
||||
if (!isPasswordValid) {
|
||||
throw new ApiError('Invalid credentials', 401)
|
||||
}
|
||||
|
||||
const token = await new SignJWT({
|
||||
identityType: 'superadmin',
|
||||
superadminId: superadmin.id,
|
||||
username: superadmin.username,
|
||||
})
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setExpirationTime('30d')
|
||||
.sign(getEncodedJwtSecret())
|
||||
|
||||
return {
|
||||
message: 'Login successful',
|
||||
token,
|
||||
superadmin: { id: superadmin.id, username: superadmin.username },
|
||||
}
|
||||
}),
|
||||
|
||||
me: superadminProcedure.query(async ({ ctx }) => {
|
||||
return { superadmin: ctx.superadmin }
|
||||
}),
|
||||
})
|
||||
151
apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts
Normal file
151
apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
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 {
|
||||
getAllRegions,
|
||||
getRegionWithBounds,
|
||||
createRegion,
|
||||
updateRegion,
|
||||
getBoundsForRegion,
|
||||
getBoundById,
|
||||
createRegionBound,
|
||||
updateRegionBound,
|
||||
getBoundSettings,
|
||||
upsertBoundSettings,
|
||||
getEffectiveRegionSettings,
|
||||
} from '@/src/dbService'
|
||||
|
||||
const geojsonSchema = z.object({
|
||||
type: z.literal('FeatureCollection'),
|
||||
features: z.array(
|
||||
z.object({
|
||||
type: z.literal('Feature'),
|
||||
properties: z.record(z.string(), z.unknown()).nullish(),
|
||||
geometry: z.object({
|
||||
type: z.string(),
|
||||
coordinates: z.unknown(),
|
||||
}),
|
||||
})
|
||||
),
|
||||
})
|
||||
|
||||
export const superadminRegionsRouter = router({
|
||||
list: superadminProcedure.query(async () => {
|
||||
return getAllRegions()
|
||||
}),
|
||||
|
||||
get: superadminProcedure
|
||||
.input(z.object({ id: z.number().int().positive() }))
|
||||
.query(async ({ input }) => {
|
||||
const region = await getRegionWithBounds(input.id)
|
||||
if (!region) throw new TRPCError({ code: 'NOT_FOUND' })
|
||||
return region
|
||||
}),
|
||||
|
||||
create: superadminProcedure
|
||||
.input(z.object({
|
||||
name: z.string().min(1),
|
||||
description: z.string().nullish(),
|
||||
}))
|
||||
.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
|
||||
}),
|
||||
|
||||
update: superadminProcedure
|
||||
.input(z.object({
|
||||
id: z.number().int().positive(),
|
||||
name: z.string().min(1).optional(),
|
||||
description: z.string().nullish(),
|
||||
}))
|
||||
.mutation(async ({ input }) => {
|
||||
const region = await updateRegion(input)
|
||||
if (!region) throw new TRPCError({ code: 'NOT_FOUND' })
|
||||
return region
|
||||
}),
|
||||
|
||||
bounds: superadminProcedure
|
||||
.input(z.object({ regionId: z.number().int().positive() }))
|
||||
.query(async ({ input }) => {
|
||||
return getBoundsForRegion(input.regionId)
|
||||
}),
|
||||
|
||||
createBound: superadminProcedure
|
||||
.input(z.object({
|
||||
regionId: z.number().int().positive(),
|
||||
description: z.string().nullish(),
|
||||
geojson: geojsonSchema,
|
||||
priority: z.string().regex(/^-?\d+(\.\d+)?$/, 'Priority must be numeric'),
|
||||
}))
|
||||
.mutation(async ({ input }) => {
|
||||
try {
|
||||
return await createRegionBound({
|
||||
regionId: input.regionId,
|
||||
description: input.description ?? null,
|
||||
geojson: input.geojson,
|
||||
priority: input.priority,
|
||||
})
|
||||
} catch (error) {
|
||||
throw new ApiError(
|
||||
'Could not create bound. Priority may already exist for this region.',
|
||||
409
|
||||
)
|
||||
}
|
||||
}),
|
||||
|
||||
updateBound: superadminProcedure
|
||||
.input(z.object({
|
||||
id: z.number().int().positive(),
|
||||
description: z.string().nullish(),
|
||||
geojson: geojsonSchema.optional(),
|
||||
priority: z.string().regex(/^-?\d+(\.\d+)?$/, 'Priority must be numeric').optional(),
|
||||
}))
|
||||
.mutation(async ({ input }) => {
|
||||
try {
|
||||
const bound = await updateRegionBound(input)
|
||||
if (!bound) throw new TRPCError({ code: 'NOT_FOUND' })
|
||||
return bound
|
||||
} catch (error) {
|
||||
if (error instanceof TRPCError) throw error
|
||||
throw new ApiError(
|
||||
'Could not update bound. Priority may already exist for this region.',
|
||||
409
|
||||
)
|
||||
}
|
||||
}),
|
||||
|
||||
boundSettings: superadminProcedure
|
||||
.input(z.object({ boundId: z.number().int().positive() }))
|
||||
.query(async ({ input }) => {
|
||||
return getBoundSettings(input.boundId)
|
||||
}),
|
||||
|
||||
updateBoundSettings: superadminProcedure
|
||||
.input(z.object({
|
||||
boundId: z.number().int().positive(),
|
||||
settings: z.array(z.object({
|
||||
key: z.string(),
|
||||
value: z.string().nullable(),
|
||||
})),
|
||||
}))
|
||||
.mutation(async ({ input }) => {
|
||||
await upsertBoundSettings(input.boundId, input.settings)
|
||||
return { success: true, updatedCount: input.settings.length }
|
||||
}),
|
||||
|
||||
effectiveSettings: superadminProcedure
|
||||
.input(z.object({ regionId: z.number().int().positive() }))
|
||||
.query(async ({ input }) => {
|
||||
const effective = await getEffectiveRegionSettings(input.regionId)
|
||||
if (!effective) {
|
||||
throw new ApiError('Region has no configured bound', 422)
|
||||
}
|
||||
return effective
|
||||
}),
|
||||
})
|
||||
108
apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts
Normal file
108
apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
|
||||
import { z } from 'zod'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import { ApiError } from '@/src/lib/api-error'
|
||||
import {
|
||||
createStaffUserWithRegion,
|
||||
updateStaffUserRegion,
|
||||
deleteStaffUser,
|
||||
getAllStaff,
|
||||
getAllRoles,
|
||||
checkStaffUserExists,
|
||||
checkStaffRoleExists,
|
||||
getRegionById,
|
||||
} from '@/src/dbService'
|
||||
|
||||
export const superadminStaffRouter = router({
|
||||
list: superadminProcedure.query(async () => {
|
||||
const staff = await getAllStaff()
|
||||
return {
|
||||
staff: staff.map((user: any) => ({
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
regionId: user.regionId ?? null,
|
||||
role: user.role
|
||||
? { id: user.role.id, name: user.role.roleName }
|
||||
: null,
|
||||
})),
|
||||
}
|
||||
}),
|
||||
|
||||
roles: superadminProcedure.query(async () => {
|
||||
const roles = await getAllRoles()
|
||||
return { roles: roles.map((role: any) => ({ id: role.id, name: role.roleName })) }
|
||||
}),
|
||||
|
||||
create: superadminProcedure
|
||||
.input(z.object({
|
||||
name: z.string().min(1, 'Name is required'),
|
||||
password: z.string().min(6, 'Password must be at least 6 characters'),
|
||||
roleId: z.number().int().positive('Role is required'),
|
||||
regionId: z.number().int().positive('Region is required'),
|
||||
}))
|
||||
.mutation(async ({ input }) => {
|
||||
const { name, password, roleId, regionId } = input
|
||||
|
||||
const existingUser = await checkStaffUserExists(name)
|
||||
if (existingUser) {
|
||||
throw new ApiError('Staff user with this name already exists', 409)
|
||||
}
|
||||
|
||||
const roleExists = await checkStaffRoleExists(roleId)
|
||||
if (!roleExists) {
|
||||
throw new ApiError('Invalid role selected', 400)
|
||||
}
|
||||
|
||||
const region = await getRegionById(regionId)
|
||||
if (!region) {
|
||||
throw new ApiError('Invalid region selected', 400)
|
||||
}
|
||||
|
||||
const hashedPassword = await bcrypt.hash(password, 12)
|
||||
const newUser = await createStaffUserWithRegion(name, hashedPassword, roleId, regionId)
|
||||
|
||||
return { success: true, user: { id: newUser.id, name: newUser.name, regionId } }
|
||||
}),
|
||||
|
||||
update: superadminProcedure
|
||||
.input(z.object({
|
||||
id: z.number().int().positive(),
|
||||
regionId: z.number().int().positive('Region is required'),
|
||||
}))
|
||||
.mutation(async ({ input }) => {
|
||||
const { id, regionId } = input
|
||||
|
||||
const region = await getRegionById(regionId)
|
||||
if (!region) {
|
||||
throw new ApiError('Invalid region selected', 400)
|
||||
}
|
||||
|
||||
const updated = await updateStaffUserRegion(id, regionId)
|
||||
if (!updated) {
|
||||
throw new ApiError('Staff user not found', 404)
|
||||
}
|
||||
|
||||
return { success: true, user: { id: updated.id, name: updated.name, regionId } }
|
||||
}),
|
||||
|
||||
remove: superadminProcedure
|
||||
.input(z.object({ id: z.number().int().positive() }))
|
||||
.mutation(async ({ input }) => {
|
||||
const result = await deleteStaffUser(input.id)
|
||||
|
||||
if (result.blockedBy === 'not_found') {
|
||||
throw new ApiError('Staff user not found', 404)
|
||||
}
|
||||
if (result.blockedBy === 'store') {
|
||||
throw new ApiError('Cannot delete this admin: they own a store. Remove or reassign the store first.', 409)
|
||||
}
|
||||
if (result.blockedBy === 'coupons') {
|
||||
throw new ApiError('Cannot delete this admin: they created coupons. Reassign or invalidate them first.', 409)
|
||||
}
|
||||
if (result.blockedBy === 'reserved_coupons') {
|
||||
throw new ApiError('Cannot delete this admin: they created reserved coupons. Reassign or invalidate them first.', 409)
|
||||
}
|
||||
|
||||
return { success: result.removed }
|
||||
}),
|
||||
})
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
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'
|
||||
|
||||
export const superadminRouter = router({
|
||||
auth: superadminAuthRouter,
|
||||
regions: superadminRegionsRouter,
|
||||
staff: superadminStaffRouter,
|
||||
})
|
||||
|
||||
export type SuperadminRouter = typeof superadminRouter
|
||||
|
|
@ -37,6 +37,7 @@ export const addressRouter = router({
|
|||
|
||||
createAddress: protectedProcedure
|
||||
.input(z.object({
|
||||
regionId: z.number().int().positive('Region is required'),
|
||||
name: z.string().min(1, 'Name is required'),
|
||||
phone: z.string().min(1, 'Phone is required'),
|
||||
addressLine1: z.string().min(1, 'Address line 1 is required'),
|
||||
|
|
@ -75,6 +76,7 @@ export const addressRouter = router({
|
|||
|
||||
const newAddress = await createUserAddressInDb({
|
||||
userId,
|
||||
regionId: input.regionId,
|
||||
name,
|
||||
phone,
|
||||
addressLine1,
|
||||
|
|
@ -94,6 +96,7 @@ export const addressRouter = router({
|
|||
updateAddress: protectedProcedure
|
||||
.input(z.object({
|
||||
id: z.number().int().positive(),
|
||||
regionId: z.number().int().positive('Region is required'),
|
||||
name: z.string().min(1, 'Name is required'),
|
||||
phone: z.string().min(1, 'Phone is required'),
|
||||
addressLine1: z.string().min(1, 'Address line 1 is required'),
|
||||
|
|
@ -134,6 +137,7 @@ export const addressRouter = router({
|
|||
const updatedAddress = await updateUserAddressInDb({
|
||||
userId,
|
||||
addressId: id,
|
||||
regionId: input.regionId,
|
||||
name,
|
||||
phone,
|
||||
addressLine1,
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ import { scaffoldAssetUrl } from '@/src/lib/s3-client'
|
|||
import { getUserActiveBanners as getUserActiveBannersInDb } from '@/src/dbService'
|
||||
import type { UserBannersResponse } from '@packages/shared'
|
||||
|
||||
export async function scaffoldBanners(): Promise<UserBannersResponse> {
|
||||
const banners = await getUserActiveBannersInDb()
|
||||
export async function scaffoldBanners(regionId: number): Promise<UserBannersResponse> {
|
||||
const banners = await getUserActiveBannersInDb(regionId)
|
||||
|
||||
const bannersWithSignedUrls = banners.map((banner) => ({
|
||||
...banner,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { router, publicProcedure } from '@/src/trpc/trpc-index'
|
||||
import { z } from 'zod'
|
||||
import { getMultipleProductsSlots } from '@/src/stores/slot-store'
|
||||
import { getSkuRegionIds as getSkuRegionIdsInDb } from '@/src/dbService'
|
||||
|
||||
export const cartRouter = router({
|
||||
// Cache-based getCartSlots
|
||||
|
|
@ -15,6 +16,24 @@ export const cartRouter = router({
|
|||
return {};
|
||||
}
|
||||
|
||||
return await getMultipleProductsSlots(productIds);
|
||||
// Regions resolved server-side from the SKUs' own product rows (never
|
||||
// client-supplied); slot reads run per region and are merged.
|
||||
const regionBySku = await getSkuRegionIdsInDb(productIds)
|
||||
const idsByRegion = new Map<number, number[]>()
|
||||
for (const skuId of productIds) {
|
||||
const regionId = regionBySku[skuId]
|
||||
if (regionId == null) continue
|
||||
if (!idsByRegion.has(regionId)) idsByRegion.set(regionId, [])
|
||||
idsByRegion.get(regionId)!.push(skuId)
|
||||
}
|
||||
|
||||
const merged: Record<number, { id: number; deliveryTime: Date; freezeTime: Date; isCapacityFull: boolean }[]> = {}
|
||||
await Promise.all(
|
||||
[...idsByRegion.entries()].map(async ([regionId, ids]) => {
|
||||
const perRegion = await getMultipleProductsSlots(regionId, ids)
|
||||
Object.assign(merged, perRegion)
|
||||
})
|
||||
)
|
||||
return merged;
|
||||
}),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import {
|
|||
getUserOrderCount,
|
||||
getUserOrdersWithRelations,
|
||||
getUserSlotCapacityStatus,
|
||||
getEffectiveRegionSettings,
|
||||
orders,
|
||||
orderItems,
|
||||
orderStatus,
|
||||
|
|
@ -26,7 +27,7 @@ import {
|
|||
import { scaffoldAssetUrl } from "@/src/lib/s3-client";
|
||||
import { ApiError } from "@/src/lib/api-error";
|
||||
import type { DeliveryStatus, OrderStatus } from "@packages/shared";
|
||||
import { CONST_KEYS, getConstant, getConstants } from "@/src/lib/const-store";
|
||||
import { CONST_KEYS } from "@/src/lib/const-store";
|
||||
import { publishFormattedOrder, publishCancellation } from "@/src/lib/post-order-handler";
|
||||
import { trackIfFirstOrder, clearFirstOrderIfMatches } from "@/src/lib/order-tracker";
|
||||
import type {
|
||||
|
|
@ -38,6 +39,7 @@ import type {
|
|||
|
||||
const placeOrderUtil = async (params: {
|
||||
userId: number;
|
||||
regionId: number;
|
||||
selectedItems: Array<{
|
||||
skuId: number;
|
||||
quantity: number;
|
||||
|
|
@ -58,16 +60,21 @@ const placeOrderUtil = async (params: {
|
|||
userNotes,
|
||||
} = params;
|
||||
|
||||
const constants = await getConstants<number>([
|
||||
CONST_KEYS.minRegularOrderValue,
|
||||
CONST_KEYS.deliveryCharge,
|
||||
CONST_KEYS.flashFreeDeliveryThreshold,
|
||||
CONST_KEYS.flashDeliveryCharge,
|
||||
]);
|
||||
const effective = await getEffectiveRegionSettings(params.regionId);
|
||||
const boundSettings = effective?.settings ?? {};
|
||||
const numSetting = (key: string): number => {
|
||||
const raw = boundSettings[key];
|
||||
const parsed = raw == null ? NaN : Number(raw);
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
};
|
||||
|
||||
const isFlashDelivery = params.isFlash;
|
||||
const minOrderValue = (isFlashDelivery ? constants[CONST_KEYS.flashFreeDeliveryThreshold] : constants[CONST_KEYS.minRegularOrderValue]) || 0;
|
||||
const deliveryCharge = (isFlashDelivery ? constants[CONST_KEYS.flashDeliveryCharge] : constants[CONST_KEYS.deliveryCharge]) || 0;
|
||||
const minOrderValue = isFlashDelivery
|
||||
? numSetting(CONST_KEYS.flashFreeDeliveryThreshold)
|
||||
: numSetting(CONST_KEYS.minRegularOrderValue);
|
||||
const deliveryCharge = isFlashDelivery
|
||||
? numSetting(CONST_KEYS.flashDeliveryCharge)
|
||||
: numSetting(CONST_KEYS.deliveryCharge);
|
||||
|
||||
const orderGroupId = `${Date.now()}-${userId}`;
|
||||
|
||||
|
|
@ -76,6 +83,14 @@ const placeOrderUtil = async (params: {
|
|||
throw new ApiError("Invalid address", 400);
|
||||
}
|
||||
|
||||
// The address and the checkout must belong to the same region.
|
||||
if (address.regionId != null && address.regionId !== params.regionId) {
|
||||
throw new ApiError(
|
||||
"Selected address belongs to a different region. Switch region and rebuild your cart to order there.",
|
||||
409
|
||||
);
|
||||
}
|
||||
|
||||
const ordersBySlot = new Map<
|
||||
number | null,
|
||||
Array<{
|
||||
|
|
@ -164,6 +179,7 @@ const placeOrderUtil = async (params: {
|
|||
|
||||
const order: Omit<typeof orders.$inferInsert, "id"> = {
|
||||
userId,
|
||||
regionId: params.regionId,
|
||||
addressId,
|
||||
slotId: params.isFlash ? null : slotId,
|
||||
isCod: paymentMethod === "cod",
|
||||
|
|
@ -251,6 +267,7 @@ export const orderRouter = router({
|
|||
})
|
||||
),
|
||||
addressId: z.number().int().positive(),
|
||||
regionId: z.number().int().positive(),
|
||||
paymentMethod: z.enum(["online", "cod"]),
|
||||
couponId: z.number().int().positive().optional(),
|
||||
userNotes: z.string().optional(),
|
||||
|
|
@ -268,6 +285,7 @@ export const orderRouter = router({
|
|||
const {
|
||||
selectedItems,
|
||||
addressId,
|
||||
regionId,
|
||||
paymentMethod,
|
||||
couponId,
|
||||
userNotes,
|
||||
|
|
@ -275,7 +293,9 @@ export const orderRouter = router({
|
|||
} = input;
|
||||
|
||||
if (isFlashDelivery) {
|
||||
const isFlashDeliveryEnabled = await getConstant<boolean>(CONST_KEYS.isFlashDeliveryEnabled);
|
||||
const effective = await getEffectiveRegionSettings(regionId);
|
||||
const raw = effective?.settings?.[CONST_KEYS.isFlashDeliveryEnabled];
|
||||
const isFlashDeliveryEnabled = raw === 'true' || raw === '1';
|
||||
if (!isFlashDeliveryEnabled) {
|
||||
throw new ApiError("Flash delivery is currently unavailable. Please opt for scheduled delivery.", 403);
|
||||
}
|
||||
|
|
@ -302,6 +322,7 @@ export const orderRouter = router({
|
|||
|
||||
return await placeOrderUtil({
|
||||
userId,
|
||||
regionId,
|
||||
selectedItems: processedItems,
|
||||
addressId,
|
||||
paymentMethod,
|
||||
|
|
@ -401,6 +422,8 @@ export const orderRouter = router({
|
|||
userNotes: order.userNotes || null,
|
||||
items,
|
||||
isFlashDelivery: order.isFlashDelivery,
|
||||
regionId: order.region?.id ?? null,
|
||||
regionName: order.region?.name ?? null,
|
||||
createdAt: order.createdAt.toISOString(),
|
||||
};
|
||||
})
|
||||
|
|
@ -542,6 +565,8 @@ export const orderRouter = router({
|
|||
discountAmount: couponData?.discountAmount || null,
|
||||
orderAmount: parseFloat(order.totalAmount.toString()),
|
||||
isFlashDelivery: order.isFlashDelivery,
|
||||
regionId: order.region?.id ?? null,
|
||||
regionName: order.region?.name ?? null,
|
||||
createdAt: order.createdAt.toISOString(),
|
||||
totalAmount: parseFloat(order.totalAmount.toString()),
|
||||
deliveryCharge: parseFloat(order.deliveryCharge.toString()),
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
getUserProductReviews as getUserProductReviewsInDb,
|
||||
getUserProductByIdBasic as getUserProductByIdBasicInDb,
|
||||
createUserProductReview as createUserProductReviewInDb,
|
||||
getSkuRegionId as getSkuRegionIdInDb,
|
||||
} from '@/src/dbService'
|
||||
import type {
|
||||
UserProductDetail,
|
||||
|
|
@ -38,8 +39,12 @@ export const productRouter = router({
|
|||
|
||||
console.log('from the api to get product details')
|
||||
|
||||
// First, try to get the product from Redis cache
|
||||
const cachedProduct = await getProductByIdFromCache(productId);
|
||||
// First, try to get the product from the region-keyed cache. The region is
|
||||
// resolved server-side from the SKU's own product row (never client-supplied).
|
||||
const skuRegionId = await getSkuRegionIdInDb(productId);
|
||||
const cachedProduct = skuRegionId != null
|
||||
? await getProductByIdFromCache(skuRegionId, productId)
|
||||
: null;
|
||||
|
||||
if (cachedProduct) {
|
||||
// Filter delivery slots to only include those with future freeze times and not at full capacity
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
import { router, publicProcedure } from "@/src/trpc/trpc-index"
|
||||
import { getAllSlots as getAllSlotsFromCache } from "@/src/stores/slot-store"
|
||||
import dayjs from 'dayjs'
|
||||
import { getUserActiveSlotsList as getUserActiveSlotsListInDb, getUserProductAvailability as getUserProductAvailabilityInDb } from '@/src/dbService'
|
||||
import { getAllSlotsWithProductsForCache, getUserActiveSlotsList as getUserActiveSlotsListInDb, getUserProductAvailability as getUserProductAvailabilityInDb, getAllRegions } from '@/src/dbService'
|
||||
import { scaffoldAssetUrl } from '@/src/lib/s3-client'
|
||||
import type { UserSlotsListResponse, UserSlotsWithProductsResponse } from '@packages/shared'
|
||||
|
||||
export async function scaffoldSlotsWithProducts(): Promise<UserSlotsWithProductsResponse> {
|
||||
const allSlots = await getAllSlotsFromCache();
|
||||
export async function scaffoldSlotsWithProducts(regionId: number): Promise<UserSlotsWithProductsResponse> {
|
||||
// Scoped DB reads directly (NOT the in-memory slot-store) so the output
|
||||
// contains ONLY in-region slots/products.
|
||||
const allSlots = await getAllSlotsWithProductsForCache(regionId);
|
||||
const currentTime = new Date();
|
||||
const validSlots = allSlots
|
||||
.filter((slot) => {
|
||||
|
|
@ -15,7 +17,7 @@ export async function scaffoldSlotsWithProducts(): Promise<UserSlotsWithProducts
|
|||
})
|
||||
.sort((a, b) => dayjs(a.deliveryTime).valueOf() - dayjs(b.deliveryTime).valueOf());
|
||||
|
||||
const productAvailability = await getUserProductAvailabilityInDb()
|
||||
const productAvailability = await getUserProductAvailabilityInDb(regionId)
|
||||
|
||||
return {
|
||||
slots: validSlots.map((slot) => ({
|
||||
|
|
@ -24,7 +26,7 @@ export async function scaffoldSlotsWithProducts(): Promise<UserSlotsWithProducts
|
|||
freezeTime: slot.freezeTime,
|
||||
products: (slot.products || []).map((product) => ({
|
||||
id: product.id,
|
||||
images: product.images,
|
||||
images: scaffoldAssetUrl((product.images as string[]) || []),
|
||||
})),
|
||||
})),
|
||||
productAvailability,
|
||||
|
|
@ -34,11 +36,14 @@ export async function scaffoldSlotsWithProducts(): Promise<UserSlotsWithProducts
|
|||
|
||||
export const slotsRouter = router({
|
||||
getSlots: publicProcedure.query(async (): Promise<UserSlotsListResponse> => {
|
||||
const slots = await getUserActiveSlotsListInDb()
|
||||
// No-input shape preserved for existing callers (separate workstream):
|
||||
// aggregate the per-region active slot lists.
|
||||
const regions = await getAllRegions()
|
||||
const perRegion = await Promise.all(regions.map((r) => getUserActiveSlotsListInDb(r.id)))
|
||||
|
||||
return {
|
||||
slots,
|
||||
count: slots.length,
|
||||
slots: perRegion.flat(),
|
||||
count: perRegion.reduce((n, list) => n + list.length, 0),
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -11,8 +11,8 @@ import type {
|
|||
UserStoreSummary,
|
||||
} from '@packages/shared'
|
||||
|
||||
export async function scaffoldStores(): Promise<UserStoresResponse> {
|
||||
const storesData = await getUserStoreSummariesInDb()
|
||||
export async function scaffoldStores(regionId: number): Promise<UserStoresResponse> {
|
||||
const storesData = await getUserStoreSummariesInDb(regionId)
|
||||
|
||||
const storesWithDetails: UserStoreSummary[] = storesData.map((store) => {
|
||||
const signedImageUrl = store.imageUrl ? scaffoldAssetUrl(store.imageUrl) : null
|
||||
|
|
@ -39,8 +39,8 @@ export async function scaffoldStores(): Promise<UserStoresResponse> {
|
|||
}
|
||||
}
|
||||
|
||||
export async function scaffoldStoreWithProducts(storeId: number): Promise<UserStoreDetail> {
|
||||
const storeDetail = await getUserStoreDetailInDb(storeId)
|
||||
export async function scaffoldStoreWithProducts(regionId: number, storeId: number): Promise<UserStoreDetail> {
|
||||
const storeDetail = await getUserStoreDetailInDb(regionId, storeId)
|
||||
|
||||
if (!storeDetail) {
|
||||
throw new ApiError('Store not found', 404)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { router } from '@/src/trpc/trpc-index'
|
||||
import { adminRouter } from '@/src/trpc/apis/admin-apis/apis/admin-trpc-index'
|
||||
import { userRouter } from '@/src/trpc/apis/user-apis/apis/user-trpc-index'
|
||||
import { superadminRouter } from '@/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index'
|
||||
import { commonApiRouter } from '@/src/trpc/apis/common-apis/common-trpc-index'
|
||||
import { scaffoldProducts, scaffoldAvailability } from './apis/common-apis/common';
|
||||
import { scaffoldStores, scaffoldStoreWithProducts } from './apis/user-apis/apis/stores';
|
||||
|
|
@ -12,6 +13,7 @@ import { scaffoldBanners } from './apis/user-apis/apis/banners';
|
|||
export const appRouter = router({
|
||||
admin: adminRouter,
|
||||
user: userRouter,
|
||||
superadmin: superadminRouter,
|
||||
common: commonApiRouter,
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,11 @@ export interface Context {
|
|||
staffUser?: {
|
||||
id: number;
|
||||
name: string;
|
||||
regionId: number;
|
||||
} | null;
|
||||
superadmin?: {
|
||||
id: number;
|
||||
username: string;
|
||||
} | null;
|
||||
callerInterface?: string | null;
|
||||
}
|
||||
|
|
@ -69,3 +74,28 @@ export const protectedProcedure = t.procedure.use(errorLoggerMiddleware).use(
|
|||
return next();
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* Staff-admin-only guard. Region is resolved from the authenticated staff row
|
||||
* (never from client input) and attached to the context.
|
||||
*/
|
||||
export const staffProcedure = t.procedure.use(errorLoggerMiddleware).use(
|
||||
middleware(async ({ ctx, next }) => {
|
||||
if (!ctx.staffUser) {
|
||||
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
||||
}
|
||||
return next();
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* Superadmin-only guard. Staff and user identities are explicitly rejected.
|
||||
*/
|
||||
export const superadminProcedure = t.procedure.use(errorLoggerMiddleware).use(
|
||||
middleware(async ({ ctx, next }) => {
|
||||
if (!ctx.superadmin) {
|
||||
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
||||
}
|
||||
return next({ ctx: { ...ctx, superadmin: ctx.superadmin } });
|
||||
})
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,17 +1,19 @@
|
|||
import React, { useState } from 'react'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { LayoutDashboard, Send, Settings2, Menu, X, LogOut } from 'lucide-react'
|
||||
import { LayoutDashboard, Send, Settings2, Menu, X, LogOut, Map, UserCog } from 'lucide-react'
|
||||
import { useAuth } from '../lib/auth-context'
|
||||
|
||||
const NAV = [
|
||||
{ to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
||||
{ to: '/regions', label: 'Regions', icon: Map },
|
||||
{ to: '/staff', label: 'Admin Users', icon: UserCog },
|
||||
{ to: '/send-notifications', label: 'Send Admin Notifications', icon: Send },
|
||||
{ to: '/constants', label: 'App Constants', icon: Settings2 },
|
||||
] as const
|
||||
|
||||
export function AppShell({ children }: { children: React.ReactNode }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const { staff, logout } = useAuth()
|
||||
const { superadmin, logout } = useAuth()
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
|
|
@ -32,8 +34,8 @@ export function AppShell({ children }: { children: React.ReactNode }) {
|
|||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
{staff?.name && (
|
||||
<span className="hidden text-sm text-gray-500 sm:inline">{staff.name}</span>
|
||||
{superadmin?.username && (
|
||||
<span className="hidden text-sm text-gray-500 sm:inline">{superadmin.username}</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
|
|
|
|||
|
|
@ -2,40 +2,42 @@ import React, { createContext, useContext, useState, useEffect, useCallback } fr
|
|||
import { trpc } from './trpc-client'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
|
||||
interface Staff {
|
||||
interface Superadmin {
|
||||
id: number
|
||||
name: string
|
||||
username: string
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
staff: Staff | null
|
||||
superadmin: Superadmin | null
|
||||
isAuthenticated: boolean
|
||||
isLoading: boolean
|
||||
token: string | null
|
||||
}
|
||||
|
||||
interface AuthContextType extends AuthState {
|
||||
login: (name: string, password: string) => Promise<void>
|
||||
login: (username: string, password: string) => Promise<void>
|
||||
logout: () => void
|
||||
isLoggingIn: boolean
|
||||
loginError: string | null
|
||||
}
|
||||
|
||||
const TOKEN_KEY = 'superadmin_token'
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [state, setState] = useState<AuthState>({
|
||||
staff: null,
|
||||
superadmin: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: true,
|
||||
token: null,
|
||||
})
|
||||
const [loginError, setLoginError] = useState<string | null>(null)
|
||||
const navigate = useNavigate()
|
||||
const loginMutation = trpc.admin.staffUser.login.useMutation()
|
||||
const loginMutation = trpc.superadmin.auth.login.useMutation()
|
||||
|
||||
useEffect(() => {
|
||||
const storedToken = localStorage.getItem('auth_token')
|
||||
const storedToken = localStorage.getItem(TOKEN_KEY)
|
||||
if (storedToken) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
|
|
@ -49,13 +51,13 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||
}, [])
|
||||
|
||||
const login = useCallback(
|
||||
async (name: string, password: string) => {
|
||||
async (username: string, password: string) => {
|
||||
setLoginError(null)
|
||||
try {
|
||||
const data = await loginMutation.mutateAsync({ name, password })
|
||||
localStorage.setItem('auth_token', data.token)
|
||||
const data = await loginMutation.mutateAsync({ username, password })
|
||||
localStorage.setItem(TOKEN_KEY, data.token)
|
||||
setState({
|
||||
staff: data.staff,
|
||||
superadmin: data.superadmin,
|
||||
token: data.token,
|
||||
isAuthenticated: true,
|
||||
isLoading: false,
|
||||
|
|
@ -69,9 +71,9 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||
)
|
||||
|
||||
const logout = useCallback(() => {
|
||||
localStorage.removeItem('auth_token')
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
setState({
|
||||
staff: null,
|
||||
superadmin: null,
|
||||
token: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ export function getTrpcClient() {
|
|||
url: `${BASE_API_URL}/api/trpc`,
|
||||
headers: async () => {
|
||||
try {
|
||||
const token = localStorage.getItem('auth_token')
|
||||
const token = localStorage.getItem('superadmin_token')
|
||||
const headers: Record<string, string> = {
|
||||
'caller-interface': 'web',
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,9 @@ import { Route as IndexRouteImport } from './routes/index'
|
|||
import { Route as ConstantsRouteImport } from './routes/constants'
|
||||
import { Route as DashboardRouteImport } from './routes/dashboard'
|
||||
import { Route as LoginRouteImport } from './routes/login'
|
||||
import { Route as RegionsRouteImport } from './routes/regions'
|
||||
import { Route as SendNotificationsRouteImport } from './routes/send-notifications'
|
||||
import { Route as StaffRouteImport } from './routes/staff'
|
||||
|
||||
const IndexRoute = IndexRouteImport.update({
|
||||
id: '/',
|
||||
|
|
@ -35,25 +37,39 @@ const LoginRoute = LoginRouteImport.update({
|
|||
path: '/login',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const RegionsRoute = RegionsRouteImport.update({
|
||||
id: '/regions',
|
||||
path: '/regions',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const SendNotificationsRoute = SendNotificationsRouteImport.update({
|
||||
id: '/send-notifications',
|
||||
path: '/send-notifications',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const StaffRoute = StaffRouteImport.update({
|
||||
id: '/staff',
|
||||
path: '/staff',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
'/constants': typeof ConstantsRoute
|
||||
'/dashboard': typeof DashboardRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/regions': typeof RegionsRoute
|
||||
'/send-notifications': typeof SendNotificationsRoute
|
||||
'/staff': typeof StaffRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof IndexRoute
|
||||
'/constants': typeof ConstantsRoute
|
||||
'/dashboard': typeof DashboardRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/regions': typeof RegionsRoute
|
||||
'/send-notifications': typeof SendNotificationsRoute
|
||||
'/staff': typeof StaffRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
|
|
@ -61,21 +77,38 @@ export interface FileRoutesById {
|
|||
'/constants': typeof ConstantsRoute
|
||||
'/dashboard': typeof DashboardRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/regions': typeof RegionsRoute
|
||||
'/send-notifications': typeof SendNotificationsRoute
|
||||
'/staff': typeof StaffRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths:
|
||||
'/' | '/constants' | '/dashboard' | '/login' | '/send-notifications'
|
||||
| '/'
|
||||
| '/constants'
|
||||
| '/dashboard'
|
||||
| '/login'
|
||||
| '/regions'
|
||||
| '/send-notifications'
|
||||
| '/staff'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/' | '/constants' | '/dashboard' | '/login' | '/send-notifications'
|
||||
to:
|
||||
| '/'
|
||||
| '/constants'
|
||||
| '/dashboard'
|
||||
| '/login'
|
||||
| '/regions'
|
||||
| '/send-notifications'
|
||||
| '/staff'
|
||||
id:
|
||||
| '__root__'
|
||||
| '/'
|
||||
| '/constants'
|
||||
| '/dashboard'
|
||||
| '/login'
|
||||
| '/regions'
|
||||
| '/send-notifications'
|
||||
| '/staff'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
|
|
@ -83,7 +116,9 @@ export interface RootRouteChildren {
|
|||
ConstantsRoute: typeof ConstantsRoute
|
||||
DashboardRoute: typeof DashboardRoute
|
||||
LoginRoute: typeof LoginRoute
|
||||
RegionsRoute: typeof RegionsRoute
|
||||
SendNotificationsRoute: typeof SendNotificationsRoute
|
||||
StaffRoute: typeof StaffRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
|
|
@ -116,6 +151,13 @@ declare module '@tanstack/react-router' {
|
|||
preLoaderRoute: typeof LoginRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/regions': {
|
||||
id: '/regions'
|
||||
path: '/regions'
|
||||
fullPath: '/regions'
|
||||
preLoaderRoute: typeof RegionsRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/send-notifications': {
|
||||
id: '/send-notifications'
|
||||
path: '/send-notifications'
|
||||
|
|
@ -123,6 +165,13 @@ declare module '@tanstack/react-router' {
|
|||
preLoaderRoute: typeof SendNotificationsRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/staff': {
|
||||
id: '/staff'
|
||||
path: '/staff'
|
||||
fullPath: '/staff'
|
||||
preLoaderRoute: typeof StaffRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -131,7 +180,9 @@ const rootRouteChildren: RootRouteChildren = {
|
|||
ConstantsRoute: ConstantsRoute,
|
||||
DashboardRoute: DashboardRoute,
|
||||
LoginRoute: LoginRoute,
|
||||
RegionsRoute: RegionsRoute,
|
||||
SendNotificationsRoute: SendNotificationsRoute,
|
||||
StaffRoute: StaffRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
._addFileChildren(rootRouteChildren)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { AppContainer, p as MyText } from 'web-components'
|
||||
import { Send, Settings2, ChevronRight } from 'lucide-react'
|
||||
import { Send, Settings2, ChevronRight, Map } from 'lucide-react'
|
||||
import { ProtectedRoute } from '../components/ProtectedRoute'
|
||||
import { AppShell } from '../components/AppShell'
|
||||
|
||||
|
|
@ -15,6 +15,12 @@ export const Route = createFileRoute('/dashboard')({
|
|||
})
|
||||
|
||||
const CARDS = [
|
||||
{
|
||||
to: '/regions',
|
||||
title: 'Regions & Bounds',
|
||||
description: 'Create regions and manage their delivery bounds.',
|
||||
icon: Map,
|
||||
},
|
||||
{
|
||||
to: '/send-notifications',
|
||||
title: 'Send Admin Notifications',
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ export const Route = createFileRoute('/login')({ component: LoginPage })
|
|||
function LoginPage() {
|
||||
const { login, isLoggingIn, loginError, isAuthenticated, isLoading } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
const [name, setName] = useState('')
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -19,9 +19,9 @@ function LoginPage() {
|
|||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!name.trim() || !password.trim()) return
|
||||
if (!username.trim() || !password.trim()) return
|
||||
try {
|
||||
await login(name.trim(), password)
|
||||
await login(username.trim(), password)
|
||||
navigate({ to: '/dashboard' })
|
||||
} catch {
|
||||
// error surfaced via loginError
|
||||
|
|
@ -85,18 +85,18 @@ function LoginPage() {
|
|||
</p>
|
||||
<h1 className="display-2 mt-1 text-gray-900">Sign in to continue</h1>
|
||||
<p className="mb-8 mt-1 text-gray-500">
|
||||
Enter your staff name and password to manage app constants
|
||||
Enter your superadmin username and password to manage regions
|
||||
</p>
|
||||
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-8 shadow-sm">
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
<PInput
|
||||
topLabel="Staff Name"
|
||||
placeholder="Enter your name"
|
||||
value={name}
|
||||
topLabel="Username"
|
||||
placeholder="Enter your username"
|
||||
value={username}
|
||||
autoCapitalize="none"
|
||||
autoCorrect="off"
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
className="bg-gray-50"
|
||||
/>
|
||||
|
||||
|
|
@ -118,7 +118,7 @@ function LoginPage() {
|
|||
<MyButton
|
||||
type="submit"
|
||||
fullWidth
|
||||
disabled={isLoggingIn || !name.trim() || !password.trim()}
|
||||
disabled={isLoggingIn || !username.trim() || !password.trim()}
|
||||
className="h-12 rounded-lg bg-brand-600 text-white shadow-md transition-colors hover:bg-brand-700"
|
||||
>
|
||||
{isLoggingIn ? 'Logging in...' : 'Login'}
|
||||
|
|
|
|||
318
apps/superadmin-ui/src/routes/regions.tsx
Normal file
318
apps/superadmin-ui/src/routes/regions.tsx
Normal file
|
|
@ -0,0 +1,318 @@
|
|||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useState } from 'react'
|
||||
import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
|
||||
import { ProtectedRoute } from '../components/ProtectedRoute'
|
||||
import { AppShell } from '../components/AppShell'
|
||||
import { trpc } from '../lib/trpc-client'
|
||||
|
||||
export const Route = createFileRoute('/regions')({
|
||||
component: () => (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
<RegionsPage />
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
),
|
||||
})
|
||||
|
||||
const SETTING_KEYS = [
|
||||
'minRegularOrderValue',
|
||||
'freeDeliveryThreshold',
|
||||
'deliveryCharge',
|
||||
'flashFreeDeliveryThreshold',
|
||||
'flashDeliveryCharge',
|
||||
'popularItems',
|
||||
'allItemsOrder',
|
||||
'isFlashDeliveryEnabled',
|
||||
'supportMobile',
|
||||
'supportEmail',
|
||||
'welcomeMessage',
|
||||
] as const
|
||||
|
||||
const SETTING_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',
|
||||
popularItems: 'Popular Items (JSON)',
|
||||
allItemsOrder: 'All Items Order (JSON)',
|
||||
isFlashDeliveryEnabled: 'Enable Flash Delivery',
|
||||
supportMobile: 'Support Mobile',
|
||||
supportEmail: 'Support Email',
|
||||
welcomeMessage: 'Welcome Message',
|
||||
}
|
||||
|
||||
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 ?? []
|
||||
|
||||
return (
|
||||
<AppContainer>
|
||||
<div className="bg-gray-50 p-4">
|
||||
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Regions</MyText>
|
||||
<MyText className="mb-6 block text-gray-600">
|
||||
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>
|
||||
|
||||
{regionsQuery.isLoading && <MyText className="text-gray-500">Loading regions...</MyText>}
|
||||
|
||||
<div className="mb-6 grid gap-3 sm:grid-cols-2">
|
||||
{regions.map((region) => (
|
||||
<button
|
||||
key={region.id}
|
||||
type="button"
|
||||
onClick={() => setSelectedRegionId(region.id)}
|
||||
className={`rounded-xl border p-4 text-left shadow-sm transition-colors ${
|
||||
selectedRegionId === region.id
|
||||
? 'border-blue-400 bg-blue-50'
|
||||
: 'border-gray-200 bg-white hover:border-blue-300'
|
||||
}`}
|
||||
>
|
||||
<MyText className="block font-semibold text-gray-900">{region.name}</MyText>
|
||||
<MyText className="block text-sm text-gray-500">
|
||||
{region.description || 'No description'}
|
||||
</MyText>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{selectedRegionId && <RegionDetail regionId={selectedRegionId} />}
|
||||
</div>
|
||||
</AppContainer>
|
||||
)
|
||||
}
|
||||
|
||||
function RegionDetail({ regionId }: { regionId: number }) {
|
||||
const regionQuery = trpc.superadmin.regions.get.useQuery({ id: regionId })
|
||||
const [activeBoundId, setActiveBoundId] = useState<number | null>(null)
|
||||
const [showAddBound, setShowAddBound] = useState(false)
|
||||
|
||||
const bounds = regionQuery.data?.bounds ?? []
|
||||
const effectiveBoundId = bounds.length > 0 ? bounds[0].id : null
|
||||
|
||||
const activeBound = bounds.find((b) => b.id === activeBoundId) ?? bounds[0] ?? null
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<MyText className="block font-semibold text-gray-900">
|
||||
{regionQuery.data?.name} — bounds
|
||||
</MyText>
|
||||
<MyButton
|
||||
onClick={() => setShowAddBound((v) => !v)}
|
||||
className="rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-700"
|
||||
>
|
||||
{showAddBound ? 'Cancel' : 'Add bound'}
|
||||
</MyButton>
|
||||
</div>
|
||||
|
||||
{showAddBound && (
|
||||
<AddBoundForm
|
||||
regionId={regionId}
|
||||
onCreated={(id) => {
|
||||
setShowAddBound(false)
|
||||
setActiveBoundId(id)
|
||||
regionQuery.refetch()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{bounds.length === 0 && !showAddBound && (
|
||||
<MyText className="block text-gray-500">
|
||||
No bounds yet. Add at least one bound so this region can take orders.
|
||||
</MyText>
|
||||
)}
|
||||
|
||||
{bounds.length > 0 && (
|
||||
<>
|
||||
<div className="mb-4 flex flex-wrap gap-2">
|
||||
{bounds.map((bound) => {
|
||||
const isActive = activeBound?.id === bound.id
|
||||
return (
|
||||
<button
|
||||
key={bound.id}
|
||||
type="button"
|
||||
onClick={() => setActiveBoundId(bound.id)}
|
||||
className={`rounded-lg border px-3 py-2 text-sm font-medium ${
|
||||
isActive ? 'border-blue-400 bg-blue-50 text-blue-700' : 'border-gray-200 text-gray-700'
|
||||
}`}
|
||||
>
|
||||
{bound.description || `Bound #${bound.id}`} (P{bound.priority})
|
||||
{bound.id === effectiveBoundId && (
|
||||
<span className="ml-2 rounded bg-green-100 px-1.5 py-0.5 text-[10px] font-bold text-green-700">
|
||||
EFFECTIVE
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<MyText className="mb-4 block text-sm text-gray-500">
|
||||
Only the lowest-priority bound's settings currently apply to checkout, regardless of
|
||||
address coordinates.
|
||||
</MyText>
|
||||
|
||||
{activeBound && <BoundSettingsEditor boundId={activeBound.id} />}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AddBoundForm({ regionId, onCreated }: { regionId: number; onCreated: (id: number) => void }) {
|
||||
const [description, setDescription] = useState('')
|
||||
const [priority, setPriority] = useState('')
|
||||
const [geojson, setGeojson] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const createBound = trpc.superadmin.regions.createBound.useMutation()
|
||||
|
||||
return (
|
||||
<div className="mb-6 rounded-lg border border-gray-200 bg-gray-50 p-4">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<PInput
|
||||
topLabel="Description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="e.g. Mbnr-1"
|
||||
/>
|
||||
<PInput
|
||||
topLabel="Priority (lower = higher precedence)"
|
||||
value={priority}
|
||||
onChange={(e) => setPriority(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={geojson}
|
||||
onChange={(e) => setGeojson(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>
|
||||
{error && <MyText className="mt-2 block text-sm text-red-600">{error}</MyText>}
|
||||
<MyButton
|
||||
onClick={async () => {
|
||||
setError(null)
|
||||
try {
|
||||
const parsed = JSON.parse(geojson)
|
||||
const bound = await createBound.mutateAsync({
|
||||
regionId,
|
||||
description: description.trim() || null,
|
||||
priority: priority.trim(),
|
||||
geojson: parsed,
|
||||
})
|
||||
onCreated(bound.id)
|
||||
} catch (e) {
|
||||
setError((e as Error).message || 'Invalid GeoJSON or duplicate priority')
|
||||
}
|
||||
}}
|
||||
disabled={createBound.isPending || !priority.trim() || !geojson.trim()}
|
||||
className="mt-3 rounded-lg bg-blue-500 px-4 py-2 text-white disabled:opacity-50"
|
||||
>
|
||||
{createBound.isPending ? 'Saving...' : 'Create bound'}
|
||||
</MyButton>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function BoundSettingsEditor({ boundId }: { boundId: number }) {
|
||||
const settingsQuery = trpc.superadmin.regions.boundSettings.useQuery({ boundId })
|
||||
const updateSettings = trpc.superadmin.regions.updateBoundSettings.useMutation({
|
||||
onSuccess: () => settingsQuery.refetch(),
|
||||
})
|
||||
|
||||
const [draft, setDraft] = useState<Record<string, string>>({})
|
||||
const [initialised, setInitialised] = useState<number | null>(null)
|
||||
|
||||
const settings = settingsQuery.data ?? {}
|
||||
|
||||
// Re-initialise the draft whenever the selected bound changes.
|
||||
if (initialised !== boundId && settingsQuery.isSuccess) {
|
||||
const next: Record<string, string> = {}
|
||||
for (const key of SETTING_KEYS) {
|
||||
next[key] = settings[key] ?? ''
|
||||
}
|
||||
setDraft(next)
|
||||
setInitialised(boundId)
|
||||
}
|
||||
|
||||
if (settingsQuery.isLoading) {
|
||||
return <MyText className="block text-gray-500">Loading settings...</MyText>
|
||||
}
|
||||
|
||||
const handleSave = () => {
|
||||
updateSettings.mutate({
|
||||
boundId,
|
||||
settings: SETTING_KEYS.map((key) => ({ key, value: draft[key] ?? '' })),
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<MyText className="mb-3 block font-semibold text-gray-900">Bound settings</MyText>
|
||||
{SETTING_KEYS.map((key) => (
|
||||
<div key={key} className="mb-3">
|
||||
<PInput
|
||||
topLabel={SETTING_LABELS[key] || key}
|
||||
value={draft[key] ?? ''}
|
||||
onChange={(e) => setDraft((prev) => ({ ...prev, [key]: e.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<MyButton
|
||||
onClick={handleSave}
|
||||
disabled={updateSettings.isPending}
|
||||
className="mt-2 rounded-lg bg-blue-500 px-4 py-2 text-white disabled:opacity-50"
|
||||
>
|
||||
{updateSettings.isPending ? 'Saving...' : 'Save settings'}
|
||||
</MyButton>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
217
apps/superadmin-ui/src/routes/staff.tsx
Normal file
217
apps/superadmin-ui/src/routes/staff.tsx
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useState } from 'react'
|
||||
import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
|
||||
import { Trash2 } from 'lucide-react'
|
||||
import { ProtectedRoute } from '../components/ProtectedRoute'
|
||||
import { AppShell } from '../components/AppShell'
|
||||
import { trpc } from '../lib/trpc-client'
|
||||
|
||||
export const Route = createFileRoute('/staff')({
|
||||
component: () => (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
<StaffPage />
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
),
|
||||
})
|
||||
|
||||
function StaffPage() {
|
||||
const staffQuery = trpc.superadmin.staff.list.useQuery()
|
||||
const rolesQuery = trpc.superadmin.staff.roles.useQuery()
|
||||
const regionsQuery = trpc.superadmin.regions.list.useQuery()
|
||||
const utils = trpc.useUtils()
|
||||
|
||||
const staffList = staffQuery.data?.staff ?? []
|
||||
const roles = rolesQuery.data?.roles ?? []
|
||||
const regions = regionsQuery.data ?? []
|
||||
const regionNameById = new Map(regions.map((r) => [r.id, r.name]))
|
||||
|
||||
const [name, setName] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [roleId, setRoleId] = useState<number | null>(null)
|
||||
const [regionId, setRegionId] = useState<number | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const createUser = trpc.superadmin.staff.create.useMutation()
|
||||
const updateUser = trpc.superadmin.staff.update.useMutation()
|
||||
const removeUser = trpc.superadmin.staff.remove.useMutation()
|
||||
|
||||
const refresh = () => {
|
||||
utils.superadmin.staff.list.invalidate()
|
||||
}
|
||||
|
||||
if (staffQuery.isLoading || rolesQuery.isLoading || regionsQuery.isLoading) {
|
||||
return (
|
||||
<AppContainer>
|
||||
<div className="bg-gray-50 p-4">
|
||||
<MyText className="text-gray-500">Loading staff...</MyText>
|
||||
</div>
|
||||
</AppContainer>
|
||||
)
|
||||
}
|
||||
|
||||
const handleCreate = async () => {
|
||||
setError(null)
|
||||
if (!name.trim() || !roleId || !regionId) return
|
||||
try {
|
||||
await createUser.mutateAsync({ name: name.trim(), password, roleId, regionId })
|
||||
setName('')
|
||||
setPassword('')
|
||||
setRoleId(null)
|
||||
setRegionId(null)
|
||||
refresh()
|
||||
} catch (e) {
|
||||
setError((e as Error).message || 'Could not create admin user')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AppContainer>
|
||||
<div className="bg-gray-50 p-4">
|
||||
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Admin Users</MyText>
|
||||
<MyText className="mb-6 block text-gray-600">
|
||||
Create admin accounts, move them between regions, or remove them.
|
||||
</MyText>
|
||||
|
||||
{/* Add admin */}
|
||||
<div className="mb-8 rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
|
||||
<MyText className="mb-3 block font-semibold text-gray-900">Add an admin</MyText>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<PInput
|
||||
topLabel="Name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="e.g. Store Manager"
|
||||
/>
|
||||
<PInput
|
||||
topLabel="Password (min 6 chars)"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="Password"
|
||||
/>
|
||||
<div>
|
||||
<MyText className="mb-1 block text-sm font-medium text-gray-700">Role</MyText>
|
||||
<select
|
||||
value={roleId ?? ''}
|
||||
onChange={(e) => setRoleId(e.target.value ? Number(e.target.value) : null)}
|
||||
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="">Select role</option>
|
||||
{roles.map((r) => (
|
||||
<option key={r.id} value={r.id}>{r.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<MyText className="mb-1 block text-sm font-medium text-gray-700">Region</MyText>
|
||||
<select
|
||||
value={regionId ?? ''}
|
||||
onChange={(e) => setRegionId(e.target.value ? Number(e.target.value) : null)}
|
||||
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="">Select region</option>
|
||||
{regions.map((r) => (
|
||||
<option key={r.id} value={r.id}>{r.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{error && <MyText className="mt-2 block text-sm text-red-600">{error}</MyText>}
|
||||
<MyButton
|
||||
onClick={handleCreate}
|
||||
disabled={createUser.isPending || !name.trim() || !roleId || !regionId}
|
||||
className="mt-4 rounded-lg bg-blue-500 px-4 py-2 text-white disabled:opacity-50"
|
||||
>
|
||||
{createUser.isPending ? 'Creating...' : 'Create admin'}
|
||||
</MyButton>
|
||||
</div>
|
||||
|
||||
{/* Staff list */}
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
|
||||
<MyText className="mb-4 block font-semibold text-gray-900">Existing admins</MyText>
|
||||
{staffList.length === 0 && (
|
||||
<MyText className="block text-gray-500">No admins yet.</MyText>
|
||||
)}
|
||||
<div className="space-y-3">
|
||||
{staffList.map((user) => (
|
||||
<StaffRow
|
||||
key={user.id}
|
||||
user={user}
|
||||
regions={regions}
|
||||
regionNameById={regionNameById}
|
||||
updatePending={updateUser.isPending}
|
||||
removePending={removeUser.isPending}
|
||||
onReassign={async (newRegionId) => {
|
||||
setError(null)
|
||||
try {
|
||||
await updateUser.mutateAsync({ id: user.id, regionId: newRegionId })
|
||||
refresh()
|
||||
} catch (e) {
|
||||
setError((e as Error).message || 'Could not reassign region')
|
||||
}
|
||||
}}
|
||||
onRemove={async () => {
|
||||
if (!window.confirm(`Remove admin "${user.name}"? This cannot be undone.`)) return
|
||||
setError(null)
|
||||
try {
|
||||
await removeUser.mutateAsync({ id: user.id })
|
||||
refresh()
|
||||
} catch (e) {
|
||||
setError((e as Error).message || 'Could not remove this admin')
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{error && <MyText className="mt-3 block text-sm text-red-600">{error}</MyText>}
|
||||
</div>
|
||||
</div>
|
||||
</AppContainer>
|
||||
)
|
||||
}
|
||||
|
||||
interface StaffRowProps {
|
||||
user: { id: number; name: string; regionId: number | null; role: { id: number; name: string } | null }
|
||||
regions: Array<{ id: number; name: string }>
|
||||
regionNameById: Map<number, string>
|
||||
updatePending: boolean
|
||||
removePending: boolean
|
||||
onReassign: (regionId: number) => Promise<void>
|
||||
onRemove: () => Promise<void>
|
||||
}
|
||||
|
||||
function StaffRow({ user, regions, regionNameById, updatePending, removePending, onReassign, onRemove }: StaffRowProps) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-gray-100 bg-gray-50 px-4 py-3">
|
||||
<div className="min-w-[10rem]">
|
||||
<MyText className="block font-semibold text-gray-900">{user.name}</MyText>
|
||||
<MyText className="block text-xs text-gray-500">
|
||||
{user.role?.name ?? 'No role'} · Region: {regionNameById.get(user.regionId ?? -1) ?? 'Unassigned'}
|
||||
</MyText>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<select
|
||||
value={user.regionId ?? ''}
|
||||
onChange={(e) => {
|
||||
if (e.target.value) void onReassign(Number(e.target.value))
|
||||
}}
|
||||
className="rounded-lg border border-gray-300 bg-white px-2 py-1.5 text-sm"
|
||||
>
|
||||
<option value="">Unassigned</option>
|
||||
{regions.map((r) => (
|
||||
<option key={r.id} value={r.id}>{r.name}</option>
|
||||
))}
|
||||
</select>
|
||||
<MyButton
|
||||
onClick={() => void onRemove()}
|
||||
disabled={updatePending || removePending}
|
||||
className="rounded-lg border border-red-200 p-2 text-red-600 hover:bg-red-50"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</MyButton>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -10,7 +10,7 @@ import AddressForm from '@/src/components/AddressForm';
|
|||
// Address view — required core of the shared UserAddress + optional geo fields
|
||||
type Address = Pick<
|
||||
UserAddress,
|
||||
'id' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'pincode' | 'isDefault'
|
||||
'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'pincode' | 'isDefault'
|
||||
> & {
|
||||
latitude?: number | null
|
||||
longitude?: number | null
|
||||
|
|
@ -136,9 +136,14 @@ export default function Addresses() {
|
|||
const handleSetDefault = (id: number) => {
|
||||
// Update the address to be default
|
||||
const addressToUpdate = addresses.find(addr => addr.id === id);
|
||||
if (addressToUpdate && addressToUpdate.regionId == null) {
|
||||
Alert.alert('Error', 'This address has no region. Please edit it and choose a region first.');
|
||||
return;
|
||||
}
|
||||
if (addressToUpdate) {
|
||||
updateAddressMutation.mutate({
|
||||
id: addressToUpdate.id,
|
||||
regionId: addressToUpdate.regionId as number,
|
||||
name: addressToUpdate.name,
|
||||
phone: addressToUpdate.phone,
|
||||
addressLine1: addressToUpdate.addressLine1,
|
||||
|
|
@ -247,6 +252,7 @@ export default function Addresses() {
|
|||
onSuccess={handleAddressSubmit}
|
||||
initialValues={editingAddress ? {
|
||||
id: editingAddress.id,
|
||||
regionId: editingAddress.regionId ?? undefined,
|
||||
name: editingAddress.name,
|
||||
phone: editingAddress.phone,
|
||||
addressLine1: editingAddress.addressLine1,
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
import React from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import { View, ScrollView } from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { useFocusEffect } from '@react-navigation/native';
|
||||
import { AppContainer, MyText, tw, MyTouchableOpacity, ProfileImage, colors } from 'common-ui';
|
||||
import { AppContainer, BottomDialog, MyText, tw, MyTouchableOpacity, ProfileImage, colors } from 'common-ui';
|
||||
import TabLayoutWrapper from '@/components/TabLayoutWrapper';
|
||||
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 { useAuth } from '@/src/contexts/AuthContext';
|
||||
import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget';
|
||||
|
||||
|
|
@ -14,6 +16,9 @@ export default function Me() {
|
|||
const router = useRouter();
|
||||
const { logout } = useAuth();
|
||||
const { getNavigationTarget } = useNavigationTarget();
|
||||
const [regionDialogOpen, setRegionDialogOpen] = useState(false);
|
||||
const selectedRegion = useRegionStore((state) => state.selectedRegion);
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId);
|
||||
|
||||
useFocusEffect(() => {
|
||||
const target = getNavigationTarget();
|
||||
|
|
@ -60,6 +65,13 @@ export default function Me() {
|
|||
onPress: () => router.push('/(drawer)/(tabs)/me/addresses'),
|
||||
subtitle: 'Manage delivery locations'
|
||||
},
|
||||
{
|
||||
title: 'Delivery Region',
|
||||
icon: 'globe-outline',
|
||||
color: '#0EA5E9',
|
||||
onPress: () => setRegionDialogOpen(true),
|
||||
subtitle: selectedRegion?.name ? `Browsing ${selectedRegion.name}` : 'Choose your region'
|
||||
},
|
||||
{
|
||||
title: 'Profile Settings',
|
||||
icon: 'person-outline',
|
||||
|
|
@ -163,6 +175,17 @@ export default function Me() {
|
|||
</MyText>
|
||||
</View>
|
||||
</ScrollView>
|
||||
|
||||
<BottomDialog open={regionDialogOpen} onClose={() => setRegionDialogOpen(false)}>
|
||||
<View style={tw`h-96`}>
|
||||
<RegionSelector
|
||||
mode="switch"
|
||||
selectedRegionId={selectedRegionId}
|
||||
onComplete={() => setRegionDialogOpen(false)}
|
||||
onCancel={() => setRegionDialogOpen(false)}
|
||||
/>
|
||||
</View>
|
||||
</BottomDialog>
|
||||
</View>
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -142,6 +142,12 @@ export default function OrderDetails() {
|
|||
<View>
|
||||
<MyText style={tw`text-slate-900 font-bold text-lg`}>Order #{order.orderId}</MyText>
|
||||
<MyText style={tw`text-slate-400 text-xs`}>{dayjs(order.orderDate).format("DD MMM, h:mm A")}</MyText>
|
||||
{!!order.regionName && (
|
||||
<View style={tw`flex-row items-center mt-0.5`}>
|
||||
<MaterialIcons name="location-on" size={11} color="#94A3B8" />
|
||||
<MyText style={tw`text-slate-400 text-[10px] ml-1`}>{order.regionName}</MyText>
|
||||
</View>
|
||||
)}
|
||||
{order.isFlashDelivery && (
|
||||
<MyText style={tw`text-amber-600 text-xs font-bold mt-1`}>⚡ 1 Hr Delivery</MyText>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -120,6 +120,12 @@ const OrderItem: React.FC<OrderItemProps> = ({
|
|||
<MyText style={tw`text-[10px] font-black text-amber-700 uppercase`}>FLASH</MyText>
|
||||
</View>
|
||||
)}
|
||||
{!!item.regionName && (
|
||||
<View style={tw`px-2 py-1 bg-slate-100 rounded-full border border-slate-200 flex-row items-center`}>
|
||||
<MaterialIcons name="location-on" size={11} color="#475569" />
|
||||
<MyText style={tw`text-[10px] font-bold text-slate-600 ml-1`}>{item.regionName}</MyText>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
|
|
@ -348,6 +354,8 @@ export default function MyOrders() {
|
|||
const [loadMoreError, setLoadMoreError] = useState<string | null>(null);
|
||||
const pageSize = 10;
|
||||
|
||||
// Account-wide history: deliberately NOT filtered by the browsing region, so
|
||||
// orders from every region remain visible. Each card shows its regionName.
|
||||
const { data: ordersData, isLoading, error, refetch } = trpc.user.order.getOrders.useQuery({
|
||||
page: currentPage,
|
||||
pageSize: pageSize,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { View, Text, TouchableOpacity, ScrollView, Alert, NativeSyntheticEvent, NativeScrollEvent } from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { tw, BottomDialog, RawBottomDialog } from 'common-ui';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import AddressForm from '@/src/components/AddressForm';
|
||||
|
|
@ -7,6 +8,8 @@ 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 { confirmRegionSwitch } from '@/src/lib/region-switch';
|
||||
import * as Location from 'expo-location';
|
||||
|
||||
interface AddressSelectorProps {
|
||||
|
|
@ -26,12 +29,15 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
const [currentIndex, setCurrentIndex] = useState(0);
|
||||
const queryClient = useQueryClient();
|
||||
const utils = trpc.useUtils();
|
||||
const router = useRouter();
|
||||
const scrollViewRef = useRef<ScrollView>(null);
|
||||
const { isAuthenticated } = useAuth();
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId);
|
||||
const { data: addresses } = trpc.user.address.getUserAddresses.useQuery(
|
||||
undefined,
|
||||
{ enabled: isAuthenticated }
|
||||
);
|
||||
const { data: regions } = trpc.common.listRegions.useQuery();
|
||||
|
||||
const updateAddressMutation = trpc.user.address.updateAddress.useMutation({
|
||||
onSuccess: () => {
|
||||
|
|
@ -66,11 +72,16 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
useEffect(() => {
|
||||
if (sortedAddresses.length > 0 && selectedAddress === null) {
|
||||
const defaultAddress = sortedAddresses.find(addr => addr.isDefault);
|
||||
if (defaultAddress) {
|
||||
// Never silently auto-select a region we are not browsing.
|
||||
const isCurrentRegion =
|
||||
!selectedRegionId ||
|
||||
defaultAddress?.regionId == null ||
|
||||
defaultAddress.regionId === selectedRegionId;
|
||||
if (defaultAddress && isCurrentRegion) {
|
||||
onAddressSelect(defaultAddress.id);
|
||||
}
|
||||
}
|
||||
}, [sortedAddresses, selectedAddress, onAddressSelect]);
|
||||
}, [sortedAddresses, selectedAddress, onAddressSelect, selectedRegionId]);
|
||||
|
||||
// Reset scroll to left when address is selected
|
||||
const resetScrollToLeft = () => {
|
||||
|
|
@ -83,6 +94,39 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
setCurrentIndex(index);
|
||||
};
|
||||
|
||||
// Selecting an address from another region requires an explicit confirmation
|
||||
// because it clears the cart and changes the browsing region.
|
||||
const handleAddressPress = (address: any) => {
|
||||
if (selectedRegionId && address.regionId && address.regionId !== selectedRegionId) {
|
||||
const targetRegion = (regions ?? []).find((region) => region.id === address.regionId);
|
||||
if (!targetRegion) {
|
||||
Alert.alert('Unavailable region', 'This address belongs to a region that is not currently available.');
|
||||
return;
|
||||
}
|
||||
Alert.alert(
|
||||
'Switch region?',
|
||||
`This address is in ${targetRegion.name}. Switching will clear your entire cart and take you home.`,
|
||||
[
|
||||
{ text: 'Cancel', style: 'cancel' },
|
||||
{
|
||||
text: 'Switch & clear cart',
|
||||
style: 'destructive',
|
||||
onPress: () => {
|
||||
void (async () => {
|
||||
await confirmRegionSwitch(targetRegion, queryClient);
|
||||
router.replace('/(drawer)/(tabs)/home');
|
||||
})();
|
||||
},
|
||||
},
|
||||
]
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
onAddressSelect(address.id);
|
||||
resetScrollToLeft();
|
||||
};
|
||||
|
||||
const handleAttachLocation = async (address: any) => {
|
||||
setEditingLocationAddressId(address.id);
|
||||
setLocationLoading(true);
|
||||
|
|
@ -104,6 +148,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
|
||||
updateAddressMutation.mutate({
|
||||
id: address.id,
|
||||
regionId: address.regionId ?? selectedRegionId ?? undefined,
|
||||
name: address.name,
|
||||
phone: address.phone,
|
||||
addressLine1: address.addressLine1,
|
||||
|
|
@ -165,10 +210,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
<TouchableOpacity
|
||||
key={address.id}
|
||||
testID={`address-option-${index}`}
|
||||
onPress={() => {
|
||||
onAddressSelect(address.id);
|
||||
resetScrollToLeft();
|
||||
}}
|
||||
onPress={() => handleAddressPress(address)}
|
||||
style={tw`w-72 p-4 mr-3 bg-gray-50 rounded-xl border-2 ${selectedAddress === address.id ? 'border-brand500 bg-blue-50' : 'border-gray-200'
|
||||
} shadow-sm`}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -2,6 +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'
|
||||
|
||||
const FirstUserWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
||||
const [isFirstTime, setIsFirstTime] = useState<boolean | null>(null)
|
||||
|
|
@ -34,7 +35,7 @@ const FirstUserWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
|||
)
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
return <RegionGate>{children}</RegionGate>
|
||||
}
|
||||
|
||||
export default FirstUserWrapper
|
||||
|
|
@ -6,6 +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 { clearLocalCart } from '@/hooks/cart-query-hooks';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { FontAwesome5, FontAwesome6 } from '@expo/vector-icons';
|
||||
|
|
@ -60,6 +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);
|
||||
|
||||
// Memoized flash-eligible product IDs
|
||||
const flashEligibleProductIds = useMemo(() => {
|
||||
|
|
@ -92,7 +94,13 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
|||
}
|
||||
},
|
||||
onError: (error: any) => {
|
||||
Alert.alert('Error', error.message || 'Failed to place order');
|
||||
// The backend rejects a checkout whose address/SKUs belong to another
|
||||
// region; surface its message without leaking the raw error object.
|
||||
const message =
|
||||
typeof error?.message === 'string' && error.message.length > 0
|
||||
? error.message
|
||||
: 'Failed to place order';
|
||||
Alert.alert('Error', message);
|
||||
},
|
||||
onSettled: () => {
|
||||
setIsLoadingDialogOpen(false);
|
||||
|
|
@ -125,6 +133,11 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
|||
return;
|
||||
}
|
||||
|
||||
if (!selectedRegionId) {
|
||||
Alert.alert('Error', 'Please select a delivery region before placing an order');
|
||||
return;
|
||||
}
|
||||
|
||||
const availableItems = cartItems
|
||||
.filter(item => {
|
||||
if (productSlotsMap[item.skuId]?.isOutOfStock) return false;
|
||||
|
|
@ -155,6 +168,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
|||
};
|
||||
}),
|
||||
addressId: selectedAddress,
|
||||
regionId: selectedRegionId,
|
||||
paymentMethod: paymentMethod,
|
||||
couponId: selectedCouponId || undefined,
|
||||
userNotes: userNotes,
|
||||
|
|
|
|||
|
|
@ -1,11 +1,14 @@
|
|||
import React, { useState } from 'react';
|
||||
import { View, ScrollView, Dimensions } from 'react-native';
|
||||
import React, { useState, useMemo } from 'react';
|
||||
import { View, ScrollView, Dimensions, Alert } from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||
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 { confirmRegionSwitch } from '@/src/lib/region-switch';
|
||||
import { useSlots } from '@/src/hooks/prominent-api-hooks';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
|
|
@ -37,6 +40,47 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
|
|||
const defaultAddress = defaultAddressData?.data;
|
||||
const addresses = addressesData?.data || [];
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId);
|
||||
const { data: regions } = trpc.common.listRegions.useQuery();
|
||||
|
||||
// An address (selected or default) that belongs to another region than the
|
||||
// one we are browsing cannot be used for quick delivery without switching.
|
||||
const foreignAddress = useMemo(() => {
|
||||
const address = selectedAddressId
|
||||
? addresses.find((candidate) => candidate.id === selectedAddressId)
|
||||
: defaultAddress;
|
||||
if (!address || !selectedRegionId) return null;
|
||||
if (address.regionId == null || address.regionId === selectedRegionId) return null;
|
||||
return address;
|
||||
}, [addresses, defaultAddress, selectedAddressId, selectedRegionId]);
|
||||
|
||||
const handleForeignAddressSwitch = () => {
|
||||
if (!foreignAddress) return;
|
||||
const targetRegion = (regions ?? []).find((region) => region.id === foreignAddress.regionId);
|
||||
if (!targetRegion) {
|
||||
Alert.alert('Unavailable region', 'This address belongs to a region that is not currently available.');
|
||||
return;
|
||||
}
|
||||
Alert.alert(
|
||||
'Switch region?',
|
||||
`This address is in ${targetRegion.name}. Switching will clear your entire cart and take you home.`,
|
||||
[
|
||||
{ text: 'Cancel', style: 'cancel' },
|
||||
{
|
||||
text: 'Switch & clear cart',
|
||||
style: 'destructive',
|
||||
onPress: () => {
|
||||
void (async () => {
|
||||
await confirmRegionSwitch(targetRegion, queryClient);
|
||||
router.replace('/(drawer)/(tabs)/home');
|
||||
})();
|
||||
},
|
||||
},
|
||||
]
|
||||
);
|
||||
};
|
||||
|
||||
// Format time range helper
|
||||
const formatTimeRange = (deliveryTime: string | Date) => {
|
||||
const time = dayjs(deliveryTime);
|
||||
|
|
@ -162,6 +206,19 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
|
|||
<MaterialIcons name="keyboard-arrow-down" size={18} color={theme.colors.brand500} />
|
||||
</MyTouchableOpacity>
|
||||
*/}
|
||||
|
||||
{foreignAddress && (
|
||||
<MyTouchableOpacity
|
||||
onPress={handleForeignAddressSwitch}
|
||||
activeOpacity={0.8}
|
||||
style={tw`mt-1 p-2.5 bg-amber-50 border border-amber-200 rounded-lg flex-row items-center`}
|
||||
>
|
||||
<MaterialIcons name="warning-amber" size={16} color="#D97706" />
|
||||
<MyText style={tw`text-amber-800 text-xs ml-2 flex-1`}>
|
||||
Selected address is in another region. Tap to switch region (clears cart).
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ import { trpc } from "@/src/trpc-client";
|
|||
import { useCentralProductStore } from '@/src/store/centralProductStore';
|
||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
||||
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks';
|
||||
import { useGetEssentialConsts } from '@/src/hooks/prominent-api-hooks';
|
||||
import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
|
||||
import type { FlashDeliveryProps } from '@packages/shared';
|
||||
|
||||
const formatDeliverySlot = (deliveryTime: string): string => {
|
||||
|
|
@ -225,7 +225,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
undefined,
|
||||
{ enabled: isAuthenticated }
|
||||
);
|
||||
const { data: constsData } = useGetEssentialConsts();
|
||||
const constsData = useRegionalConsts();
|
||||
const products = useCentralProductStore((state) => state.products);
|
||||
const productsById = useCentralProductStore((state) => state.productsById);
|
||||
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import { trpc } from '@/src/trpc-client';
|
|||
import { useCentralProductStore } from '@/src/store/centralProductStore';
|
||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
||||
import { useGetCart } from '@/hooks/cart-query-hooks';
|
||||
import { useGetEssentialConsts } from '@/src/hooks/prominent-api-hooks';
|
||||
import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
|
||||
import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent';
|
||||
import CheckoutAddressSelector from '@/components/CheckoutAddressSelector';
|
||||
import { useAddressStore } from '@/src/store/addressStore';
|
||||
|
|
@ -38,7 +38,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
|||
{ enabled: isAuthenticated }
|
||||
);
|
||||
const { data: slotsData, refetch: refetchSlots } = trpc.user.slots.getSlots.useQuery();
|
||||
const { data: constsData } = useGetEssentialConsts();
|
||||
const constsData = useRegionalConsts();
|
||||
const products = useCentralProductStore((state) => state.products);
|
||||
const productsById = useCentralProductStore((state) => state.productsById);
|
||||
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ import {
|
|||
useAddToCart,
|
||||
type CartType,
|
||||
} from "@/hooks/cart-query-hooks";
|
||||
import { useGetEssentialConsts, useSlots } from "@/src/hooks/prominent-api-hooks"
|
||||
import { useRegionalConsts, useSlots } from "@/src/hooks/prominent-api-hooks"
|
||||
import { useProductSlotIdentifier } from "@/hooks/useProductSlotIdentifier";
|
||||
import { useCentralProductStore } from "@/src/store/centralProductStore";
|
||||
import dayjs from "dayjs";
|
||||
|
|
@ -87,7 +87,7 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
const isExpanded = controlledIsExpanded ?? localIsExpanded;
|
||||
const setIsExpanded = controlledSetIsExpanded ?? setLocalIsExpanded;
|
||||
const { data: cartData, refetch: refetchCart } = useGetCart({}, cartType);
|
||||
const { data: constsData } = useGetEssentialConsts();
|
||||
const constsData = useRegionalConsts();
|
||||
const { data: slotsData } = useSlots();
|
||||
const productsById = useCentralProductStore((state) => state.productsById);
|
||||
const { productSlotsMap } = useProductSlotIdentifier();
|
||||
|
|
|
|||
|
|
@ -4,21 +4,31 @@ import { useMutation } from '@tanstack/react-query';
|
|||
import { Formik } from 'formik';
|
||||
import * as Yup from 'yup';
|
||||
import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , LoadingDialog } from 'common-ui';
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||
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';
|
||||
|
||||
const AddressForm: React.FC<AddressFormProps> = ({ onSuccess, initialValues, isEdit = false }) => {
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
const [showGoogleMapsField, setShowGoogleMapsField] = useState(!!initialValues?.googleMapsUrl);
|
||||
const [showRegionOptions, setShowRegionOptions] = useState(false);
|
||||
const [currentLocation, setCurrentLocation] = useState<{ latitude: number; longitude: number } | null>(
|
||||
initialValues?.latitude && initialValues?.longitude
|
||||
? { latitude: initialValues.latitude, longitude: initialValues.longitude }
|
||||
: null
|
||||
);
|
||||
|
||||
const browsingRegionId = useRegionStore((state) => state.selectedRegionId);
|
||||
const { data: regions } = trpc.common.listRegions.useQuery();
|
||||
|
||||
// Edits keep the stored region unless the user explicitly changes it; new
|
||||
// addresses default to the region the user is currently browsing.
|
||||
const initialRegionId = initialValues?.regionId ?? browsingRegionId ?? undefined;
|
||||
|
||||
const createAddressMutation = trpc.user.address.createAddress.useMutation({
|
||||
onSuccess: (data) => {
|
||||
setIsSubmitting(false);
|
||||
|
|
@ -45,6 +55,9 @@ const AddressForm: React.FC<AddressFormProps> = ({ onSuccess, initialValues, isE
|
|||
});
|
||||
|
||||
const validationSchema = Yup.object({
|
||||
regionId: Yup.number()
|
||||
.typeError('Region is required')
|
||||
.required('Region is required'),
|
||||
name: Yup.string().required('Name is required'),
|
||||
phone: Yup.string().required('Phone is required').matches(/^\d{10}$/, 'Phone must be 10 digits'),
|
||||
addressLine1: Yup.string().required('Address Line 1 is required'),
|
||||
|
|
@ -80,7 +93,8 @@ const AddressForm: React.FC<AddressFormProps> = ({ onSuccess, initialValues, isE
|
|||
</View>
|
||||
)}
|
||||
<Formik
|
||||
initialValues={initialValues || {
|
||||
initialValues={initialValues ? { ...initialValues, regionId: initialRegionId } : {
|
||||
regionId: initialRegionId,
|
||||
name: '',
|
||||
phone: '',
|
||||
addressLine1: '',
|
||||
|
|
@ -95,10 +109,15 @@ const AddressForm: React.FC<AddressFormProps> = ({ onSuccess, initialValues, isE
|
|||
}}
|
||||
validationSchema={validationSchema}
|
||||
onSubmit={(values) => {
|
||||
if (!values.regionId) {
|
||||
setSubmitError('Please select a delivery region');
|
||||
return;
|
||||
}
|
||||
setIsSubmitting(true);
|
||||
setSubmitError(null);
|
||||
const payload = {
|
||||
...values,
|
||||
regionId: values.regionId,
|
||||
latitude: currentLocation?.latitude,
|
||||
longitude: currentLocation?.longitude,
|
||||
googleMapsUrl: values.googleMapsUrl || undefined,
|
||||
|
|
@ -112,6 +131,51 @@ const AddressForm: React.FC<AddressFormProps> = ({ onSuccess, initialValues, isE
|
|||
>
|
||||
{({ handleChange, handleBlur, handleSubmit, values, errors, touched, setFieldValue }) => (
|
||||
<View style={tw`flex-col gap-2`}>
|
||||
{/* Delivery Region (required) */}
|
||||
<View style={tw`mb-1`}>
|
||||
<MyText style={tw`text-gray-500 text-xs mb-1`}>Delivery Region *</MyText>
|
||||
<MyTouchableOpacity
|
||||
testID="address-region"
|
||||
onPress={() => setShowRegionOptions((prev) => !prev)}
|
||||
style={tw`border border-gray-200 rounded-lg p-3 flex-row items-center justify-between bg-gray-50`}
|
||||
>
|
||||
<MyText style={tw`${values.regionId ? 'text-gray-900' : 'text-gray-400'}`}>
|
||||
{(regions ?? []).find((region) => region.id === values.regionId)?.name || 'Select region'}
|
||||
</MyText>
|
||||
<MaterialIcons
|
||||
name={showRegionOptions ? 'keyboard-arrow-up' : 'keyboard-arrow-down'}
|
||||
size={20}
|
||||
color="#9CA3AF"
|
||||
/>
|
||||
</MyTouchableOpacity>
|
||||
{showRegionOptions && (
|
||||
<View style={tw`border border-gray-200 rounded-lg mt-1 bg-white overflow-hidden`}>
|
||||
{(regions ?? []).map((region) => (
|
||||
<MyTouchableOpacity
|
||||
key={region.id}
|
||||
testID={`address-region-option-${region.id}`}
|
||||
onPress={() => {
|
||||
setFieldValue('regionId', region.id);
|
||||
setShowRegionOptions(false);
|
||||
}}
|
||||
style={tw`p-3 border-b border-gray-50 flex-row items-center justify-between`}
|
||||
>
|
||||
<MyText style={tw`text-gray-800`}>{region.name}</MyText>
|
||||
{values.regionId === region.id && (
|
||||
<MaterialIcons name="check" size={18} color="#3B82F6" />
|
||||
)}
|
||||
</MyTouchableOpacity>
|
||||
))}
|
||||
{(regions ?? []).length === 0 && (
|
||||
<MyText style={tw`p-3 text-gray-400 text-sm`}>No regions available</MyText>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
{touched.regionId && errors.regionId && (
|
||||
<MyText style={tw`text-red-500 text-sm mt-1`}>{errors.regionId}</MyText>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<MyTextInput
|
||||
testID="address-name"
|
||||
placeholder="Name"
|
||||
|
|
|
|||
70
apps/user-ui/src/components/RegionGate.tsx
Normal file
70
apps/user-ui/src/components/RegionGate.tsx
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
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
|
||||
159
apps/user-ui/src/components/RegionSelector.tsx
Normal file
159
apps/user-ui/src/components/RegionSelector.tsx
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
import React, { useState } from 'react'
|
||||
import { View, ScrollView, ActivityIndicator, Alert } from 'react-native'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { tw, MyText, MyTouchableOpacity, theme } from 'common-ui'
|
||||
import type { RegionSummary } from '@packages/shared'
|
||||
import { trpc } from '@/src/trpc-client'
|
||||
import { confirmRegionSwitch } from '@/src/lib/region-switch'
|
||||
|
||||
interface RegionSelectorProps {
|
||||
/**
|
||||
* 'gate' — first-run full-screen chooser, cannot be dismissed.
|
||||
* 'switch' — content for a caller-owned dialog; shows a cart-clear confirmation.
|
||||
*/
|
||||
mode?: 'gate' | 'switch'
|
||||
selectedRegionId?: number | null
|
||||
onComplete?: (region: RegionSummary) => void
|
||||
onCancel?: () => void
|
||||
}
|
||||
|
||||
const RegionSelector: React.FC<RegionSelectorProps> = ({
|
||||
mode = 'gate',
|
||||
selectedRegionId = null,
|
||||
onComplete,
|
||||
onCancel,
|
||||
}) => {
|
||||
const queryClient = useQueryClient()
|
||||
const [isSwitching, setIsSwitching] = useState(false)
|
||||
const { data: regions, isLoading, error, refetch } = trpc.common.listRegions.useQuery()
|
||||
|
||||
const applySwitch = async (region: RegionSummary) => {
|
||||
setIsSwitching(true)
|
||||
try {
|
||||
await confirmRegionSwitch(region, queryClient)
|
||||
onComplete?.(region)
|
||||
} finally {
|
||||
setIsSwitching(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePick = (region: RegionSummary) => {
|
||||
if (isSwitching) return
|
||||
|
||||
// First run: no cart exists yet, select directly.
|
||||
if (mode === 'gate') {
|
||||
void applySwitch(region)
|
||||
return
|
||||
}
|
||||
|
||||
if (region.id === selectedRegionId) {
|
||||
onCancel?.()
|
||||
return
|
||||
}
|
||||
|
||||
Alert.alert(
|
||||
'Switch region?',
|
||||
`Switching to ${region.name} will clear your entire cart (regular and 1-hour delivery). This cannot be undone.`,
|
||||
[
|
||||
{ text: 'Cancel', style: 'cancel', onPress: () => onCancel?.() },
|
||||
{
|
||||
text: 'Switch & clear cart',
|
||||
style: 'destructive',
|
||||
onPress: () => {
|
||||
void applySwitch(region)
|
||||
},
|
||||
},
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
const header = mode === 'gate' ? (
|
||||
<View style={tw`px-6 pt-12 pb-6`}>
|
||||
<MyText style={tw`text-3xl font-extrabold text-gray-900`}>Choose your region</MyText>
|
||||
<MyText style={tw`text-gray-500 mt-2`}>
|
||||
We deliver to one region at a time. Pick where you want your groceries delivered.
|
||||
</MyText>
|
||||
</View>
|
||||
) : (
|
||||
<View style={tw`px-5 pt-2 pb-4`}>
|
||||
<MyText style={tw`text-xl font-bold text-gray-900`}>Delivery Region</MyText>
|
||||
<MyText style={tw`text-gray-500 text-sm mt-1`}>
|
||||
Switching region clears your current cart.
|
||||
</MyText>
|
||||
</View>
|
||||
)
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<View style={tw`flex-1 justify-center items-center py-16`}>
|
||||
<ActivityIndicator size="large" color={theme.colors.brand500} />
|
||||
<MyText style={tw`text-gray-500 mt-4`}>Loading regions...</MyText>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<View style={tw`flex-1 justify-center items-center py-16 px-6`}>
|
||||
<MaterialIcons name="public-off" size={48} color="#EF4444" />
|
||||
<MyText style={tw`text-gray-900 font-bold text-lg mt-3`}>Unable to load regions</MyText>
|
||||
<MyText style={tw`text-gray-500 text-center mt-2 mb-5`}>
|
||||
Please check your connection and try again.
|
||||
</MyText>
|
||||
<MyTouchableOpacity
|
||||
onPress={() => refetch()}
|
||||
style={tw`bg-brand500 px-6 py-3 rounded-xl`}
|
||||
>
|
||||
<MyText style={tw`text-white font-bold`}>Retry</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={tw`flex-1`}>
|
||||
{header}
|
||||
<ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={tw`px-5 pb-10`}>
|
||||
{(regions ?? []).map((region) => {
|
||||
const isSelected = region.id === selectedRegionId
|
||||
return (
|
||||
<MyTouchableOpacity
|
||||
key={region.id}
|
||||
testID={`region-option-${region.id}`}
|
||||
activeOpacity={0.85}
|
||||
disabled={isSwitching}
|
||||
onPress={() => handlePick(region)}
|
||||
style={tw`flex-row items-center bg-white border ${isSelected ? 'border-brand500 bg-blue-50' : 'border-gray-100'} rounded-2xl p-4 mb-3 shadow-sm`}
|
||||
>
|
||||
<View style={tw`w-11 h-11 rounded-full ${isSelected ? 'bg-brand500' : 'bg-gray-100'} items-center justify-center mr-3`}>
|
||||
<MaterialIcons
|
||||
name="location-on"
|
||||
size={22}
|
||||
color={isSelected ? 'white' : theme.colors.brand500}
|
||||
/>
|
||||
</View>
|
||||
<View style={tw`flex-1`}>
|
||||
<MyText style={tw`text-base font-bold text-gray-900`}>{region.name}</MyText>
|
||||
{!!region.description && (
|
||||
<MyText style={tw`text-gray-500 text-xs mt-0.5`} numberOfLines={2}>
|
||||
{region.description}
|
||||
</MyText>
|
||||
)}
|
||||
</View>
|
||||
{isSelected && (
|
||||
<MaterialIcons name="check-circle" size={22} color={theme.colors.brand500} />
|
||||
)}
|
||||
</MyTouchableOpacity>
|
||||
)
|
||||
})}
|
||||
|
||||
{isSwitching && (
|
||||
<MyText style={tw`text-center text-gray-400 text-xs mt-2`}>Switching region...</MyText>
|
||||
)}
|
||||
</ScrollView>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
export default RegionSelector
|
||||
|
|
@ -2,25 +2,39 @@ 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 } from '@packages/shared'
|
||||
import type { ProductPriceFlags, EffectiveRegionSettings } 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'
|
||||
|
||||
// The only persisted payload: the small essential-consts config object
|
||||
// (assetsDomain, cache versions, etc.). The big data payloads (products,
|
||||
// stores, slots, availability, banners) are fetched fresh each session and
|
||||
// kept in memory by react-query — they are NOT written to storage.
|
||||
const ESSENTIAL_CONSTS_KEY = 'essential_consts'
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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}`
|
||||
|
||||
export const useGetEssentialConsts = () => {
|
||||
const [initialData, setInitialData] = useState<EssentialConstsApiType | undefined>(undefined)
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const [initialData, setInitialData] = useState<DiscoveryData | undefined>(undefined)
|
||||
const [isReady, setIsReady] = useState(false)
|
||||
|
||||
// Load the last persisted response so config is available immediately.
|
||||
// Load the last persisted response for THIS region so config is available immediately.
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
StorageServiceCasual.getItem(ESSENTIAL_CONSTS_KEY).then((raw) => {
|
||||
setIsReady(false)
|
||||
setInitialData(undefined)
|
||||
if (selectedRegionId == null) {
|
||||
setIsReady(true)
|
||||
return
|
||||
}
|
||||
StorageServiceCasual.getItem(essentialConstsKey(selectedRegionId)).then((raw) => {
|
||||
if (cancelled) return
|
||||
if (raw) {
|
||||
try {
|
||||
|
|
@ -32,24 +46,54 @@ export const useGetEssentialConsts = () => {
|
|||
setIsReady(true)
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [])
|
||||
}, [selectedRegionId])
|
||||
|
||||
const query = trpc.common.essentialConsts.useQuery(undefined, {
|
||||
// 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, {
|
||||
refetchInterval: 60000,
|
||||
enabled: isReady,
|
||||
placeholderData: initialData,
|
||||
enabled: isReady && selectedRegionId != null,
|
||||
placeholderData: initialData as any,
|
||||
})
|
||||
|
||||
// Persist the latest response.
|
||||
// Persist the latest response under this region's key.
|
||||
useEffect(() => {
|
||||
if (query.data) {
|
||||
StorageServiceCasual.setItem(ESSENTIAL_CONSTS_KEY, JSON.stringify(query.data))
|
||||
if (query.data && selectedRegionId != null) {
|
||||
StorageServiceCasual.setItem(essentialConstsKey(selectedRegionId), JSON.stringify(query.data))
|
||||
}
|
||||
}, [query.data])
|
||||
}, [query.data, selectedRegionId])
|
||||
|
||||
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() {
|
||||
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])
|
||||
}
|
||||
|
||||
type ProductsResponse = AllProductsApiType;
|
||||
type StoresResponse = StoresApiType;
|
||||
type SlotsResponse = SlotsApiType;
|
||||
|
|
@ -63,44 +107,53 @@ export type MergedProduct = BaseProduct & ProductPriceFlags & {
|
|||
isComboOnly?: boolean
|
||||
}
|
||||
|
||||
function useDiscoveryRegionId(essentialConsts: unknown): number | null {
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const effectiveRegionId = (essentialConsts as DiscoveryData | undefined)?.effectiveSettings?.regionId
|
||||
return effectiveRegionId ?? selectedRegionId
|
||||
}
|
||||
|
||||
function useCacheUrl(filename: string): string | null {
|
||||
const { data: essentialConsts } = useGetEssentialConsts()
|
||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||
|
||||
const assetsDomain = essentialConsts?.assetsDomain
|
||||
const apiCacheKey = essentialConsts?.apiCacheKey
|
||||
const cacheVersion = essentialConsts?.cacheVersion
|
||||
|
||||
if (!assetsDomain || !apiCacheKey || cacheVersion === undefined || cacheVersion === null) {
|
||||
if (!assetsDomain || !apiCacheKey || cacheVersion === undefined || cacheVersion === null || regionId == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
return `${assetsDomain}${apiCacheKey}/v-${cacheVersion}/${filename}`
|
||||
return `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${cacheVersion}/${filename}`
|
||||
}
|
||||
|
||||
function useAvailabilityCacheUrl(): string | null {
|
||||
const { data: essentialConsts } = useGetEssentialConsts()
|
||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||
|
||||
const assetsDomain = essentialConsts?.assetsDomain
|
||||
const availabilityVersionNum = essentialConsts?.availabilityVersionNum
|
||||
|
||||
if (!assetsDomain || availabilityVersionNum === undefined || availabilityVersionNum === null) {
|
||||
if (!assetsDomain || availabilityVersionNum === undefined || availabilityVersionNum === null || regionId == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
return `${assetsDomain}av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}`
|
||||
return `${assetsDomain}regions/${regionId}/av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}`
|
||||
}
|
||||
|
||||
function useSlotsCacheUrl(): string | null {
|
||||
const { data: essentialConsts } = useGetEssentialConsts()
|
||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||
|
||||
const assetsDomain = essentialConsts?.assetsDomain
|
||||
const slotsVersionNum = essentialConsts?.slotsVersionNum
|
||||
|
||||
if (!assetsDomain || slotsVersionNum === undefined || slotsVersionNum === null) {
|
||||
if (!assetsDomain || slotsVersionNum === undefined || slotsVersionNum === null || regionId == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
return `${assetsDomain}slots/v-${slotsVersionNum}/${CACHE_FILENAMES.slots}`
|
||||
return `${assetsDomain}regions/${regionId}/slots/v-${slotsVersionNum}/${CACHE_FILENAMES.slots}`
|
||||
}
|
||||
|
||||
export function useAllProducts() {
|
||||
|
|
@ -215,13 +268,14 @@ export function useSlots() {
|
|||
|
||||
export function useStoreWithProducts(storeId: number) {
|
||||
const { data: essentialConsts } = useGetEssentialConsts()
|
||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||
|
||||
const assetsDomain = essentialConsts?.assetsDomain
|
||||
const apiCacheKey = essentialConsts?.apiCacheKey
|
||||
const cacheVersion = essentialConsts?.cacheVersion;
|
||||
|
||||
const cacheUrl = assetsDomain && apiCacheKey
|
||||
? `${assetsDomain}${apiCacheKey}/v-${cacheVersion}/stores/${storeId}.json`
|
||||
const cacheUrl = assetsDomain && apiCacheKey && regionId != null
|
||||
? `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${cacheVersion}/stores/${storeId}.json`
|
||||
: null
|
||||
const version = cacheUrl ?? ''
|
||||
|
||||
|
|
|
|||
60
apps/user-ui/src/lib/region-switch.ts
Normal file
60
apps/user-ui/src/lib/region-switch.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import type { QueryClient } from '@tanstack/react-query'
|
||||
import type { RegionSummary } from '@packages/shared'
|
||||
import { clearLocalCart } from '@/hooks/cart-query-hooks'
|
||||
import { useRegionStore } from '@/src/store/regionStore'
|
||||
import { useCartStore } from '@/src/store/cartStore'
|
||||
import { useFlashCartStore } from '@/src/store/flashCartStore'
|
||||
import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore'
|
||||
import { useAddressStore } from '@/src/store/addressStore'
|
||||
import { useCentralProductStore } from '@/src/store/centralProductStore'
|
||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
||||
import { useSlotStore } from '@/components/stores/slotStore'
|
||||
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
|
||||
|
||||
/**
|
||||
* The one and only way to change the browsing region.
|
||||
*
|
||||
* Manual switching (RegionSelector) and the checkout address flow both call
|
||||
* this so the reset behaviour can never drift. It clears every cart variant,
|
||||
* drops derived checkout selections, persists the new region and invalidates
|
||||
* region-scoped react-query caches.
|
||||
*
|
||||
* NOTE: callers must obtain a user confirmation before invoking this.
|
||||
*/
|
||||
export async function confirmRegionSwitch(
|
||||
region: RegionSummary,
|
||||
queryClient: QueryClient,
|
||||
): Promise<void> {
|
||||
// 1. Clear the persisted local carts (regular + flash).
|
||||
await Promise.all([clearLocalCart('regular'), clearLocalCart('flash')])
|
||||
|
||||
// 2. Drop in-memory checkout / quick-delivery selections.
|
||||
useQuickDeliveryStore.getState().setSelectedSlotId(null)
|
||||
useAddressStore.getState().setSelectedAddressId(null)
|
||||
useSlotStore.getState().setSlotId(undefined)
|
||||
useSlotStore.getState().setStoreId(undefined)
|
||||
useCartStore.getState().clearAddedToCartProduct()
|
||||
useFlashCartStore.getState().clearAddedFlashProduct()
|
||||
useFlashNavigationStore.getState().reset()
|
||||
|
||||
// 3. Drop cached regional catalog/slot snapshots so they cannot leak across.
|
||||
const productStore = useCentralProductStore.getState()
|
||||
productStore.setProducts([])
|
||||
productStore.setRefetchProducts(null)
|
||||
useCentralSlotStore.getState().setSlotsData([], [], [])
|
||||
|
||||
// Drop the old region's versioned catalog queries so no stale cross-region
|
||||
// products/prices/tags survive; the invalidate below refetches discovery +
|
||||
// catalog files for the new region.
|
||||
queryClient.removeQueries({ queryKey: ['all-products'] })
|
||||
queryClient.removeQueries({ queryKey: ['stores'] })
|
||||
queryClient.removeQueries({ queryKey: ['slots'] })
|
||||
queryClient.removeQueries({ queryKey: ['availability'] })
|
||||
queryClient.removeQueries({ queryKey: ['store-with-products'] })
|
||||
|
||||
// 4. Persist the new browsing region.
|
||||
useRegionStore.getState().setRegion(region)
|
||||
|
||||
// 5. Refetch everything now scoped to the new region.
|
||||
await queryClient.invalidateQueries()
|
||||
}
|
||||
51
apps/user-ui/src/store/regionStore.ts
Normal file
51
apps/user-ui/src/store/regionStore.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { create } from 'zustand'
|
||||
import { persist, createJSONStorage } from 'zustand/middleware'
|
||||
import { StorageServiceCasual } from 'common-ui'
|
||||
import type { RegionSummary } from '@packages/shared'
|
||||
|
||||
// Browsing region — the single region the user is currently shopping in.
|
||||
// Kept separate from account identity and persisted so the choice survives
|
||||
// app restarts. `regionGeneration` is a monotonic marker bumped on every
|
||||
// change so stale regional responses can be ignored.
|
||||
interface RegionStore {
|
||||
selectedRegionId: number | null
|
||||
selectedRegion: RegionSummary | null
|
||||
regionGeneration: number
|
||||
setRegion: (region: RegionSummary) => void
|
||||
clearRegion: () => void
|
||||
}
|
||||
|
||||
export const useRegionStore = create<RegionStore>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
selectedRegionId: null,
|
||||
selectedRegion: null,
|
||||
regionGeneration: 0,
|
||||
setRegion: (region) =>
|
||||
set((state) => ({
|
||||
selectedRegionId: region.id,
|
||||
selectedRegion: region,
|
||||
regionGeneration: state.regionGeneration + 1,
|
||||
})),
|
||||
clearRegion: () =>
|
||||
set((state) => ({
|
||||
selectedRegionId: null,
|
||||
selectedRegion: null,
|
||||
regionGeneration: state.regionGeneration + 1,
|
||||
})),
|
||||
}),
|
||||
{
|
||||
name: 'freshyo-region',
|
||||
version: 1,
|
||||
storage: createJSONStorage<RegionStore>(() => StorageServiceCasual),
|
||||
partialize: (state) => ({
|
||||
selectedRegionId: state.selectedRegionId,
|
||||
selectedRegion: state.selectedRegion,
|
||||
regionGeneration: state.regionGeneration,
|
||||
// Functions are dropped from the persisted payload.
|
||||
setRegion: state.setRegion,
|
||||
clearRegion: state.clearRegion,
|
||||
}),
|
||||
}
|
||||
)
|
||||
)
|
||||
|
|
@ -1,11 +1,15 @@
|
|||
import React, { useState } from 'react'
|
||||
import { trpc } from '../lib/trpc-client'
|
||||
import { useRegionStore } from '../lib/stores/region-store'
|
||||
import { p, pInput as PInput, MyButton, div } from 'web-components'
|
||||
import { MapPin, X, Plus } from 'lucide-react'
|
||||
import * as Yup from 'yup'
|
||||
import type { AddressFormProps } from '@packages/shared'
|
||||
|
||||
const validationSchema = Yup.object({
|
||||
regionId: Yup.number()
|
||||
.typeError('Region is required')
|
||||
.required('Region is required'),
|
||||
name: Yup.string().required('Name is required'),
|
||||
phone: Yup.string().required('Phone is required').matches(/^\d{10}$/, 'Phone must be 10 digits'),
|
||||
addressLine1: Yup.string().required('Address Line 1 is required'),
|
||||
|
|
@ -26,16 +30,25 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false }: Addres
|
|||
: null
|
||||
)
|
||||
|
||||
const [values, setValues] = useState({
|
||||
name: initialValues?.name || '',
|
||||
phone: initialValues?.phone || '',
|
||||
addressLine1: initialValues?.addressLine1 || '',
|
||||
addressLine2: initialValues?.addressLine2 || '',
|
||||
city: initialValues?.city || 'Mahabubnagar',
|
||||
state: initialValues?.state || 'Telangana',
|
||||
pincode: initialValues?.pincode || '509001',
|
||||
isDefault: initialValues?.isDefault || false,
|
||||
googleMapsUrl: initialValues?.googleMapsUrl || '',
|
||||
const browsingRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const { data: regions } = trpc.common.listRegions.useQuery()
|
||||
|
||||
const [values, setValues] = useState(() => {
|
||||
// Edits keep the stored region unless the user explicitly changes it; new
|
||||
// addresses default to the region the user is currently browsing.
|
||||
const initialRegionId = initialValues?.regionId ?? browsingRegionId ?? null
|
||||
return {
|
||||
regionId: initialRegionId as number | null,
|
||||
name: initialValues?.name || '',
|
||||
phone: initialValues?.phone || '',
|
||||
addressLine1: initialValues?.addressLine1 || '',
|
||||
addressLine2: initialValues?.addressLine2 || '',
|
||||
city: initialValues?.city || 'Mahabubnagar',
|
||||
state: initialValues?.state || 'Telangana',
|
||||
pincode: initialValues?.pincode || '509001',
|
||||
isDefault: initialValues?.isDefault || false,
|
||||
googleMapsUrl: initialValues?.googleMapsUrl || '',
|
||||
}
|
||||
})
|
||||
|
||||
const [errors, setErrors] = useState<Record<string, string>>({})
|
||||
|
|
@ -62,7 +75,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false }: Addres
|
|||
},
|
||||
})
|
||||
|
||||
const handleChange = (field: string, value: string | boolean) => {
|
||||
const handleChange = (field: string, value: string | boolean | number | null) => {
|
||||
setValues((prev) => ({ ...prev, [field]: value }))
|
||||
if (errors[field]) {
|
||||
setErrors((prev) => ({ ...prev, [field]: '' }))
|
||||
|
|
@ -72,11 +85,18 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false }: Addres
|
|||
const handleSubmit = async () => {
|
||||
try {
|
||||
await validationSchema.validate(values, { abortEarly: false })
|
||||
const regionId = values.regionId
|
||||
if (regionId == null) {
|
||||
setErrors((prev) => ({ ...prev, regionId: 'Please select a delivery region' }))
|
||||
setSubmitError('Please select a delivery region')
|
||||
return
|
||||
}
|
||||
setIsSubmitting(true)
|
||||
setSubmitError(null)
|
||||
|
||||
const payload = {
|
||||
...values,
|
||||
regionId,
|
||||
latitude: currentLocation?.latitude,
|
||||
longitude: currentLocation?.longitude,
|
||||
googleMapsUrl: values.googleMapsUrl || undefined,
|
||||
|
|
@ -122,6 +142,28 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false }: Addres
|
|||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<p className="mb-1 text-xs text-gray-500">Delivery Region *</p>
|
||||
<select
|
||||
data-testid="address-region"
|
||||
value={values.regionId ?? ''}
|
||||
onChange={(e) =>
|
||||
handleChange('regionId', e.target.value ? Number(e.target.value) : null)
|
||||
}
|
||||
className={`w-full rounded-lg border bg-gray-50 p-3 text-base outline-none ${
|
||||
errors.regionId ? 'border-red-500' : 'border-gray-200'
|
||||
}`}
|
||||
>
|
||||
<option value="">Select region</option>
|
||||
{(regions ?? []).map((region) => (
|
||||
<option key={region.id} value={region.id}>
|
||||
{region.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{errors.regionId && <p className="mt-1 text-sm text-red-500">{errors.regionId}</p>}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<PInput
|
||||
placeholder="Name"
|
||||
|
|
|
|||
|
|
@ -1,9 +1,14 @@
|
|||
import React from 'react'
|
||||
import React, { useState } from 'react'
|
||||
import { useCheckoutAddress } from '../hooks/checkout-hooks'
|
||||
import { trpc } from '../lib/trpc-client'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { p, div } from 'web-components'
|
||||
import { MapPin, Home, Briefcase, Check, Plus, Edit2, Trash2 } from 'lucide-react'
|
||||
import { MapPin, Home, Briefcase, Check, Plus, Edit2, Trash2, MapPinned } from 'lucide-react'
|
||||
import type { RegionSummary } from '@packages/shared'
|
||||
import { useRegionStore } from '../lib/stores/region-store'
|
||||
import { confirmRegionSwitch } from '../lib/region-switch'
|
||||
import { Dialog } from './Dialog'
|
||||
|
||||
interface AddressSelectorProps {
|
||||
onAddressSelect?: (addressId: number) => void
|
||||
|
|
@ -12,6 +17,7 @@ interface AddressSelectorProps {
|
|||
}
|
||||
|
||||
export function CheckoutAddressSelector({ onAddressSelect, onAddAddress, onEditAddress }: AddressSelectorProps) {
|
||||
const navigate = useNavigate()
|
||||
const {
|
||||
sortedAddresses,
|
||||
selectedAddressId,
|
||||
|
|
@ -19,12 +25,47 @@ export function CheckoutAddressSelector({ onAddressSelect, onAddAddress, onEditA
|
|||
} = useCheckoutAddress({ onAddressSelect })
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const { data: regions } = trpc.common.listRegions.useQuery()
|
||||
const [pendingRegion, setPendingRegion] = useState<RegionSummary | null>(null)
|
||||
const [isSwitching, setIsSwitching] = useState(false)
|
||||
|
||||
const deleteMutation = trpc.user.address.deleteAddress.useMutation({
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['user.address.getUserAddresses'] })
|
||||
},
|
||||
})
|
||||
|
||||
const regionNameById = new Map((regions ?? []).map((region) => [region.id, region.name]))
|
||||
|
||||
// Selecting an address from another region requires an explicit confirmation
|
||||
// because it clears the cart and changes the browsing region.
|
||||
const handleAddressPress = (address: any) => {
|
||||
if (selectedRegionId && address.regionId && address.regionId !== selectedRegionId) {
|
||||
const targetRegion = (regions ?? []).find((region) => region.id === address.regionId)
|
||||
if (!targetRegion) {
|
||||
alert('This address belongs to a region that is not currently available.')
|
||||
return
|
||||
}
|
||||
setPendingRegion(targetRegion)
|
||||
return
|
||||
}
|
||||
|
||||
handleAddressSelect(address.id)
|
||||
}
|
||||
|
||||
const handleConfirmSwitch = async () => {
|
||||
if (!pendingRegion) return
|
||||
setIsSwitching(true)
|
||||
try {
|
||||
await confirmRegionSwitch(pendingRegion, queryClient)
|
||||
setPendingRegion(null)
|
||||
navigate({ to: '/home' })
|
||||
} finally {
|
||||
setIsSwitching(false)
|
||||
}
|
||||
}
|
||||
|
||||
const getAddressIcon = (name: string) => {
|
||||
const lower = name.toLowerCase()
|
||||
if (lower.includes('home')) return <Home className="h-5 w-5" />
|
||||
|
|
@ -72,7 +113,7 @@ export function CheckoutAddressSelector({ onAddressSelect, onAddAddress, onEditA
|
|||
{sortedAddresses.map((address: any) => (
|
||||
<div
|
||||
key={address.id}
|
||||
onClick={() => handleAddressSelect(address.id)}
|
||||
onClick={() => handleAddressPress(address)}
|
||||
className={`relative cursor-pointer rounded-xl border-2 p-4 transition-all ${
|
||||
selectedAddressId === address.id
|
||||
? 'border-brand-500 bg-blue-50'
|
||||
|
|
@ -89,7 +130,7 @@ export function CheckoutAddressSelector({ onAddressSelect, onAddAddress, onEditA
|
|||
{getAddressIcon(address.name)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<div className="mb-1 flex flex-wrap items-center gap-2">
|
||||
<p className={`font-bold ${selectedAddressId === address.id ? 'text-brand-600' : 'text-gray-900'}`}>
|
||||
{address.name}
|
||||
</p>
|
||||
|
|
@ -98,6 +139,12 @@ export function CheckoutAddressSelector({ onAddressSelect, onAddAddress, onEditA
|
|||
Default
|
||||
</span>
|
||||
)}
|
||||
{!!address.regionId && regionNameById.get(address.regionId) && (
|
||||
<span className="flex items-center gap-1 rounded bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-600">
|
||||
<MapPinned className="h-3 w-3" />
|
||||
{regionNameById.get(address.regionId)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm leading-relaxed text-gray-600">
|
||||
{address.addressLine1}
|
||||
|
|
@ -145,6 +192,37 @@ export function CheckoutAddressSelector({ onAddressSelect, onAddAddress, onEditA
|
|||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
open={pendingRegion !== null}
|
||||
onClose={() => {
|
||||
if (!isSwitching) setPendingRegion(null)
|
||||
}}
|
||||
title="Switch region?"
|
||||
>
|
||||
<div className="p-6">
|
||||
<p className="text-sm leading-relaxed text-gray-600">
|
||||
This address is in {pendingRegion?.name}. Switching will clear your entire cart and
|
||||
take you home.
|
||||
</p>
|
||||
<div className="mt-6 flex gap-2">
|
||||
<button
|
||||
onClick={() => setPendingRegion(null)}
|
||||
disabled={isSwitching}
|
||||
className="flex-1 rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm font-bold text-gray-700"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={() => void handleConfirmSwitch()}
|
||||
disabled={isSwitching}
|
||||
className="flex-1 rounded-xl bg-red-600 px-4 py-3 text-sm font-bold text-white disabled:opacity-50"
|
||||
>
|
||||
{isSwitching ? 'Switching...' : 'Switch & clear cart'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import type { FlashDeliveryProps } from '@packages/shared'
|
|||
import { useNavigate, useLocation } from '@tanstack/react-router'
|
||||
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks'
|
||||
import { useAllProducts } from '../hooks/prominent-api-hooks'
|
||||
import { useGetEssentialConsts } from '../hooks/prominent-api-hooks'
|
||||
import { useRegionalConsts } from '../hooks/prominent-api-hooks'
|
||||
import { MiniQuantifier } from 'web-components'
|
||||
import { ShoppingCart, ChevronRight, Clock, X, Package } from 'lucide-react'
|
||||
import dayjs from 'dayjs'
|
||||
|
|
@ -34,7 +34,7 @@ export function FloatingCartBar({ isFlashDelivery = false }: FlashDeliveryProps)
|
|||
const cartType = isFlashDelivery ? 'flash' : 'regular'
|
||||
|
||||
const { data: cartData } = useGetCart(cartType)
|
||||
const { data: constsData } = useGetEssentialConsts()
|
||||
const constsData = useRegionalConsts()
|
||||
const { data: productsData } = useAllProducts()
|
||||
const updateCartItem = useUpdateCartItem(cartType)
|
||||
const removeFromCart = useRemoveFromCart(cartType)
|
||||
|
|
|
|||
|
|
@ -3,8 +3,9 @@ import { trpc } from '../lib/trpc-client'
|
|||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { p, MyButton, pInput, div, LoadingDialog } from 'web-components'
|
||||
import { useAllProducts } from '../hooks/prominent-api-hooks'
|
||||
import { useGetEssentialConsts } from '../hooks/prominent-api-hooks'
|
||||
import { useRegionalConsts } from '../hooks/prominent-api-hooks'
|
||||
import { clearLocalCart } from '../hooks/cart-query-hooks'
|
||||
import { useRegionStore } from '../lib/stores/region-store'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { CreditCard, Banknote, Wallet, Tag, Info, Star, ShoppingBag, ArrowLeft } from 'lucide-react'
|
||||
|
||||
|
|
@ -28,7 +29,8 @@ export function PaymentAndOrderComponent({
|
|||
const [paymentMethod, setPaymentMethod] = useState<'online' | 'cod'>('cod')
|
||||
|
||||
const { data: productsData } = useAllProducts()
|
||||
const { data: constsData } = useGetEssentialConsts()
|
||||
const constsData = useRegionalConsts()
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
|
||||
const products = productsData?.products || []
|
||||
const productsById: Record<number, any> = {}
|
||||
|
|
@ -65,7 +67,13 @@ export function PaymentAndOrderComponent({
|
|||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
alert(error.message || 'Failed to place order')
|
||||
// The backend rejects a checkout whose address/SKUs belong to another
|
||||
// region; surface its message without leaking the raw error object.
|
||||
const message =
|
||||
typeof error?.message === 'string' && error.message.length > 0
|
||||
? error.message
|
||||
: 'Failed to place order'
|
||||
alert(message)
|
||||
},
|
||||
onSettled: () => {
|
||||
setIsLoading(false)
|
||||
|
|
@ -78,6 +86,11 @@ export function PaymentAndOrderComponent({
|
|||
return
|
||||
}
|
||||
|
||||
if (!selectedRegionId) {
|
||||
alert('Please select a delivery region before placing an order')
|
||||
return
|
||||
}
|
||||
|
||||
if (cartItems.length === 0) {
|
||||
alert('No items in cart')
|
||||
return
|
||||
|
|
@ -92,6 +105,7 @@ export function PaymentAndOrderComponent({
|
|||
slotId: isFlashDelivery ? null : item.slotId,
|
||||
})),
|
||||
addressId: selectedAddress,
|
||||
regionId: selectedRegionId,
|
||||
paymentMethod: paymentMethod,
|
||||
userNotes: userNotes,
|
||||
isFlashDelivery: isFlashDelivery,
|
||||
|
|
@ -280,6 +294,14 @@ export function PaymentAndOrderComponent({
|
|||
|
||||
{/* Bottom Action Bar */}
|
||||
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
||||
{!selectedRegionId && (
|
||||
<div className="mb-3 flex items-center gap-2 rounded-lg bg-amber-50 p-3">
|
||||
<Info className="h-4 w-4 text-amber-500" />
|
||||
<p className="font-medium text-sm text-amber-700">
|
||||
Please choose a delivery region to place order
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{!selectedAddress && (
|
||||
<div className="mb-3 flex items-center gap-2 rounded-lg bg-red-50 p-3">
|
||||
<Info className="h-4 w-4 text-red-500" />
|
||||
|
|
@ -293,9 +315,9 @@ export function PaymentAndOrderComponent({
|
|||
fullWidth
|
||||
textContent="Place Order"
|
||||
onClick={handlePlaceOrder}
|
||||
disabled={!selectedAddress || placeOrderMutation.isPending}
|
||||
disabled={!selectedAddress || !selectedRegionId || placeOrderMutation.isPending}
|
||||
className={`py-4 text-lg ${
|
||||
selectedAddress ? 'bg-brand-500 text-white' : 'bg-gray-300 text-gray-500'
|
||||
selectedAddress && selectedRegionId ? 'bg-brand-500 text-white' : 'bg-gray-300 text-gray-500'
|
||||
}`}
|
||||
/>
|
||||
</div>
|
||||
|
|
|
|||
78
apps/web-ui/src/components/RegionGate.tsx
Normal file
78
apps/web-ui/src/components/RegionGate.tsx
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import React, { useEffect, useState } from 'react'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { trpc } from '../lib/trpc-client'
|
||||
import { useRegionStore } from '../lib/stores/region-store'
|
||||
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.
|
||||
*
|
||||
* SSR note: until the persisted region hydrates on the client, children
|
||||
* render as-is so the server markup matches the first client render (no
|
||||
* hydration mismatch). The gate overlay only appears after hydration when
|
||||
* there is genuinely no valid region.
|
||||
*/
|
||||
export function RegionGate({ children }: { children: React.ReactNode }) {
|
||||
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 <>{children}</>
|
||||
}
|
||||
|
||||
if (selectedRegionId == null) {
|
||||
return (
|
||||
<>
|
||||
{children}
|
||||
<div className="fixed inset-0 z-[90] overflow-y-auto bg-white">
|
||||
<div className="mx-auto w-full max-w-2xl">
|
||||
<RegionSelector mode="gate" />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default RegionGate
|
||||
169
apps/web-ui/src/components/RegionSelector.tsx
Normal file
169
apps/web-ui/src/components/RegionSelector.tsx
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
import React, { useState } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { MapPin, Check, Loader2, Globe } from 'lucide-react'
|
||||
import type { RegionSummary } from '@packages/shared'
|
||||
import { trpc } from '../lib/trpc-client'
|
||||
import { confirmRegionSwitch } from '../lib/region-switch'
|
||||
import { useRegionStore } from '../lib/stores/region-store'
|
||||
|
||||
interface RegionSelectorProps {
|
||||
/**
|
||||
* 'gate' — first-run full-screen chooser, cannot be dismissed.
|
||||
* 'switch' — content for a caller-owned dialog; shows a cart-clear confirmation.
|
||||
*/
|
||||
mode?: 'gate' | 'switch'
|
||||
selectedRegionId?: number | null
|
||||
onComplete?: (region: RegionSummary) => void
|
||||
onCancel?: () => void
|
||||
}
|
||||
|
||||
export function RegionSelector({
|
||||
mode = 'gate',
|
||||
selectedRegionId: selectedRegionIdProp,
|
||||
onComplete,
|
||||
onCancel,
|
||||
}: RegionSelectorProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [isSwitching, setIsSwitching] = useState(false)
|
||||
const [pendingRegion, setPendingRegion] = useState<RegionSummary | null>(null)
|
||||
const storeRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const selectedRegionId = selectedRegionIdProp ?? storeRegionId
|
||||
const { data: regions, isLoading, error, refetch } = trpc.common.listRegions.useQuery()
|
||||
|
||||
const applySwitch = async (region: RegionSummary) => {
|
||||
setIsSwitching(true)
|
||||
try {
|
||||
await confirmRegionSwitch(region, queryClient)
|
||||
setPendingRegion(null)
|
||||
onComplete?.(region)
|
||||
} finally {
|
||||
setIsSwitching(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePick = (region: RegionSummary) => {
|
||||
if (isSwitching) return
|
||||
|
||||
// First run: no cart exists yet, select directly.
|
||||
if (mode === 'gate') {
|
||||
void applySwitch(region)
|
||||
return
|
||||
}
|
||||
|
||||
if (region.id === selectedRegionId) {
|
||||
onCancel?.()
|
||||
return
|
||||
}
|
||||
|
||||
// Manual switch: confirm first — the whole cart will be cleared.
|
||||
setPendingRegion(region)
|
||||
}
|
||||
|
||||
const header =
|
||||
mode === 'gate' ? (
|
||||
<div className="px-6 pb-6 pt-12">
|
||||
<p className="text-3xl font-extrabold text-gray-900">Choose your region</p>
|
||||
<p className="mt-2 text-gray-500">
|
||||
We deliver to one region at a time. Pick where you want your groceries delivered.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="px-5 pb-4 pt-2">
|
||||
<p className="text-xl font-bold text-gray-900">Delivery Region</p>
|
||||
<p className="mt-1 text-sm text-gray-500">Switching region clears your current cart.</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-16">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-brand-500" />
|
||||
<p className="mt-4 text-gray-500">Loading regions...</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center px-6 py-16">
|
||||
<Globe className="h-12 w-12 text-red-500" />
|
||||
<p className="mt-3 text-lg font-bold text-gray-900">Unable to load regions</p>
|
||||
<p className="mb-5 mt-2 text-center text-gray-500">Please check your connection and try again.</p>
|
||||
<button
|
||||
onClick={() => refetch()}
|
||||
className="rounded-xl bg-brand-500 px-6 py-3 font-bold text-white"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{header}
|
||||
<div className="px-5 pb-10">
|
||||
{(regions ?? []).map((region) => {
|
||||
const isSelected = region.id === selectedRegionId
|
||||
return (
|
||||
<button
|
||||
key={region.id}
|
||||
data-testid={`region-option-${region.id}`}
|
||||
disabled={isSwitching}
|
||||
onClick={() => handlePick(region)}
|
||||
className={`mb-3 flex w-full items-center rounded-2xl border bg-white p-4 text-left shadow-sm transition-colors ${
|
||||
isSelected ? 'border-brand-500 bg-blue-50' : 'border-gray-100 hover:border-gray-300'
|
||||
}`}
|
||||
>
|
||||
<div
|
||||
className={`mr-3 flex h-11 w-11 items-center justify-center rounded-full ${
|
||||
isSelected ? 'bg-brand-500' : 'bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
<MapPin className={`h-5 w-5 ${isSelected ? 'text-white' : 'text-brand-500'}`} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-base font-bold text-gray-900">{region.name}</p>
|
||||
{!!region.description && (
|
||||
<p className="mt-0.5 line-clamp-2 text-xs text-gray-500">{region.description}</p>
|
||||
)}
|
||||
</div>
|
||||
{isSelected && <Check className="h-5 w-5 shrink-0 text-brand-500" />}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
|
||||
{isSwitching && <p className="mt-2 text-center text-xs text-gray-400">Switching region...</p>}
|
||||
|
||||
{/* Inline cart-clear confirmation for manual switches. */}
|
||||
{mode === 'switch' && pendingRegion && (
|
||||
<div className="mt-2 rounded-2xl border border-amber-200 bg-amber-50 p-4">
|
||||
<p className="font-bold text-gray-900">Switch region?</p>
|
||||
<p className="mt-1 text-sm text-gray-600">
|
||||
Switching to {pendingRegion.name} will clear your entire cart (regular and 1-hour
|
||||
delivery). This cannot be undone.
|
||||
</p>
|
||||
<div className="mt-3 flex gap-2">
|
||||
<button
|
||||
onClick={() => setPendingRegion(null)}
|
||||
disabled={isSwitching}
|
||||
className="flex-1 rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm font-bold text-gray-700"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={() => void applySwitch(pendingRegion)}
|
||||
disabled={isSwitching}
|
||||
className="flex-1 rounded-xl bg-red-600 px-4 py-2.5 text-sm font-bold text-white disabled:opacity-50"
|
||||
>
|
||||
{isSwitching ? 'Switching...' : 'Switch & clear cart'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default RegionSelector
|
||||
|
|
@ -3,6 +3,7 @@ import { useQueryClient } from '@tanstack/react-query'
|
|||
import { trpc } from '#/lib/trpc-client'
|
||||
import { useAuth } from '#/lib/auth-context'
|
||||
import { useAddressStore } from '#/lib/stores'
|
||||
import { useRegionStore } from '#/lib/stores/region-store'
|
||||
|
||||
interface CheckoutAddressSelectorProps {
|
||||
onAddressSelect?: (addressId: number) => void
|
||||
|
|
@ -12,6 +13,7 @@ export function useCheckoutAddress({ onAddressSelect }: CheckoutAddressSelectorP
|
|||
const { isAuthenticated } = useAuth()
|
||||
const queryClient = useQueryClient()
|
||||
const { selectedAddressId, setSelectedAddressId } = useAddressStore()
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const [showAddAddress, setShowAddAddress] = useState(false)
|
||||
const [editingAddress, setEditingAddress] = useState<any>(null)
|
||||
|
||||
|
|
@ -38,11 +40,16 @@ export function useCheckoutAddress({ onAddressSelect }: CheckoutAddressSelectorP
|
|||
})
|
||||
})()
|
||||
|
||||
// Auto-select default address when addresses are loaded and none is selected
|
||||
// Auto-select default address when addresses are loaded and none is selected.
|
||||
// Never silently auto-select a region we are not browsing.
|
||||
useEffect(() => {
|
||||
if (sortedAddresses.length > 0 && selectedAddressId === null) {
|
||||
const defaultAddress = sortedAddresses.find((addr: any) => addr.isDefault)
|
||||
if (defaultAddress) {
|
||||
const isCurrentRegion =
|
||||
!selectedRegionId ||
|
||||
defaultAddress?.regionId == null ||
|
||||
defaultAddress.regionId === selectedRegionId
|
||||
if (defaultAddress && isCurrentRegion) {
|
||||
setSelectedAddressId(defaultAddress.id)
|
||||
onAddressSelect?.(defaultAddress.id)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,8 @@ import { useMemo, useEffect, useState } from 'react'
|
|||
import { useQuery } from '@tanstack/react-query'
|
||||
import axios from 'axios'
|
||||
import { trpc } from '../lib/trpc-client'
|
||||
import type { ProductPriceFlags } from '@packages/shared'
|
||||
import { useRegionStore } from '../lib/stores/region-store'
|
||||
import type { ProductPriceFlags, EffectiveRegionSettings } from '@packages/shared'
|
||||
import type {
|
||||
AllProductsApiType,
|
||||
AvailabilityApiType,
|
||||
|
|
@ -15,12 +16,53 @@ import type {
|
|||
import { CACHE_FILENAMES } from '@packages/shared'
|
||||
|
||||
export const useGetEssentialConsts = () => {
|
||||
const query = trpc.common.essentialConsts.useQuery(undefined, {
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
// FIXED CONTRACT: essentialConsts REQUIRES {regionId}. The input is cast so
|
||||
// this typechecks against the current backend (which takes no input and
|
||||
// ignores the extra field at runtime) and the future one. tRPC includes the
|
||||
// input in the query key, so switching regions refetches discovery. No
|
||||
// region selected -> the query stays disabled (the region gate covers this).
|
||||
const query = trpc.common.essentialConsts.useQuery({ regionId: selectedRegionId ?? 0 } as any, {
|
||||
refetchInterval: 60000,
|
||||
enabled: selectedRegionId != null,
|
||||
})
|
||||
return { ...query, refetch: query.refetch }
|
||||
}
|
||||
|
||||
// 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 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() {
|
||||
const { data } = useGetEssentialConsts()
|
||||
return 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])
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Persisted cache helpers — store fetched JSON keyed by its versioned URL.
|
||||
// Only refetch + repersist when the version (URL) changes.
|
||||
|
|
@ -95,8 +137,15 @@ type AvailabilityEntry = AvailabilityApiType['availability'][number]
|
|||
|
||||
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
|
||||
}
|
||||
|
||||
function useCacheUrl(filename: string): string | null {
|
||||
const { data: essentialConsts } = useGetEssentialConsts()
|
||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||
|
||||
const assetsDomain = essentialConsts?.assetsDomain
|
||||
const apiCacheKey = essentialConsts?.apiCacheKey
|
||||
|
|
@ -106,38 +155,41 @@ function useCacheUrl(filename: string): string | null {
|
|||
!assetsDomain ||
|
||||
!apiCacheKey ||
|
||||
cacheVersion === undefined ||
|
||||
cacheVersion === null
|
||||
cacheVersion === null ||
|
||||
regionId == null
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
return `${assetsDomain}${apiCacheKey}/v-${cacheVersion}/${filename}`
|
||||
return `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${cacheVersion}/${filename}`
|
||||
}
|
||||
|
||||
function useAvailabilityCacheUrl(): string | null {
|
||||
const { data: essentialConsts } = useGetEssentialConsts()
|
||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||
|
||||
const assetsDomain = essentialConsts?.assetsDomain
|
||||
const availabilityVersionNum = essentialConsts?.availabilityVersionNum
|
||||
|
||||
if (!assetsDomain || availabilityVersionNum === undefined || availabilityVersionNum === null) {
|
||||
if (!assetsDomain || availabilityVersionNum === undefined || availabilityVersionNum === null || regionId == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
return `${assetsDomain}av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}`
|
||||
return `${assetsDomain}regions/${regionId}/av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}`
|
||||
}
|
||||
|
||||
function useSlotsCacheUrl(): string | null {
|
||||
const { data: essentialConsts } = useGetEssentialConsts()
|
||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||
|
||||
const assetsDomain = essentialConsts?.assetsDomain
|
||||
const slotsVersionNum = essentialConsts?.slotsVersionNum
|
||||
|
||||
if (!assetsDomain || slotsVersionNum === undefined || slotsVersionNum === null) {
|
||||
if (!assetsDomain || slotsVersionNum === undefined || slotsVersionNum === null || regionId == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
return `${assetsDomain}slots/v-${slotsVersionNum}/${CACHE_FILENAMES.slots}`
|
||||
return `${assetsDomain}regions/${regionId}/slots/v-${slotsVersionNum}/${CACHE_FILENAMES.slots}`
|
||||
}
|
||||
|
||||
export function useAllProducts() {
|
||||
|
|
@ -285,14 +337,15 @@ export function useBanners() {
|
|||
|
||||
export function useStoreWithProducts(storeId: number) {
|
||||
const { data: essentialConsts } = useGetEssentialConsts()
|
||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||
|
||||
const assetsDomain = essentialConsts?.assetsDomain
|
||||
const apiCacheKey = essentialConsts?.apiCacheKey
|
||||
const cacheVersion = essentialConsts?.cacheVersion
|
||||
|
||||
const cacheUrl =
|
||||
assetsDomain && apiCacheKey
|
||||
? `${assetsDomain}${apiCacheKey}/v-${cacheVersion}/stores/${storeId}.json`
|
||||
assetsDomain && apiCacheKey && regionId != null
|
||||
? `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${cacheVersion}/stores/${storeId}.json`
|
||||
: null
|
||||
const version = cacheUrl ?? ''
|
||||
const { initialData, isReady } = usePersistedCache<StoreWithProductsResponse>(CACHE_STORAGE_KEYS.storeProducts(storeId), version)
|
||||
|
|
|
|||
64
apps/web-ui/src/lib/region-switch.ts
Normal file
64
apps/web-ui/src/lib/region-switch.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import type { QueryClient } from '@tanstack/react-query'
|
||||
import type { RegionSummary } from '@packages/shared'
|
||||
import { clearLocalCart } from '../hooks/cart-query-hooks'
|
||||
import { useRegionStore } from './stores/region-store'
|
||||
import { useCartStore } from './stores/cart-store'
|
||||
import { useFlashCartStore } from './stores/flash-cart-store'
|
||||
import { useQuickDeliveryStore } from './stores/quick-delivery-store'
|
||||
import { useAddressStore } from './stores/address-store'
|
||||
import { useCentralProductStore } from './stores/central-product-store'
|
||||
import { useCentralSlotStore } from './stores/central-slot-store'
|
||||
import { useSlotStore } from './stores/slot-store'
|
||||
import { useFlashNavigationStore } from './stores/flash-navigation-store'
|
||||
|
||||
/**
|
||||
* The one and only way to change the browsing region.
|
||||
*
|
||||
* Manual switching (RegionSelector) and the checkout address flow both call
|
||||
* this so the reset behaviour can never drift. It clears every cart variant,
|
||||
* drops derived checkout selections, persists the new region and invalidates
|
||||
* region-scoped react-query caches.
|
||||
*
|
||||
* NOTE: callers must obtain a user confirmation before invoking this.
|
||||
*/
|
||||
export async function confirmRegionSwitch(
|
||||
region: RegionSummary,
|
||||
queryClient: QueryClient
|
||||
): Promise<void> {
|
||||
// 1. Clear the persisted local carts (regular + flash).
|
||||
clearLocalCart('regular')
|
||||
clearLocalCart('flash')
|
||||
|
||||
// 2. Drop in-memory checkout / quick-delivery selections.
|
||||
useQuickDeliveryStore.getState().setSelectedSlotId(null)
|
||||
useAddressStore.getState().clearSelectedAddress()
|
||||
useSlotStore.getState().setSlotId(null)
|
||||
useSlotStore.getState().setStoreId(null)
|
||||
useCartStore.getState().clearAddedToCartProduct()
|
||||
useFlashCartStore.getState().setAddedFlashProduct(null)
|
||||
useFlashNavigationStore.getState().setShouldNavigateToCart(false)
|
||||
|
||||
// 3. Drop cached regional catalog/slot snapshots so they cannot leak across.
|
||||
const productStore = useCentralProductStore.getState()
|
||||
productStore.setProducts([])
|
||||
productStore.setRefetchProducts(null)
|
||||
const slotStore = useCentralSlotStore.getState()
|
||||
slotStore.setSlots([])
|
||||
slotStore.setProductSlotsMap({})
|
||||
|
||||
// Drop the old region's versioned catalog queries so no stale cross-region
|
||||
// products/prices/tags survive; the invalidate below refetches discovery +
|
||||
// catalog files for the new region.
|
||||
queryClient.removeQueries({ queryKey: ['all-products'] })
|
||||
queryClient.removeQueries({ queryKey: ['stores'] })
|
||||
queryClient.removeQueries({ queryKey: ['banners'] })
|
||||
queryClient.removeQueries({ queryKey: ['slots'] })
|
||||
queryClient.removeQueries({ queryKey: ['availability'] })
|
||||
queryClient.removeQueries({ queryKey: ['store-with-products'] })
|
||||
|
||||
// 4. Persist the new browsing region.
|
||||
useRegionStore.getState().setRegion(region)
|
||||
|
||||
// 5. Refetch everything now scoped to the new region.
|
||||
await queryClient.invalidateQueries()
|
||||
}
|
||||
77
apps/web-ui/src/lib/stores/region-store.ts
Normal file
77
apps/web-ui/src/lib/stores/region-store.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import { create } from 'zustand'
|
||||
import { persist, createJSONStorage } from 'zustand/middleware'
|
||||
import type { RegionSummary } from '@packages/shared'
|
||||
|
||||
// Browsing region — the single region the user is currently shopping in.
|
||||
// Kept separate from account identity and persisted so the choice survives
|
||||
// restarts. `regionGeneration` is a monotonic marker bumped on every change
|
||||
// so stale regional responses can be ignored.
|
||||
interface RegionStore {
|
||||
selectedRegionId: number | null
|
||||
selectedRegion: RegionSummary | null
|
||||
regionGeneration: number
|
||||
setRegion: (region: RegionSummary) => void
|
||||
clearRegion: () => void
|
||||
}
|
||||
|
||||
// localStorage is unavailable during SSR — guard every access so the module
|
||||
// can be imported (and the store created) on the server. Reads return null
|
||||
// there, so the server simply starts with no region selected.
|
||||
const webStorage = {
|
||||
getItem: (key: string): string | null => {
|
||||
try {
|
||||
return typeof localStorage === 'undefined' ? null : localStorage.getItem(key)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
setItem: (key: string, value: string): void => {
|
||||
try {
|
||||
if (typeof localStorage !== 'undefined') localStorage.setItem(key, value)
|
||||
} catch {
|
||||
// Quota or privacy mode — region simply won't persist.
|
||||
}
|
||||
},
|
||||
removeItem: (key: string): void => {
|
||||
try {
|
||||
if (typeof localStorage !== 'undefined') localStorage.removeItem(key)
|
||||
} catch {
|
||||
// Ignore.
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
export const useRegionStore = create<RegionStore>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
selectedRegionId: null,
|
||||
selectedRegion: null,
|
||||
regionGeneration: 0,
|
||||
setRegion: (region) =>
|
||||
set((state) => ({
|
||||
selectedRegionId: region.id,
|
||||
selectedRegion: region,
|
||||
regionGeneration: state.regionGeneration + 1,
|
||||
})),
|
||||
clearRegion: () =>
|
||||
set((state) => ({
|
||||
selectedRegionId: null,
|
||||
selectedRegion: null,
|
||||
regionGeneration: state.regionGeneration + 1,
|
||||
})),
|
||||
}),
|
||||
{
|
||||
name: 'freshyo-region',
|
||||
version: 1,
|
||||
storage: createJSONStorage<RegionStore>(() => webStorage),
|
||||
partialize: (state) => ({
|
||||
selectedRegionId: state.selectedRegionId,
|
||||
selectedRegion: state.selectedRegion,
|
||||
regionGeneration: state.regionGeneration,
|
||||
// Functions are dropped from the persisted payload.
|
||||
setRegion: state.setRegion,
|
||||
clearRegion: state.clearRegion,
|
||||
}),
|
||||
}
|
||||
)
|
||||
)
|
||||
|
|
@ -6,6 +6,7 @@ import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
|
|||
import { trpc, getTrpcClient } from '../lib/trpc-client'
|
||||
import { getQueryClient } from '../lib/query-client'
|
||||
import { AuthProvider } from '../lib/auth-context'
|
||||
import { RegionGate } from '../components/RegionGate'
|
||||
import appCss from '../styles.css?url'
|
||||
|
||||
const queryClient = getQueryClient()
|
||||
|
|
@ -39,7 +40,9 @@ function RootDocument({ children }: { children: React.ReactNode }) {
|
|||
<QueryClientProvider client={queryClient}>
|
||||
<trpc.Provider client={trpcClient} queryClient={queryClient}>
|
||||
<AuthProvider>
|
||||
<div id="app">{children}</div>
|
||||
<RegionGate>
|
||||
<div id="app">{children}</div>
|
||||
</RegionGate>
|
||||
<ReactQueryDevtools />
|
||||
</AuthProvider>
|
||||
</trpc.Provider>
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ import { useState } from 'react'
|
|||
import { useAuth } from '../lib/auth-context'
|
||||
import { useGetCart } from '../hooks/cart-query-hooks'
|
||||
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
||||
import { useRegionStore } from '../lib/stores/region-store'
|
||||
import { confirmRegionSwitch } from '../lib/region-switch'
|
||||
import { trpc } from '../lib/trpc-client'
|
||||
import { clearLocalCart } from '../hooks/cart-query-hooks'
|
||||
import { p, MyButton, LoadingDialog, AppContainer } from 'web-components'
|
||||
|
|
@ -21,6 +23,8 @@ function FlashCheckoutPage() {
|
|||
const { data: addresses } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
||||
enabled: isAuthenticated,
|
||||
})
|
||||
const { data: regions } = trpc.common.listRegions.useQuery()
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const [selectedAddressId, setSelectedAddressId] = useState<number | null>(null)
|
||||
|
||||
const placeOrderMutation = trpc.user.order.placeOrder.useMutation({
|
||||
|
|
@ -33,6 +37,13 @@ function FlashCheckoutPage() {
|
|||
search: { orderId: String(order?.id), totalAmount: String(total) },
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
const message =
|
||||
typeof error?.message === 'string' && error.message.length > 0
|
||||
? error.message
|
||||
: 'Failed to place order'
|
||||
alert(message)
|
||||
},
|
||||
onSettled: () => setIsLoading(false),
|
||||
})
|
||||
|
||||
|
|
@ -46,8 +57,38 @@ function FlashCheckoutPage() {
|
|||
}
|
||||
})
|
||||
|
||||
const handleAddressPress = (addr: any) => {
|
||||
// Cross-region addresses switch the browsing region (clearing the cart).
|
||||
if (selectedRegionId && addr.regionId && addr.regionId !== selectedRegionId) {
|
||||
const targetRegion = (regions ?? []).find((region) => region.id === addr.regionId)
|
||||
if (!targetRegion) {
|
||||
alert('This address belongs to a region that is not currently available.')
|
||||
return
|
||||
}
|
||||
const ok = window.confirm(
|
||||
`This address is in ${targetRegion.name}. Switching will clear your entire cart and take you home. Continue?`
|
||||
)
|
||||
if (!ok) return
|
||||
setIsLoading(true)
|
||||
void (async () => {
|
||||
try {
|
||||
await confirmRegionSwitch(targetRegion, queryClient)
|
||||
navigate({ to: '/home' })
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
})()
|
||||
return
|
||||
}
|
||||
setSelectedAddressId(addr.id)
|
||||
}
|
||||
|
||||
const handlePlaceOrder = () => {
|
||||
if (!selectedAddressId) return
|
||||
if (!selectedRegionId) {
|
||||
alert('Please select a delivery region before placing an order')
|
||||
return
|
||||
}
|
||||
setIsLoading(true)
|
||||
placeOrderMutation.mutate({
|
||||
selectedItems: cartItems.map((item) => ({
|
||||
|
|
@ -56,6 +97,7 @@ function FlashCheckoutPage() {
|
|||
slotId: null,
|
||||
})),
|
||||
addressId: selectedAddressId,
|
||||
regionId: selectedRegionId,
|
||||
paymentMethod: 'cod',
|
||||
isFlashDelivery: true,
|
||||
})
|
||||
|
|
@ -74,7 +116,7 @@ function FlashCheckoutPage() {
|
|||
{addresses?.data?.map((addr: any) => (
|
||||
<button
|
||||
key={addr.id}
|
||||
onClick={() => setSelectedAddressId(addr.id)}
|
||||
onClick={() => handleAddressPress(addr)}
|
||||
className={`mb-2 w-full rounded-xl border p-3 text-left ${
|
||||
selectedAddressId === addr.id
|
||||
? 'border-brand-500 bg-brand-50'
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ import { useState } from 'react'
|
|||
import { useAuth } from '../lib/auth-context'
|
||||
import { useGetCart } from '../hooks/cart-query-hooks'
|
||||
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
||||
import { useRegionStore } from '../lib/stores/region-store'
|
||||
import { confirmRegionSwitch } from '../lib/region-switch'
|
||||
import { trpc } from '../lib/trpc-client'
|
||||
import { clearLocalCart } from '../hooks/cart-query-hooks'
|
||||
import { p, MyButton, LoadingDialog, AppContainer, div } from 'web-components'
|
||||
|
|
@ -21,6 +23,8 @@ function CheckoutPage() {
|
|||
const { data: addresses } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
||||
enabled: isAuthenticated,
|
||||
})
|
||||
const { data: regions } = trpc.common.listRegions.useQuery()
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const [selectedAddressId, setSelectedAddressId] = useState<number | null>(null)
|
||||
|
||||
const placeOrderMutation = trpc.user.order.placeOrder.useMutation({
|
||||
|
|
@ -33,6 +37,13 @@ function CheckoutPage() {
|
|||
search: { orderId: String(order?.id), totalAmount: String(total) },
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
const message =
|
||||
typeof error?.message === 'string' && error.message.length > 0
|
||||
? error.message
|
||||
: 'Failed to place order'
|
||||
alert(message)
|
||||
},
|
||||
onSettled: () => setIsLoading(false),
|
||||
})
|
||||
|
||||
|
|
@ -46,8 +57,38 @@ function CheckoutPage() {
|
|||
}
|
||||
})
|
||||
|
||||
const handleAddressPress = (addr: any) => {
|
||||
// Cross-region addresses switch the browsing region (clearing the cart).
|
||||
if (selectedRegionId && addr.regionId && addr.regionId !== selectedRegionId) {
|
||||
const targetRegion = (regions ?? []).find((region) => region.id === addr.regionId)
|
||||
if (!targetRegion) {
|
||||
alert('This address belongs to a region that is not currently available.')
|
||||
return
|
||||
}
|
||||
const ok = window.confirm(
|
||||
`This address is in ${targetRegion.name}. Switching will clear your entire cart and take you home. Continue?`
|
||||
)
|
||||
if (!ok) return
|
||||
setIsLoading(true)
|
||||
void (async () => {
|
||||
try {
|
||||
await confirmRegionSwitch(targetRegion, queryClient)
|
||||
navigate({ to: '/home' })
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
})()
|
||||
return
|
||||
}
|
||||
setSelectedAddressId(addr.id)
|
||||
}
|
||||
|
||||
const handlePlaceOrder = () => {
|
||||
if (!selectedAddressId) return
|
||||
if (!selectedRegionId) {
|
||||
alert('Please select a delivery region before placing an order')
|
||||
return
|
||||
}
|
||||
setIsLoading(true)
|
||||
placeOrderMutation.mutate({
|
||||
selectedItems: cartItems.map((item) => ({
|
||||
|
|
@ -56,6 +97,7 @@ function CheckoutPage() {
|
|||
slotId: null,
|
||||
})),
|
||||
addressId: selectedAddressId,
|
||||
regionId: selectedRegionId,
|
||||
paymentMethod: 'cod',
|
||||
isFlashDelivery: false,
|
||||
})
|
||||
|
|
@ -75,7 +117,7 @@ function CheckoutPage() {
|
|||
{addresses?.data?.map((addr: any) => (
|
||||
<div
|
||||
key={addr.id}
|
||||
onClick={() => setSelectedAddressId(addr.id)}
|
||||
onClick={() => handleAddressPress(addr)}
|
||||
className={`mb-2 rounded-xl border p-3 ${
|
||||
selectedAddressId === addr.id
|
||||
? 'border-brand-500 bg-brand-50'
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ export const Route = createFileRoute('/me/addresses')({ component: AddressesPage
|
|||
// Address view — required core of the shared UserAddress + optional geo fields
|
||||
type Address = Pick<
|
||||
UserAddress,
|
||||
'id' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'pincode' | 'isDefault'
|
||||
'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'pincode' | 'isDefault'
|
||||
> & {
|
||||
latitude?: number | null
|
||||
longitude?: number | null
|
||||
|
|
@ -129,9 +129,14 @@ function AddressesPage() {
|
|||
const handleSetDefault = (id: number) => {
|
||||
const addressToUpdate = addresses.find((addr) => addr.id === id)
|
||||
if (!addressToUpdate) return
|
||||
if (addressToUpdate.regionId == null) {
|
||||
alert('This address has no region. Please edit it and choose a region first.')
|
||||
return
|
||||
}
|
||||
updateAddressMutation.mutate(
|
||||
{
|
||||
id: addressToUpdate.id,
|
||||
regionId: addressToUpdate.regionId,
|
||||
name: addressToUpdate.name,
|
||||
phone: addressToUpdate.phone,
|
||||
addressLine1: addressToUpdate.addressLine1,
|
||||
|
|
@ -230,6 +235,7 @@ function AddressesPage() {
|
|||
editingAddress
|
||||
? {
|
||||
id: editingAddress.id,
|
||||
regionId: editingAddress.regionId ?? undefined,
|
||||
name: editingAddress.name,
|
||||
phone: editingAddress.phone,
|
||||
addressLine1: editingAddress.addressLine1,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { createFileRoute, useNavigate, useParams } from '@tanstack/react-router'
|
||||
import { trpc } from '../lib/trpc-client'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { ChevronLeft, CreditCard, CheckCircle, Zap, Edit2, Tag, XCircle, X, AlertCircle, Loader2 } from 'lucide-react'
|
||||
import { ChevronLeft, CreditCard, CheckCircle, Zap, Edit2, Tag, XCircle, X, AlertCircle, Loader2, MapPin } from 'lucide-react'
|
||||
import { BottomDialog } from 'web-components'
|
||||
import ComplaintForm from '../components/ComplaintForm'
|
||||
import { orderStatusManipulator } from '../lib/string-manipulators'
|
||||
|
|
@ -136,6 +136,12 @@ function OrderDetailPage() {
|
|||
<p className="text-xs text-slate-400">
|
||||
{dayjs(order.orderDate || order.createdAt).format('DD MMM, h:mm A')}
|
||||
</p>
|
||||
{!!(order as any).regionName && (
|
||||
<p className="mt-0.5 flex items-center text-[10px] text-slate-400">
|
||||
<MapPin className="mr-1 h-3 w-3" />
|
||||
{(order as any).regionName}
|
||||
</p>
|
||||
)}
|
||||
{order.isFlashDelivery && (
|
||||
<p className="mt-1 text-xs font-bold text-amber-600">⚡ 1 Hr Delivery</p>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { MeOrderMenu } from '../components/me/MeOrderMenu'
|
|||
import { MeScreenHeader } from '../components/me/MeScreenHeader'
|
||||
import { orderStatusManipulator } from '../lib/string-manipulators'
|
||||
import dayjs from 'dayjs'
|
||||
import { AlertCircle, Package } from 'lucide-react'
|
||||
import { AlertCircle, Package, MapPin } from 'lucide-react'
|
||||
|
||||
// Matches packages/ui (RN common-ui) REFUND_STATUS values used by user-ui.
|
||||
const REFUND_STATUS = {
|
||||
|
|
@ -117,6 +117,12 @@ function OrderCard({
|
|||
<span className="text-[10px] font-black uppercase text-amber-700">Flash</span>
|
||||
</span>
|
||||
)}
|
||||
{!!item.regionName && (
|
||||
<span className="flex flex-row items-center rounded-full border border-slate-200 bg-slate-100 px-2 py-1">
|
||||
<MapPin className="h-3 w-3 text-slate-500" />
|
||||
<span className="ml-1 text-[10px] font-bold text-slate-600">{item.regionName}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -3,11 +3,15 @@ import { useAuth } from '../lib/auth-context'
|
|||
import { MyButton } from 'web-components'
|
||||
import { AppLayout } from '../components/AppLayout'
|
||||
import { NextOrderGlimpse } from '../components/me/NextOrderGlimpse'
|
||||
import { Dialog } from '../components/Dialog'
|
||||
import { RegionSelector } from '../components/RegionSelector'
|
||||
import { useRegionStore } from '../lib/stores/region-store'
|
||||
import {
|
||||
Package,
|
||||
ShoppingCart,
|
||||
Ticket,
|
||||
MapPin,
|
||||
Globe,
|
||||
User,
|
||||
MessageSquare,
|
||||
FileText,
|
||||
|
|
@ -15,7 +19,7 @@ import {
|
|||
ChevronRight,
|
||||
Settings,
|
||||
} from 'lucide-react'
|
||||
import React from 'react'
|
||||
import React, { useState } from 'react'
|
||||
|
||||
export const Route = createFileRoute('/me')({ component: MePage })
|
||||
|
||||
|
|
@ -47,6 +51,9 @@ function MePage() {
|
|||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const { user, logout } = useAuth()
|
||||
const [regionDialogOpen, setRegionDialogOpen] = useState(false)
|
||||
const selectedRegion = useRegionStore((state) => state.selectedRegion)
|
||||
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
|
||||
// Check if we're on the exact /me path (not a child route like /me/orders)
|
||||
const isExactMePath = location.pathname === '/me'
|
||||
|
|
@ -192,6 +199,28 @@ function MePage() {
|
|||
<p className="text-base font-bold text-rose-500">Log Out from Freshyo</p>
|
||||
</button>
|
||||
|
||||
{/* Delivery region row */}
|
||||
<button
|
||||
onClick={() => setRegionDialogOpen(true)}
|
||||
className="mt-3 flex w-full flex-row items-center p-4 text-left transition-colors hover:bg-gray-50"
|
||||
>
|
||||
<div
|
||||
className="mr-4 flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl"
|
||||
style={{ backgroundColor: '#1570EF15' }}
|
||||
>
|
||||
<Globe size={24} color="#1570EF" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-base font-semibold text-gray-800">Delivery Region</p>
|
||||
<p className="mt-0.5 text-xs text-gray-400">
|
||||
{selectedRegion?.name ? `Browsing ${selectedRegion.name}` : 'Choose your region'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="ml-2 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gray-50">
|
||||
<ChevronRight size={16} color="#94A3B8" />
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<p className="mt-12 text-center text-[10px] uppercase tracking-[3px] text-gray-300">
|
||||
Version 1.2.0 • Freshyo App
|
||||
</p>
|
||||
|
|
@ -202,6 +231,19 @@ function MePage() {
|
|||
/* Render child routes when not on exact /me path */
|
||||
<Outlet />
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
open={regionDialogOpen}
|
||||
onClose={() => setRegionDialogOpen(false)}
|
||||
title="Delivery Region"
|
||||
>
|
||||
<RegionSelector
|
||||
mode="switch"
|
||||
selectedRegionId={selectedRegionId}
|
||||
onComplete={() => setRegionDialogOpen(false)}
|
||||
onCancel={() => setRegionDialogOpen(false)}
|
||||
/>
|
||||
</Dialog>
|
||||
</AppLayout>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
767
change-log.txt
Normal file
767
change-log.txt
Normal file
|
|
@ -0,0 +1,767 @@
|
|||
[2026-10-07 13:00:00] BACKEND per-region storefront cache generation (fixed contract; UI clients done by a second agent).
|
||||
|
||||
Planned diffs (backend + db_helper only; NO UI app touched; NO migration run; NO tests):
|
||||
|
||||
packages/shared/types/region.types.ts
|
||||
- Add RegionCacheVersions { regionId, cacheVersion, availabilityVersionNum, slotsVersionNum }.
|
||||
|
||||
packages/db_helper_sqlite/src/db/schema.ts
|
||||
- New table regionCacheVersions (region_id NOT NULL UNIQUE FK->regions.id,
|
||||
cache_version / availability_version_num / slots_version_num NOT NULL DEFAULT 1).
|
||||
|
||||
packages/db_helper_sqlite/drizzle/0008_region_cache_versions.sql (new, NOT run)
|
||||
- CREATE TABLE IF NOT EXISTS + UNIQUE index + INSERT seed row per existing region.
|
||||
packages/db_helper_sqlite/drizzle/meta/_journal.json
|
||||
- Append journal entry idx 8 -> 0008_region_cache_versions.
|
||||
|
||||
packages/db_helper_sqlite/src/lib/region-cache-versions.ts (new)
|
||||
- getRegionCacheVersions(regionId) (auto-creates row when missing),
|
||||
incrementRegionCacheVersion / incrementRegionAvailabilityVersionNum /
|
||||
incrementRegionSlotsVersionNum. Global key_val_store counters untouched.
|
||||
packages/db_helper_sqlite/index.ts — export the four helpers.
|
||||
|
||||
packages/db_helper_sqlite/src/stores/store-helpers.ts
|
||||
- regionId FIRST param on getAllProductsForCache, getAvailabilityForCache,
|
||||
getAllStoresForCache, getAllDeliverySlotsForCache, getAllSpecialDealsForCache,
|
||||
getAllProductTagsForCache, getAllTagsForCache, getAllTagProductMappings,
|
||||
getAllSlotsWithProductsForCache, getAllBannersForCache
|
||||
(+ getAllProductCombosForCache, same treatment — needed so combo rows stay
|
||||
in-region; not in the contract list, reported).
|
||||
- SQL where region_id on region-owned tables; JS-filter SKU-linked rows via the
|
||||
parent product_info.region_id; banner skuIds / slot skuIds / tag relatedStores
|
||||
filtered to in-region ids.
|
||||
packages/db_helper_sqlite/src/user-apis/stores.ts
|
||||
- getStoreSummaries(regionId, ...), getStoreDetail(regionId, storeId) (null
|
||||
outside region), getStoresSummary(regionId).
|
||||
packages/db_helper_sqlite/src/user-apis/banners.ts — getActiveBanners(regionId).
|
||||
packages/db_helper_sqlite/src/user-apis/slots.ts
|
||||
- getActiveSlotsList(regionId), getProductAvailability(regionId, in-region SKUs).
|
||||
packages/db_helper_sqlite/src/user-apis/product.ts
|
||||
- getSuspendedSkuIds(regionId); new getSkuRegionId/getSkuRegionIds (server-side
|
||||
SKU->region resolution for region-less live user endpoints; no client trust).
|
||||
apps/backend/src/sqliteImporter.ts — re-export new/changed helpers.
|
||||
|
||||
apps/backend/src/trpc/apis/common-apis/common.ts
|
||||
- scaffoldProducts(regionId): reads scoped DB helper directly (NOT the
|
||||
in-memory product-store); nextDeliveryDate = latest in-region slot per SKU
|
||||
(matches old DESC semantics); tags/mappings scoped; images signed.
|
||||
- scaffoldAvailability(regionId). getAllProductsSummary keeps no-input shape
|
||||
for admin UIs (untouched apps) by aggregating per-region scaffolds (reported).
|
||||
apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
|
||||
- scaffoldEssentialConsts(regionId): global consts + region's three versions +
|
||||
assetsDomain/apiCacheKey + regionId + regionSettings via
|
||||
getEffectiveRegionSettings. essentialConsts now REQUIRES {regionId} input
|
||||
(UI callers cannot be updated here — reported for the client agent).
|
||||
- getStoresSummary endpoint keeps no-input shape via per-region aggregation
|
||||
(reported).
|
||||
apps/backend/src/trpc/apis/user-apis/apis/stores.ts
|
||||
- scaffoldStores(regionId), scaffoldStoreWithProducts(regionId, storeId)
|
||||
(404/NOT_FOUND outside region).
|
||||
apps/backend/src/trpc/apis/user-apis/apis/slots.ts
|
||||
- scaffoldSlotsWithProducts(regionId) via scoped DB helper directly
|
||||
(slot-store NOT keyed by region); getSlots endpoint aggregates per region.
|
||||
apps/backend/src/trpc/apis/user-apis/apis/banners.ts — scaffoldBanners(regionId).
|
||||
apps/backend/src/trpc/apis/user-apis/apis/product.ts + cart.ts (live, region-less)
|
||||
- Resolve region server-side per requested SKU ids, then call region-keyed
|
||||
in-memory stores (no client-region trust).
|
||||
apps/backend/src/stores/product-store.ts + slot-store.ts
|
||||
- regionId FIRST param on initialize*/getAll*/get*/getMultipleProductsSlots.
|
||||
apps/backend/src/stores/product-tag-store.ts + banner-store.ts
|
||||
- initialize*(regionId).
|
||||
apps/backend/src/lib/gen-store.ts
|
||||
- KV key `essential_consts:{regionId}`; refreshGenKv(regionId?) (no-arg =
|
||||
all regions, kept for seed/flash/const callers); readEssentialConstsFromKv
|
||||
requires regionId (throws when missing — no silent global fallback).
|
||||
apps/backend/src/lib/cloud_cache.ts
|
||||
- createRegionCacheFiles(regionId) writing ONLY per-region paths
|
||||
({key}/regions/{id}/v-{cv}/products|stores|banners|essential-consts.json +
|
||||
stores/{storeId}.json, regions/{id}/av-{av}/availability.json,
|
||||
regions/{id}/slots/v-{sv}/slots.json); per-region purge + KV mirror.
|
||||
- createAllCacheFiles(regionId?) iterates all regions (or one); GLOBAL file
|
||||
generation REMOVED (all known consumers are the UI cache hooks being migrated
|
||||
by the client agent; backend tests also read them — reported, not updated).
|
||||
- createSlotsCacheFile(regionId, refresh) / createAvailabilityCacheFile(regionId,
|
||||
refresh) — admin slots/product routers pass ctx.staffUser region.
|
||||
apps/backend/src/stores/store-initializer.ts
|
||||
- initializeAllStores(regionId?) resolves target regions (one or all) and
|
||||
inits each; scheduleStoreInitialization(regionId?) forwards region to the DO.
|
||||
apps/backend/src/jobs/cache-creator.ts (CacheCreator DO)
|
||||
- schedule(regionId?) accumulates pendingRegions; alarm drains them (all-region
|
||||
when empty). No global mutable current-region.
|
||||
apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts
|
||||
- create: fire-and-forget createRegionCacheFiles(newRegion.id) with error log.
|
||||
apps/backend/src/trpc/apis/admin-apis/apis/{store,banner,product,slots}.ts
|
||||
- Pass ctx.staffUser region into scheduleStoreInitialization /
|
||||
createSlotsCacheFile / createAvailabilityCacheFile.
|
||||
|
||||
In-memory store decision: scaffolds read the scoped DB helpers directly; the
|
||||
in-memory stores (product/slot) are keyed by region (regionId first param) and
|
||||
live region-less user endpoints resolve the region server-side from SKU ids.
|
||||
Global-files: REMOVED (see above).
|
||||
Typecheck: tsc --noEmit for db_helper_sqlite + backend; fix own errors.
|
||||
|
||||
[2026-10-07 00:34:48] sqlite drizzle query logging — enable SQL logging on the current D1 instance.
|
||||
|
||||
File: packages/db_helper_sqlite/src/db/db_index.ts
|
||||
Diff plan:
|
||||
- Add isQueryLoggingDisabled() helper reading (globalThis as any).ENV?.DRIZZLE_LOG
|
||||
?? (globalThis as any).process?.env?.DRIZZLE_LOG (safe on Workers, no direct
|
||||
process.env access). Logging is ON unless flag is false/'false'/'0'.
|
||||
- Add queryLogger = { logQuery(query, params) } printing `[drizzle] <query>` + params
|
||||
via console.log.
|
||||
- Pass `logger` into drizzle(database, { schema, logger }) in initDb so every query
|
||||
through the current instance is logged. Set DRIZZLE_LOG=false to silence.
|
||||
|
||||
[2026-10-07 10:11:12] Phase 1 (superadmin) — regions, bounds, bound settings, superadmin identities.
|
||||
|
||||
New migration 0006 plus a new superadmin API channel and superadmin UI. Planned diffs:
|
||||
|
||||
packages/db_helper_sqlite/src/db/schema.ts
|
||||
- Add RegionGeoJson interface and tables regions, region_bounds,
|
||||
region_bound_settings (region_id + bound_id + key + value), superadmins.
|
||||
- Add relations for the above.
|
||||
|
||||
packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql (new)
|
||||
- Create the four tables + unique indexes.
|
||||
- Seed region "Mahabubnagar"; two bounds (Mbnr-1 priority 1, Mbnr-2 priority 2)
|
||||
with exact GeoJSON; 11 bound settings rows per bound; bootstrap superadmin.
|
||||
packages/db_helper_sqlite/drizzle/meta/_journal.json
|
||||
- Append journal entry idx 6 -> 0006_regions_and_superadmins.
|
||||
|
||||
packages/db_helper_sqlite/src/superadmin-apis/regions.ts (new)
|
||||
- Region/bound/settings persistence + effective-bound (lowest priority).
|
||||
packages/db_helper_sqlite/src/superadmin-apis/auth.ts (new)
|
||||
- Superadmin lookup.
|
||||
packages/db_helper_sqlite/index.ts
|
||||
- Export the new persistence helpers.
|
||||
|
||||
packages/shared/types/region.types.ts (new), superadmin.types.ts (new)
|
||||
packages/shared/types/index.ts
|
||||
- Re-export the new types.
|
||||
|
||||
apps/backend/src/trpc/trpc-index.ts
|
||||
- Add superadmin context field and superadminProcedure guard.
|
||||
apps/backend/src/app.ts
|
||||
- Resolve superadmin identity from token (identityType/superadminId).
|
||||
apps/backend/src/trpc/router.ts
|
||||
- Register superadmin router.
|
||||
apps/backend/src/trpc/apis/superadmin-apis/apis/{auth,regions,superadmin-trpc-index}.ts (new)
|
||||
apps/backend/src/sqliteImporter.ts
|
||||
- Re-export new superadmin/region helpers.
|
||||
|
||||
apps/superadmin-ui/src/lib/trpc-client.ts
|
||||
- Use a separate superadmin_token storage key.
|
||||
apps/superadmin-ui/src/lib/auth-context.tsx
|
||||
- Authenticate via superadmin.auth (login/me).
|
||||
apps/superadmin-ui/src/routes/login.tsx
|
||||
- Superadmin username/password copy.
|
||||
apps/superadmin-ui/src/routes/regions.tsx (new)
|
||||
apps/superadmin-ui/src/routes/dashboard.tsx, src/components/AppShell.tsx
|
||||
- Add Regions navigation.
|
||||
apps/superadmin-ui/src/routeTree.gen.ts
|
||||
- Register the /regions route (normally regenerated by the router plugin).
|
||||
|
||||
[2026-10-07 10:49:25] Phase 2 (staff/admin) — per-bound regional settings in admin-ui.
|
||||
|
||||
apps/admin-ui/components/context/staff-auth-context.tsx
|
||||
- Extend the session `Staff` shape with optional `regionId: number | null`
|
||||
(login already returns it); expose `regionId` on the auth context value.
|
||||
- Capture regionId from the login response (setStaff(data.staff)).
|
||||
- Non-breaking: existing consumers of `staff` keep working.
|
||||
|
||||
apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
|
||||
- Replace the single global constants form with one tab per region bound
|
||||
(admin.region.bounds, ascending priority). Each tab shows the bound
|
||||
description (or "Bound #id") + priority and marks the lowest-priority
|
||||
bound as "Effective" (its settings apply to checkout).
|
||||
- Selected bound loads admin.region.getBoundSettings and renders the 11
|
||||
regional keys as editable inputs (reuse ConstantInput; add a
|
||||
`allowSectionNavigation` prop so popularItems/allItemsOrder become inline
|
||||
comma-separated inputs instead of links to the global editors).
|
||||
- Save via admin.region.updateBoundSettings with only changed keys
|
||||
(string|null values). Default-select lowest-priority bound; reinitialize
|
||||
the form (Formik enableReinitialize + key) so drafts do not leak between
|
||||
tabs. Loading / error / "no bounds configured" states.
|
||||
- Keep the existing global constants form reachable via a top-level
|
||||
"Regional Settings" / "Global Constants" switch (admin.const.* unchanged).
|
||||
- Show the current region name (admin.region.current) in the header.
|
||||
- No staff-account creation UI exists in admin-ui (createStaffUser/
|
||||
getRoles are unused); nothing to remove.
|
||||
|
||||
[2026-10-07 10:51:16] Phase 3 (user-ui) — browsing region store, selection UI, switch/reset, address region, regional checkout + history labels.
|
||||
|
||||
New files:
|
||||
- apps/user-ui/src/store/regionStore.ts (new)
|
||||
- zustand store persisted via zustand/middleware `persist` + `createJSONStorage`
|
||||
over common-ui `StorageServiceCasual`. State: `selectedRegionId: number | null`,
|
||||
`selectedRegion: RegionSummary | null`, monotonic `regionGeneration` marker
|
||||
(race guard). Actions: `setRegion(region)`, `clearRegion()`. Persist key
|
||||
`freshyo-region`, version 1.
|
||||
- apps/user-ui/src/lib/region-switch.ts (new)
|
||||
- Centralized `confirmRegionSwitch(region, queryClient)`: clears regular+flash
|
||||
local carts (clearLocalCart), resets quick-delivery selected slot, address
|
||||
selection, slot/store stores and flash-cart/flash-navigation state, calls
|
||||
regionStore.setRegion, then invalidates all react-query caches.
|
||||
- apps/user-ui/src/components/RegionSelector.tsx (new)
|
||||
- Lists trpc.common.listRegions. `mode='gate'` renders a full-screen first-run
|
||||
chooser; `mode='switch'` is dialog content and opens an Alert confirmation
|
||||
stating the whole cart will be cleared, then runs confirmRegionSwitch.
|
||||
- apps/user-ui/src/components/RegionGate.tsx (new)
|
||||
- Hydration-aware gate: waits for persisted region, validates the saved region
|
||||
against common.listRegions (clears stale ids), renders RegionSelector until a
|
||||
region exists, otherwise children.
|
||||
|
||||
Modified files:
|
||||
- packages/shared/types/app-common.types.ts
|
||||
- Add optional `regionId?: number` to AddressFormProps.initialValues.
|
||||
- apps/user-ui/src/components/AddressForm.tsx
|
||||
- Query common.listRegions; required inline region dropdown; new addresses
|
||||
default to the browsing region while edits keep the stored region unless
|
||||
explicitly changed; include `regionId` in create/update payloads + Yup rule.
|
||||
- apps/user-ui/components/CheckoutAddressSelector.tsx
|
||||
- Region-aware selection: cross-region address prompts confirmation, runs
|
||||
confirmRegionSwitch and routes home; default auto-select only for the current
|
||||
region; attach-location update now sends regionId.
|
||||
- apps/user-ui/components/QuickDeliveryAddressSelector.tsx
|
||||
- Same cross-region address handling (confirmation + centralized switch +
|
||||
navigate home); shows a switch prompt when the selected/default address
|
||||
belongs to another region.
|
||||
- apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx
|
||||
- Carry regionId on the edit view-model/initialValues and include it in the
|
||||
set-default updateAddress payload.
|
||||
- apps/user-ui/components/PaymentAndOrderComponent.tsx
|
||||
- Read selectedRegionId from regionStore, block submit without a region, and
|
||||
pass `regionId` to user.order.placeOrder; surface backend errors safely.
|
||||
- apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx
|
||||
- Render `regionName` badge on each order (list stays account-wide).
|
||||
- apps/user-ui/app/(drawer)/(tabs)/me/my-orders/[id].tsx
|
||||
- Show order region label in the detail header.
|
||||
- apps/user-ui/components/FirstUserWrapper.tsx
|
||||
- Wrap children in RegionGate so a user with no saved region is prompted.
|
||||
- apps/user-ui/app/(drawer)/(tabs)/me/index.tsx
|
||||
- Add a "Delivery Region" entry that opens RegionSelector in switch mode.
|
||||
|
||||
[2026-10-07 10:54:56] Phase 1 follow-up — backend region wiring + migrations 0006/0007.
|
||||
|
||||
packages/db_helper_sqlite/src/db/schema.ts
|
||||
- region_id added (nullable, app-enforced) to product_info, staff_users,
|
||||
store_info, vendor_snippets, product_tag_info, product_group_info,
|
||||
delivery_slot_info, coupons, home_banners, addresses, orders.
|
||||
- ordersRelations gains region relation.
|
||||
packages/db_helper_sqlite/drizzle/0007_region_columns_backfill.sql (new)
|
||||
- ALTER TABLE add nullable region_id + backfill all rows to Mahabubnagar + indexes.
|
||||
packages/db_helper_sqlite/drizzle/meta/_journal.json
|
||||
- journal entry idx 7 -> 0007_region_columns_backfill.
|
||||
packages/db_helper_sqlite/src/admin-apis/staff-user.ts
|
||||
- createStaffUserWithRegion(); getAllStaff now returns regionId.
|
||||
packages/db_helper_sqlite/src/user-apis/address.ts
|
||||
- createUserAddress/updateUserAddress accept and persist regionId; mapUserAddress returns regionId.
|
||||
packages/db_helper_sqlite/src/user-apis/order.ts
|
||||
- OrderWithRelations gains regionId/region; order reads include region relation.
|
||||
packages/shared/types/user.ts
|
||||
- UserAddress.regionId; UserOrderSummary.regionId/regionName.
|
||||
|
||||
apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts (new)
|
||||
- superadmin.staff.list/roles/create (region required).
|
||||
apps/backend/src/trpc/apis/admin-apis/apis/region.ts (new)
|
||||
- admin.region.current/bounds/effective/getBoundSettings/updateBoundSettings (staff region scoped).
|
||||
apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
|
||||
- common.listRegions + common.regionSettings (public).
|
||||
apps/backend/src/trpc/apis/user-apis/apis/address.ts
|
||||
- createAddress/updateAddress require regionId.
|
||||
apps/backend/src/trpc/apis/user-apis/apis/order.ts
|
||||
- placeOrder requires regionId; address/region mismatch rejected; order stores region; history returns regionName.
|
||||
apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts
|
||||
- staff login returns staff.regionId.
|
||||
apps/backend/src/sqliteImporter.ts
|
||||
- re-export createStaffUserWithRegion and region helpers.
|
||||
|
||||
apps/admin-ui, apps/user-ui: region-aware screens per the two UI workstreams
|
||||
(bound tabs + staff region; region store/selector/switch + address region + history labels).
|
||||
|
||||
Typecheck: db_helper_sqlite, backend and superadmin-ui all pass (tsc --noEmit). No migrations run, no tests run, no git.
|
||||
|
||||
[2026-10-07 11:12:00] Phase 1 addendum — 0007 now rebuilds the region FK subgraph with region_id NOT NULL.
|
||||
|
||||
packages/db_helper_sqlite/drizzle/0007_region_columns_backfill.sql
|
||||
- After the nullable ADD COLUMN + backfill, rebuild every table in the region_id
|
||||
FK subgraph (31 tables incl. product_skus, order_items, orders, staff_notif_creds,
|
||||
coupon_* etc.) per docs/recreate-referenced-tables.md: create __new parent-first,
|
||||
copy all columns, drop leaves-first, rename parents-first, recreate indexes.
|
||||
- region_id is now NOT NULL (FK to regions) in the rebuilt tables.
|
||||
- CHECK on product_reviews written unqualified.
|
||||
|
||||
Schema note: Drizzle schema keeps region_id nullable to avoid breaking existing
|
||||
insert call sites; the DB is stricter. Remaining admin create paths (product, store,
|
||||
banner, coupon, tag, group, slot) must be updated to supply the staff region.
|
||||
|
||||
[2026-10-07 11:24:00] Wire regionId into all region-owned create paths (region is required, no defaults).
|
||||
|
||||
DB helpers (packages/db_helper_sqlite/src):
|
||||
- admin-apis/product.ts: createProduct(input, regionId), createProductTag(input, regionId),
|
||||
createProductGroup(..., regionId) now write region_id.
|
||||
- admin-apis/store.ts: createStore(input, products, regionId).
|
||||
- admin-apis/banner.ts: createBanner(input, regionId).
|
||||
- admin-apis/vendor-snippets.ts: createVendorSnippet({..., regionId}).
|
||||
- admin-apis/slots.ts: createSlotWithRelations(input, regionId); snippet inserts inherit region.
|
||||
- admin-apis/coupon.ts: createCouponWithRelations(..., regionId),
|
||||
createReservedCouponWithProducts(..., regionId), generateCancellationCoupon(..., regionId),
|
||||
createCouponForUser(..., regionId).
|
||||
- admin-apis/staff-user.ts: createStaffUser(..., regionId).
|
||||
- user-apis/coupon.ts: redeemReservedCoupon copies reservedCoupon.regionId into the coupon.
|
||||
- schema.ts + 0007: reserved_coupons is now region-owned too (ALTER + backfill + rebuild NOT NULL + index).
|
||||
- Removed all `?? 1` fallbacks; regionId is mandatory and must be supplied by the caller.
|
||||
|
||||
Routers (apps/backend/src/trpc/apis/admin-apis/apis):
|
||||
- product.ts / store.ts / banner.ts / vendor-snippets.ts create procedures now use staffProcedure
|
||||
and pass ctx.staffUser.regionId.
|
||||
- slots.ts / coupon.ts / staff-user.ts pass ctx.staffUser.regionId (and order.regionId for
|
||||
cancellation coupons).
|
||||
|
||||
Typecheck: db_helper_sqlite and backend pass.
|
||||
|
||||
[2026-10-07 11:27:35] Fix 0007 migration failure (FOREIGN KEY constraint failed).
|
||||
|
||||
Root cause (proven on a copy of the local D1 DB, statement-by-statement):
|
||||
- The drop/rebuild ordering was correct; the real problem is legacy DATA written
|
||||
before FK enforcement that violates the FKs the rebuilt tables declare:
|
||||
* 5 orders.address_id values no longer exist in addresses.
|
||||
* 11 payments rows whose order no longer exists (ALL payment rows are orphans).
|
||||
The __new_orders copy (statement #75) and later __new_payments copy (#83) fail
|
||||
on these live orphan rows.
|
||||
- Additionally the first partial run had already committed phase 1 (ALTERs +
|
||||
backfill + 19 __new_ copies), so re-running the file as-is would fail on duplicate columns.
|
||||
|
||||
Planned diff for packages/db_helper_sqlite/drizzle/0007_region_columns_backfill.sql:
|
||||
- Remove the ALTER-ADD-COLUMN + backfill phase entirely. region_id is added by the
|
||||
rebuild itself, computed at DB level in each copy SELECT
|
||||
((SELECT id FROM regions WHERE name='Mahabubnagar')). No app-level defaults.
|
||||
- Add a repair phase before the copy:
|
||||
* DELETE FROM payments WHERE order_id NOT IN (SELECT id FROM orders);
|
||||
* remove the 5 orphan orders AND their dependents: delete their
|
||||
payments/order_items/order_status/refunds, null out coupon_usage.order_id /
|
||||
coupon_usage.order_item_id / complaints.order_id / user_incidents.order_id.
|
||||
- Drop the pre-rebuild region indexes (created after rename only).
|
||||
- Journal entry unchanged (idx 7).
|
||||
- After migration: user resets local D1 state and re-runs 0006 + 0007;
|
||||
verify with PRAGMA foreign_key_check and row counts.
|
||||
|
||||
[2026-10-07 11:41:00] 0007 repair extended + proof harness run (read-only, on a COPY of the local DB).
|
||||
|
||||
- Repair phase also deletes order_status and refunds of the 5 orphan orders
|
||||
(their copies would otherwise fail FK to __new_orders first).
|
||||
- Proof harness on a copy of the actual local D1 DB (freshyo-dev, FK enforcement ON,
|
||||
statement-by-statement like wrangler):
|
||||
* All statements pass; PRAGMA foreign_key_check = 0 violations; zero __new_ leftovers.
|
||||
* Row deltas exactly as intended: orders -5, order_items -19, order_status -5,
|
||||
payments -11 (all), refunds -2; every other table unchanged.
|
||||
* region_id NOT NULL enforced and FK rejection verified post-rename (writes rejected).
|
||||
* All 13 original unique indexes recreated (4 table-prefixed + 9 unique_*).
|
||||
- Important: wrangler runs the file in one transaction — the earlier failed run left
|
||||
NO partial state, so the fixed 0007 can simply be re-run (0006 already applied).
|
||||
|
||||
[2026-10-07 11:45:00] Superadmin staff-user CRUD (regions reassignment + removal).
|
||||
|
||||
- admin-apis/staff-user.ts (db_helper_sqlite): add updateStaffUserRegion(staffId, regionId)
|
||||
and deleteStaffUser(staffId). Delete removes staff_notif_creds rows, clears nullable
|
||||
references (user_incidents.added_by), and refuses when the staff still owns a store
|
||||
or created coupons / reserved coupons (NOT NULL dependent FKs would break).
|
||||
- export both helpers from packages/db_helper_sqlite/index.ts and re-export them in
|
||||
apps/backend/src/sqliteImporter.ts.
|
||||
- superadmin-apis/apis/staff.ts: add superadmin.staff.update (reassign region) and
|
||||
superadmin.staff.remove (delete with blockedBy reason).
|
||||
- superadmin-ui: new routes/staff.tsx CRUD screen (list, add with role+region, region
|
||||
reassignment, delete w/ confirmation + blocked-reason display); AppShell nav entry
|
||||
"Admin Users"; routeTree.gen.ts registers /staff.
|
||||
|
||||
[2026-10-07 11:41:17] Enable Maestro MCP server in project opencode.jsonc.
|
||||
|
||||
- Ran: opencode mcp add maestro -- maestro mcp
|
||||
(registers local stdio MCP server "maestro" running `maestro mcp`,
|
||||
Maestro 2.11.0 built-in MCP server, project-local config).
|
||||
|
||||
[2026-10-07 12:03:54] Phase 4 (admin-web) — per-bound regional settings port from admin-ui.
|
||||
|
||||
Planned diffs:
|
||||
|
||||
apps/admin-web/src/components/context/staff-auth-context.tsx
|
||||
- Extend session `Staff` shape with optional `regionId: number | null`
|
||||
(login already returns it); expose `regionId` on the auth context value.
|
||||
- Non-breaking: existing consumers of `staff` keep working.
|
||||
|
||||
apps/admin-web/src/routes/dashboard.customize-app.tsx
|
||||
- Replace the single global constants form with one tab per region bound
|
||||
(admin.region.bounds, ascending priority). Each tab shows the bound
|
||||
description (or "Bound #id") + priority and marks the lowest-priority
|
||||
bound as "Effective" (its settings apply to checkout).
|
||||
- Selected bound loads admin.region.getBoundSettings and renders the 11
|
||||
regional keys as editable inputs (ConstantInput gains an
|
||||
`allowSectionNavigation` prop so popularItems/allItemsOrder become inline
|
||||
comma-separated inputs instead of links to the global editors).
|
||||
- Save via admin.region.updateBoundSettings with only changed keys
|
||||
(string|null values). Default-select lowest-priority bound; reinitialize
|
||||
the form (Formik enableReinitialize + key) so drafts do not leak between
|
||||
tabs. Loading / error / "no bounds configured" states.
|
||||
- Keep the existing global constants form reachable via a top-level
|
||||
"Regional Settings" / "Global Constants" switch (admin.const.* unchanged).
|
||||
- Show the current region name (admin.region.current) in the header.
|
||||
- No staff-account creation UI exists in admin-web (createStaffUser/
|
||||
getRoles unused); nothing to remove.
|
||||
|
||||
[2026-10-07 $(date +%H:%M:%S)] Phase 4 (web-ui) — port browsing-region features from user-ui (Expo) to web-ui (TanStack Start).
|
||||
|
||||
New files:
|
||||
- apps/web-ui/src/lib/stores/region-store.ts (new)
|
||||
- zustand `persist` store over an SSR-safe localStorage wrapper (web equivalent
|
||||
of Expo's StorageServiceCasual). Same shape as user-ui regionStore:
|
||||
selectedRegionId / selectedRegion / regionGeneration + setRegion / clearRegion.
|
||||
Persist key `freshyo-region`, version 1.
|
||||
- apps/web-ui/src/lib/region-switch.ts (new)
|
||||
- Centralized `confirmRegionSwitch(region, queryClient)`: clears regular+flash
|
||||
local carts (localStorage + react-query cart keys), resets quick-delivery
|
||||
selected slot, address selection, slot store ids, cart-store added product,
|
||||
flash-cart product, flash-navigation flag, clears central product/slot
|
||||
snapshots, persists the new region, then invalidates all react-query caches.
|
||||
Callers must confirm with the user before invoking.
|
||||
- apps/web-ui/src/components/RegionSelector.tsx (new)
|
||||
- Lists trpc.common.listRegions. mode='gate' full-screen first-run chooser
|
||||
(direct select, no cart exists yet); mode='switch' dialog content with an
|
||||
inline "entire cart will be cleared" confirmation before confirmRegionSwitch.
|
||||
- apps/web-ui/src/components/RegionGate.tsx (new)
|
||||
- Hydration-aware gate: waits for persisted region, validates saved region
|
||||
against common.listRegions (clears stale ids), renders children until
|
||||
hydrated (SSR-safe, avoids hydration mismatch) then a blocking overlay with
|
||||
RegionSelector until a region exists.
|
||||
|
||||
Modified files:
|
||||
- apps/web-ui/src/routes/__root.tsx
|
||||
- Wrap app children in RegionGate (inside trpc/Auth providers).
|
||||
- apps/web-ui/src/components/AddressForm.tsx
|
||||
- Required region <select> from common.listRegions; new addresses default to
|
||||
the browsing region, edits keep the stored region; regionId in
|
||||
create/update payloads + Yup required rule.
|
||||
- apps/web-ui/src/hooks/checkout-hooks.ts (useCheckoutAddress)
|
||||
- Default auto-select only for current-region addresses; expose cross-region
|
||||
helper data (addresses carry regionId).
|
||||
- apps/web-ui/src/components/CheckoutAddressSelector.tsx
|
||||
- Cross-region tap -> confirm (entire cart cleared) -> confirmRegionSwitch ->
|
||||
navigate home; same-region selection preserves cart.
|
||||
- apps/web-ui/src/routes/home.checkout.tsx + flash.checkout.tsx
|
||||
- Same cross-region address handling; placeOrder payloads gain regionId;
|
||||
backend mismatch errors surfaced.
|
||||
- apps/web-ui/src/components/PaymentAndOrderComponent.tsx
|
||||
- Reads selectedRegionId, blocks submit without a region, passes regionId to
|
||||
placeOrder, surfaces backend mismatch message.
|
||||
- apps/web-ui/src/routes/me.orders.tsx + me.orders.$id.tsx
|
||||
- Account-wide history (no region filter) with regionName labels.
|
||||
- apps/web-ui/src/routes/me.addresses.tsx
|
||||
- Address view-model carries regionId; edit initialValues keep stored region;
|
||||
set-default payload includes regionId (blocked with a message when missing).
|
||||
- apps/web-ui/src/routes/me.tsx
|
||||
- "Delivery Region" menu entry opening RegionSelector in switch mode.
|
||||
- Query keys: same as Expo (version-keyed global catalog caches, no region in
|
||||
keys); region switch clears central stores + invalidates all queries so no
|
||||
stale cross-region snapshots survive.
|
||||
|
||||
Typecheck: `npx tsc --noEmit --project apps/web-ui/tsconfig.json` from repo root.
|
||||
|
||||
[2026-10-07 12:14:52] Browser verification fix — allow localhost:4176 in backend CORS.
|
||||
|
||||
apps/backend/src/app.ts
|
||||
- CORS origin list gains 'http://localhost:4176' (admin-web auto-bumps to 4176
|
||||
when superadmin-ui already holds 4175; without this the browser blocks API calls).
|
||||
|
||||
[2026-10-07 12:18:39] Browser verification (Playwright MCP): web-ui region gate + admin-web bound tabs.
|
||||
- web-ui :4174 region gate renders with Mahabubnagar; selection dismisses gate.
|
||||
- admin-web :4176 staff login (uitest/test1234, regionId 1) works; customize-app shows
|
||||
Region: Mahabubnagar, Mbnr-1 P1 EFFECTIVE / Mbnr-2 P2 tabs, all 11 settings loaded.
|
||||
- E2E save verified twice in D1 (deliveryCharge 20->25, minRegularOrderValue 300->350
|
||||
on bound 1 only; bound 2 untouched), then restored to seeded values via SQL.
|
||||
- test staff row 'uitest' left in local D1 for reuse (region 1, role admin).
|
||||
- Note: backend CORS already included :4176. One benign console error (numberOfLines prop).
|
||||
|
||||
[2026-10-07 12:20:40] Isolation test fixtures in LOCAL dev D1 only (not app code).
|
||||
- Region 2 'Testnagar' + 1 bound (priority 1, square GeoJSON) + 11 settings rows
|
||||
(deliveryCharge 30 / minRegularOrderValue 500 to distinguish from Mahabubnagar).
|
||||
- Staff 'uitest2' (region 2, role admin, password test1234) for cross-region API tests.
|
||||
- All fixture rows are test-only and removable.
|
||||
|
||||
[2026-10-07 12:24:46] Region-scope CATALOG admin read paths (staff sees own region only).
|
||||
|
||||
Planned diffs:
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/product.ts
|
||||
- getAllProducts(regionId), getProductById(regionId, id),
|
||||
getAllProductTags(regionId), getAllProductTagInfos(regionId),
|
||||
getProductTagInfoById(regionId, tagId), getProductTagById(regionId, tagId),
|
||||
getProductReviews(regionId, productId, limit, offset),
|
||||
getAllProductGroups(regionId): regionId as FIRST param; list endpoints add
|
||||
eq(<table>.regionId, regionId); single-ID reads use and(id, regionId) and
|
||||
return null outside the region; reviews scoped via product_info.region_id
|
||||
join (reviews + count). checkProductExistsByName /
|
||||
checkProductTagExistsByName stay GLOBAL. Writes, price/stock mutations,
|
||||
respondToReview untouched.
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/store.ts
|
||||
- getAllStores(regionId), getStoreById(regionId, id); add `and` import.
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/banner.ts
|
||||
- getBanners(regionId), getBannerById(regionId, id); add `and` import.
|
||||
|
||||
apps/backend/src/trpc/apis/admin-apis/apis/product.ts, store.ts, banner.ts
|
||||
- Read procedures keep protectedProcedure (no auth restructure) and pass
|
||||
ctx.staffUser!.regionId, including read-before-write existence checks in
|
||||
updateStore / updateProductTag / deleteProductTag.
|
||||
|
||||
apps/backend/src/stores/banner-store.ts
|
||||
- getBannerById wrapper threads regionId through (dead code, no callers;
|
||||
updated only for typecheck).
|
||||
|
||||
apps/backend/src/stores/product-tag-store.ts
|
||||
- getTagsByStoreId resolves the store's own regionId via storeInfo and
|
||||
scopes getAllProductTags to it; user-apis callers untouched (stay working).
|
||||
|
||||
Typecheck: tsc --noEmit for packages/db_helper_sqlite + apps/backend.
|
||||
|
||||
[2026-10-07 12:24:34] Region-scope OPERATIONAL admin read paths (slots, snippets, coupons, orders, users, complaints).
|
||||
|
||||
Planned diffs (regionId added as FIRST param of each read helper; lists filter by
|
||||
region; single-ID reads constrain by region and return null outside it; writes,
|
||||
check*Exists validators, superadmin/user/region/const paths untouched):
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/slots.ts
|
||||
- getActiveSlotsWithProducts(regionId, limit): where isActive + region_id.
|
||||
- getSlotsAfterDate(regionId|null, afterDate): region filter when non-null
|
||||
(null = global, used only by the public vendor getUpcomingSlots link).
|
||||
- getSlotByIdWithRelations(regionId, id): and(id, region_id), null outside.
|
||||
- getSlotDeliverySequence(regionId, slotId): and(id, region_id), null outside.
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts (add `and` import)
|
||||
- getVendorSnippetById(regionId, id): and(id, region_id).
|
||||
- getVendorSnippetByCode(regionId|null, code): region-verified when non-null
|
||||
(null = global public vendor order-list links).
|
||||
- getAllVendorSnippets(regionId): where region_id.
|
||||
- getProductsByIds(regionId|null, skuIds): empty->[]; when region set, keep only
|
||||
SKUs whose parent product is in-region (columns gain product.regionId).
|
||||
- getVendorSlotById(regionId|null, slotId): region-verified when non-null.
|
||||
- getVendorOrdersBySlotId(regionId|null, slotId): and(slot, region) when non-null.
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/coupon.ts (add `sql`/`SQL` imports)
|
||||
- getAllCoupons(regionId, cursor, limit, search): push region condition.
|
||||
- getCouponById(regionId, id): and(id, region_id).
|
||||
- getReservedCoupons(regionId, cursor, limit, search): push region condition.
|
||||
- getOrderWithUser(regionId, orderId): and(id, region_id).
|
||||
- getUsersForCoupon(regionId, search, limit, offset): EXISTS in-region order filter
|
||||
(users scoped via orders.region_id, not addresses).
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/order.ts (import deliverySlotInfo)
|
||||
- getOrderDetails(regionId, orderId): and(id, region_id).
|
||||
- getSlotOrders(regionId, slotId): verify slot in-region first (else empty list);
|
||||
then and(slot, region) on orders.
|
||||
- getAllOrders(regionId, input): seed whereCondition with region equality.
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/user.ts (add `and`/`or`/`isNull` imports)
|
||||
- getUnresolvedComplaintsCount(regionId): unresolved AND (orderless OR order in-region).
|
||||
- getAllUsersWithFilters(regionId, limit, cursor, search): EXISTS in-region order.
|
||||
- getOrderCountsByUserIds / getLastOrdersByUserIds(regionId, userIds): AND region.
|
||||
- getSuspensionStatusesByUserIds(regionId, userIds): param added for uniformity;
|
||||
no filter (user_details has no region; callers pass in-region users only).
|
||||
- getUserBasicInfo(regionId, userId): null unless >=1 in-region order.
|
||||
- getUserOrders(regionId, userId): and(user, region).
|
||||
- getOrderStatusesByOrderIds / getItemCountsByOrderIds(regionId, orderIds):
|
||||
prefetch in-region order ids, query only those.
|
||||
- searchUsers(regionId, search): EXISTS in-region order (both branches).
|
||||
- getUserIncidentsWithRelations(regionId, userId): keep orderless or in-region-order
|
||||
incidents (JS filter on joined order.regionId).
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/complaint.ts (add `and`/`or`/`isNull`, orders import)
|
||||
- getComplaintById(regionId, id): null when order-backed and order out-of-region/missing.
|
||||
- getComplaints(regionId, cursor, limit): left-join orders, keep orderless OR
|
||||
in-region-order complaints (+ cursor).
|
||||
|
||||
apps/backend/src/trpc/apis/admin-apis/apis/{slots,vendor-snippets,coupon,order,user,complaint}.ts
|
||||
- Thread ctx.staffUser.regionId (staffProcedure where imported, else
|
||||
protectedProcedure + ctx.staffUser!.regionId) into every scoped helper call.
|
||||
- Public vendor endpoints (getOrdersBySnippet, getOrdersBySnippetAndSlot,
|
||||
getUpcomingSlots) pass null = deliberately global vendor links (no staff region).
|
||||
- slots.getDeliverySequence gains the missing staff guard (needed for region).
|
||||
- complaint.resolve's pre-check becomes region-scoped (write helper untouched).
|
||||
- payments.ts: stub, no order reads -> no change.
|
||||
- Writes (updates/deletes/invalidates/suspends), check*Exists validators, notif-cred
|
||||
reads, and non-admin callers unchanged by design; residual cross-region write
|
||||
paths noted in final report, not altered.
|
||||
|
||||
Typecheck: npx tsc --noEmit --project packages/db_helper_sqlite/tsconfig.json AND
|
||||
apps/backend/tsconfig.json; fix introduced errors. No tests, no git, no migrations.
|
||||
|
||||
[2026-10-07 12:31:10] Region-scope admin UPDATE/DELETE-by-ID paths + cross-region relationship validation on creates.
|
||||
|
||||
Planned diffs (regionId as FIRST param on helpers; single-ID mutations constrain with
|
||||
and(id, regionId) and return null/false outside the region; creates validate related
|
||||
IDs resolve to in-region rows and throw Error('... belongs to a different region')):
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/product.ts
|
||||
- deleteProduct(regionId, id), updateProduct(regionId, id, input: region-scoped
|
||||
pre-read + update where; cross-region combo skuIds + storeId rejected.
|
||||
- createProduct: storeId must resolve to an in-region store; combo-item skuIds
|
||||
must resolve via parent product_info.region_id (validation BEFORE the
|
||||
generic try/catch so the message surfaces).
|
||||
- createProductTag: relatedStores must be in-region stores.
|
||||
- replaceTagProducts(regionId, tagId, productIds): tag must be in-region; skuIds
|
||||
must be in-region (via parent product).
|
||||
- updateProductTag(regionId, tagId, input) -> null outside region; validates
|
||||
relatedStores in-region. deleteProductTag(regionId, tagId) -> boolean.
|
||||
- createProductGroup/updateProductGroup: productIds (SKU ids) validated in-region.
|
||||
- updateProductGroup(regionId, ...), deleteProductGroup(regionId, ...) scoped.
|
||||
- updateProductPrices(regionId, updates): out-of-region SKUs reported as invalidIds.
|
||||
- toggleProductOutOfStock(regionId, productId): null outside region.
|
||||
- respondToReview(regionId, reviewId, ...): null when the review's product is
|
||||
out-of-region. check*Exists validators stay global.
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/store.ts
|
||||
- updateStore(regionId, id, input, products?), deleteStore(regionId, id) scoped
|
||||
(delete/update throw 'Store not found' when outside region, as before).
|
||||
- createStore/updateStore: owner staff must be in-region; product SKU ids must
|
||||
resolve to in-region products.
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/banner.ts
|
||||
- updateBanner(regionId, id, input) -> Banner|null; deleteBanner(regionId, id)
|
||||
-> boolean. createBanner/updateBanner: skuIds validated in-region.
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/slots.ts
|
||||
- updateSlotWithRelations(regionId, input), updateSlotCapacity(regionId, ...),
|
||||
updateSlotDeliverySequence(regionId, ...) scoped (null outside region).
|
||||
- createSlotWithRelations/updateSlotWithRelations: skuIds + snippet skuIds +
|
||||
groupIds validated in-region. staleSlotsCleanup left global (maintenance).
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts
|
||||
- updateVendorSnippet(regionId, id, updates) -> null outside region; new slotId +
|
||||
skuIds validated in-region. deleteVendorSnippet(regionId, id) scoped.
|
||||
- createVendorSnippet: slotId + skuIds validated in-region.
|
||||
- updateVendorOrderItemPackaging left global (public vendor link, no staff ctx).
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/coupon.ts
|
||||
- updateCouponWithRelations(regionId, id, ...) -> null outside region; new
|
||||
applicableProducts validated in-region. invalidateCoupon(regionId, id) ->
|
||||
Coupon|null. createCouponWithRelations/createReservedCouponWithProducts:
|
||||
applicableProducts validated in-region. generateCancellationCoupon verifies
|
||||
the order's region matches. createCouponForUser unchanged (note).
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/order.ts
|
||||
- updateOrderNotes/updateOrderPackaged/updateOrderDelivered/removeDeliveryCharge/
|
||||
cancelOrder/deleteOrderById(regionId, ...) scoped (null/false/order_not_found
|
||||
outside region). updateOrderItemPackaging(regionId, ...) resolves the parent
|
||||
order's region first. updateAddressCoords(regionId, ...) constrains
|
||||
addresses.regionId. rebalanceSlots(regionId, slotIds) only touches in-region
|
||||
slots/orders. deleteOrdersWithRelations left global (note: caller is the
|
||||
global lib/delete-orders cleanup path).
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/user.ts — untouched (upsertUserSuspension
|
||||
account-global, createUserIncident no region needed — noted only).
|
||||
packages/db_helper_sqlite/src/admin-apis/complaint.ts — resolveComplaint(regionId,
|
||||
id, response) -> boolean, constrained via the getComplaintById region pattern.
|
||||
|
||||
apps/backend/src/trpc/apis/admin-apis/apis/{product,store,banner,slots,
|
||||
vendor-snippets,coupon,order,complaint}.ts — thread ctx.staffUser.regionId
|
||||
(staffProcedure where imported, else protectedProcedure + ctx.staffUser!.regionId)
|
||||
into every changed helper; map null/false to NOT_FOUND (no cross-region leak);
|
||||
create-validation Errors surface as-is.
|
||||
|
||||
Typecheck: npx tsc --noEmit --project packages/db_helper_sqlite/tsconfig.json AND
|
||||
apps/backend/tsconfig.json; fix introduced errors. No tests, no git, no migrations.
|
||||
|
||||
[2026-10-07 12:52:57] Region isolation testing — two-region (Mahabubnagar + Testnagar) verification.
|
||||
API (26/26 checks pass):
|
||||
- Creates in both regions via admin API: stores, tags, products, slots, coupons, banners.
|
||||
- Lists isolated: staff1 sees R1-only tags, staff2 sees R2-only tags.
|
||||
- Cross-region reads 404 without leaking (tag by id both ways; order details both ways).
|
||||
- Cross-region updates rejected (store update, slot capacity); own-region update works.
|
||||
- Cross-region create validation: R1 product with R2 store rejected.
|
||||
- Address saves regionId; mismatched checkout (region 1 order + region 2 address) rejected.
|
||||
- Region-2 order placed end-to-end (id 2454, regionId 2); staff1 list/detail exclude it,
|
||||
staff2 list/detail include it; user history carries regionName labels.
|
||||
- Duplicate (region_id, priority) rejected by unique index (proven at DB level).
|
||||
Browser (Playwright MCP):
|
||||
- web-ui gate lists both regions; switch Testnagar->Mahabubnagar with seeded cart:
|
||||
confirm dialog clears cart 1->0; cancel preserves cart + region.
|
||||
- admin-web customize bound tabs + E2E save verified earlier.
|
||||
- staff2 bounds endpoint returns Test-1 only; staff1 returns Mbnr-1/2 only.
|
||||
Left in LOCAL dev D1 (test-only, removable): region Testnagar + bound + settings,
|
||||
staff uitest/uitest2, ISO stores/tags/products/slots/coupons/banners, test address 875,
|
||||
order 2454. Temp scripts removed from repo.
|
||||
NOT covered: superadmin Regions/Staff UI pages (need superadmin password);
|
||||
storefront browsing still serves the global cache (per-region cache files pending).
|
||||
|
||||
[2026-10-07 13:05:00] Region-aware storefront catalog (user-ui + web-ui) against the FIXED backend contract.
|
||||
|
||||
Planned diffs (frontend only; backend untouched — another agent implements the contract):
|
||||
|
||||
apps/user-ui/src/hooks/prominent-api-hooks.ts
|
||||
- useGetEssentialConsts reads selectedRegionId from regionStore and calls
|
||||
trpc.common.essentialConsts with { regionId } (cast for forward-compat;
|
||||
current backend ignores the extra input at runtime). Enabled only when a
|
||||
region is selected; persisted discovery key becomes per-region
|
||||
(essential_consts_r<regionId>) so regions never share snapshots.
|
||||
- Regional URL builders from discovery data (effectiveSettings.regionId with
|
||||
selectedRegionId fallback):
|
||||
products/stores/per-store files:
|
||||
{assetsDomain}{apiCacheKey}/regions/{regionId}/v-{cacheVersion}/{file}
|
||||
availability:
|
||||
{assetsDomain}regions/{regionId}/av-{availabilityVersion}/availability.json
|
||||
slots:
|
||||
{assetsDomain}regions/{regionId}/slots/v-{slotsVersion}/slots.json
|
||||
Null regionId -> null URL -> catalog queries stay disabled (gate covers
|
||||
the no-region case).
|
||||
- New useRegionalConsts(): discovery data with the 5 delivery/minimum fields
|
||||
(deliveryCharge, freeDeliveryThreshold, flashDeliveryCharge,
|
||||
flashFreeDeliveryThreshold, minRegularOrderValue) overridden from
|
||||
effectiveSettings.settings (numeric parse, global fallback). Display-only;
|
||||
backend stays authoritative for the actual charge.
|
||||
|
||||
apps/user-ui/src/lib/region-switch.ts
|
||||
- confirmRegionSwitch additionally drops old-region react-query catalog
|
||||
snapshots (removeQueries on all-products/stores/slots/availability/
|
||||
store-with-products) before setRegion + invalidateQueries refetches
|
||||
discovery and catalog for the new region. Central stores cleared as before.
|
||||
Cancel path unchanged.
|
||||
|
||||
apps/user-ui/components/{cart-page,checkout-page,floating-cart-bar}.tsx
|
||||
- Delivery-charge/threshold messaging reads useRegionalConsts() (regional
|
||||
effective settings first, global fallback).
|
||||
|
||||
apps/web-ui/src/hooks/prominent-api-hooks.ts
|
||||
- Mirror of the user-ui hook changes above (localStorage persisted catalog
|
||||
caches stay version-gated; the versioned URL now contains the region so no
|
||||
cross-region placeholder can match). Banners go through the regional URL.
|
||||
apps/web-ui/src/lib/region-switch.ts
|
||||
- Mirror of the user-ui switch extension.
|
||||
apps/web-ui/src/components/{PaymentAndOrderComponent,FloatingCartBar}.tsx
|
||||
- Delivery-charge/threshold display prefers effectiveSettings via
|
||||
useRegionalConsts(); submit logic (regionId payload) untouched.
|
||||
|
||||
Admin apps: grep apps/admin-ui + apps/admin-web for essentialConsts/cache-file
|
||||
consumers — report only, no edits.
|
||||
|
||||
Typecheck: npx tsc --noEmit --project apps/user-ui/tsconfig.json AND
|
||||
apps/web-ui/tsconfig.json. No tests, no git, no migrations.
|
||||
|
||||
[2026-10-07 13:06:59] Per-region storefront cache phase — backend + clients implemented, pending 0008.
|
||||
Backend: region_cache_versions table + 0008 migration (NOT run); all *ForCache
|
||||
helpers + scaffolds region-first; KV essential_consts:{regionId}; regional paths
|
||||
regions/{id}/...; createRegionCacheFiles/createAllCacheFiles(regionId?);
|
||||
essentialConsts now REQUIRES {regionId}; CacheCreator DO drains per-region queue.
|
||||
Clients (user-ui + web-ui): discovery passes browsing regionId; regional URL builders;
|
||||
switch refetches discovery+catalog; checkout display uses effectiveSettings.
|
||||
Verified: all 4 typechecks pass; new code live on :8787 (regionId required; versions
|
||||
query fails until 0008 applied — expected).
|
||||
NEXT: user runs 0008 on dev D1, then per-region generation is triggered and verified.
|
||||
|
||||
[2026-10-07 13:13:31] Per-region storefront verified end-to-end.
|
||||
- 0008 applied by user; per-region generation triggered (store updates) — all
|
||||
counters 1->2 in both regions; regional files live on CDN.
|
||||
- File partition proven: r1 products.json 150 rows incl ISOProdR1, tags ISOTagR1 only;
|
||||
r2 1 row (ISOProdR2), tags ISOTagR2 only; zero cross-leaks either way.
|
||||
- Browser (web-ui): Testnagar storefront shows ISOTagR2+ISOProdR2, no R1 leaks;
|
||||
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'.
|
||||
165
docs/recreate-referenced-tables.md
Normal file
165
docs/recreate-referenced-tables.md
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
# Re-creating a Table Whose Keys Are Foreign Keys Elsewhere
|
||||
|
||||
> **Problem:** you need to rebuild a table (drop a column that participates in an
|
||||
> FK, change nullability, etc. — anything SQLite's limited `ALTER TABLE` cannot
|
||||
> do), but other tables hold foreign keys into it and the database has live rows.
|
||||
> A naive `DROP TABLE` fails with `FOREIGN KEY constraint failed`, on D1 no
|
||||
> matter which executor you use (dashboard, CLI, `migrations apply`).
|
||||
>
|
||||
> Last reviewed: 2026-10-05 (written after `0007_region_scoping.sql` forced us
|
||||
> to rebuild a 13-table subgraph on D1).
|
||||
|
||||
## 1. Why the textbook pattern dies on D1
|
||||
|
||||
The standard SQLite table-rebuild recipe relies on switching enforcement off
|
||||
around the rebuild:
|
||||
|
||||
```sql
|
||||
PRAGMA foreign_keys = OFF; -- or PRAGMA defer_foreign_keys = ON;
|
||||
-- ... create-copy-drop-rename ...
|
||||
PRAGMA foreign_keys = ON;
|
||||
```
|
||||
|
||||
D1 **enforces foreign keys and ignores both pragmas**. `DROP TABLE parent`
|
||||
runs an implicit `DELETE FROM parent` first, which trips every live child row
|
||||
(`ON DELETE no action`). Verified locally: the DROP fails with exit 19 while
|
||||
the identical statements pass with enforcement off. There is no executor-side
|
||||
workaround — dashboard, `d1 execute --file`, and `migrations apply` all fail
|
||||
the same way. (Side effect: `scripts/clear-db.sql`'s `PRAGMA foreign_keys=OFF`
|
||||
likewise cannot protect a full wipe on D1 remote.)
|
||||
|
||||
On an **empty** database the same migration passes (no child rows → the
|
||||
implicit delete violates nothing). So this failure only appears on populated
|
||||
DBs, which is why it slips past dev-time testing.
|
||||
|
||||
## 2. The pattern: rebuild the whole FK subgraph, leaves first
|
||||
|
||||
Since no referenced table with live rows can be dropped, rebuild **every table
|
||||
in the connected subgraph** so that at each DROP, nothing references the table
|
||||
being dropped. Every step is individually FK-legal, so per-statement autocommit
|
||||
(D1 dashboard/CLI) is fine — no transaction wrapping needed.
|
||||
|
||||
### Step 0 — Map the full subgraph (not just direct children)
|
||||
|
||||
Audit `schema.ts` for every `references(() => T)` where `T` is in your set,
|
||||
**recursively**. Grandchildren matter: in our case `coupon_usage.order_item_id
|
||||
-> order_items(id)` meant `order_items` was not a leaf and `coupon_usage` had
|
||||
to join the rebuild set. Also audit for anything the schema may not know about
|
||||
(legacy tables, views, triggers) — see pre-flight below.
|
||||
|
||||
Classify each table:
|
||||
|
||||
- **Leaf** — nothing references it. Rebuild directly with the final schema
|
||||
(NOT NULL preserved natively, no temp columns needed).
|
||||
- **Mid-level** — referenced by other tables in the set. Build the replacement
|
||||
under a `__new_<t>` name first; it gets dropped/renamed later once
|
||||
unreferenced.
|
||||
|
||||
### Step 1 — Pre-flight on the live target (read-only, mandatory)
|
||||
|
||||
```sql
|
||||
SELECT type, name FROM sqlite_master
|
||||
WHERE (sql LIKE '%<child_table>%' OR sql LIKE '%<parent_table>%')
|
||||
AND name NOT LIKE 'sqlite_%';
|
||||
```
|
||||
|
||||
Repeat the `LIKE` for every table in the set. The result must show **only** the
|
||||
known tables plus their indexes. Anything else (legacy table, view, trigger)
|
||||
must be folded into the plan before proceeding — the migration cannot branch
|
||||
at runtime.
|
||||
|
||||
Also confirm no index covers a column you plan to `DROP COLUMN` (SQLite blocks
|
||||
dropping indexed columns; FK-child columns are droppable, PK/UNIQUE columns
|
||||
are not).
|
||||
|
||||
### Step 2 — Create + copy, parents before children
|
||||
|
||||
```sql
|
||||
CREATE TABLE `__new_parent` ( ... final schema ... );
|
||||
INSERT INTO `__new_parent` (...) SELECT ... FROM `parent`;
|
||||
CREATE TABLE `__new_child` (
|
||||
...
|
||||
FOREIGN KEY (`pid`) REFERENCES `__new_parent`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
INSERT INTO `__new_child` (...) SELECT ... FROM `child`;
|
||||
```
|
||||
|
||||
- Preserve explicit `id`s so existing cross-references stay valid.
|
||||
- `INSERT` validates FKs immediately under autocommit, so fill parents first.
|
||||
- Point `__new_` FKs at `__new_` names. SQLite resolves FK parents **by name
|
||||
at enforcement time**, and `RENAME TABLE` (3.25+) rewrites other tables' FK
|
||||
clauses to the new name — so after the renames everything points at the
|
||||
final tables. (Verified: post-rename `sqlite_master` shows
|
||||
`REFERENCES "parent"`, and `foreign_key_check` is clean.)
|
||||
- Copy **all** columns explicitly; `sqlite_sequence` stays correct
|
||||
automatically since ids are preserved.
|
||||
|
||||
### Step 3 — Drop originals, leaves first
|
||||
|
||||
```sql
|
||||
DROP TABLE `leaf_1`;
|
||||
DROP TABLE `leaf_2`;
|
||||
-- ...
|
||||
DROP TABLE `mid_child`; -- now unreferenced
|
||||
DROP TABLE `parent`; -- now unreferenced
|
||||
```
|
||||
|
||||
Each DROP succeeds because nothing references the table at that moment.
|
||||
|
||||
### Step 4 — Rename top-down, then recreate indexes
|
||||
|
||||
```sql
|
||||
ALTER TABLE `__new_parent` RENAME TO `parent`;
|
||||
ALTER TABLE `__new_child` RENAME TO `child`;
|
||||
-- ...
|
||||
CREATE UNIQUE INDEX `<original_name>` ON `<table>` (...);
|
||||
```
|
||||
|
||||
Create indexes **after** the drops: index names live in a global namespace, so
|
||||
reusing the original names before dropping the old tables collides. (Non-unique
|
||||
indexes too — same namespace.)
|
||||
|
||||
### Step 5 — Verify
|
||||
|
||||
```sql
|
||||
PRAGMA foreign_key_check; -- must return zero rows
|
||||
-- plus per-table COUNT(*) compared against pre-migration counts
|
||||
```
|
||||
|
||||
Also exercise post-rename writes once: an INSERT violating a CHECK / FK /
|
||||
NOT NULL must still fail (proves constraints survived the rename — see
|
||||
pitfalls).
|
||||
|
||||
## 3. Pitfalls (each one bit us)
|
||||
|
||||
1. **CHECK constraints are NOT rewritten by RENAME.** Only other tables' FK
|
||||
clauses follow a rename. A drizzle-rendered
|
||||
`CHECK("old_name"."col" ...)` dangles after promotion and breaks all
|
||||
subsequent writes. Write CHECKs **unqualified**: `CHECK(col >= 1 AND ...)`.
|
||||
2. **No `ALTER COLUMN` in SQLite** (syntax error). Nullability can only change
|
||||
via rebuild — which is why mid-level tables go through `__new_` tables
|
||||
instead of `ADD/DROP COLUMN` surgery. (`ADD ... REFERENCES ... NOT NULL
|
||||
DEFAULT` is explicitly rejected by SQLite, so temp FK columns would be
|
||||
stuck nullable — another reason to rebuild leaves directly.)
|
||||
3. **`DROP COLUMN` works on FK-child columns** (verified) but is unnecessary in
|
||||
this pattern — prefer full rebuilds so NOT NULL survives everywhere.
|
||||
4. **Transcribe schemas from the migration target state, not from history.**
|
||||
Old migration files (e.g. `0000`) show stale shapes (integer timestamps,
|
||||
pre-rename columns). The `__new_` definitions must match post-migration
|
||||
reality = current `schema.ts` (we cross-checked every column/index/default
|
||||
against it).
|
||||
5. **`NUMERIC` affinity** (`numericText`) has no precedent in our migration
|
||||
history but is valid SQLite — safe to emit.
|
||||
6. **Fix the audit, not just the symptom.** The `coupon_usage -> order_items`
|
||||
edge was found by grepping all `references()` targets, not by trial and
|
||||
error. One missed edge = same FK failure one level down.
|
||||
|
||||
## 4. Proof harness
|
||||
|
||||
`0007`'s chain was proven before shipping by extracting the migration block
|
||||
verbatim and running it statement-by-statement in autocommit with
|
||||
`PRAGMA foreign_keys=ON` against an in-memory DB with all tables populated,
|
||||
asserting: row counts preserved, `foreign_key_check` clean, no `__new_`
|
||||
leftovers, indexes present, and post-rename CHECK/FK/NOT NULL enforcement
|
||||
alive. Reuse that approach for the next rebuild: populate → extract → run →
|
||||
assert. (Scratch script used: `/tmp`-adjacent `proof_0007.py`; not committed.)
|
||||
467
docs/regions-code-change-spec.md
Normal file
467
docs/regions-code-change-spec.md
Normal file
|
|
@ -0,0 +1,467 @@
|
|||
# Regions: Code Change Specification
|
||||
|
||||
Date: 2026-10-07
|
||||
Status: Implementation specification only
|
||||
Companion: `docs/regions-proposal.md`
|
||||
|
||||
No application changes are made by this document. Examples specify intended contracts and behavior; adapt exact imports, field names, and existing helper signatures to the repository during implementation.
|
||||
|
||||
## 1. Schema changes
|
||||
|
||||
### 1.1 New entities
|
||||
|
||||
In `packages/db_helper_sqlite/src/db/schema.ts`, introduce these Drizzle tables:
|
||||
|
||||
```ts
|
||||
regions = {
|
||||
id: integer primary key autoIncrement,
|
||||
name: required text,
|
||||
description: nullable text,
|
||||
createdAt: required timestampText default CURRENT_TIMESTAMP,
|
||||
}
|
||||
|
||||
regionBounds = {
|
||||
id: integer primary key autoIncrement,
|
||||
regionId: required integer references regions.id,
|
||||
description: nullable text,
|
||||
geojson: required jsonText<PolygonFeatureCollection>,
|
||||
priority: required numeric value,
|
||||
}
|
||||
// UNIQUE(region_id, priority)
|
||||
|
||||
regionBoundSettings = {
|
||||
id: integer primary key autoIncrement,
|
||||
boundId: required unique integer references regionBounds.id,
|
||||
// Explicit delivery/checkout fields mapped from existing constants.
|
||||
}
|
||||
|
||||
superadmins = {
|
||||
id: integer primary key autoIncrement,
|
||||
username: required unique text,
|
||||
passwordHash: required text,
|
||||
createdAt: required timestampText default CURRENT_TIMESTAMP,
|
||||
}
|
||||
```
|
||||
|
||||
Use SQL names `regions`, `region_bounds`, `region_bound_settings`, and `superadmins`; snake-case column names. Use the repository's JSON and timestamp helpers. Final bound-setting columns must be derived from existing delivery-charge, minimum-order, and flash-delivery code, not speculative defaults.
|
||||
|
||||
Define relations for regions → bounds, bounds → settings, and each region-owned root record → region. A nullable product `storeId` remains nullable.
|
||||
|
||||
### 1.2 Ownership columns
|
||||
|
||||
Add `regionId: integer('region_id').notNull().references(() => regions.id)` to root records identified in the proposal: products, staff, stores, snippets, tags, groups, slots, coupons, banners, zones, addresses, and orders.
|
||||
|
||||
Do not duplicate the column on every dependent table unnecessarily. For example, SKU ownership is resolved through its product, and order-item ownership through its order. Validate the SKU/order region match when inserting order items.
|
||||
|
||||
Add indexes for actual access patterns:
|
||||
|
||||
- Root record `region_id` filters.
|
||||
- Region + order pagination/filter columns where supported by query plans.
|
||||
- `order_items.order_id` and `order_status.order_id` relation lookups.
|
||||
- Bound `(region_id, priority)` uniqueness/index.
|
||||
|
||||
Index existence must be checked against existing migration SQL as well as the Drizzle schema. Do not assume deployed indexes are absent merely because they are not declared in the current schema.
|
||||
|
||||
### 1.3 Migration code
|
||||
|
||||
Prepare, but do not run, a migration with this ordering:
|
||||
|
||||
1. Create regions and insert `Mahabubnagar` immediately.
|
||||
2. Create bounds/settings and insert exact GeoJSON from both attached map files, priorities 1 and 2 respectively.
|
||||
3. Populate both bounds' settings from current behavior.
|
||||
4. Backfill ownership fields using the newly inserted region ID.
|
||||
5. Enforce non-null ownership and rebuild SQLite tables if required, preserving foreign keys and data.
|
||||
6. Create superadmins and immediately insert username `superadmin` with the supplied bcrypt hash from the proposal.
|
||||
|
||||
Do not hash the bootstrap hash again. Do not default all future inserts to Mahabubnagar: new root records must receive their region from an authorized creation path.
|
||||
|
||||
Update the supported PostgreSQL schema consistently, without switching the active backend or executing PostgreSQL migrations.
|
||||
|
||||
### 1.4 Required table-recreation guide
|
||||
|
||||
Follow `docs/recreate-referenced-tables.md` whenever migration changes require recreating a table. Do not use a naive single-parent create/copy/drop/rename sequence on populated referenced tables.
|
||||
|
||||
- Audit the complete recursive FK dependency subgraph, including grandchildren and objects outside the current Drizzle schema.
|
||||
- Document mandatory read-only target preflight for legacy tables, views, triggers, and affected indexes. Preparing this document does not authorize remote database access.
|
||||
- Derive replacement definitions from the actual migration target state, preserving all columns, IDs, defaults, constraints, and relations.
|
||||
- Create/copy replacements parent-first; replacement foreign keys reference replacement names where required.
|
||||
- Drop originals leaf-first only after no live original child references them.
|
||||
- Rename replacements parent-first and recreate indexes after original index names have been released.
|
||||
- Use unqualified CHECK column expressions so table promotion does not leave stale table-name references.
|
||||
- Do not rely on toggling foreign-key enforcement to make D1 drops safe.
|
||||
- Provide verification steps for preserved row counts, clean `foreign_key_check`, restored indexes, absence of replacement leftovers, and continued FK/CHECK/NOT NULL enforcement.
|
||||
|
||||
Prepare a populated-data, statement-by-statement proof harness following the guide when necessary, but do not run it without explicit authorization. Migration execution remains the user's responsibility.
|
||||
|
||||
## 2. Shared TypeScript contracts
|
||||
|
||||
Add `packages/shared/types/region.types.ts` and `superadmin.types.ts`, and export them through shared entry points.
|
||||
|
||||
Illustrative public contracts:
|
||||
|
||||
```ts
|
||||
interface RegionSummary {
|
||||
id: number
|
||||
name: string
|
||||
description: string | null
|
||||
}
|
||||
|
||||
interface RegionBoundDto {
|
||||
id: number
|
||||
regionId: number
|
||||
description: string | null
|
||||
geojson: PolygonFeatureCollection
|
||||
priority: number
|
||||
}
|
||||
|
||||
interface EffectiveRegionSettings {
|
||||
regionId: number
|
||||
boundId: number
|
||||
priority: number
|
||||
// Existing delivery/checkout settings, explicitly typed.
|
||||
}
|
||||
|
||||
interface StaffSession {
|
||||
id: number
|
||||
name: string
|
||||
regionId: number
|
||||
regionName: string
|
||||
}
|
||||
|
||||
interface SuperadminSession {
|
||||
id: number
|
||||
username: string
|
||||
}
|
||||
```
|
||||
|
||||
Use a typed GeoJSON dependency if already available, or define the required FeatureCollection/Polygon structure locally. Preserve feature properties and holes; validate coordinate/ring structure at runtime.
|
||||
|
||||
Extend address DTOs and inputs with region ownership. Extend order summaries/details with region identity/name. Extend cache discovery contracts with region ID and regional URLs/versions. Do not expose `passwordHash` through shared public DTOs.
|
||||
|
||||
## 3. Identity and request context
|
||||
|
||||
### 3.1 Token separation
|
||||
|
||||
Use an explicit identity discriminator in newly issued JWT claims:
|
||||
|
||||
```ts
|
||||
type IdentityClaims =
|
||||
| { identityType: 'user'; userId: number }
|
||||
| { identityType: 'staff'; staffId: number }
|
||||
| { identityType: 'superadmin'; superadminId: number }
|
||||
```
|
||||
|
||||
Resolve the referenced identity from the appropriate database table. Staff region is resolved from the staff row, not trusted from token/client input. Decide how old tokens are expired or supported during rollout; never treat an old staff token as superadmin authority.
|
||||
|
||||
### 3.2 tRPC context
|
||||
|
||||
Update `apps/backend/src/app.ts` and `src/trpc/trpc-index.ts`:
|
||||
|
||||
- Keep distinct `user`, `staffUser`, and `superadmin` context fields.
|
||||
- Add staff `regionId` to the resolved identity.
|
||||
- Introduce `userProcedure`, `staffProcedure`, and `superadminProcedure` guards.
|
||||
- Keep public procedures for login and region discovery only where intended.
|
||||
- Replace generic protected guards on privileged routers with the correct identity guard.
|
||||
|
||||
Conceptual staff middleware:
|
||||
|
||||
```ts
|
||||
if (!ctx.staffUser) throw UNAUTHORIZED
|
||||
return next({ ctx: { ...ctx, staffUser: ctx.staffUser } })
|
||||
```
|
||||
|
||||
A user or superadmin identity does not automatically satisfy this guard. `Caller-Interface` is metadata, not authorization.
|
||||
|
||||
### 3.3 Superadmin auth
|
||||
|
||||
Implement username/password login backed exclusively by `superadmins`. Use the existing bcrypt library to compare plaintext login input against `password_hash`; issue a superadmin-typed token on success. Return a uniform authentication error on failure and avoid logging login credentials/hash values.
|
||||
|
||||
Update existing superadmin UI session handling to this channel. Namespace stored session credentials where needed so staff and superadmin clients cannot accidentally reuse the same identity.
|
||||
|
||||
## 4. Superadmin router contracts
|
||||
|
||||
Register a new `superadmin` root router in `apps/backend/src/trpc/router.ts`. Proposed procedure layout:
|
||||
|
||||
```text
|
||||
superadmin.auth.login public login
|
||||
superadmin.auth.me authenticated identity
|
||||
superadmin.regions.list list regions
|
||||
superadmin.regions.get region + bounds
|
||||
superadmin.regions.create create region
|
||||
superadmin.regions.update update name/description
|
||||
superadmin.regions.createBound create validated bound
|
||||
superadmin.regions.updateBound update geometry/description/priority
|
||||
superadmin.staff.create create staff with required region
|
||||
superadmin.staff.list administrative staff listing
|
||||
superadmin.staff.update authorized staff/region management
|
||||
```
|
||||
|
||||
These are proposed names; preserve established API naming conventions where appropriate. There is no region-delete procedure. Bound deletion is not required by the confirmed requirements; do not introduce it without deciding effective-settings safety.
|
||||
|
||||
Validate region existence, GeoJSON structure, and priority uniqueness. Map uniqueness violations to useful API errors. For priority swaps, use a safe atomic strategy compatible with D1 rather than assuming a multi-step update has transactional rollback.
|
||||
|
||||
Staff creation leaves the admin API and becomes superadmin-only. Keep roles/credentials consistent with existing staff login behavior.
|
||||
|
||||
## 5. Region-scoped persistence helpers
|
||||
|
||||
### 5.1 Explicit scope parameters
|
||||
|
||||
Change regional helper signatures so callers cannot omit trusted scope accidentally:
|
||||
|
||||
```ts
|
||||
getAllOrders(regionId: number, input: GetAllOrdersInput)
|
||||
getOrderDetails(regionId: number, orderId: number)
|
||||
getProducts(regionId: number, input: ProductListInput)
|
||||
updateProduct(regionId: number, productId: number, input: ProductUpdateInput)
|
||||
```
|
||||
|
||||
Preserve actual helper names and result types. Admin router calls pass `ctx.staffUser.regionId`; do not accept an override from request input.
|
||||
|
||||
### 5.2 Scoped reads and writes
|
||||
|
||||
For root records, combine scope with existing predicates:
|
||||
|
||||
```ts
|
||||
where: and(eq(orders.regionId, regionId), existingPredicate)
|
||||
```
|
||||
|
||||
For updates/deletes, put region ownership in the mutation predicate, not merely in an earlier UI lookup. Return a consistent inaccessible/not-found response when no matching row is found.
|
||||
|
||||
For dependent records such as order items or SKU market stats, resolve or constrain ownership via joins/EXISTS against their root record. Do not mutate by dependent ID alone.
|
||||
|
||||
Every create/update connecting entities validates matching regions, including optional product stores, combos, slots, snippet membership, tags/groups, coupons, and order lines. Validate bulk operations too.
|
||||
|
||||
### 5.3 User visibility to staff
|
||||
|
||||
Build regional user listings using an EXISTS condition on orders:
|
||||
|
||||
```sql
|
||||
EXISTS (
|
||||
SELECT 1 FROM orders
|
||||
WHERE orders.user_id = users.id
|
||||
AND orders.region_id = :staff_region_id
|
||||
)
|
||||
```
|
||||
|
||||
Scope user-order details, item counts, last-order lookups, totals, and related complaints to the same region. An address in the region does not qualify a user without an order.
|
||||
|
||||
Account-global actions require an explicit authority decision; do not silently give regional staff cross-region suspension/deletion effects.
|
||||
|
||||
### 5.4 Existing D1 transaction caveat
|
||||
|
||||
`packages/db_helper_sqlite/src/db/db_index.ts` currently supplies a transaction-shaped wrapper that executes the callback without a real database transaction. Do not assume rollback protection when designing region switching, multi-record checkout validation, migration steps, or priority swaps. Use supported D1 atomic batching/constraints or another deliberate consistency strategy after auditing the existing helpers.
|
||||
|
||||
## 6. Effective bound settings
|
||||
|
||||
Introduce a helper such as:
|
||||
|
||||
```ts
|
||||
getEffectiveRegionSettings(regionId: number): Promise<EffectiveRegionSettings>
|
||||
```
|
||||
|
||||
Algorithm:
|
||||
|
||||
1. Validate region existence.
|
||||
2. Fetch that region's bound ordered by priority ascending, limit 1.
|
||||
3. Fetch the chosen bound's configured settings.
|
||||
4. Fail clearly if either is missing.
|
||||
|
||||
Do not filter bounds by coordinates. Do not select another bound just because the lowest-priority bound is missing configuration. Do not borrow another region's values.
|
||||
|
||||
Use this helper as the authoritative source in checkout and payment calculations. Frontend estimates consume corresponding settings, but backend calculations remain authoritative.
|
||||
|
||||
Add staff-only read/update settings procedures. Identify bounds through a query constrained to `ctx.staffUser.regionId`. Editing another bound is allowed within the region; only the current lowest-priority bound affects calculations.
|
||||
|
||||
## 7. User API changes
|
||||
|
||||
### 7.1 Discovery and browsing
|
||||
|
||||
Expose a public region list returning safe summaries. Regional catalog/slot/store/banner/availability requests require `regionId` and validate it before reading data.
|
||||
|
||||
Common scaffold functions become explicit regional functions, for example:
|
||||
|
||||
```ts
|
||||
scaffoldProducts(regionId: number)
|
||||
scaffoldAvailability(regionId: number)
|
||||
scaffoldSlotsWithProducts(regionId: number)
|
||||
scaffoldStores(regionId: number)
|
||||
scaffoldBanners(regionId: number)
|
||||
```
|
||||
|
||||
Apply scope inside the DB readers as well as the router; background generation calls must not accidentally retrieve global records.
|
||||
|
||||
### 7.2 Addresses
|
||||
|
||||
Create/update inputs include a required region ID. Validate region existence and user ownership on editing. Coordinate containment is explicitly not required. Updating address region must be an explicit user action, not a hidden consequence of changing browsing region.
|
||||
|
||||
### 7.3 Checkout
|
||||
|
||||
Request includes the intended region along with selected items, address, slot choices, and coupon. Backend verifies:
|
||||
|
||||
- Authenticated user owns the address.
|
||||
- Address region equals checkout region.
|
||||
- Every SKU and slot belongs to checkout region.
|
||||
- Requested slot availability and SKU membership are valid.
|
||||
- Coupon eligibility and ownership match the region.
|
||||
- Current prices and effective bound settings produce the authoritative total.
|
||||
|
||||
Reject mixed-region requests before creating orders/payments. Persist `orders.region_id`. Preserve existing order-item price snapshots rather than relying on future catalog prices for order history.
|
||||
|
||||
### 7.4 History
|
||||
|
||||
`getOrders` remains filtered by user ownership, not browsing region. `getOrderById` verifies user ownership and returns the order's region label. Do not require the currently browsed region to match a historical order.
|
||||
|
||||
## 8. Regional cache implementation
|
||||
|
||||
### 8.1 Path builders
|
||||
|
||||
Centralize region prefixes in `apps/backend/src/lib/cloud_cache.ts`:
|
||||
|
||||
```ts
|
||||
const regionPrefix = (regionId: number) => `regions/${regionId}`
|
||||
const catalogPath = (regionId: number, version: number, filename: string) =>
|
||||
`${regionPrefix(regionId)}/v-${version}/${filename}`
|
||||
```
|
||||
|
||||
Add equivalent availability/slot builders using existing filename constants and asset-domain/API-key prefixes. Use these same builders for writes, returned URLs, and cache purges so paths cannot drift.
|
||||
|
||||
### 8.2 Generation flow
|
||||
|
||||
Split orchestration into a region-specific generator and an all-region generator:
|
||||
|
||||
```ts
|
||||
createRegionCacheFiles(regionId: number)
|
||||
createAllRegionsCacheFiles()
|
||||
```
|
||||
|
||||
The all-region function lists regions and invokes region generation with controlled concurrency. Region generation reads only its region, updates that region's versions, writes files, purges regional URLs, and refreshes the region's metadata mirror.
|
||||
|
||||
Do not update a successful-version pointer before required files are available. Plan failure recovery so clients do not discover partially published regional snapshots.
|
||||
|
||||
### 8.3 Invalidation and jobs
|
||||
|
||||
Namespace product/availability/slot version metadata by region. Mutations regenerate the affected region. Scheduled jobs iterate regions or receive explicit regional context. Order queue jobs derive region from the stored order and scope operational recipients accordingly.
|
||||
|
||||
Any process cache must be keyed by region. Avoid storing one mutable `currentRegion` in worker globals.
|
||||
|
||||
## 9. User UI state transitions
|
||||
|
||||
### 9.1 Region store
|
||||
|
||||
Add `apps/user-ui/src/store/regionStore.ts` with persisted selected-region ID and a validated loaded region summary. Keep it separate from user identity.
|
||||
|
||||
Proposed operations:
|
||||
|
||||
```text
|
||||
initializeRegion() validate saved ID or show selection
|
||||
requestRegionSwitch(target) open confirmation without modifying state
|
||||
confirmRegionSwitch(target) perform centralized switch/reset
|
||||
cancelRegionSwitch() preserve existing state
|
||||
```
|
||||
|
||||
Use existing store/persistence conventions. Do not persist secrets. A missing/unavailable saved region leads to selection, not silent checkout fallback.
|
||||
|
||||
### 9.2 Confirmed-switch sequence
|
||||
|
||||
Centralize the reset so manual switching and address-triggered switching use the same behavior:
|
||||
|
||||
1. Block new checkout submissions and cancel/ignore stale regional fetch responses.
|
||||
2. Clear normal cart, flash cart, quick-delivery state, selected slots, coupons, and checkout totals/selections.
|
||||
3. Clear/update server-backed cart state if the existing cart implementation persists it remotely.
|
||||
4. Update and persist selected region.
|
||||
5. Reset or namespace regional product/slot/config stores and queries.
|
||||
6. Fetch regional metadata and files.
|
||||
7. For an address-triggered switch, navigate home rather than resume the old checkout.
|
||||
|
||||
Handle remote-clear failure explicitly instead of claiming the cart is cleared while stale server items remain. The final mechanism depends on the existing cart persistence audit.
|
||||
|
||||
### 9.3 Race protection
|
||||
|
||||
Use a region generation/version marker or query cancellation so an old-region response cannot overwrite new-region stores. Checkout captures the intended region and cart snapshot; region changes invalidate that attempt before any new submit.
|
||||
|
||||
If an already accepted backend order completes during switching, preserve access to it through all-region history rather than trying to undo it with client-side resets.
|
||||
|
||||
### 9.4 Address and history components
|
||||
|
||||
- `AddressForm.tsx`: load region choices; default only new addresses to browsing region.
|
||||
- `CheckoutAddressSelector.tsx` and `QuickDeliveryAddressSelector.tsx`: stage selection; confirm cross-region changes before committing state.
|
||||
- `checkout-page.tsx` and `PaymentAndOrderComponent.tsx`: use effective settings and explicit region; handle backend mismatch errors safely.
|
||||
- Order list/details and `NextOrderGlimpse.tsx`: render region labels; remain account-wide.
|
||||
|
||||
Use common-ui primitives according to repository rules.
|
||||
|
||||
## 10. Admin and superadmin UI code
|
||||
|
||||
### 10.1 Superadmin
|
||||
|
||||
Update auth context, tRPC client, and login route to separate superadmin credentials. Add regions and staff routes using the proposed router contracts.
|
||||
|
||||
Region forms submit name/description; bound forms submit parsed GeoJSON, description, and numeric priority. Validate inputs client-side for feedback and again server-side for correctness. Show duplicate-priority errors and effective-bound status. Do not display a region-delete action.
|
||||
|
||||
Staff forms require region selection. Existing constants/notification screens must be audited and routed through explicit superadmin authority if retained. Regenerate the TanStack route tree through its normal tooling rather than manually editing generated output.
|
||||
|
||||
### 10.2 Admin
|
||||
|
||||
Extend `staff-auth-context.tsx` to expose region identity. Display it in the shell; do not let staff arbitrarily change it. Remove staff-create operations from admin screens.
|
||||
|
||||
Modify the existing `apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx` Customize App Constants screen rather than adding a new settings route:
|
||||
|
||||
- Fetch bounds belonging to the authenticated staff region and display one tab per bound, ordered by ascending priority.
|
||||
- Label tabs with bound description (or bound ID when description is absent) and priority. Mark the lowest-priority bound as currently effective.
|
||||
- Select the lowest-priority bound initially. Each tab displays only that bound's customizable constants.
|
||||
- Change the current unscoped `admin.const.getConstants` / `updateConstants` flow to bound-scoped reads/writes, or use the proposed bound-settings procedures. Read input includes `boundId`; save input includes `boundId` and the changed constants/settings. Backend verifies that the bound belongs to the staff region.
|
||||
- Keep existing `ConstantInput` controls and visibility rules where compatible with the audited per-bound settings model. Global infrastructure constants must not become editable per-bound values.
|
||||
- Include `boundId` in query keys and form identity. Initialize the form from that bound's saved values, never from the previous tab's values.
|
||||
- Save only the active bound's changes. Capture its ID when submitting so changing tabs cannot redirect an in-flight save to another bound.
|
||||
- Isolate drafts by bound or confirm before discarding unsaved edits when changing tabs; never silently overwrite a draft. Disable conflicting interactions while saving where needed.
|
||||
- Refetch/invalidate the saved bound and affected region's effective-settings/cache metadata after a successful update.
|
||||
- Replace the existing claim that all changes take effect immediately: explain that only the lowest-priority bound's values currently affect checkout, regardless of address coordinates. Changes to other bounds are saved but not currently effective.
|
||||
- Provide loading/error/retry states per selected bound and a clear no-bounds configuration state.
|
||||
- Preserve existing non-constants customization navigation, subject to regional ownership checks.
|
||||
|
||||
There is no new `region-settings` UI route. The existing Customize App entry point remains the location for bound-specific constants.
|
||||
|
||||
Update existing screen contracts and inaccessible-record behavior. No UI region filter substitutes for backend scoping. Scope cache regeneration controls to the assigned region.
|
||||
|
||||
## 11. Error semantics
|
||||
|
||||
Use existing custom error and tRPC conventions:
|
||||
|
||||
- Unauthenticated/wrong identity: authorization error.
|
||||
- Foreign-region ID: inaccessible/not-found without disclosing sensitive existence.
|
||||
- Invalid/mixed region or malformed GeoJSON: validation error.
|
||||
- Duplicate priority: conflict/validation error with a clear message.
|
||||
- Missing effective bound/settings: explicit configuration error.
|
||||
- Stale checkout state: clear retry/reselection guidance, with no partial order creation where avoidable.
|
||||
|
||||
Do not introduce broad catch blocks that hide failures. Ensure logging avoids credentials and password hashes.
|
||||
|
||||
## 12. Implementation order and validation
|
||||
|
||||
Implement in dependency order:
|
||||
|
||||
1. Shared schema/contracts and prepared migration.
|
||||
2. Identity guards and superadmin APIs.
|
||||
3. Scoped persistence helpers and all API entry points.
|
||||
4. Effective settings and regional cache generation.
|
||||
5. Superadmin/admin UI contracts.
|
||||
6. User startup, switch/reset, address, checkout, and history flows.
|
||||
7. Static review/typechecking and prepared test cases.
|
||||
|
||||
Validate foreign-region ID access, mixed-region relationships, regional user aggregates, generated file contents, duplicate priority, startup state, switch cancellation/confirmation, stale response races, and all-region order history.
|
||||
|
||||
Before any non-Markdown/non-text implementation edit, append its exact diff and current timestamp to the required change log. Do not execute migrations or run tests unless authorized under repository instructions. Do not perform git operations.
|
||||
|
||||
## 13. Remaining audit boundaries
|
||||
|
||||
The agreed behavior is settled, but implementation must establish the exact existing names and mechanisms for:
|
||||
|
||||
- Delivery/flash settings fields and current defaults.
|
||||
- Server-backed versus local cart storage and reset behavior.
|
||||
- Existing cache-version storage and URL-discovery consumers.
|
||||
- Staff management UI route locations and retained superadmin capabilities.
|
||||
- Account-global moderation permissions.
|
||||
- D1 atomic operations and priority-reordering safety.
|
||||
- Legacy REST routes, direct helper consumers, and deployed migration/index state.
|
||||
|
||||
Resolve these through source inspection rather than silently introducing new business requirements. Use the file-by-file map in `docs/regions-proposal.md` as the implementation checklist.
|
||||
480
docs/regions-proposal.md
Normal file
480
docs/regions-proposal.md
Normal file
|
|
@ -0,0 +1,480 @@
|
|||
# Region Isolation Proposal
|
||||
|
||||
Date: 2026-10-07
|
||||
Status: Proposed; no implementation included
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
Introduce regions as the ownership boundary for catalogs, regional administration, delivery operations, and generated catalog files. Separate superadmin identities and APIs from staff-admin identities. Allow users to browse different regions while preventing mixed-region carts and checkouts.
|
||||
|
||||
This document records the agreed requirements and proposed implementation. It does not authorize running migrations or tests.
|
||||
|
||||
## 2. Confirmed decisions
|
||||
|
||||
- Every product must belong to a region. A product may still have no store.
|
||||
- Every staff admin belongs to one region.
|
||||
- Stores, vendor snippets, tags, product groups, delivery slots, coupons, banners, and delivery zones are region-owned.
|
||||
- Regional admins can only access and change data belonging to their region.
|
||||
- Regional admins can see users who have orders in their region. User-related order data shown to them must also be region-filtered.
|
||||
- Only superadmins create staff accounts and assign their regions.
|
||||
- Regions cannot be deleted.
|
||||
- Users select a browsing region at startup and can change it later.
|
||||
- Region switching requires a confirmation dialog. Confirming clears the entire cart.
|
||||
- Addresses have an explicitly selected region. The browsing region is the default in the address form.
|
||||
- Address coordinates do not need to fall within the selected region's bounds.
|
||||
- Selecting a different-region address during checkout requires confirmation, switches the browsing region, clears the cart, and returns to the home page.
|
||||
- User order history includes all regions, with region labels.
|
||||
- Catalog and availability files are generated separately for every region, with the region ID in their URLs.
|
||||
- Delivery charges, minimum order amounts, and similar business settings belong to individual bounds.
|
||||
- Regional admins can configure all bounds in their own region.
|
||||
- For now, use the region's lowest-numbered-priority bound settings regardless of address coordinates. Priority 1 is used when it is the lowest priority present; do not hard-code a requirement that priority 1 always exists.
|
||||
|
||||
## 3. Database design
|
||||
|
||||
### 3.1 `regions`
|
||||
|
||||
| Column | Proposed definition |
|
||||
| --- | --- |
|
||||
| `id` | Auto-increment integer primary key |
|
||||
| `name` | Required text |
|
||||
| `description` | Nullable text |
|
||||
| `created_at` | Required timestamp with current-time default |
|
||||
|
||||
Provide create, list, detail, and update operations. Do not expose a delete operation. Protect against deletion through referenced ownership records as well.
|
||||
|
||||
### 3.2 `region_bounds`
|
||||
|
||||
| Column | Proposed definition |
|
||||
| --- | --- |
|
||||
| `id` | Auto-increment integer primary key |
|
||||
| `region_id` | Required foreign key to `regions.id` |
|
||||
| `description` | Nullable text |
|
||||
| `geojson` | Required JSON text |
|
||||
| `priority` | Required numeric value |
|
||||
|
||||
`region_id` is an addition to the originally listed columns, necessary to support multiple bounds per region.
|
||||
|
||||
Constraints and validation:
|
||||
|
||||
- Unique constraint on `(region_id, priority)`.
|
||||
- Lower numeric priority takes precedence.
|
||||
- Validate that priorities are finite numeric values.
|
||||
- Store the supplied FeatureCollection structure without discarding feature properties.
|
||||
- Initially validate polygon FeatureCollections, including coordinates and closed polygon rings. Additional geometry support is not required by the supplied examples.
|
||||
- Use `ORDER BY priority ASC LIMIT 1` to choose effective business settings, without testing address coordinates.
|
||||
- A region must have a configured bound before checkout can operate. If none exists, return a clear configuration error rather than borrowing another region's settings.
|
||||
|
||||
### 3.3 Bound-level business settings
|
||||
|
||||
Propose a `region_bound_settings` table with a required, unique `bound_id` foreign key. This keeps geometry and operational settings separate while providing one settings record per bound.
|
||||
|
||||
Map existing delivery and checkout constants to explicit settings fields, including:
|
||||
|
||||
- Delivery charges and any existing charge thresholds.
|
||||
- Minimum order amount.
|
||||
- Applicable flash-delivery configuration.
|
||||
- Other region-specific checkout/business constants discovered during the implementation audit.
|
||||
|
||||
Preserve current calculation rules and numeric representations unless a change is explicitly required. Inventory existing constants before finalizing column names and defaults; do not invent new pricing rules.
|
||||
|
||||
Seed both Mahabubnagar bounds with current business settings so rollout preserves existing behavior. Infrastructure settings, credentials, and deployment configuration remain global.
|
||||
|
||||
### 3.4 Regional ownership
|
||||
|
||||
Add mandatory `region_id` ownership to the relevant root records:
|
||||
|
||||
- `product_info`
|
||||
- Staff-user records
|
||||
- Store records
|
||||
- Vendor snippets
|
||||
- Product-tag definitions
|
||||
- Product-group definitions
|
||||
- Delivery slots
|
||||
- Coupons
|
||||
- Banners
|
||||
- Delivery zones
|
||||
- Addresses
|
||||
- Orders
|
||||
|
||||
Audit actual schema names before making changes. Addresses and orders need explicit regions in addition to catalog/admin ownership.
|
||||
|
||||
Derived ownership:
|
||||
|
||||
- `product_skus` inherit region through `product_info`.
|
||||
- `product_market_stats`, `sku_features`, and SKU-level deals inherit their SKU's region.
|
||||
- `order_items` inherit region through their order; their SKUs must belong to that same region.
|
||||
- Tag memberships, group memberships, combo memberships, and snippet mappings must link entities in the same region.
|
||||
- Reviews remain product-linked; regional admin visibility follows the product's region.
|
||||
- Users are not assigned one exclusive region; they can browse and order across regions.
|
||||
|
||||
Enforce cross-entity consistency in backend writes and use database constraints where feasible. Foreign keys on individual IDs alone do not guarantee matching regions.
|
||||
|
||||
Add indexes matching regional filters and relation lookups. Review uniqueness rules individually: do not assume every currently global name becomes region-unique, or that login identifiers can be duplicated.
|
||||
|
||||
### 3.5 `superadmins`
|
||||
|
||||
Create a separate identity table, not a staff role or a row in `staff_users`.
|
||||
|
||||
Proposed minimum fields:
|
||||
|
||||
- `id`: primary key.
|
||||
- `username`: required and unique.
|
||||
- `password_hash`: required text.
|
||||
- `created_at`: required timestamp.
|
||||
|
||||
The bootstrap account is inserted in the migration immediately after table creation:
|
||||
|
||||
- Username: `superadmin`
|
||||
- Bcrypt password hash: `$2a$12$pDL1ooXdvmdpCFpeXgEnB.7eRot4ygtL/Z9lSmW8ApjRLAhTiuOCu`
|
||||
|
||||
The supplied value is already a hash. Store it directly, do not hash it again, and never return it through APIs or write it into application logs. Password login verifies the submitted password against this hash. No public superadmin registration endpoint is proposed.
|
||||
|
||||
## 4. Migration and existing data
|
||||
|
||||
Prepare migrations for the active SQLite/D1 database. Audit the PostgreSQL helper and keep schema definitions coherent where it remains supported; do not assume it is the active runtime database.
|
||||
|
||||
Migration sequence:
|
||||
|
||||
1. Create `regions`.
|
||||
2. Immediately insert a region named **Mahabubnagar**.
|
||||
3. Create bounds and bound-settings tables.
|
||||
4. Insert two Mahabubnagar bounds containing the exact GeoJSON from:
|
||||
- `apps/backend/src/map-assets/Mbnr-1.geojson`: priority **1**.
|
||||
- `apps/backend/src/map-assets/Mbnr-2.geojson`: priority **2**.
|
||||
5. Copy current business settings into each bound's settings.
|
||||
6. Add regional ownership fields and assign all existing regional records, addresses, orders, and staff admins to Mahabubnagar.
|
||||
7. Enforce required ownership and add relevant constraints/indexes after backfill. Account for SQLite table-rebuild requirements.
|
||||
8. Create `superadmins` and immediately insert the bootstrap account.
|
||||
|
||||
Use the inserted region's actual ID rather than assuming a preexisting ID. Preserve existing records, IDs, foreign-key relationships, and order history. Do not automatically turn staff accounts into superadmins.
|
||||
|
||||
The user runs migrations. The agent must not execute them.
|
||||
|
||||
For any table recreation, follow `docs/recreate-referenced-tables.md`. Audit the complete recursive foreign-key subgraph and target schema, including legacy tables, views, and triggers. Plan copies parent-first, drops leaf-first, renames parent-first, and index recreation after original tables are dropped. Preserve explicit IDs and all columns; use unqualified CHECK expressions. Do not rely on disabling foreign-key enforcement as a D1 rebuild strategy. Document read-only target preflight and post-migration foreign-key/row-count verification for the user. Any proof-harness execution requires explicit authorization under the repository's test restrictions.
|
||||
|
||||
## 5. Backend API and authentication
|
||||
|
||||
### 5.1 Three authenticated channels
|
||||
|
||||
The existing root tRPC router exposes `user`, `admin`, and `common`. Add `superadmin` while retaining needed common/public discovery endpoints.
|
||||
|
||||
- `user`: user identity and ownership checks.
|
||||
- `admin`: authenticated staff identity with its database-assigned region.
|
||||
- `superadmin`: authenticated identity from `superadmins`.
|
||||
|
||||
Introduce dedicated authorization middleware for each identity. The existing generic protected procedure accepting either users or staff is not sufficient as the only guard for these channels.
|
||||
|
||||
Distinguish token identity types explicitly. Reject staff/user tokens on superadmin endpoints and superadmin tokens on staff-only endpoints unless an explicit permission is designed. Do not trust the UI's caller-interface header as an authorization boundary.
|
||||
|
||||
### 5.2 Superadmin operations
|
||||
|
||||
- Login and current-identity/session operations.
|
||||
- Region create/list/detail/update, with no delete endpoint.
|
||||
- Bound create/list/update and priority management.
|
||||
- Staff-account creation, region assignment, and management required by the existing staff workflows.
|
||||
- Adapt existing superadmin UI operations to genuine superadmin authorization rather than reusing staff credentials.
|
||||
|
||||
Avoid expanding superadmin permissions to unrelated operations without examining current functionality.
|
||||
|
||||
### 5.3 Staff-admin isolation
|
||||
|
||||
Resolve the staff region from authenticated database state. Do not allow a request's `region_id` to override it.
|
||||
|
||||
Apply scope to:
|
||||
|
||||
- Lists, searches, counts, details, exports, and aggregates.
|
||||
- Create/update/delete operations on regional entities.
|
||||
- Packaging, order status changes, refunds, cancellation actions, and slot reassignment.
|
||||
- Product, SKU, pricing, tag, group, store, snippet, and availability operations.
|
||||
- Bound business-setting operations.
|
||||
- Cache regeneration triggered by regional changes.
|
||||
|
||||
ID-based endpoints must check ownership too; hiding another region's records in lists is insufficient. Avoid revealing whether an inaccessible foreign-region record exists.
|
||||
|
||||
Regional user visibility is based on the existence of an order in the staff region, not address ownership. Show only that region's user orders and order-derived totals/counts. Audit shared account-level actions so a regional admin cannot unintentionally affect unrelated regions.
|
||||
|
||||
### 5.4 User operations
|
||||
|
||||
- Provide region discovery before a browsing region has been selected.
|
||||
- Validate selected region IDs for catalog, availability, slots, banners, stores, and other regional browsing requests.
|
||||
- Validate address region on address creation and updates; coordinate containment is not required.
|
||||
- Check checkout region against every item, SKU, slot, address, and applicable coupon.
|
||||
- Determine business settings from the lowest-priority bound of that region.
|
||||
- Store region ownership on resulting orders.
|
||||
- Continue to enforce user ownership for all-region order history and individual order access.
|
||||
|
||||
Do not infer checkout region solely from client state. Reject malformed or mixed-region requests at the backend.
|
||||
|
||||
## 6. Generated files and background work
|
||||
|
||||
Current generation in `apps/backend/src/lib/cloud_cache.ts` uses global scaffolds and versioned product, availability, slot, banner, and store paths. Make scaffolds and generation region-aware.
|
||||
|
||||
Proposed path examples, retaining existing versioning semantics:
|
||||
|
||||
```text
|
||||
regions/{regionId}/v-{cacheVersion}/products.json
|
||||
regions/{regionId}/v-{cacheVersion}/stores.json
|
||||
regions/{regionId}/v-{cacheVersion}/banners.json
|
||||
regions/{regionId}/v-{cacheVersion}/stores/{storeId}.json
|
||||
regions/{regionId}/av-{availabilityVersion}/availability.json
|
||||
regions/{regionId}/slots/v-{slotsVersion}/slots.json
|
||||
```
|
||||
|
||||
These are illustrative names; preserve actual `CACHE_FILENAMES` and any required URL prefix in implementation.
|
||||
|
||||
Requirements:
|
||||
|
||||
- Generate each regional file using only that region's records.
|
||||
- Namespace cache metadata, query caches, version discovery, and KV mirrors by region.
|
||||
- Prefer per-region version counters so a change in one region does not invalidate every region.
|
||||
- Make region-scoped business settings available through the appropriate generated/config payloads; do not continue exposing global delivery settings as authoritative.
|
||||
- Regenerate all regions for full-generation jobs, and only the affected region for targeted updates.
|
||||
- Update cache purge URLs to the regional paths.
|
||||
- Audit durable objects, scheduled jobs, queues, and notifications for regional context and avoid global mutable region state shared across concurrent requests.
|
||||
- Ensure new regions have generated files before browsing relies on them, or return a clear not-ready state.
|
||||
|
||||
## 7. Superadmin UI
|
||||
|
||||
In `apps/superadmin-ui/`:
|
||||
|
||||
- Switch authentication to the new superadmin identity/channel.
|
||||
- Add region listing, creation, and editing.
|
||||
- Add bounds management with description, GeoJSON input, and priority validation.
|
||||
- Explain priority ordering and show which bound currently supplies effective settings.
|
||||
- Do not offer region deletion.
|
||||
- Add staff creation and region assignment; remove reliance on staff-admin APIs for this capability.
|
||||
- Keep password hashes out of UI payloads and displays.
|
||||
|
||||
## 8. Admin UI
|
||||
|
||||
In `apps/admin-ui/`:
|
||||
|
||||
- Include assigned region in staff session/profile data and display it clearly.
|
||||
- Do not provide a region switcher allowing staff to escape their assignment.
|
||||
- Scope all data through backend authorization, including existing order, user, product, store, slot, tag, group, snippet, coupon, and banner screens.
|
||||
- Remove staff-account creation from regional-admin workflows; adapt remaining staff views to the authorized scope.
|
||||
- Update the existing Customize App Constants screen with one tab per bound in the assigned region. Each tab edits that bound's customizable constants; do not introduce a separate settings screen.
|
||||
- Clearly indicate that the lowest-priority bound's settings are currently effective, regardless of address coordinates.
|
||||
|
||||
## 9. User UI
|
||||
|
||||
### 9.1 Region selection
|
||||
|
||||
In `apps/user-ui/`, maintain a persisted browsing region independently from the user's account identity.
|
||||
|
||||
- On startup, validate any saved selection; prompt before regional browsing when none is selected.
|
||||
- Offer a region switch control later.
|
||||
- Show a confirmation dialog before switching, explaining that the entire cart will be removed.
|
||||
- Cancel leaves region and cart unchanged.
|
||||
- Confirm clears all cart state, selections, coupon state, and checkout-derived state, updates the region, invalidates regional queries, and loads the new regional files.
|
||||
- Include region IDs in client query keys and persisted regional data to prevent stale cross-region results.
|
||||
|
||||
### 9.2 Addresses and checkout
|
||||
|
||||
- Add a required region dropdown to address creation/editing.
|
||||
- Default new-address region to the browsing region.
|
||||
- Existing addresses retain their stored region; editing must not silently reassign them to the browsing region.
|
||||
- Same-region address selection preserves the cart.
|
||||
- Different-region checkout address selection presents confirmation before changing state.
|
||||
- On confirmation, switch browsing region, clear the whole cart and checkout state, and navigate home. Do not place the original cart's order under the new address region.
|
||||
- Prevent stale in-flight checkout actions from completing against a switched cart/region.
|
||||
|
||||
### 9.3 Order history
|
||||
|
||||
- Show orders from all regions regardless of the browsing region.
|
||||
- Add region labels to summaries and details.
|
||||
- Keep order details tied to the order's stored region and user ownership.
|
||||
- Do not let browsing-region filters hide historical orders.
|
||||
|
||||
## 10. Shared contracts and implementation areas
|
||||
|
||||
Update shared types and API contracts for region identities, bounds, effective settings, staff region, address region, order region, and regional cache metadata.
|
||||
|
||||
Known starting points:
|
||||
|
||||
- `packages/db_helper_sqlite/src/db/schema.ts`
|
||||
- `packages/db_helper_postgres/src/db/schema.ts`
|
||||
- `packages/shared/`
|
||||
- `apps/backend/src/app.ts`
|
||||
- `apps/backend/src/trpc/trpc-index.ts`
|
||||
- `apps/backend/src/trpc/router.ts`
|
||||
- `apps/backend/src/trpc/apis/`
|
||||
- `apps/backend/src/lib/cloud_cache.ts`
|
||||
- `apps/backend/src/lib/gen-store.ts`
|
||||
- `apps/backend/src/jobs/`
|
||||
- `apps/superadmin-ui/src/lib/auth-context.tsx`
|
||||
- `apps/superadmin-ui/src/routes/`
|
||||
- Relevant authentication, catalog, cart, address, checkout, and order screens/stores in admin-ui and user-ui.
|
||||
|
||||
This is an implementation map, not an exhaustive file inventory. Audit call sites before editing so legacy REST routes, direct helper calls, and background consumers are not missed.
|
||||
|
||||
## 11. Proposed rollout stages
|
||||
|
||||
1. Audit regional entities, existing auth, settings, cache contracts, and all API entry points.
|
||||
2. Prepare schema changes, migrations, backfill, bootstrap account, and shared types.
|
||||
3. Implement separate superadmin authentication and management APIs.
|
||||
4. Enforce regional backend isolation and consistent relationships across all entry points.
|
||||
5. Implement regional settings selection, file generation, version discovery, and background jobs.
|
||||
6. Update superadmin and admin interfaces.
|
||||
7. Update user region selection, cart switching, address handling, and history labels.
|
||||
8. Validate and coordinate database/backend/client deployment so old clients cannot bypass region requirements or consume incompatible caches.
|
||||
|
||||
Do not expose partially isolated APIs in production. Define a compatibility or coordinated-release strategy during implementation.
|
||||
|
||||
## 12. Acceptance checks
|
||||
|
||||
Prepare checks covering:
|
||||
|
||||
- Existing records all belong to Mahabubnagar after backfill.
|
||||
- Both supplied bounds are stored exactly, with priorities 1 and 2.
|
||||
- Duplicate priorities within one region are rejected; the same priority across different regions is allowed.
|
||||
- Products can omit a store but cannot omit a region.
|
||||
- Regions cannot be deleted.
|
||||
- The bootstrap superadmin authenticates through the separate identity table.
|
||||
- Regional staff cannot create staff accounts or access another region's records by ID.
|
||||
- Cross-region product/store, slot/SKU, tag/SKU, group/SKU, snippet/SKU, coupon, and checkout relationships are rejected.
|
||||
- Regional user lists include only users with orders in that region, and aggregates do not leak other-region activity.
|
||||
- Checkout always uses lowest-priority-bound settings, independent of coordinates.
|
||||
- Switching cancellation preserves state; confirmation clears the complete cart.
|
||||
- A different-region checkout address redirects home only after confirmation.
|
||||
- User history retains orders across all regions and labels them.
|
||||
- Generated URLs, contents, version metadata, and invalidations remain region-isolated.
|
||||
- Staff/user tokens cannot access superadmin operations.
|
||||
|
||||
Typechecking and static review may be used during implementation. Do not run the test suite unless the user explicitly requests it. Do not run migrations, perform git operations, or implement application changes as part of writing this proposal.
|
||||
|
||||
## 13. Items requiring implementation-time audit
|
||||
|
||||
These are not changes to the confirmed requirements:
|
||||
|
||||
- Exact existing business-setting fields and defaults to move to bounds.
|
||||
- Existing superadmin UI functions that need corresponding superadmin permissions.
|
||||
- Account-global actions such as suspension/deletion and how regional staff authority should apply; do not silently grant cross-region effects.
|
||||
- Whether bound removal/reassignment is needed; region deletion is forbidden, and any bound operation must preserve usable effective settings.
|
||||
- Existing clients and deployment compatibility during mandatory region rollout.
|
||||
|
||||
## 14. File-by-file implementation map
|
||||
|
||||
Paths below are relative to the repository root. **New** marks proposed files, not files already created. Directory-level entries intentionally cover every applicable file in that directory; the implementation audit must enumerate their call sites before editing. This map describes responsibilities, not permission to implement them now.
|
||||
|
||||
### 14.1 Database and shared contracts
|
||||
|
||||
| File / directory | Planned change |
|
||||
| --- | --- |
|
||||
| `packages/db_helper_sqlite/src/db/schema.ts` | Define regions, bounds, bound settings, and superadmins; add regional ownership, relations, constraints, and indexes. Keep product store ownership nullable. |
|
||||
| `packages/db_helper_postgres/src/db/schema.ts` | Mirror the intended ownership model where this helper remains supported, using PostgreSQL-appropriate types and constraints. |
|
||||
| SQLite migration output directory configured by `packages/db_helper_sqlite/drizzle.config.ts` | **New migration:** create and seed Mahabubnagar, exact GeoJSON bounds, existing bound settings, and bootstrap superadmin; backfill existing regional data and enforce constraints. Prepare only; do not execute. |
|
||||
| `packages/db_helper_sqlite/index.ts` | Export new regional/superadmin helpers and schema definitions through the package entry point. |
|
||||
| `packages/db_helper_sqlite/src/admin-apis/*.ts` | Accept trusted staff-region scope; constrain lists, ID lookups, writes, aggregates, and related records. Restrict user visibility by regional orders. |
|
||||
| `packages/db_helper_sqlite/src/user-apis/*.ts` | Scope catalog and checkout helpers; save address/order regions; preserve all-region user history while enforcing user ownership. |
|
||||
| `packages/db_helper_sqlite/src/helper_methods/upload-url.ts` | Audit upload authorization where an upload is tied to regional records; prevent ID-based authorization gaps. |
|
||||
| `packages/db_helper_sqlite/src/lib/*.ts` | Audit cache data readers, seed helpers, automated jobs, and order deletion for explicit regional scope. |
|
||||
| `packages/db_helper_sqlite/src/superadmin-apis/regions.ts` — **New** | Region and bound persistence, priority validation, and effective-bound selection. |
|
||||
| `packages/db_helper_sqlite/src/superadmin-apis/auth.ts` — **New** | Superadmin lookup and password verification support; never expose hashes. |
|
||||
| `packages/db_helper_sqlite/src/superadmin-apis/staff.ts` — **New** | Create/manage staff accounts and validate assigned region. |
|
||||
| `packages/shared/types/region.types.ts` — **New** | Region, bound, bound-settings, and effective-settings DTOs and inputs. |
|
||||
| `packages/shared/types/superadmin.types.ts` — **New** | Public superadmin identity and management contracts without password hashes. |
|
||||
| `packages/shared/types/staff-user.types.ts`, `admin.ts`, `inputs.types.ts` | Staff region and scoped administration contracts; separate staff creation from regional admin operations. |
|
||||
| `packages/shared/types/user.ts`, `order.types.ts` | Address region and order region labels; retain all-region history response support. |
|
||||
| `packages/shared/types/cache.types.ts`, `const.types.ts`, `app-common.types.ts` | Regional cache discovery/version contracts and effective bound business settings. |
|
||||
| `packages/shared/types/index.ts`, `packages/shared/index.ts` | Export new and updated shared contracts. |
|
||||
|
||||
### 14.2 Backend authentication and API channels
|
||||
|
||||
| File / directory | Planned change |
|
||||
| --- | --- |
|
||||
| `apps/backend/src/app.ts` | Resolve distinct user/staff/superadmin identities; include trusted staff region in context; audit legacy route mounting and token validation. |
|
||||
| `apps/backend/src/trpc/trpc-index.ts` | Define identity-specific procedures and trusted regional context; do not authorize all channels through the current generic user-or-staff guard. |
|
||||
| `apps/backend/src/trpc/router.ts` | Register `superadmin` alongside existing channels; update inferred regional payload contracts. |
|
||||
| `apps/backend/src/trpc/apis/superadmin-apis/superadmin-trpc-index.ts` — **New** | Aggregate superadmin auth, region/bounds, and staff-management routers. |
|
||||
| `apps/backend/src/trpc/apis/superadmin-apis/auth.ts` — **New** | Separate superadmin login/session APIs and explicitly typed tokens. |
|
||||
| `apps/backend/src/trpc/apis/superadmin-apis/regions.ts` — **New** | Region create/list/detail/update and bound management; no region deletion. |
|
||||
| `apps/backend/src/trpc/apis/superadmin-apis/staff.ts` — **New** | Superadmin-only staff account creation and region assignment. |
|
||||
| `apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts` | Register bound-settings APIs and ensure all child routers use staff-only authorization. |
|
||||
| `apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts` | Remove regional staff-account creation authority; scope remaining staff visibility and authentication appropriately. |
|
||||
| `apps/backend/src/trpc/apis/admin-apis/apis/product.ts`, `store.ts`, `vendor-snippets.ts` | Use trusted region for catalog ownership; validate same-region relationships, including tag/group/snippet mappings. |
|
||||
| `apps/backend/src/trpc/apis/admin-apis/apis/order.ts`, `slots.ts`, `payments.ts` | Scope orders, slot management, packaging, cancellations, and financial actions to staff region. |
|
||||
| `apps/backend/src/trpc/apis/admin-apis/apis/user.ts`, `complaint.ts` | Filter user access through regional orders and prevent cross-region history/aggregate disclosure; audit account-global actions. |
|
||||
| `apps/backend/src/trpc/apis/admin-apis/apis/banner.ts`, `coupon.ts`, `const.ts` | Scope banners/coupons; move delivery business settings out of global constants while retaining genuinely global configuration. |
|
||||
| `apps/backend/src/trpc/apis/admin-apis/apis/region-settings.ts` — **New** | Read/edit all bound settings in the authenticated staff region; return the effective lowest-priority bound. |
|
||||
| `apps/backend/src/trpc/apis/user-apis/apis/address.ts` | Require and validate address region; do not require coordinate containment. |
|
||||
| `apps/backend/src/trpc/apis/user-apis/apis/order.ts`, `payments.ts`, `cart.ts`, `coupon.ts` | Validate a consistent checkout region, apply lowest-priority-bound settings, and reject stale/mixed-region checkout requests. |
|
||||
| `apps/backend/src/trpc/apis/user-apis/apis/product.ts`, `slots.ts`, `stores.ts`, `banners.ts` | Require validated browsing region for regional data and scaffold operations. |
|
||||
| `apps/backend/src/trpc/apis/common-apis/common.ts`, `common-trpc-index.ts` | Regionalize catalog/config scaffolds and add public region discovery. |
|
||||
| `apps/backend/src/dbService.ts`, `sqliteImporter.ts` | Re-export regional and superadmin persistence helpers without changing the active DB selection. |
|
||||
| `apps/backend/src/main-router.ts`, `v1-router.ts`, `apis/` | Audit legacy REST entry points and enforce equivalent identity/region checks; do not leave unscoped bypasses. |
|
||||
|
||||
### 14.3 Generated files and background processing
|
||||
|
||||
| File / directory | Planned change |
|
||||
| --- | --- |
|
||||
| `apps/backend/src/lib/cloud_cache.ts` | Add region IDs to scaffold calls, object paths, metadata, and purge URLs; support all-region and targeted regeneration. |
|
||||
| `apps/backend/src/lib/gen-store.ts` | Namespace generated version metadata/KV mirrors by region and publish region-aware discovery. |
|
||||
| `apps/backend/src/stores/` | Audit in-memory data caches; key regional state by region rather than keeping one global regional snapshot. |
|
||||
| `apps/backend/src/jobs/cache-creator.ts` | Schedule/coordinate regeneration per region and include regional settings data. |
|
||||
| `apps/backend/src/jobs/`, `apps/backend/src/lib/flash-delivery-cron.ts` | Make delivery/availability jobs iterate or explicitly target regions; use effective bound settings. |
|
||||
| `apps/backend/src/lib/queue-data-pusher.ts`, `queue-consumer.ts`, `post-order-handler.ts`, `notif-job.ts` | Carry or resolve region from the order; avoid cross-region operational reads/recipients. |
|
||||
| `apps/backend/src/lib/worker-init.ts`, `apps/backend/worker.ts` | Audit worker/durable-object initialization and job entry points; never use one mutable global browsing region. |
|
||||
| `apps/backend/src/map-assets/Mbnr-1.geojson`, `Mbnr-2.geojson` | Use exact contents as migration seed inputs. No geometry edits planned. |
|
||||
| `apps/backend/src/lib/mbnr-geojson.ts`, `apps/backend/src/map-assets/mbnr-1.ts` | Audit hard-coded geography consumers; replace assumptions where they should use persisted regional bounds. |
|
||||
|
||||
### 14.4 Superadmin UI
|
||||
|
||||
| File / directory | Planned change |
|
||||
| --- | --- |
|
||||
| `apps/superadmin-ui/src/lib/auth-context.tsx` | Authenticate and persist the separate superadmin identity/session rather than a staff identity. |
|
||||
| `apps/superadmin-ui/src/lib/trpc-client.ts` | Send superadmin session credentials and consume new channel contracts. |
|
||||
| `apps/superadmin-ui/src/routes/login.tsx` | Use superadmin username/password login. |
|
||||
| `apps/superadmin-ui/src/routes/__root.tsx`, `dashboard.tsx` | Add region/staff navigation and authenticated superadmin layout integration. |
|
||||
| `apps/superadmin-ui/src/routes/regions.tsx` — **New** | Region list/create/edit and bounds management, including GeoJSON and unique priority validation. |
|
||||
| `apps/superadmin-ui/src/routes/staff.tsx` — **New** | Staff account creation/management with required region assignment. |
|
||||
| `apps/superadmin-ui/src/routes/constants.tsx`, `send-notifications.tsx` | Audit existing privileged operations and move them to appropriately authorized superadmin endpoints where retained. |
|
||||
| `apps/superadmin-ui/src/routeTree.gen.ts` | Regenerate using the app's routing workflow after adding routes; do not hand-maintain generated output. |
|
||||
|
||||
### 14.5 Admin UI
|
||||
|
||||
| File / directory | Planned change |
|
||||
| --- | --- |
|
||||
| `apps/admin-ui/components/context/staff-auth-context.tsx` | Include assigned region in the authenticated staff profile/session. |
|
||||
| `apps/admin-ui/src/trpc-client.ts` | Consume updated identity/contracts; invalidate stale session-scoped data when necessary. |
|
||||
| `apps/admin-ui/app/(drawer)/` layouts and dashboard navigation | Display assigned region; retain existing Customize App navigation and remove staff-account creation access. |
|
||||
| `apps/admin-ui/app/(drawer)/dashboard/manage-orders/orders/index.tsx` | Consume region-scoped order data and retain item packaging behavior. |
|
||||
| `apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx` | Handle scoped order lookups/actions and inaccessible records. |
|
||||
| `apps/admin-ui/app/(drawer)/dashboard/manage-orders/delivery-sequences/index.tsx` | Use only assigned-region slots/orders/staff. |
|
||||
| `apps/admin-ui/app/(drawer)/dashboard/user-management/[id].tsx` | Display only regional user-order history and aggregates. |
|
||||
| `apps/admin-ui/app/(drawer)/dashboard/vendor-snippets/index.tsx` | Consume scoped snippets and same-region SKU/order selections. |
|
||||
| Other catalog, stores, tags, groups, coupons, banners, user lists, complaints, and staff dashboard files | Update changed contracts/selectors; rely on backend isolation rather than passing arbitrary region overrides. Audit actual screen files before edits. |
|
||||
| `apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx` | Replace the single global constants form with bound tabs, sorted by ascending priority. Fetch/save constants for the selected bound, retain reusable input controls, and identify the effective lowest-priority bound. Isolate drafts by bound and confirm before discarding unsaved edits. |
|
||||
|
||||
### 14.6 User UI
|
||||
|
||||
| File / directory | Planned change |
|
||||
| --- | --- |
|
||||
| `apps/user-ui/src/store/regionStore.ts` — **New** | Persist browsing region and coordinate confirmed switching, complete cart reset, and regional state invalidation. |
|
||||
| `apps/user-ui/src/components/RegionSelector.tsx` — **New** | Startup selection and later region-switch UI with confirmation/cancel behavior. |
|
||||
| `apps/user-ui/app/_layout.tsx` | Integrate saved-region validation and startup gating without blocking public region discovery. |
|
||||
| `apps/user-ui/src/contexts/AuthContext.tsx` | Keep browsing-region selection separate from user identity; coordinate session/state resets where required. |
|
||||
| `apps/user-ui/src/trpc-client.ts`, `utils/queryClient.ts` | Update regional request contracts and query-cache handling; include region in relevant query keys. |
|
||||
| `apps/user-ui/src/store/centralProductStore.ts`, `centralSlotStore.ts`, `appStore.ts` | Fetch regional generated URLs/configuration and clear or namespace cached regional snapshots. |
|
||||
| `apps/user-ui/src/store/cartStore.ts`, `flashCartStore.ts`, `quickDeliveryStore.ts` | Reset all normal/flash/quick-delivery cart and derived checkout state on confirmed switching. |
|
||||
| `apps/user-ui/hooks/cart-query-hooks.tsx` | Prevent stale cart queries/mutations from repopulating the previous region after a switch. |
|
||||
| `apps/user-ui/src/store/addressStore.ts` | Carry address region metadata and preserve explicitly selected address ownership. |
|
||||
| `apps/user-ui/src/components/AddressForm.tsx` | Required region dropdown; browsing-region default for new addresses only. |
|
||||
| `apps/user-ui/components/CheckoutAddressSelector.tsx`, `QuickDeliveryAddressSelector.tsx` | Confirm different-region address selection; switch, clear state, and navigate home only after confirmation. |
|
||||
| `apps/user-ui/components/checkout-page.tsx`, `PaymentAndOrderComponent.tsx` | Consume effective bound settings, submit consistent regional checkout data, and block stale/in-flight actions after switching. |
|
||||
| `apps/user-ui/components/SlotSpecificView.tsx`, `ProductCard.tsx`, `ProductDetail.tsx`, `components/stores/` | Consume region-specific catalog/availability/slot data and avoid stale cross-region selections. |
|
||||
| `apps/user-ui/src/types/orders.ts` | Include order-region identity/labels in the UI view model. |
|
||||
| `apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx`, `[id].tsx` | Preserve all-region history and add region labels to orders/details. |
|
||||
| `apps/user-ui/components/NextOrderGlimpse.tsx` | Preserve account-wide upcoming orders and identify their regions. |
|
||||
| Region-switch entry points in tab/drawer/home layouts | Add access to the selector and show current browsing region; enumerate actual layouts during implementation. |
|
||||
|
||||
### 14.7 Validation and documentation
|
||||
|
||||
| File / directory | Planned change |
|
||||
| --- | --- |
|
||||
| `apps/backend/tests/` | Add/update fixtures and checks for region isolation, identity separation, backfill assumptions, priority settings, mixed-region checkout, and all-region history. Execute only if explicitly requested. |
|
||||
| `apps/admin-ui/tests/`, `apps/user-ui/tests/` | Update regional fixtures and add region switching, address selection, history labels, and admin access UI checks. Execute only if explicitly requested. |
|
||||
| `docs/regions-proposal.md` | Keep agreed design and implementation map current if requirements change. |
|
||||
| `change-log.txt` | Before each non-Markdown/non-text edit, record the exact planned diff with a current timestamp per repository instructions. |
|
||||
|
||||
Build outputs such as `dist/`, dependency folders, and local worker database state are not manual-edit targets. Migration execution remains the user's responsibility.
|
||||
|
|
@ -1,4 +1,23 @@
|
|||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"permission": "allow"
|
||||
"permission": "allow",
|
||||
"mcp": {
|
||||
"servers": {
|
||||
"maestro": {
|
||||
"type": "local",
|
||||
"command": [
|
||||
"maestro",
|
||||
"mcp"
|
||||
]
|
||||
},
|
||||
"playwright": {
|
||||
"type": "local",
|
||||
"command": [
|
||||
"npx",
|
||||
"-y",
|
||||
"@playwright/mcp"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,103 @@
|
|||
-- 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');
|
||||
|
|
@ -0,0 +1,744 @@
|
|||
-- 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`);
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
-- 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`);
|
||||
|
|
@ -43,6 +43,27 @@
|
|||
"when": 1790926061639,
|
||||
"tag": "0005_order_timestamps",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 6,
|
||||
"version": "6",
|
||||
"when": 1791367872000,
|
||||
"tag": "0006_regions_and_superadmins",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 7,
|
||||
"version": "6",
|
||||
"when": 1791368000000,
|
||||
"tag": "0007_region_columns_backfill",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 8,
|
||||
"version": "6",
|
||||
"when": 1791374400000,
|
||||
"tag": "0008_region_cache_versions",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -117,6 +117,9 @@ export {
|
|||
checkStaffUserExists,
|
||||
checkStaffRoleExists,
|
||||
createStaffUser,
|
||||
createStaffUserWithRegion,
|
||||
updateStaffUserRegion,
|
||||
deleteStaffUser,
|
||||
getAllRoles,
|
||||
getStaffNotifCred,
|
||||
upsertStaffNotifCred,
|
||||
|
|
@ -324,6 +327,14 @@ export {
|
|||
getAllKeyValStore,
|
||||
} from './src/lib/automated-jobs'
|
||||
|
||||
// Per-Region Cache Version Helpers
|
||||
export {
|
||||
getRegionCacheVersions,
|
||||
incrementRegionCacheVersion,
|
||||
incrementRegionAvailabilityVersionNum,
|
||||
incrementRegionSlotsVersionNum,
|
||||
} from './src/lib/region-cache-versions'
|
||||
|
||||
// Health Check
|
||||
export {
|
||||
healthCheck,
|
||||
|
|
@ -333,6 +344,8 @@ export {
|
|||
export {
|
||||
getSuspendedSkuIds,
|
||||
getNextDeliveryDateWithCapacity,
|
||||
getSkuRegionId,
|
||||
getSkuRegionIds,
|
||||
} from './src/user-apis/product'
|
||||
|
||||
export {
|
||||
|
|
@ -369,3 +382,24 @@ export {
|
|||
type StaffRoleName,
|
||||
type StaffPermissionName,
|
||||
} from './src/lib/seed'
|
||||
|
||||
// Superadmin / Region Helpers
|
||||
export {
|
||||
getSuperadminByUsername,
|
||||
getSuperadminById,
|
||||
} from './src/superadmin-apis/auth'
|
||||
|
||||
export {
|
||||
getAllRegions,
|
||||
getRegionById,
|
||||
getRegionWithBounds,
|
||||
createRegion,
|
||||
updateRegion,
|
||||
getBoundsForRegion,
|
||||
getBoundById,
|
||||
createRegionBound,
|
||||
updateRegionBound,
|
||||
getBoundSettings,
|
||||
upsertBoundSettings,
|
||||
getEffectiveRegionSettings,
|
||||
} from './src/superadmin-apis/regions'
|
||||
|
|
|
|||
|
|
@ -1,12 +1,31 @@
|
|||
import { db } from '../db/db_index'
|
||||
import { homeBanners, staffUsers } from '../db/schema'
|
||||
import { eq, desc } from 'drizzle-orm'
|
||||
import { homeBanners, productSkus } from '../db/schema'
|
||||
import { eq, desc, and, inArray } from 'drizzle-orm'
|
||||
import type { Banner, CreateBannerInput, UpdateBannerInput } from '@packages/shared'
|
||||
|
||||
const assertBannerSkuIdsInRegion = async (txOrDb: any, skuIds: number[], regionId: number): Promise<void> => {
|
||||
const unique = [...new Set((skuIds || []).map(Number).filter((n) => Number.isFinite(n)))]
|
||||
if (unique.length === 0) return
|
||||
const rows = await txOrDb.query.productSkus.findMany({
|
||||
where: inArray(productSkus.id, unique),
|
||||
with: { product: { columns: { regionId: true } } },
|
||||
columns: { id: true },
|
||||
})
|
||||
if (rows.length !== unique.length) {
|
||||
const found = new Set(rows.map((r: { id: number }) => r.id))
|
||||
throw new Error(`Invalid SKU IDs: ${unique.filter((id) => !found.has(id)).join(', ')}`)
|
||||
}
|
||||
const foreign = rows.filter((r: any) => r.product?.regionId !== regionId)
|
||||
if (foreign.length > 0) {
|
||||
throw new Error(`SKU ${foreign.map((r: any) => r.id).join(', ')} belongs to a different region`)
|
||||
}
|
||||
}
|
||||
|
||||
type BannerRow = typeof homeBanners.$inferSelect
|
||||
|
||||
export async function getBanners(): Promise<Banner[]> {
|
||||
export async function getBanners(regionId: number): Promise<Banner[]> {
|
||||
const banners = await db.query.homeBanners.findMany({
|
||||
where: eq(homeBanners.regionId, regionId),
|
||||
orderBy: desc(homeBanners.createdAt),
|
||||
}) as BannerRow[]
|
||||
|
||||
|
|
@ -24,9 +43,9 @@ export async function getBanners(): Promise<Banner[]> {
|
|||
}))
|
||||
}
|
||||
|
||||
export async function getBannerById(id: number): Promise<Banner | null> {
|
||||
export async function getBannerById(regionId: number, id: number): Promise<Banner | null> {
|
||||
const banner = await db.query.homeBanners.findFirst({
|
||||
where: eq(homeBanners.id, id),
|
||||
where: and(eq(homeBanners.id, id), eq(homeBanners.regionId, regionId)),
|
||||
})
|
||||
|
||||
if (!banner) return null
|
||||
|
|
@ -45,8 +64,11 @@ export async function getBannerById(id: number): Promise<Banner | null> {
|
|||
}
|
||||
}
|
||||
|
||||
export async function createBanner(input: CreateBannerInput): Promise<Banner> {
|
||||
export async function createBanner(input: CreateBannerInput, regionId: number): Promise<Banner> {
|
||||
await assertBannerSkuIdsInRegion(db, input.skuIds || [], regionId)
|
||||
|
||||
const [banner] = await db.insert(homeBanners).values({
|
||||
regionId,
|
||||
name: input.name,
|
||||
imageUrl: input.imageUrl,
|
||||
description: input.description,
|
||||
|
|
@ -70,15 +92,23 @@ export async function createBanner(input: CreateBannerInput): Promise<Banner> {
|
|||
}
|
||||
}
|
||||
|
||||
export async function updateBanner(id: number, input: UpdateBannerInput): Promise<Banner> {
|
||||
export async function updateBanner(regionId: number, id: number, input: UpdateBannerInput): Promise<Banner | null> {
|
||||
if (input.skuIds !== undefined) {
|
||||
await assertBannerSkuIdsInRegion(db, input.skuIds ?? [], regionId)
|
||||
}
|
||||
|
||||
const [banner] = await db.update(homeBanners)
|
||||
.set({
|
||||
...input,
|
||||
lastUpdated: new Date(),
|
||||
})
|
||||
.where(eq(homeBanners.id, id))
|
||||
.where(and(eq(homeBanners.id, id), eq(homeBanners.regionId, regionId)))
|
||||
.returning()
|
||||
|
||||
if (!banner) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
id: banner.id,
|
||||
name: banner.name,
|
||||
|
|
@ -93,6 +123,9 @@ export async function updateBanner(id: number, input: UpdateBannerInput): Promis
|
|||
}
|
||||
}
|
||||
|
||||
export async function deleteBanner(id: number): Promise<void> {
|
||||
await db.delete(homeBanners).where(eq(homeBanners.id, id))
|
||||
export async function deleteBanner(regionId: number, id: number): Promise<boolean> {
|
||||
const [deleted] = await db.delete(homeBanners)
|
||||
.where(and(eq(homeBanners.id, id), eq(homeBanners.regionId, regionId)))
|
||||
.returning({ id: homeBanners.id })
|
||||
return !!deleted
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,22 +1,44 @@
|
|||
import { db } from '../db/db_index'
|
||||
import { complaints, users } from '../db/schema'
|
||||
import { eq, desc, lt } from 'drizzle-orm'
|
||||
import { complaints, orders, users } from '../db/schema'
|
||||
import { eq, desc, lt, and, or, isNull } from 'drizzle-orm'
|
||||
import type { Complaint, ComplaintWithUser } from '@packages/shared'
|
||||
|
||||
|
||||
export async function getComplaintById(id: number): Promise<Complaint | null> {
|
||||
export async function getComplaintById(regionId: number, id: number): Promise<Complaint | null> {
|
||||
const complaint = await db.query.complaints.findFirst({
|
||||
where: eq(complaints.id, id),
|
||||
})
|
||||
|
||||
return complaint ?? null
|
||||
if (!complaint) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (complaint.orderId == null) {
|
||||
return complaint
|
||||
}
|
||||
|
||||
const [order] = await db
|
||||
.select({ regionId: orders.regionId })
|
||||
.from(orders)
|
||||
.where(eq(orders.id, complaint.orderId))
|
||||
.limit(1)
|
||||
|
||||
if (!order || order.regionId !== regionId) {
|
||||
return null
|
||||
}
|
||||
|
||||
return complaint
|
||||
}
|
||||
|
||||
export async function getComplaints(
|
||||
regionId: number,
|
||||
cursor?: number,
|
||||
limit: number = 20
|
||||
): Promise<{ complaints: ComplaintWithUser[]; hasMore: boolean }> {
|
||||
const whereCondition = cursor ? lt(complaints.id, cursor) : undefined
|
||||
const regionCondition = or(isNull(complaints.orderId), eq(orders.regionId, regionId))
|
||||
const whereCondition = cursor
|
||||
? and(lt(complaints.id, cursor), regionCondition)
|
||||
: regionCondition
|
||||
|
||||
const complaintsData = await db
|
||||
.select({
|
||||
|
|
@ -33,6 +55,7 @@ export async function getComplaints(
|
|||
})
|
||||
.from(complaints)
|
||||
.leftJoin(users, eq(complaints.userId, users.id))
|
||||
.leftJoin(orders, eq(complaints.orderId, orders.id))
|
||||
.where(whereCondition)
|
||||
.orderBy(desc(complaints.id))
|
||||
.limit(limit + 1)
|
||||
|
|
@ -58,11 +81,33 @@ export async function getComplaints(
|
|||
}
|
||||
|
||||
export async function resolveComplaint(
|
||||
regionId: number,
|
||||
id: number,
|
||||
response?: string
|
||||
): Promise<void> {
|
||||
): Promise<boolean> {
|
||||
// Same region pattern as getComplaintById: orderless complaints are visible
|
||||
// to every region; order-backed ones only to the order's region.
|
||||
const complaint = await db.query.complaints.findFirst({
|
||||
where: eq(complaints.id, id),
|
||||
})
|
||||
if (!complaint) {
|
||||
return false
|
||||
}
|
||||
if (complaint.orderId != null) {
|
||||
const [order] = await db
|
||||
.select({ regionId: orders.regionId })
|
||||
.from(orders)
|
||||
.where(eq(orders.id, complaint.orderId))
|
||||
.limit(1)
|
||||
if (!order || order.regionId !== regionId) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
await db
|
||||
.update(complaints)
|
||||
.set({ isResolved: true, response })
|
||||
.where(eq(complaints.id, id))
|
||||
|
||||
return true
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,37 @@
|
|||
import { db } from '../db/db_index'
|
||||
import { coupons, reservedCoupons, users, orders, orderStatus, couponApplicableUsers, couponApplicableProducts } from '../db/schema'
|
||||
import { eq, and, like, or, inArray, lt, desc, asc } from 'drizzle-orm'
|
||||
import { coupons, reservedCoupons, users, orders, orderStatus, couponApplicableUsers, couponApplicableProducts, productSkus } from '../db/schema'
|
||||
import { eq, and, like, or, inArray, lt, desc, asc, sql, SQL } from 'drizzle-orm'
|
||||
import type { Coupon, CouponFormInput, CouponValidationResult, UserMiniInfo } from '@packages/shared'
|
||||
|
||||
const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regionId: number): Promise<void> => {
|
||||
const unique = [...new Set((skuIds || []).map(Number).filter((n) => Number.isFinite(n)))]
|
||||
if (unique.length === 0) return
|
||||
const rows = await txOrDb.query.productSkus.findMany({
|
||||
where: inArray(productSkus.id, unique),
|
||||
with: { product: { columns: { regionId: true } } },
|
||||
columns: { id: true },
|
||||
})
|
||||
if (rows.length !== unique.length) {
|
||||
const found = new Set(rows.map((r: { id: number }) => r.id))
|
||||
throw new Error(`Invalid SKU IDs: ${unique.filter((id) => !found.has(id)).join(', ')}`)
|
||||
}
|
||||
const foreign = rows.filter((r: any) => r.product?.regionId !== regionId)
|
||||
if (foreign.length > 0) {
|
||||
throw new Error(`SKU ${foreign.map((r: any) => r.id).join(', ')} belongs to a different region`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAllCoupons(
|
||||
regionId: number,
|
||||
cursor?: number,
|
||||
limit: number = 50,
|
||||
search?: string
|
||||
): Promise<{ coupons: any[]; hasMore: boolean }> {
|
||||
let whereCondition = undefined
|
||||
const conditions = []
|
||||
|
||||
|
||||
conditions.push(eq(coupons.regionId, regionId))
|
||||
|
||||
if (cursor) {
|
||||
conditions.push(lt(coupons.id, cursor))
|
||||
}
|
||||
|
|
@ -50,9 +71,12 @@ export async function getAllCoupons(
|
|||
return { coupons: couponsList, hasMore }
|
||||
}
|
||||
|
||||
export async function getCouponById(id: number): Promise<any | null> {
|
||||
export async function getCouponById(regionId: number, id: number): Promise<any | null> {
|
||||
return await db.query.coupons.findFirst({
|
||||
where: eq(coupons.id, id),
|
||||
where: and(
|
||||
eq(coupons.id, id),
|
||||
eq(coupons.regionId, regionId)
|
||||
),
|
||||
with: {
|
||||
creator: true,
|
||||
applicableUsers: {
|
||||
|
|
@ -73,11 +97,15 @@ export async function getCouponById(id: number): Promise<any | null> {
|
|||
|
||||
export async function createCouponWithRelations(
|
||||
input: CouponFormInput,
|
||||
applicableUsers?: number[],
|
||||
applicableProducts?: number[]
|
||||
applicableUsers: number[] | undefined,
|
||||
applicableProducts: number[] | undefined,
|
||||
regionId: number
|
||||
): Promise<Coupon> {
|
||||
await assertApplicableSkusInRegion(db, applicableProducts || [], regionId)
|
||||
|
||||
return await db.transaction(async (tx) => {
|
||||
const [coupon] = await tx.insert(coupons).values({
|
||||
regionId,
|
||||
couponCode: input.couponCode,
|
||||
isUserBased: input.isUserBased,
|
||||
discountPercent: input.discountPercent,
|
||||
|
|
@ -116,11 +144,23 @@ export async function createCouponWithRelations(
|
|||
}
|
||||
|
||||
export async function updateCouponWithRelations(
|
||||
regionId: number,
|
||||
id: number,
|
||||
input: CouponFormInput,
|
||||
applicableUsers?: number[],
|
||||
applicableProducts?: number[]
|
||||
): Promise<Coupon> {
|
||||
): Promise<Coupon | null> {
|
||||
const existing = await db.query.coupons.findFirst({
|
||||
where: and(eq(coupons.id, id), eq(coupons.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
})
|
||||
if (!existing) {
|
||||
return null
|
||||
}
|
||||
if (applicableProducts !== undefined) {
|
||||
await assertApplicableSkusInRegion(db, applicableProducts, regionId)
|
||||
}
|
||||
|
||||
return await db.transaction(async (tx) => {
|
||||
// createdBy is always sent (complete payload) but never rewritten on update
|
||||
const { createdBy: _createdBy, ...updateFields } = input
|
||||
|
|
@ -129,7 +169,7 @@ export async function updateCouponWithRelations(
|
|||
.set({
|
||||
...updateFields,
|
||||
})
|
||||
.where(eq(coupons.id, id))
|
||||
.where(and(eq(coupons.id, id), eq(coupons.regionId, regionId)))
|
||||
.returning()
|
||||
|
||||
if (applicableUsers !== undefined) {
|
||||
|
|
@ -160,23 +200,26 @@ export async function updateCouponWithRelations(
|
|||
})
|
||||
}
|
||||
|
||||
export async function invalidateCoupon(id: number): Promise<Coupon> {
|
||||
export async function invalidateCoupon(regionId: number, id: number): Promise<Coupon | null> {
|
||||
const result = await db.update(coupons)
|
||||
.set({ isInvalidated: true })
|
||||
.where(eq(coupons.id, id))
|
||||
.where(and(eq(coupons.id, id), eq(coupons.regionId, regionId)))
|
||||
.returning()
|
||||
|
||||
return result[0] as Coupon
|
||||
return (result[0] ?? null) as Coupon | null
|
||||
}
|
||||
|
||||
export async function getReservedCoupons(
|
||||
regionId: number,
|
||||
cursor?: number,
|
||||
limit: number = 50,
|
||||
search?: string
|
||||
): Promise<{ coupons: any[]; hasMore: boolean }> {
|
||||
let whereCondition = undefined
|
||||
const conditions = []
|
||||
|
||||
|
||||
conditions.push(eq(reservedCoupons.regionId, regionId))
|
||||
|
||||
if (cursor) {
|
||||
conditions.push(lt(reservedCoupons.id, cursor))
|
||||
}
|
||||
|
|
@ -210,10 +253,14 @@ export async function getReservedCoupons(
|
|||
|
||||
export async function createReservedCouponWithProducts(
|
||||
input: any,
|
||||
applicableProducts?: number[]
|
||||
applicableProducts: number[] | undefined,
|
||||
regionId: number
|
||||
): Promise<any> {
|
||||
await assertApplicableSkusInRegion(db, applicableProducts || [], regionId)
|
||||
|
||||
return await db.transaction(async (tx) => {
|
||||
const [coupon] = await tx.insert(reservedCoupons).values({
|
||||
regionId,
|
||||
secretCode: input.secretCode,
|
||||
couponCode: input.couponCode,
|
||||
discountPercent: input.discountPercent,
|
||||
|
|
@ -268,13 +315,26 @@ export async function generateCancellationCoupon(
|
|||
staffUserId: number,
|
||||
userId: number,
|
||||
orderAmount: number,
|
||||
couponCode: string
|
||||
couponCode: string,
|
||||
regionId: number
|
||||
): Promise<Coupon> {
|
||||
const order = await db.query.orders.findFirst({
|
||||
where: eq(orders.id, orderId),
|
||||
columns: { id: true, regionId: true },
|
||||
})
|
||||
if (!order) {
|
||||
throw new Error('Order not found')
|
||||
}
|
||||
if (order.regionId !== regionId) {
|
||||
throw new Error('Order belongs to a different region')
|
||||
}
|
||||
|
||||
return await db.transaction(async (tx) => {
|
||||
const expiryDate = new Date()
|
||||
expiryDate.setDate(expiryDate.getDate() + 30)
|
||||
|
||||
const [coupon] = await tx.insert(coupons).values({
|
||||
regionId,
|
||||
couponCode,
|
||||
isUserBased: true,
|
||||
flatDiscount: orderAmount.toString(),
|
||||
|
|
@ -299,9 +359,12 @@ export async function generateCancellationCoupon(
|
|||
})
|
||||
}
|
||||
|
||||
export async function getOrderWithUser(orderId: number): Promise<any | null> {
|
||||
export async function getOrderWithUser(regionId: number, orderId: number): Promise<any | null> {
|
||||
return await db.query.orders.findFirst({
|
||||
where: eq(orders.id, orderId),
|
||||
where: and(
|
||||
eq(orders.id, orderId),
|
||||
eq(orders.regionId, regionId)
|
||||
),
|
||||
with: {
|
||||
user: true,
|
||||
},
|
||||
|
|
@ -311,7 +374,8 @@ export async function getOrderWithUser(orderId: number): Promise<any | null> {
|
|||
export async function createCouponForUser(
|
||||
mobile: string,
|
||||
couponCode: string,
|
||||
staffUserId: number
|
||||
staffUserId: number,
|
||||
regionId: number
|
||||
): Promise<{ coupon: Coupon; user: { id: number; mobile: string; name: string | null } }> {
|
||||
return await db.transaction(async (tx) => {
|
||||
let user = await tx.query.users.findFirst({
|
||||
|
|
@ -328,6 +392,7 @@ export async function createCouponForUser(
|
|||
}
|
||||
|
||||
const [coupon] = await tx.insert(coupons).values({
|
||||
regionId,
|
||||
couponCode,
|
||||
isUserBased: true,
|
||||
discountPercent: '20',
|
||||
|
|
@ -357,15 +422,19 @@ export async function createCouponForUser(
|
|||
}
|
||||
|
||||
export async function getUsersForCoupon(
|
||||
regionId: number,
|
||||
search?: string,
|
||||
limit: number = 20,
|
||||
offset: number = 0
|
||||
): Promise<{ users: UserMiniInfo[] }> {
|
||||
let whereCondition = undefined
|
||||
let whereCondition: SQL<unknown> | undefined = sql`EXISTS (SELECT 1 FROM ${orders} WHERE ${orders.userId} = ${users.id} AND ${orders.regionId} = ${regionId})`
|
||||
if (search && search.trim()) {
|
||||
whereCondition = or(
|
||||
like(users.name, `%${search}%`),
|
||||
like(users.mobile, `%${search}%`)
|
||||
whereCondition = and(
|
||||
whereCondition,
|
||||
or(
|
||||
like(users.name, `%${search}%`),
|
||||
like(users.mobile, `%${search}%`)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import {
|
|||
addresses,
|
||||
complaints,
|
||||
couponUsage,
|
||||
deliverySlotInfo,
|
||||
orderItems,
|
||||
orders,
|
||||
orderStatus,
|
||||
|
|
@ -57,18 +58,26 @@ const mapOrderStatusRecord = (record: OrderStatusRow): AdminOrderStatusRecord =>
|
|||
refundCouponId: record.refundCouponId ?? null,
|
||||
})
|
||||
|
||||
export async function updateOrderNotes(orderId: number, adminNotes: string | null): Promise<AdminOrderRow | null> {
|
||||
export async function updateOrderNotes(regionId: number, orderId: number, adminNotes: string | null): Promise<AdminOrderRow | null> {
|
||||
const [result] = await db
|
||||
.update(orders)
|
||||
.set({ adminNotes })
|
||||
.where(eq(orders.id, orderId))
|
||||
.where(and(eq(orders.id, orderId), eq(orders.regionId, regionId)))
|
||||
.returning()
|
||||
return (result || null) as AdminOrderRow | null
|
||||
}
|
||||
|
||||
export async function updateOrderPackaged(orderId: string, isPackaged: boolean): Promise<AdminOrderUpdateResult> {
|
||||
export async function updateOrderPackaged(regionId: number, orderId: string, isPackaged: boolean): Promise<AdminOrderUpdateResult | null> {
|
||||
const orderIdNumber = parseInt(orderId)
|
||||
|
||||
const orderCheck = await db.query.orders.findFirst({
|
||||
where: and(eq(orders.id, orderIdNumber), eq(orders.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
})
|
||||
if (!orderCheck) {
|
||||
return null
|
||||
}
|
||||
|
||||
await db
|
||||
.update(orderItems)
|
||||
.set({ is_packaged: isPackaged })
|
||||
|
|
@ -87,31 +96,42 @@ export async function updateOrderPackaged(orderId: string, isPackaged: boolean):
|
|||
}
|
||||
|
||||
const order = await db.query.orders.findFirst({
|
||||
where: eq(orders.id, orderIdNumber),
|
||||
where: and(eq(orders.id, orderIdNumber), eq(orders.regionId, regionId)),
|
||||
})
|
||||
|
||||
return { success: true, userId: order?.userId ?? null }
|
||||
}
|
||||
|
||||
export async function updateOrderDelivered(orderId: string, isDelivered: boolean): Promise<AdminOrderUpdateResult> {
|
||||
export async function updateOrderDelivered(regionId: number, orderId: string, isDelivered: boolean): Promise<AdminOrderUpdateResult | null> {
|
||||
const orderIdNumber = parseInt(orderId)
|
||||
|
||||
const orderCheck = await db.query.orders.findFirst({
|
||||
where: and(eq(orders.id, orderIdNumber), eq(orders.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
})
|
||||
if (!orderCheck) {
|
||||
return null
|
||||
}
|
||||
|
||||
await db
|
||||
.update(orderStatus)
|
||||
.set({ isDelivered })
|
||||
.where(eq(orderStatus.orderId, orderIdNumber))
|
||||
|
||||
const order = await db.query.orders.findFirst({
|
||||
where: eq(orders.id, orderIdNumber),
|
||||
where: and(eq(orders.id, orderIdNumber), eq(orders.regionId, regionId)),
|
||||
})
|
||||
|
||||
return { success: true, userId: order?.userId ?? null }
|
||||
}
|
||||
|
||||
export async function getOrderDetails(orderId: number): Promise<AdminOrderDetails | null> {
|
||||
export async function getOrderDetails(regionId: number, orderId: number): Promise<AdminOrderDetails | null> {
|
||||
// Single optimized query with all relations
|
||||
const orderData = await db.query.orders.findFirst({
|
||||
where: eq(orders.id, orderId),
|
||||
where: and(
|
||||
eq(orders.id, orderId),
|
||||
eq(orders.regionId, regionId)
|
||||
),
|
||||
with: {
|
||||
user: true,
|
||||
address: true,
|
||||
|
|
@ -284,15 +304,17 @@ export async function getOrderDetails(orderId: number): Promise<AdminOrderDetail
|
|||
}
|
||||
|
||||
export async function updateOrderItemPackaging(
|
||||
regionId: number,
|
||||
orderItemId: number,
|
||||
isPackaged?: boolean,
|
||||
isPackageVerified?: boolean
|
||||
): Promise<AdminOrderItemPackagingResult> {
|
||||
const orderItem = await db.query.orderItems.findFirst({
|
||||
where: eq(orderItems.id, orderItemId),
|
||||
with: { order: { columns: { regionId: true } } },
|
||||
})
|
||||
|
||||
if (!orderItem) {
|
||||
if (!orderItem || orderItem.order?.regionId !== regionId) {
|
||||
return { success: false, updated: false }
|
||||
}
|
||||
|
||||
|
|
@ -316,9 +338,9 @@ export async function updateOrderItemPackaging(
|
|||
return { success: true, updated: true }
|
||||
}
|
||||
|
||||
export async function removeDeliveryCharge(orderId: number): Promise<AdminOrderMessageResult | null> {
|
||||
export async function removeDeliveryCharge(regionId: number, orderId: number): Promise<AdminOrderMessageResult | null> {
|
||||
const order = await db.query.orders.findFirst({
|
||||
where: eq(orders.id, orderId),
|
||||
where: and(eq(orders.id, orderId), eq(orders.regionId, regionId)),
|
||||
})
|
||||
|
||||
if (!order) {
|
||||
|
|
@ -335,14 +357,30 @@ export async function removeDeliveryCharge(orderId: number): Promise<AdminOrderM
|
|||
deliveryCharge: '0',
|
||||
totalAmount: newTotalAmount.toString(),
|
||||
})
|
||||
.where(eq(orders.id, orderId))
|
||||
.where(and(eq(orders.id, orderId), eq(orders.regionId, regionId)))
|
||||
|
||||
return { success: true, message: 'Delivery charge removed' }
|
||||
}
|
||||
|
||||
export async function getSlotOrders(slotId: string): Promise<AdminGetSlotOrdersResult> {
|
||||
export async function getSlotOrders(regionId: number, slotId: string): Promise<AdminGetSlotOrdersResult> {
|
||||
const slotIdNumber = parseInt(slotId)
|
||||
const slot = await db.query.deliverySlotInfo.findFirst({
|
||||
where: and(
|
||||
eq(deliverySlotInfo.id, slotIdNumber),
|
||||
eq(deliverySlotInfo.regionId, regionId)
|
||||
),
|
||||
columns: { id: true },
|
||||
})
|
||||
|
||||
if (!slot) {
|
||||
return { success: true, data: [] }
|
||||
}
|
||||
|
||||
const slotOrders = await db.query.orders.findMany({
|
||||
where: eq(orders.slotId, parseInt(slotId)),
|
||||
where: and(
|
||||
eq(orders.slotId, slotIdNumber),
|
||||
eq(orders.regionId, regionId)
|
||||
),
|
||||
with: {
|
||||
user: true,
|
||||
address: true,
|
||||
|
|
@ -427,6 +465,7 @@ export async function getSlotOrders(slotId: string): Promise<AdminGetSlotOrdersR
|
|||
}
|
||||
|
||||
export async function updateAddressCoords(
|
||||
regionId: number,
|
||||
addressId: number,
|
||||
latitude: number,
|
||||
longitude: number
|
||||
|
|
@ -437,13 +476,13 @@ export async function updateAddressCoords(
|
|||
adminLatitude: latitude,
|
||||
adminLongitude: longitude,
|
||||
})
|
||||
.where(eq(addresses.id, addressId))
|
||||
.where(and(eq(addresses.id, addressId), eq(addresses.regionId, regionId)))
|
||||
.returning()
|
||||
|
||||
return { success: result.length > 0 }
|
||||
}
|
||||
|
||||
export async function getAllOrders(input: GetAllOrdersInput): Promise<AdminGetAllOrdersResultWithUserId> {
|
||||
export async function getAllOrders(regionId: number, input: GetAllOrdersInput): Promise<AdminGetAllOrdersResultWithUserId> {
|
||||
const {
|
||||
cursor,
|
||||
limit,
|
||||
|
|
@ -454,7 +493,7 @@ export async function getAllOrders(input: GetAllOrdersInput): Promise<AdminGetAl
|
|||
flashDeliveryFilter,
|
||||
} = input
|
||||
|
||||
let whereCondition: SQL<unknown> | undefined = undefined
|
||||
let whereCondition: SQL<unknown> | undefined = eq(orders.regionId, regionId)
|
||||
|
||||
if(!cursor) {
|
||||
// Get max order ID for initial pagination
|
||||
|
|
@ -592,9 +631,19 @@ export async function getAllOrders(input: GetAllOrdersInput): Promise<AdminGetAl
|
|||
}
|
||||
}
|
||||
|
||||
export async function rebalanceSlots(slotIds: number[]): Promise<AdminRebalanceSlotsResult> {
|
||||
export async function rebalanceSlots(regionId: number, slotIds: number[]): Promise<AdminRebalanceSlotsResult> {
|
||||
// Only in-region slots may be rebalanced — out-of-region slot ids are ignored.
|
||||
const inRegionSlots = await db.query.deliverySlotInfo.findMany({
|
||||
where: and(inArray(deliverySlotInfo.id, slotIds), eq(deliverySlotInfo.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
})
|
||||
const inRegionSlotIds = inRegionSlots.map((s) => s.id)
|
||||
if (inRegionSlotIds.length === 0) {
|
||||
return { success: true, updatedOrders: [], message: 'Rebalanced 0 orders.' }
|
||||
}
|
||||
|
||||
const ordersList = await db.query.orders.findMany({
|
||||
where: inArray(orders.slotId, slotIds),
|
||||
where: and(inArray(orders.slotId, inRegionSlotIds), eq(orders.regionId, regionId)),
|
||||
with: {
|
||||
orderItems: {
|
||||
with: {
|
||||
|
|
@ -673,9 +722,9 @@ export async function rebalanceSlots(slotIds: number[]): Promise<AdminRebalanceS
|
|||
}
|
||||
}
|
||||
|
||||
export async function cancelOrder(orderId: number, reason: string): Promise<AdminCancelOrderResult> {
|
||||
export async function cancelOrder(regionId: number, orderId: number, reason: string): Promise<AdminCancelOrderResult> {
|
||||
const order = await db.query.orders.findFirst({
|
||||
where: eq(orders.id, orderId),
|
||||
where: and(eq(orders.id, orderId), eq(orders.regionId, regionId)),
|
||||
with: {
|
||||
orderStatus: true,
|
||||
},
|
||||
|
|
@ -729,7 +778,15 @@ export async function cancelOrder(orderId: number, reason: string): Promise<Admi
|
|||
}
|
||||
}
|
||||
|
||||
export async function deleteOrderById(orderId: number): Promise<void> {
|
||||
export async function deleteOrderById(regionId: number, orderId: number): Promise<boolean> {
|
||||
const order = await db.query.orders.findFirst({
|
||||
where: and(eq(orders.id, orderId), eq(orders.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
})
|
||||
if (!order) {
|
||||
return false
|
||||
}
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.delete(orderItems).where(eq(orderItems.orderId, orderId))
|
||||
await tx.delete(orderStatus).where(eq(orderStatus.orderId, orderId))
|
||||
|
|
@ -737,6 +794,8 @@ export async function deleteOrderById(orderId: number): Promise<void> {
|
|||
await tx.delete(refunds).where(eq(refunds.orderId, orderId))
|
||||
await tx.delete(couponUsage).where(eq(couponUsage.orderId, orderId))
|
||||
await tx.delete(complaints).where(eq(complaints.orderId, orderId))
|
||||
await tx.delete(orders).where(eq(orders.id, orderId))
|
||||
await tx.delete(orders).where(and(eq(orders.id, orderId), eq(orders.regionId, regionId)))
|
||||
})
|
||||
|
||||
return true
|
||||
}
|
||||
|
|
|
|||
|
|
@ -80,6 +80,62 @@ const getStringArray = (value: unknown): string[] | null => {
|
|||
return value.map((item) => String(item))
|
||||
}
|
||||
|
||||
// Region guards: SKUs resolve to a region through their parent product
|
||||
// (productSkus.productId -> productInfo.regionId). Throws on unknown ids or
|
||||
// ids whose parent product lives in another region.
|
||||
const resolveSkuRegions = async (txOrDb: any, skuIds: number[]): Promise<Map<number, number | null>> => {
|
||||
if (skuIds.length === 0) return new Map()
|
||||
const rows = await txOrDb.query.productSkus.findMany({
|
||||
where: inArray(productSkus.id, skuIds),
|
||||
with: { product: { columns: { regionId: true } } },
|
||||
columns: { id: true },
|
||||
})
|
||||
return new Map(rows.map((r: any) => [r.id, r.product?.regionId ?? null]))
|
||||
}
|
||||
|
||||
const assertSkuIdsInRegion = async (txOrDb: any, skuIds: number[], regionId: number, noun = 'SKU'): Promise<void> => {
|
||||
const unique = [...new Set(skuIds.map(Number).filter((n) => Number.isFinite(n)))]
|
||||
if (unique.length === 0) return
|
||||
const regions = await resolveSkuRegions(txOrDb, unique)
|
||||
const missing = unique.filter((id) => !regions.has(id))
|
||||
if (missing.length > 0) {
|
||||
throw new Error(`Invalid ${noun} IDs: ${missing.join(', ')}`)
|
||||
}
|
||||
const foreign = unique.filter((id) => regions.get(id) !== regionId)
|
||||
if (foreign.length > 0) {
|
||||
throw new Error(`${noun} ${foreign.join(', ')} belongs to a different region`)
|
||||
}
|
||||
}
|
||||
|
||||
const assertStoreInRegion = async (txOrDb: any, storeId: number, regionId: number): Promise<void> => {
|
||||
const store = await txOrDb.query.storeInfo.findFirst({
|
||||
where: eq(storeInfo.id, storeId),
|
||||
columns: { id: true, regionId: true },
|
||||
})
|
||||
if (!store) {
|
||||
throw new Error(`Invalid store ID: ${storeId}`)
|
||||
}
|
||||
if (store.regionId !== regionId) {
|
||||
throw new Error('Store belongs to a different region')
|
||||
}
|
||||
}
|
||||
|
||||
const assertStoreIdsInRegion = async (txOrDb: any, storeIds: number[], regionId: number): Promise<void> => {
|
||||
const unique = [...new Set(storeIds.map(Number).filter((n) => Number.isFinite(n)))]
|
||||
if (unique.length === 0) return
|
||||
const rows = await txOrDb.query.storeInfo.findMany({
|
||||
where: inArray(storeInfo.id, unique),
|
||||
columns: { id: true, regionId: true },
|
||||
})
|
||||
if (rows.length !== unique.length) {
|
||||
const found = new Set(rows.map((r: { id: number }) => r.id))
|
||||
throw new Error(`Invalid store IDs: ${unique.filter((id) => !found.has(id)).join(', ')}`)
|
||||
}
|
||||
if (rows.some((r: { regionId: number | null }) => r.regionId !== regionId)) {
|
||||
throw new Error('Store belongs to a different region')
|
||||
}
|
||||
}
|
||||
|
||||
const mapStore = (store: StoreRow): Store => ({
|
||||
id: store.id,
|
||||
name: store.name,
|
||||
|
|
@ -152,12 +208,13 @@ const mapTagInfo = (tag: ProductTagInfoRow): AdminProductTagInfo => ({
|
|||
createdAt: tag.createdAt,
|
||||
})
|
||||
|
||||
export async function getAllProducts(): Promise<AdminProductWithRelations[]> {
|
||||
export async function getAllProducts(regionId: number): Promise<AdminProductWithRelations[]> {
|
||||
type ProductWithRelationsRow = ProductRow & {
|
||||
store: StoreRow | null
|
||||
skus: Array<SkuRow & { features: SkuFeatureRow[]; comboItems: any[]; marketStats: MarketStatsRow | null }>
|
||||
}
|
||||
const products = await db.query.productInfo.findMany({
|
||||
where: eq(productInfo.regionId, regionId),
|
||||
orderBy: productInfo.name,
|
||||
with: {
|
||||
store: true,
|
||||
|
|
@ -192,9 +249,9 @@ export async function getAllProducts(): Promise<AdminProductWithRelations[]> {
|
|||
}))
|
||||
}
|
||||
|
||||
export async function getProductById(id: number): Promise<AdminProductWithDetails | null> {
|
||||
export async function getProductById(regionId: number, id: number): Promise<AdminProductWithDetails | null> {
|
||||
const product = await db.query.productInfo.findFirst({
|
||||
where: eq(productInfo.id, id),
|
||||
where: and(eq(productInfo.id, id), eq(productInfo.regionId, regionId)),
|
||||
with: {
|
||||
store: true,
|
||||
skus: {
|
||||
|
|
@ -252,10 +309,10 @@ export async function getProductById(id: number): Promise<AdminProductWithDetail
|
|||
}
|
||||
}
|
||||
|
||||
export async function deleteProduct(id: number): Promise<AdminProduct | null> {
|
||||
export async function deleteProduct(regionId: number, id: number): Promise<AdminProduct | null> {
|
||||
const [deletedProduct] = await db
|
||||
.delete(productInfo)
|
||||
.where(eq(productInfo.id, id))
|
||||
.where(and(eq(productInfo.id, id), eq(productInfo.regionId, regionId)))
|
||||
.returning()
|
||||
|
||||
if (!deletedProduct) {
|
||||
|
|
@ -267,7 +324,7 @@ export async function deleteProduct(id: number): Promise<AdminProduct | null> {
|
|||
|
||||
type ProductInfoInsert = InferInsertModel<typeof productInfo>
|
||||
|
||||
export async function createProduct(input: CreateProductInput): Promise<AdminProductWithRelations> {
|
||||
export async function createProduct(input: CreateProductInput, regionId: number): Promise<AdminProductWithRelations> {
|
||||
if (!input.skus || input.skus.length === 0) {
|
||||
throw new Error('At least one SKU is required')
|
||||
}
|
||||
|
|
@ -279,11 +336,24 @@ export async function createProduct(input: CreateProductInput): Promise<AdminPro
|
|||
throw new Error('Every SKU must have a quantity feature')
|
||||
}
|
||||
|
||||
// Cross-region validation BEFORE the generic try/catch so the specific
|
||||
// message reaches the caller instead of the masked generic failure.
|
||||
if ((input as any).storeId != null) {
|
||||
await assertStoreInRegion(db, (input as any).storeId, regionId)
|
||||
}
|
||||
await assertSkuIdsInRegion(
|
||||
db,
|
||||
(input.skus || []).flatMap((sku: any) => (sku.comboItems || []).map((ci: any) => Number(ci.skuId))),
|
||||
regionId,
|
||||
'Combo SKU'
|
||||
)
|
||||
|
||||
try {
|
||||
return await db.transaction(async (tx) => {
|
||||
const { skus, ...productData } = input
|
||||
|
||||
const [product] = await tx.insert(productInfo).values({
|
||||
regionId,
|
||||
name: productData.name,
|
||||
shortDescription: productData.shortDescription ?? null,
|
||||
longDescription: productData.longDescription ?? null,
|
||||
|
|
@ -364,9 +434,9 @@ export async function createProduct(input: CreateProductInput): Promise<AdminPro
|
|||
}
|
||||
}
|
||||
|
||||
export async function updateProduct(id: number, input: any): Promise<AdminProductWithRelations | null> {
|
||||
export async function updateProduct(regionId: number, id: number, input: any): Promise<AdminProductWithRelations | null> {
|
||||
const product = await db.query.productInfo.findFirst({
|
||||
where: eq(productInfo.id, id),
|
||||
where: and(eq(productInfo.id, id), eq(productInfo.regionId, regionId)),
|
||||
})
|
||||
|
||||
if (!product) {
|
||||
|
|
@ -376,6 +446,9 @@ export async function updateProduct(id: number, input: any): Promise<AdminProduc
|
|||
const { skus, ...productData } = input
|
||||
|
||||
// Input validation outside the transaction so specific messages reach the UI.
|
||||
if (productData.storeId != null) {
|
||||
await assertStoreInRegion(db, productData.storeId, regionId)
|
||||
}
|
||||
if (skus !== undefined) {
|
||||
if (skus.length === 0) {
|
||||
throw new Error('At least one SKU is required')
|
||||
|
|
@ -394,6 +467,13 @@ export async function updateProduct(id: number, input: any): Promise<AdminProduc
|
|||
})
|
||||
const existingSkuIdSet = new Set(existingSkus.map((s) => s.id))
|
||||
|
||||
await assertSkuIdsInRegion(
|
||||
db,
|
||||
skus.flatMap((sku: any) => (sku.comboItems || []).map((ci: any) => Number(ci.skuId))),
|
||||
regionId,
|
||||
'Combo SKU'
|
||||
)
|
||||
|
||||
const skusBeingSuspended = skus.filter(
|
||||
(sku: any) => sku.isSuspended && sku.id != null && existingSkuIdSet.has(sku.id)
|
||||
)
|
||||
|
|
@ -431,7 +511,7 @@ export async function updateProduct(id: number, input: any): Promise<AdminProduc
|
|||
incrementStep: productData.incrementStep ?? 1,
|
||||
productType: productData.productType,
|
||||
})
|
||||
.where(eq(productInfo.id, id))
|
||||
.where(and(eq(productInfo.id, id), eq(productInfo.regionId, regionId)))
|
||||
|
||||
if (skus !== undefined) {
|
||||
const existingSkus = await tx.query.productSkus.findMany({
|
||||
|
|
@ -580,8 +660,9 @@ export async function updateProduct(id: number, input: any): Promise<AdminProduc
|
|||
}
|
||||
}
|
||||
|
||||
export async function getAllProductTags(): Promise<AdminProductTagWithProducts[]> {
|
||||
export async function getAllProductTags(regionId: number): Promise<AdminProductTagWithProducts[]> {
|
||||
const tags = await db.query.productTagInfo.findMany({
|
||||
where: eq(productTagInfo.regionId, regionId),
|
||||
with: {
|
||||
products: {
|
||||
with: {
|
||||
|
|
@ -605,17 +686,18 @@ export async function getAllProductTags(): Promise<AdminProductTagWithProducts[]
|
|||
}))
|
||||
}
|
||||
|
||||
export async function getAllProductTagInfos(): Promise<AdminProductTagInfo[]> {
|
||||
export async function getAllProductTagInfos(regionId: number): Promise<AdminProductTagInfo[]> {
|
||||
const tags = await db.query.productTagInfo.findMany({
|
||||
where: eq(productTagInfo.regionId, regionId),
|
||||
orderBy: productTagInfo.tagName,
|
||||
})
|
||||
|
||||
return tags.map(mapTagInfo)
|
||||
}
|
||||
|
||||
export async function getProductTagInfoById(tagId: number): Promise<AdminProductTagInfo | null> {
|
||||
export async function getProductTagInfoById(regionId: number, tagId: number): Promise<AdminProductTagInfo | null> {
|
||||
const tag = await db.query.productTagInfo.findFirst({
|
||||
where: eq(productTagInfo.id, tagId),
|
||||
where: and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)),
|
||||
})
|
||||
|
||||
if (!tag) {
|
||||
|
|
@ -629,8 +711,13 @@ export interface CreateProductTagInput extends ProductTagCore {
|
|||
sortOrder?: number[]
|
||||
}
|
||||
|
||||
export async function createProductTag(input: CreateProductTagInput): Promise<AdminProductTagWithProducts> {
|
||||
export async function createProductTag(input: CreateProductTagInput, regionId: number): Promise<AdminProductTagWithProducts> {
|
||||
if (input.relatedStores && input.relatedStores.length > 0) {
|
||||
await assertStoreIdsInRegion(db, input.relatedStores, regionId)
|
||||
}
|
||||
|
||||
const [tag] = await db.insert(productTagInfo).values({
|
||||
regionId,
|
||||
tagName: input.tagName,
|
||||
tagDescription: input.tagDescription || null,
|
||||
imageUrl: input.imageUrl || null,
|
||||
|
|
@ -646,9 +733,9 @@ export async function createProductTag(input: CreateProductTagInput): Promise<Ad
|
|||
}
|
||||
}
|
||||
|
||||
export async function getProductTagById(tagId: number): Promise<AdminProductTagWithProducts | null> {
|
||||
export async function getProductTagById(regionId: number, tagId: number): Promise<AdminProductTagWithProducts | null> {
|
||||
const tag = await db.query.productTagInfo.findFirst({
|
||||
where: eq(productTagInfo.id, tagId),
|
||||
where: and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)),
|
||||
with: {
|
||||
products: {
|
||||
with: {
|
||||
|
|
@ -681,7 +768,11 @@ export type UpdateProductTagInput = Omit<ProductTagCore, 'tagName'> & {
|
|||
sortOrder?: number[]
|
||||
}
|
||||
|
||||
export async function updateProductTag(tagId: number, input: UpdateProductTagInput): Promise<AdminProductTagWithProducts> {
|
||||
export async function updateProductTag(regionId: number, tagId: number, input: UpdateProductTagInput): Promise<AdminProductTagWithProducts | null> {
|
||||
if (input.relatedStores != null && input.relatedStores.length > 0) {
|
||||
await assertStoreIdsInRegion(db, input.relatedStores, regionId)
|
||||
}
|
||||
|
||||
const [tag] = await db.update(productTagInfo).set({
|
||||
...(input.tagName !== undefined && { tagName: input.tagName }),
|
||||
...(input.tagDescription !== undefined && { tagDescription: input.tagDescription }),
|
||||
|
|
@ -689,7 +780,11 @@ export async function updateProductTag(tagId: number, input: UpdateProductTagInp
|
|||
...(input.isDashboardTag !== undefined && { isDashboardTag: input.isDashboardTag }),
|
||||
...(input.relatedStores !== undefined && { relatedStores: input.relatedStores }),
|
||||
...(input.sortOrder !== undefined && { sortOrder: input.sortOrder }),
|
||||
}).where(eq(productTagInfo.id, tagId)).returning()
|
||||
}).where(and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId))).returning()
|
||||
|
||||
if (!tag) {
|
||||
return null
|
||||
}
|
||||
|
||||
const fullTag = await db.query.productTagInfo.findFirst({
|
||||
where: eq(productTagInfo.id, tagId),
|
||||
|
|
@ -716,8 +811,11 @@ export async function updateProductTag(tagId: number, input: UpdateProductTagInp
|
|||
}
|
||||
}
|
||||
|
||||
export async function deleteProductTag(tagId: number): Promise<void> {
|
||||
await db.delete(productTagInfo).where(eq(productTagInfo.id, tagId))
|
||||
export async function deleteProductTag(regionId: number, tagId: number): Promise<boolean> {
|
||||
const [deleted] = await db.delete(productTagInfo)
|
||||
.where(and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)))
|
||||
.returning({ id: productTagInfo.id })
|
||||
return !!deleted
|
||||
}
|
||||
|
||||
export async function checkProductTagExistsByName(tagName: string): Promise<boolean> {
|
||||
|
|
@ -727,7 +825,7 @@ export async function checkProductTagExistsByName(tagName: string): Promise<bool
|
|||
return !!tag
|
||||
}
|
||||
|
||||
export async function getProductReviews(productId: number, limit: number, offset: number) {
|
||||
export async function getProductReviews(regionId: number, productId: number, limit: number, offset: number) {
|
||||
const reviews = await db
|
||||
.select({
|
||||
id: productReviews.id,
|
||||
|
|
@ -741,7 +839,8 @@ export async function getProductReviews(productId: number, limit: number, offset
|
|||
})
|
||||
.from(productReviews)
|
||||
.innerJoin(users, eq(productReviews.userId, users.id))
|
||||
.where(eq(productReviews.productId, productId))
|
||||
.innerJoin(productInfo, eq(productReviews.productId, productInfo.id))
|
||||
.where(and(eq(productReviews.productId, productId), eq(productInfo.regionId, regionId)))
|
||||
.orderBy(desc(productReviews.reviewTime))
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
|
|
@ -749,7 +848,8 @@ export async function getProductReviews(productId: number, limit: number, offset
|
|||
const totalCountResult = await db
|
||||
.select({ count: sql`count(*)` })
|
||||
.from(productReviews)
|
||||
.where(eq(productReviews.productId, productId))
|
||||
.innerJoin(productInfo, eq(productReviews.productId, productInfo.id))
|
||||
.where(and(eq(productReviews.productId, productId), eq(productInfo.regionId, regionId)))
|
||||
|
||||
const totalCount = Number(totalCountResult[0].count)
|
||||
|
||||
|
|
@ -771,10 +871,26 @@ export async function getProductReviews(productId: number, limit: number, offset
|
|||
}
|
||||
|
||||
export async function respondToReview(
|
||||
regionId: number,
|
||||
reviewId: number,
|
||||
adminResponse: string | undefined,
|
||||
adminResponseImages: string[]
|
||||
): Promise<AdminProductReview | null> {
|
||||
const review = await db.query.productReviews.findFirst({
|
||||
where: eq(productReviews.id, reviewId),
|
||||
columns: { id: true, productId: true },
|
||||
})
|
||||
if (!review) {
|
||||
return null
|
||||
}
|
||||
const product = await db.query.productInfo.findFirst({
|
||||
where: and(eq(productInfo.id, review.productId), eq(productInfo.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
})
|
||||
if (!product) {
|
||||
return null
|
||||
}
|
||||
|
||||
const [updatedReview] = await db
|
||||
.update(productReviews)
|
||||
.set({
|
||||
|
|
@ -800,8 +916,9 @@ export async function respondToReview(
|
|||
}
|
||||
}
|
||||
|
||||
export async function getAllProductGroups() {
|
||||
export async function getAllProductGroups(regionId: number) {
|
||||
const groups = await db.query.productGroupInfo.findMany({
|
||||
where: eq(productGroupInfo.regionId, regionId),
|
||||
with: {
|
||||
memberships: {
|
||||
with: {
|
||||
|
|
@ -830,11 +947,15 @@ export async function getAllProductGroups() {
|
|||
export async function createProductGroup(
|
||||
groupName: string,
|
||||
description: string | undefined,
|
||||
productIds: number[]
|
||||
productIds: number[],
|
||||
regionId: number
|
||||
): Promise<AdminProductGroupInfo> {
|
||||
await assertSkuIdsInRegion(db, productIds, regionId, 'Product')
|
||||
|
||||
const [newGroup] = await db
|
||||
.insert(productGroupInfo)
|
||||
.values({
|
||||
regionId,
|
||||
groupName,
|
||||
description,
|
||||
})
|
||||
|
|
@ -858,11 +979,16 @@ export async function createProductGroup(
|
|||
}
|
||||
|
||||
export async function updateProductGroup(
|
||||
regionId: number,
|
||||
id: number,
|
||||
groupName: string | undefined,
|
||||
description: string | undefined,
|
||||
productIds: number[] | undefined
|
||||
): Promise<AdminProductGroupInfo | null> {
|
||||
if (productIds !== undefined) {
|
||||
await assertSkuIdsInRegion(db, productIds, regionId, 'Product')
|
||||
}
|
||||
|
||||
const updateData: Partial<{
|
||||
groupName: string
|
||||
description: string | null
|
||||
|
|
@ -874,7 +1000,7 @@ export async function updateProductGroup(
|
|||
const [updatedGroup] = await db
|
||||
.update(productGroupInfo)
|
||||
.set(updateData)
|
||||
.where(eq(productGroupInfo.id, id))
|
||||
.where(and(eq(productGroupInfo.id, id), eq(productGroupInfo.regionId, regionId)))
|
||||
.returning()
|
||||
|
||||
if (!updatedGroup) {
|
||||
|
|
@ -902,7 +1028,15 @@ export async function updateProductGroup(
|
|||
}
|
||||
}
|
||||
|
||||
export async function deleteProductGroup(id: number): Promise<AdminProductGroupInfo | null> {
|
||||
export async function deleteProductGroup(regionId: number, id: number): Promise<AdminProductGroupInfo | null> {
|
||||
const group = await db.query.productGroupInfo.findFirst({
|
||||
where: and(eq(productGroupInfo.id, id), eq(productGroupInfo.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
})
|
||||
if (!group) {
|
||||
return null
|
||||
}
|
||||
|
||||
await db.delete(productGroupMembership).where(eq(productGroupMembership.groupId, id))
|
||||
|
||||
const [deletedGroup] = await db
|
||||
|
|
@ -922,7 +1056,7 @@ export async function deleteProductGroup(id: number): Promise<AdminProductGroupI
|
|||
}
|
||||
}
|
||||
|
||||
export async function updateProductPrices(updates: Array<{
|
||||
export async function updateProductPrices(regionId: number, updates: Array<{
|
||||
productId: number
|
||||
price?: number
|
||||
marketPrice?: number | null
|
||||
|
|
@ -935,15 +1069,22 @@ export async function updateProductPrices(updates: Array<{
|
|||
|
||||
const productIds = updates.map((update) => update.productId)
|
||||
|
||||
// Validate all SKU IDs exist (in chunks to avoid large IN clauses)
|
||||
// Validate all SKU IDs exist AND belong to the staff region (in chunks to
|
||||
// avoid large IN clauses). Out-of-region SKUs are reported as invalid so no
|
||||
// cross-region existence leaks through this bulk path.
|
||||
const existingSkuChunks = await runBatched(db, productIds, 10, async (tx, chunk) => {
|
||||
return tx.query.productSkus.findMany({
|
||||
where: inArray(productSkus.id, chunk),
|
||||
with: { product: { columns: { regionId: true } } },
|
||||
columns: { id: true },
|
||||
})
|
||||
})
|
||||
const existingIds = new Set(existingSkuChunks.flat().map((sku: { id: number }) => sku.id))
|
||||
const invalidIds = productIds.filter((id) => !existingIds.has(id))
|
||||
const inRegionIds = new Set(
|
||||
existingSkuChunks.flat()
|
||||
.filter((sku: { id: number; product?: { regionId: number | null } | null }) => sku.product?.regionId === regionId)
|
||||
.map((sku: { id: number }) => sku.id)
|
||||
)
|
||||
const invalidIds = productIds.filter((id) => !inRegionIds.has(id))
|
||||
|
||||
if (invalidIds.length > 0) {
|
||||
return { updatedCount: 0, invalidIds }
|
||||
|
|
@ -988,8 +1129,17 @@ export async function updateProductPrices(updates: Array<{
|
|||
}
|
||||
|
||||
export async function toggleProductOutOfStock(
|
||||
regionId: number,
|
||||
productId: number
|
||||
): Promise<{ id: number; isOutOfStock: boolean } | null> {
|
||||
const product = await db.query.productInfo.findFirst({
|
||||
where: and(eq(productInfo.id, productId), eq(productInfo.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
})
|
||||
if (!product) {
|
||||
return null
|
||||
}
|
||||
|
||||
const skus = await db.query.productSkus.findMany({
|
||||
where: eq(productSkus.productId, productId),
|
||||
with: { marketStats: true },
|
||||
|
|
@ -1024,7 +1174,16 @@ export async function checkProductExistsByName(name: string): Promise<boolean> {
|
|||
return !!product
|
||||
}
|
||||
|
||||
export async function replaceTagProducts(tagId: number, productIds: number[]): Promise<void> {
|
||||
export async function replaceTagProducts(regionId: number, tagId: number, productIds: number[]): Promise<void> {
|
||||
const tag = await db.query.productTagInfo.findFirst({
|
||||
where: and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
})
|
||||
if (!tag) {
|
||||
throw new Error('Tag belongs to a different region')
|
||||
}
|
||||
await assertSkuIdsInRegion(db, productIds, regionId, 'Product')
|
||||
|
||||
await db.delete(productTags).where(eq(productTags.tagId, tagId))
|
||||
|
||||
if (productIds.length === 0) {
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue