Compare commits

...
Sign in to create a new pull request.

6 commits

Author SHA1 Message Date
shafi54
90c6c90505 enh 2026-11-16 01:30:53 +05:30
shafi54
2cb1cfd807 enh 2026-11-15 23:53:14 +05:30
shafi54
442e20c88a enh 2026-11-08 16:07:19 +05:30
shafi54
a09ae70b9f enh 2026-11-08 15:43:46 +05:30
shafi54
7a5fc0ff67 enh 2026-11-08 14:22:40 +05:30
shafi54
f9fb1c53a7 neo region commit 2026-11-08 13:49:17 +05:30
113 changed files with 6980 additions and 1345 deletions

File diff suppressed because one or more lines are too long

View file

@ -895,6 +895,9 @@ Use these fixture names in the cases below.
| AOD-23 | happy | Back to orders | route | | AOD-23 | happy | Back to orders | route |
| AOD-24 | edge | customer link | user detail route | | AOD-24 | edge | customer link | user detail route |
| AOD-25 | edge | no OrderOptionsMenu on details | only the explicit Cancel/Back actions are present (current) | | AOD-25 | edge | no OrderOptionsMenu on details | only the explicit Cancel/Back actions are present (current) |
| AOD-26 | edge | delivered timestamp | "Delivered on …" when deliveredAt is set |
| AOD-27 | edge | not delivered | no delivered timestamp |
| AOD-28 | edge | packed timestamp | per-item "Packed …" only when packagedAt is set |
### 13.2 OrderNotesForm / CancelOrderDialog / OrderOptionsMenu ### 13.2 OrderNotesForm / CancelOrderDialog / OrderOptionsMenu

View file

@ -182,6 +182,17 @@ export default function OrderDetails() {
Placed on {dayjs(order.createdAt).format("MMM DD, YYYY • h:mm A")} Placed on {dayjs(order.createdAt).format("MMM DD, YYYY • h:mm A")}
</MyText> </MyText>
</View> </View>
{order.deliveredAt && (
<View
testID="order-delivered-at"
style={tw`flex-row items-center bg-green-50 p-3 rounded-xl mt-2`}
>
<MaterialIcons name="check-circle" size={20} color="#10B981" />
<MyText style={tw`ml-2 text-green-800 font-medium`}>
Delivered on {dayjs(order.deliveredAt).format("MMM DD, YYYY • h:mm A")}
</MyText>
</View>
)}
</View> </View>
{/* Cancellation Reason */} {/* Cancellation Reason */}
@ -403,6 +414,14 @@ export default function OrderDetails() {
</MyText> </MyText>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
{item.packagedAt && (
<MyText
testID={`order-item-packaged-at-${item.id}`}
style={tw`text-[10px] text-gray-400 mt-1`}
>
Packed {dayjs(item.packagedAt).format("MMM DD, YYYY • h:mm A")}
</MyText>
)}
</View> </View>
<MyText style={tw`text-sm font-bold text-gray-900`}> <MyText style={tw`text-sm font-bold text-gray-900`}>
₹{item.amount} ₹{item.amount}

View file

@ -196,8 +196,7 @@ export default function EditProduct() {
newImageUrls: allUploadUrls, newImageUrls: allUploadUrls,
} as any) } as any)
await refetch() await Promise.all([refetch(), refetchProducts()])
await refetchProducts()
Alert.alert('Success', 'Product updated successfully!') Alert.alert('Success', 'Product updated successfully!')
productFormRef.current?.clearImages() productFormRef.current?.clearImages()
} catch (error: any) { } catch (error: any) {
@ -241,8 +240,7 @@ export default function EditProduct() {
deletedImageKeys: [], deletedImageKeys: [],
newImageUrls: [], newImageUrls: [],
} as any) } as any)
await refetch() await Promise.all([refetch(), refetchProducts()])
await refetchProducts()
Alert.alert('Success', 'Market data updated for your region') Alert.alert('Success', 'Market data updated for your region')
} catch (error: any) { } catch (error: any) {
Alert.alert('Error', error.message || 'Failed to update product') Alert.alert('Error', error.message || 'Failed to update product')

View file

@ -61,8 +61,10 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
{ name, password }, { name, password },
{ {
onSuccess: async (data) => { onSuccess: async (data) => {
await saveJWT(data.token); await Promise.all([
await saveStaff(data.staff); saveJWT(data.token),
saveStaff(data.staff),
]);
setStaff(data.staff); setStaff(data.staff);
setIsLoggedIn(true); setIsLoggedIn(true);
// A push tapped while signed out waits here; land on it first. // A push tapped while signed out waits here; land on it first.
@ -77,8 +79,10 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
}; };
const logout = async () => { const logout = async () => {
await deleteJWT(); await Promise.all([
await deleteStaff(); deleteJWT(),
deleteStaff(),
]);
setIsLoggedIn(false); setIsLoggedIn(false);
setStaff(null); setStaff(null);
queryClient.clear(); queryClient.clear();

View file

@ -10,6 +10,10 @@ import { CreateCouponPayload } from 'common-ui/shared-types';
import { ADMIN_LIST_VIRTUALIZATION } from '@/src/lib/list-virtualization'; import { ADMIN_LIST_VIRTUALIZATION } from '@/src/lib/list-virtualization';
const USERS_PAGE_SIZE = 10; const USERS_PAGE_SIZE = 10;
// The user search fires on every keystroke; debounce it so a 10-digit mobile
// number does not issue 10 overlapping queries (which saturated D1 in prod and
// surfaced as a 401 / forced logout).
const USER_SEARCH_DEBOUNCE_MS = 350;
interface CouponFormValues extends CreateCouponPayload { interface CouponFormValues extends CreateCouponPayload {
isReservedCoupon?: boolean; isReservedCoupon?: boolean;
@ -79,6 +83,9 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
// User dropdown states // User dropdown states
const [userSearchQuery, setUserSearchQuery] = useState(''); const [userSearchQuery, setUserSearchQuery] = useState('');
// Debounced mirror of the input: the query below keys on this, not on every
// keystroke, so a burst of requests cannot overlap.
const [debouncedUserSearch, setDebouncedUserSearch] = useState('');
const [userOffset, setUserOffset] = useState(0); const [userOffset, setUserOffset] = useState(0);
const [allUsers, setAllUsers] = useState<{ id: number; name: string; mobile: string | null }[]>([]); const [allUsers, setAllUsers] = useState<{ id: number; name: string; mobile: string | null }[]>([]);
const [hasMoreUsers, setHasMoreUsers] = useState(true); const [hasMoreUsers, setHasMoreUsers] = useState(true);
@ -88,8 +95,16 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
const [multiDialogOpen, setMultiDialogOpen] = useState(false); const [multiDialogOpen, setMultiDialogOpen] = useState(false);
const [multiCount, setMultiCount] = useState(''); const [multiCount, setMultiCount] = useState('');
useEffect(() => {
const timer = setTimeout(
() => setDebouncedUserSearch(userSearchQuery),
USER_SEARCH_DEBOUNCE_MS
);
return () => clearTimeout(timer);
}, [userSearchQuery]);
const { data: usersData, isFetching: isFetchingUsers } = trpc.admin.coupon.getUsersMiniInfo.useQuery( const { data: usersData, isFetching: isFetchingUsers } = trpc.admin.coupon.getUsersMiniInfo.useQuery(
{ search: userSearchQuery, limit: USERS_PAGE_SIZE, offset: userOffset }, { search: debouncedUserSearch, limit: USERS_PAGE_SIZE, offset: userOffset },
{ enabled: usersDropdownOpen } { enabled: usersDropdownOpen }
); );
@ -115,6 +130,7 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
setAllUsers([]); setAllUsers([]);
setHasMoreUsers(true); setHasMoreUsers(true);
setUserSearchQuery(''); setUserSearchQuery('');
setDebouncedUserSearch('');
} }
}, [usersDropdownOpen]); }, [usersDropdownOpen]);

View file

@ -6,6 +6,27 @@ import { getJWT } from '@/hooks/useJWT';
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs'; import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs';
import { DeviceEventEmitter } from 'react-native'; import { DeviceEventEmitter } from 'react-native';
// TEMP DIAGNOSTIC: decode (not verify) so we can see expiry/identity.
function decodeJwtClaims(token: string): Record<string, any> | null {
try {
const part = token.split('.')[1];
if (!part) return null;
const b64 = part.replace(/-/g, '+').replace(/_/g, '/');
const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);
const atobFn = (globalThis as any).atob as ((value: string) => string) | undefined;
if (!atobFn) return null;
const json = decodeURIComponent(
atobFn(padded)
.split('')
.map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
.join('')
);
return JSON.parse(json);
} catch {
return null;
}
}
// Create tRPC React hooks without strict typing for now // Create tRPC React hooks without strict typing for now
export const trpc = createTRPCReact<AppRouter>(); export const trpc = createTRPCReact<AppRouter>();
@ -16,11 +37,52 @@ export const trpcClient = createTRPCProxyClient<AppRouter>({
url: BASE_API_URL+'/api/trpc', url: BASE_API_URL+'/api/trpc',
headers: async () => { headers: async () => {
const token = await getJWT(); const token = await getJWT();
const claims = token ? decodeJwtClaims(token) : null;
console.log(
`[admin-ui][trpc] getJWT: ${token ? `present (${token.length} chars)` : 'MISSING'}`
);
console.log(
`[admin-ui][trpc] token claims: ${
claims
? `staffId=${claims.staffId ?? '-'} userId=${claims.userId ?? '-'} exp=${
claims.exp ? new Date(claims.exp * 1000).toISOString() : '-'
} expired=${claims.exp ? claims.exp * 1000 <= Date.now() : '?'}`
: 'unreadable'
}`
);
return token ? { Authorization: `Bearer ${token}` } : {}; return token ? { Authorization: `Bearer ${token}` } : {};
}, },
fetch: async (url, options) => { fetch: async (url, options) => {
const rawHeaders: any = options?.headers;
const authHeader =
typeof rawHeaders?.get === 'function'
? rawHeaders.get('authorization')
: rawHeaders?.Authorization ?? rawHeaders?.authorization;
console.log(
`[admin-ui][trpc] request ${String(url)} | auth: ${
authHeader ? `PRESENT (${String(authHeader).length} chars)` : 'MISSING'
}`
);
const response = await fetch(url, options); const response = await fetch(url, options);
if (response.status === 401) { if (response.status === 401) {
console.log(
`[admin-ui][trpc] 401 ${String(url)} | auth was: ${authHeader ? 'PRESENT' : 'MISSING'}`
);
// TEMP DIAGNOSTIC: is the same bearer still accepted on a trivial protected query?
// Skipped in tests: it adds a fetch, and ATRPC-01 asserts exactly one.
if (process.env.NODE_ENV !== 'test') {
try {
const probe = await fetch(
`${BASE_API_URL}/api/trpc/admin.staffUser.me?batch=1&input=%7B%7D`,
{ method: 'GET', headers: options?.headers }
);
console.log(`[admin-ui][trpc] 401 probe (staffUser.me) -> ${probe.status}`);
} catch (probeError: any) {
console.log(
`[admin-ui][trpc] 401 probe failed: ${probeError?.message ?? probeError}`
);
}
}
const data = await response.clone().json().catch(() => ({})); const data = await response.clone().json().catch(() => ({}));
let code = ''; let code = '';
if(data[0]?.error || data?.error) { if(data[0]?.error || data?.error) {

View file

@ -68,6 +68,15 @@ async function openUsersWith(
await flush(2) await flush(2)
} }
const USER_SEARCH_DEBOUNCE_MS = 350
async function waitForUserSearchDebounce() {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, USER_SEARCH_DEBOUNCE_MS + 50))
})
await flush(2)
}
const BASE_INITIAL = { const BASE_INITIAL = {
couponCodes: ['SAVE10'], couponCodes: ['SAVE10'],
isUserBased: false, isUserBased: false,
@ -280,11 +289,11 @@ describe('CouponForm (ACOUPF-01..24)', () => {
view.getByPlaceholderText('Search users by name or mobile...'), view.getByPlaceholderText('Search users by name or mobile...'),
'Test' 'Test'
) )
await flush(2) // The query is debounced, so seed the response before the timer fires.
setProcedure('admin.coupon.getUsersMiniInfo', { setProcedure('admin.coupon.getUsersMiniInfo', {
data: { users: [{ id: 5, name: 'Test User', mobile: '9876543210' }], count: 1 }, data: { users: [{ id: 5, name: 'Test User', mobile: '9876543210' }], count: 1 },
}) })
await flush(2) await waitForUserSearchDebounce()
expect(lastProcedureInput('admin.coupon.getUsersMiniInfo')).toEqual({ expect(lastProcedureInput('admin.coupon.getUsersMiniInfo')).toEqual({
search: 'Test', search: 'Test',
@ -308,6 +317,26 @@ describe('CouponForm (ACOUPF-01..24)', () => {
expect(procedureQueryCalls('admin.coupon.getUsersMiniInfo')).toHaveLength(1) expect(procedureQueryCalls('admin.coupon.getUsersMiniInfo')).toHaveLength(1)
}) })
it('ACOUPF-18: rapid typing is debounced into a single user-search request', async () => {
const { view } = renderForm()
await openUsersWith(view, [{ id: 5, name: 'Test User', mobile: '9876543210' }])
const input = view.getByPlaceholderText('Search users by name or mobile...')
for (const value of ['9', '96', '967', '9676']) {
fireEvent.changeText(input, value)
}
await flush(2)
// Still only the request made when the dialog opened; the debounce has not elapsed.
expect(procedureQueryCalls('admin.coupon.getUsersMiniInfo')).toHaveLength(1)
await waitForUserSearchDebounce()
const calls = procedureQueryCalls('admin.coupon.getUsersMiniInfo')
expect(calls).toHaveLength(2)
expect(calls[1]).toMatchObject({ search: '9676', limit: 10, offset: 0 })
})
it('ACOUPF-17: selecting and deselecting a user updates applicableUsers', async () => { it('ACOUPF-17: selecting and deselecting a user updates applicableUsers', async () => {
setProcedure('admin.coupon.getUsersMiniInfo', { setProcedure('admin.coupon.getUsersMiniInfo', {
data: { data: {

View file

@ -312,10 +312,11 @@ export const ORDER_DETAILS = {
adminNotes: null, adminNotes: null,
userNotes: null, userNotes: null,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
deliveredAt: null,
status: 'pending', status: 'pending',
isPackaged: false, isPackaged: false,
isDelivered: false, isDelivered: false,
items: ORDER_ITEMS.map((i) => ({ ...i, quantity: String(i.quantity), price: String(i.price) })), items: ORDER_ITEMS.map((i) => ({ ...i, quantity: String(i.quantity), price: String(i.price), packagedAt: null })),
cancelReason: null, cancelReason: null,
cancellationReviewed: false, cancellationReviewed: false,
couponData: null, couponData: null,

View file

@ -357,4 +357,40 @@ describe('Order details (AOD-01..25)', () => {
expect(view.getByTestId('order-details-cancel-button')).toBeTruthy() expect(view.getByTestId('order-details-cancel-button')).toBeTruthy()
expect(view.getByTestId('order-details-back-button')).toBeTruthy() expect(view.getByTestId('order-details-back-button')).toBeTruthy()
}) })
it('AOD-26: the delivered timestamp renders when the order is delivered', async () => {
setProcedure('admin.order.getOrderDetails', {
data: order({
status: 'delivered',
isDelivered: true,
isPackaged: true,
deliveredAt: '2026-11-10T10:15:00.000Z',
}),
})
const view = await renderDetails()
expect(view.getByTestId('order-delivered-at')).toBeTruthy()
expect(view.getByText(/Delivered on/)).toBeTruthy()
})
it('AOD-27: no delivered timestamp before the order is delivered', async () => {
const view = await renderDetails()
expect(view.queryByTestId('order-delivered-at')).toBeNull()
})
it('AOD-28: a packaged item shows when it was packed', async () => {
const items = ORDER_DETAILS.items.map((item, index) =>
index === 0
? { ...item, isPackaged: true, packagedAt: '2026-11-10T09:30:00.000Z' }
: { ...item, isPackaged: true, packagedAt: null },
)
setProcedure('admin.order.getOrderDetails', { data: order({ items }) })
const view = await renderDetails()
expect(view.getByTestId('order-item-packaged-at-1')).toBeTruthy()
expect(view.getByText(/Packed/)).toBeTruthy()
// A packaged item with no recorded time renders no timestamp.
expect(view.queryByTestId('order-item-packaged-at-2')).toBeNull()
})
}) })

View file

@ -26,6 +26,10 @@ export interface CreateCouponPayload {
} }
const USERS_PAGE_SIZE = 10 const USERS_PAGE_SIZE = 10
// The user search fires on every keystroke; debounce it so a 10-digit mobile
// number does not issue 10 overlapping queries (which saturated D1 in prod and
// surfaced as a 401 / forced logout).
const USER_SEARCH_DEBOUNCE_MS = 350
interface CouponFormValues extends CreateCouponPayload { interface CouponFormValues extends CreateCouponPayload {
isReservedCoupon?: boolean isReservedCoupon?: boolean
@ -93,6 +97,9 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
// User dropdown states // User dropdown states
const [userSearchQuery, setUserSearchQuery] = useState('') const [userSearchQuery, setUserSearchQuery] = useState('')
// Debounced mirror of the input: the query below keys on this, not on every
// keystroke, so a burst of requests cannot overlap.
const [debouncedUserSearch, setDebouncedUserSearch] = useState('')
const [userOffset, setUserOffset] = useState(0) const [userOffset, setUserOffset] = useState(0)
const [allUsers, setAllUsers] = useState<{ id: number; name: string; mobile: string | null }[]>([]) const [allUsers, setAllUsers] = useState<{ id: number; name: string; mobile: string | null }[]>([])
const [hasMoreUsers, setHasMoreUsers] = useState(true) const [hasMoreUsers, setHasMoreUsers] = useState(true)
@ -102,8 +109,16 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
const [multiDialogOpen, setMultiDialogOpen] = useState(false) const [multiDialogOpen, setMultiDialogOpen] = useState(false)
const [multiCount, setMultiCount] = useState('') const [multiCount, setMultiCount] = useState('')
useEffect(() => {
const timer = setTimeout(
() => setDebouncedUserSearch(userSearchQuery),
USER_SEARCH_DEBOUNCE_MS
)
return () => clearTimeout(timer)
}, [userSearchQuery])
const { data: usersData, isFetching: isFetchingUsers } = trpc.admin.coupon.getUsersMiniInfo.useQuery( const { data: usersData, isFetching: isFetchingUsers } = trpc.admin.coupon.getUsersMiniInfo.useQuery(
{ search: userSearchQuery, limit: USERS_PAGE_SIZE, offset: userOffset }, { search: debouncedUserSearch, limit: USERS_PAGE_SIZE, offset: userOffset },
{ enabled: usersDropdownOpen } { enabled: usersDropdownOpen }
) )
@ -129,6 +144,7 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
setAllUsers([]) setAllUsers([])
setHasMoreUsers(true) setHasMoreUsers(true)
setUserSearchQuery('') setUserSearchQuery('')
setDebouncedUserSearch('')
} }
}, [usersDropdownOpen]) }, [usersDropdownOpen])

View file

@ -10,6 +10,25 @@ import { BASE_API_URL as DEFAULT_API_URL } from '@packages/shared'
export const BASE_API_URL = export const BASE_API_URL =
(import.meta.env?.VITE_API_URL as string | undefined) || DEFAULT_API_URL (import.meta.env?.VITE_API_URL as string | undefined) || DEFAULT_API_URL
// TEMP DIAGNOSTIC: decode (not verify) so we can see expiry/identity.
function decodeJwtClaims(token: string): Record<string, any> | null {
try {
const part = token.split('.')[1]
if (!part) return null
const b64 = part.replace(/-/g, '+').replace(/_/g, '/')
const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4)
const json = decodeURIComponent(
atob(padded)
.split('')
.map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
.join('')
)
return JSON.parse(json)
} catch {
return null
}
}
export const trpc = createTRPCReact<AppRouter>() export const trpc = createTRPCReact<AppRouter>()
export function getTrpcClient() { export function getTrpcClient() {
@ -19,11 +38,52 @@ export function getTrpcClient() {
url: `${BASE_API_URL}/api/trpc`, url: `${BASE_API_URL}/api/trpc`,
headers: async () => { headers: async () => {
const token = await getJWT() const token = await getJWT()
const claims = token ? decodeJwtClaims(token) : null
console.log(
`[admin-web][trpc] getJWT: ${token ? `present (${token.length} chars)` : 'MISSING'}`
)
console.log(
`[admin-web][trpc] token claims: ${
claims
? `staffId=${claims.staffId ?? '-'} userId=${claims.userId ?? '-'} exp=${
claims.exp ? new Date(claims.exp * 1000).toISOString() : '-'
} expired=${claims.exp ? claims.exp * 1000 <= Date.now() : '?'}`
: 'unreadable'
}`
)
return token ? { Authorization: `Bearer ${token}` } : {} return token ? { Authorization: `Bearer ${token}` } : {}
}, },
fetch: async (url, options) => { fetch: async (url, options) => {
const rawHeaders: any = options?.headers
const authHeader =
typeof rawHeaders?.get === 'function'
? rawHeaders.get('authorization')
: rawHeaders?.Authorization ?? rawHeaders?.authorization
console.log(
`[admin-web][trpc] request ${String(url)} | auth: ${
authHeader ? `PRESENT (${String(authHeader).length} chars)` : 'MISSING'
}`
)
const response = await fetch(url, options) const response = await fetch(url, options)
if (response.status === 401) { if (response.status === 401) {
console.log(
`[admin-web][trpc] 401 ${String(url)} | auth was: ${authHeader ? 'PRESENT' : 'MISSING'}`
)
// TEMP DIAGNOSTIC: is the same bearer still accepted on a trivial protected query?
// Skipped in tests: it adds a fetch, and the client tests assert an exact count.
if (process.env.NODE_ENV !== 'test') {
try {
const probe = await fetch(
`${BASE_API_URL}/api/trpc/admin.staffUser.me?batch=1&input=%7B%7D`,
{ method: 'GET', headers: options?.headers }
)
console.log(`[admin-web][trpc] 401 probe (staffUser.me) -> ${probe.status}`)
} catch (probeError: any) {
console.log(
`[admin-web][trpc] 401 probe failed: ${probeError?.message ?? probeError}`
)
}
}
const data = await response.clone().json().catch(() => ({})) const data = await response.clone().json().catch(() => ({}))
let code = '' let code = ''
if (data[0]?.error || data?.error) { if (data[0]?.error || data?.error) {

View file

@ -9,6 +9,7 @@ import {
Zap, Zap,
CircleAlert, CircleAlert,
Check, Check,
CheckCircle,
Package, Package,
Truck, Truck,
ChevronRight, ChevronRight,
@ -192,6 +193,17 @@ function OrderDetails() {
Placed on {dayjs(order.createdAt).format('MMM DD, YYYY • h:mm A')} Placed on {dayjs(order.createdAt).format('MMM DD, YYYY • h:mm A')}
</MyText> </MyText>
</div> </div>
{order.deliveredAt && (
<div
data-testid="order-delivered-at"
className="mt-2 flex flex-row items-center rounded-xl bg-green-50 p-3"
>
<CheckCircle size={20} color="#10B981" />
<MyText className="ml-2 font-medium text-green-800">
Delivered on {dayjs(order.deliveredAt).format('MMM DD, YYYY • h:mm A')}
</MyText>
</div>
)}
</div> </div>
{/* Cancellation Reason */} {/* Cancellation Reason */}
@ -391,6 +403,14 @@ function OrderDetails() {
</MyText> </MyText>
</button> </button>
</div> </div>
{item.packagedAt && (
<MyText
data-testid={`order-item-packaged-at-${item.id}`}
className="mt-1 block text-[10px] text-gray-400"
>
Packed {dayjs(item.packagedAt).format('MMM DD, YYYY • h:mm A')}
</MyText>
)}
</div> </div>
<MyText className="text-sm font-bold text-gray-900"> <MyText className="text-sm font-bold text-gray-900">
₹{item.amount} ₹{item.amount}

View file

@ -189,8 +189,7 @@ function EditProduct() {
newImageUrls: allUploadUrls, newImageUrls: allUploadUrls,
} as any) } as any)
await refetch() await Promise.all([refetch(), refetchProducts()])
await refetchProducts()
window.alert('Product updated successfully!') window.alert('Product updated successfully!')
productFormRef.current?.clearImages() productFormRef.current?.clearImages()
} catch (error: any) { } catch (error: any) {
@ -233,8 +232,7 @@ function EditProduct() {
deletedImageKeys: [], deletedImageKeys: [],
newImageUrls: [], newImageUrls: [],
} as any) } as any)
await refetch() await Promise.all([refetch(), refetchProducts()])
await refetchProducts()
window.alert('Market data updated for your region') window.alert('Market data updated for your region')
} catch (error: any) { } catch (error: any) {
window.alert(error.message || 'Failed to update product') window.alert(error.message || 'Failed to update product')

View file

@ -1187,12 +1187,12 @@ Covered by UCOMP-01..11. Add admin-side cases in section 7.
| AORD-10 | happy | updateNotes | stored | | AORD-10 | happy | updateNotes | stored |
| AORD-11 | error | unknown | error | | AORD-11 | error | unknown | error |
| AORD-12 | edge | empty notes | stored null | | AORD-12 | edge | empty notes | stored null |
| AORD-13 | happy | updatePackaged true/false | status; user notification | | AORD-13 | happy | updatePackaged true/false | status; user notification; item packagedAt stamped then cleared |
| AORD-14 | error | unknown order | 404 | | AORD-14 | error | unknown order | 404 |
| AORD-15 | edge | string orderId | schema requires string | | AORD-15 | edge | string orderId | schema requires string |
| AORD-16 | happy | updateDelivered true/false | user status success/pending | | AORD-16 | happy | updateDelivered true/false | user status success/pending; deliveredAt stamped, kept on repeat, cleared |
| AORD-17 | error | unknown | 404 | | AORD-17 | error | unknown | 404 |
| AORD-18 | happy | updateOrderItemPackaging | flags | | AORD-18 | happy | updateOrderItemPackaging | flags; packagedAt follows the Packaged toggle |
| AORD-19 | error | unknown item | 404 | | AORD-19 | error | unknown item | 404 |
| AORD-20 | edge | only one flag supplied | other preserved | | AORD-20 | edge | only one flag supplied | other preserved |
| AORD-21 | happy | removeDeliveryCharge | 0; user sees | | AORD-21 | happy | removeDeliveryCharge | 0; user sees |

File diff suppressed because one or more lines are too long

View file

@ -40,15 +40,20 @@ export async function initializeProducts(regionId: number): Promise<void> {
try { try {
console.log('Initializing product store in Redis...') console.log('Initializing product store in Redis...')
// Fetch all products with full details (similar to productMega logic) // All five cache slices are independent: fetch them together.
const productsData = await getAllProductsForCache(regionId) const [productsData, allStores, allDeliverySlots, allSpecialDeals, allProductTags] =
await Promise.all([
// All products with full details (similar to productMega logic)
getAllProductsForCache(regionId),
getAllStoresForCache(regionId),
// Delivery slots, excluding full capacity slots.
getAllDeliverySlotsForCache(regionId),
getAllSpecialDealsForCache(regionId),
getAllProductTagsForCache(regionId),
])
// Fetch all stores
const allStores = await getAllStoresForCache(regionId)
const storeMap = new Map(allStores.map((s) => [s.id, s])) const storeMap = new Map(allStores.map((s) => [s.id, s]))
// Fetch all delivery slots (excluding full capacity slots)
const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
const deliverySlotsMap = new Map<number, DeliverySlotData[]>() const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
for (const slot of allDeliverySlots) { for (const slot of allDeliverySlots) {
if (!deliverySlotsMap.has(slot.skuId)) if (!deliverySlotsMap.has(slot.skuId))
@ -56,8 +61,7 @@ export async function initializeProducts(regionId: number): Promise<void> {
deliverySlotsMap.get(slot.skuId)!.push(slot) deliverySlotsMap.get(slot.skuId)!.push(slot)
} }
// Fetch all special deals // Special deals by sku
const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
const specialDealsMap = new Map<number, SpecialDealData[]>() const specialDealsMap = new Map<number, SpecialDealData[]>()
for (const deal of allSpecialDeals) { for (const deal of allSpecialDeals) {
if (!specialDealsMap.has(deal.skuId)) if (!specialDealsMap.has(deal.skuId))
@ -65,8 +69,7 @@ export async function initializeProducts(regionId: number): Promise<void> {
specialDealsMap.get(deal.skuId)!.push(deal) specialDealsMap.get(deal.skuId)!.push(deal)
} }
// Fetch all product tags // Tag names by product
const allProductTags = await getAllProductTagsForCache(regionId)
const productTagsMap = new Map<number, string[]>() const productTagsMap = new Map<number, string[]>()
for (const tag of allProductTags) { for (const tag of allProductTags) {
if (!productTagsMap.has(tag.productId)) if (!productTagsMap.has(tag.productId))
@ -158,12 +161,25 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
// //
// return products // return products
const productsData = await getAllProductsForCache(regionId) // All six cache slices are independent: fetch them together.
const [
productsData,
allStores,
allDeliverySlots,
allSpecialDeals,
allProductTags,
allProductCombos,
] = await Promise.all([
getAllProductsForCache(regionId),
getAllStoresForCache(regionId),
getAllDeliverySlotsForCache(regionId),
getAllSpecialDealsForCache(regionId),
getAllProductTagsForCache(regionId),
getAllProductCombosForCache(regionId),
])
const allStores = await getAllStoresForCache(regionId)
const storeMap = new Map(allStores.map((s) => [s.id, s])) const storeMap = new Map(allStores.map((s) => [s.id, s]))
const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
const deliverySlotsMap = new Map<number, DeliverySlotData[]>() const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
for (const slot of allDeliverySlots) { for (const slot of allDeliverySlots) {
if (!deliverySlotsMap.has(slot.skuId)) if (!deliverySlotsMap.has(slot.skuId))
@ -171,7 +187,6 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
deliverySlotsMap.get(slot.skuId)!.push(slot) deliverySlotsMap.get(slot.skuId)!.push(slot)
} }
const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
const specialDealsMap = new Map<number, SpecialDealData[]>() const specialDealsMap = new Map<number, SpecialDealData[]>()
for (const deal of allSpecialDeals) { for (const deal of allSpecialDeals) {
if (!specialDealsMap.has(deal.skuId)) if (!specialDealsMap.has(deal.skuId))
@ -179,7 +194,6 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
specialDealsMap.get(deal.skuId)!.push(deal) specialDealsMap.get(deal.skuId)!.push(deal)
} }
const allProductTags = await getAllProductTagsForCache(regionId)
const productTagsMap = new Map<number, string[]>() const productTagsMap = new Map<number, string[]>()
for (const tag of allProductTags) { for (const tag of allProductTags) {
if (!productTagsMap.has(tag.productId)) if (!productTagsMap.has(tag.productId))
@ -188,7 +202,6 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
} }
const products: Product[] = [] const products: Product[] = []
const allProductCombos = await getAllProductCombosForCache(regionId)
const productCombosMap = new Map<number, ProductComboCacheData[]>() const productCombosMap = new Map<number, ProductComboCacheData[]>()
for (const comboItem of allProductCombos) { for (const comboItem of allProductCombos) {
if (!productCombosMap.has(comboItem.comboSkuId)) if (!productCombosMap.has(comboItem.comboSkuId))

View file

@ -45,11 +45,11 @@ export async function initializeProductTagStore(regionId: number): Promise<void>
try { try {
console.log('Initializing product tag store in Redis...') console.log('Initializing product tag store in Redis...')
// Fetch all tags // The tags and their product mappings are independent reads.
const tagsData = await getAllTagsForCache(regionId) const [tagsData, productTagsData] = await Promise.all([
getAllTagsForCache(regionId),
// Fetch product IDs for each tag getAllTagProductMappings(regionId),
const productTagsData = await getAllTagProductMappings(regionId) ])
// Group product IDs by tag // Group product IDs by tag
const productIdsByTag = new Map<number, number[]>() const productIdsByTag = new Map<number, number[]>()

View file

@ -81,9 +81,17 @@ export async function getMultipleUserNegativityScores(
// //
// return result // return result
// One query per user, all independent: run them together.
const entries = await Promise.all(
userIds.map(async (userId) => ({
userId,
score: await getUserNegativityScoreFromDb(userId),
}))
)
const result: Record<number, number> = {} const result: Record<number, number> = {}
for (const userId of userIds) { for (const entry of entries) {
result[userId] = await getUserNegativityScoreFromDb(userId) result[entry.userId] = entry.score
} }
return result return result
} catch (error) { } catch (error) {

View file

@ -367,9 +367,11 @@ export const productRouter = router({
skus: skuInputs, skus: skuInputs,
} as any, ctx.staffUser!.regionId) } as any, ctx.staffUser!.regionId)
await claimUploadUrls(allUploadUrls) // Both are post-write side effects and independent of each other.
await Promise.all([
await scheduleStoreInitialization(ctx.staffUser!.regionId) claimUploadUrls(allUploadUrls),
scheduleStoreInitialization(ctx.staffUser!.regionId),
])
const productWithImageUrls = { const productWithImageUrls = {
...newProduct, ...newProduct,
@ -470,11 +472,12 @@ export const productRouter = router({
throw new ApiError('Product not found', 404) throw new ApiError('Product not found', 404)
} }
if (uploadsToValidate.length > 0) { await Promise.all([
await claimUploadUrls(uploadsToValidate) uploadsToValidate.length > 0
} ? claimUploadUrls(uploadsToValidate)
: Promise.resolve(),
await scheduleStoreInitialization(ctx.staffUser!.regionId) scheduleStoreInitialization(ctx.staffUser!.regionId),
])
const productWithImageUrls = { const productWithImageUrls = {
...updatedProduct, ...updatedProduct,
@ -712,9 +715,10 @@ export const productRouter = router({
await replaceTagProducts(ctx.staffUser!.regionId, createdTag.id, productIds) await replaceTagProducts(ctx.staffUser!.regionId, createdTag.id, productIds)
await claimUploadUrls(uploadUrls) await Promise.all([
claimUploadUrls(uploadUrls),
await scheduleStoreInitialization(ctx.staffUser!.regionId) scheduleStoreInitialization(ctx.staffUser!.regionId),
])
const { products, ...createdTagInfo } = createdTag const { products, ...createdTagInfo } = createdTag
@ -779,9 +783,10 @@ export const productRouter = router({
await replaceTagProducts(ctx.staffUser!.regionId, id, productIds) await replaceTagProducts(ctx.staffUser!.regionId, id, productIds)
} }
await claimUploadUrls(uploadUrls) await Promise.all([
claimUploadUrls(uploadUrls),
await scheduleStoreInitialization(ctx.staffUser!.regionId) scheduleStoreInitialization(ctx.staffUser!.regionId),
])
const { products, ...updatedTagInfo } = updatedTag const { products, ...updatedTagInfo } = updatedTag

View file

@ -51,9 +51,12 @@ export const userRouter = {
// Get order stats for each user // Get order stats for each user
const userIds = usersToReturn.map((u: any) => u.id); const userIds = usersToReturn.map((u: any) => u.id);
const orderCounts = await getOrderCountsByUserIds(ctx.staffUser!.regionId, userIds); // The three per-user stats are independent reads.
const lastOrders = await getLastOrdersByUserIds(ctx.staffUser!.regionId, userIds); const [orderCounts, lastOrders, suspensionStatuses] = await Promise.all([
const suspensionStatuses = await getSuspensionStatusesByUserIds(ctx.staffUser!.regionId, userIds); getOrderCountsByUserIds(ctx.staffUser!.regionId, userIds),
getLastOrdersByUserIds(ctx.staffUser!.regionId, userIds),
getSuspensionStatusesByUserIds(ctx.staffUser!.regionId, userIds),
]);
// Create lookup maps // Create lookup maps
const orderCountMap = new Map(orderCounts.map(o => [o.userId, o.totalOrders])); const orderCountMap = new Map(orderCounts.map(o => [o.userId, o.totalOrders]));
@ -92,18 +95,19 @@ export const userRouter = {
throw new ApiError('User not found', 404); throw new ApiError('User not found', 404);
} }
// Get user suspension status // Suspension status and the order list are independent reads.
const isSuspended = await getUserSuspensionStatus(userId); const [isSuspended, userOrders] = await Promise.all([
getUserSuspensionStatus(userId),
// Get all orders for this user getUserOrders(ctx.staffUser!.regionId, userId),
const userOrders = await getUserOrders(ctx.staffUser!.regionId, userId); ]);
// Get order status for each order // Get order status for each order
const orderIds = userOrders.map((o: any) => o.id); const orderIds = userOrders.map((o: any) => o.id);
const orderStatuses = await getOrderStatusesByOrderIds(ctx.staffUser!.regionId, orderIds); // Order status and item counts both key off orderIds; run them together.
const [orderStatuses, itemCounts] = await Promise.all([
// Get item counts for each order getOrderStatusesByOrderIds(ctx.staffUser!.regionId, orderIds),
const itemCounts = await getItemCountsByOrderIds(ctx.staffUser!.regionId, orderIds); getItemCountsByOrderIds(ctx.staffUser!.regionId, orderIds),
]);
// Create lookup maps // Create lookup maps
const statusMap = new Map(orderStatuses.map(s => [s.orderId, s])); const statusMap = new Map(orderStatuses.map(s => [s.orderId, s]));
@ -163,10 +167,11 @@ export const userRouter = {
.query(async ({ input, ctx }) => { .query(async ({ input, ctx }) => {
const { search } = input; const { search } = input;
const usersList = await searchUsers(ctx.staffUser!.regionId, search); // The user list and the notif_creds lookup are independent.
const [usersList, eligibleUsers] = await Promise.all([
// Get eligible users (have notif_creds entry) searchUsers(ctx.staffUser!.regionId, search),
const eligibleUsers = await getAllNotifCreds(); getAllNotifCreds(),
]);
const eligibleSet = new Set(eligibleUsers.map(u => u.userId)); const eligibleSet = new Set(eligibleUsers.map(u => u.userId));
@ -203,8 +208,10 @@ export const userRouter = {
if (userIds.length === 0) { if (userIds.length === 0) {
// Send to all users - get tokens from both logged-in and unlogged users // Send to all users - get tokens from both logged-in and unlogged users
const loggedInTokens = await getAllNotifCreds(); const [loggedInTokens, unloggedTokens] = await Promise.all([
const unloggedTokens = await getAllUnloggedTokens(); getAllNotifCreds(),
getAllUnloggedTokens(),
]);
tokens = [ tokens = [
...loggedInTokens.map(t => t.token), ...loggedInTokens.map(t => t.token),

View file

@ -450,8 +450,10 @@ export const orderRouter = router({
const userId = ctx.user.userId; const userId = ctx.user.userId;
const offset = (page - 1) * pageSize; const offset = (page - 1) * pageSize;
const totalCount = await getUserOrderCount(userId); const [totalCount, userOrders] = await Promise.all([
const userOrders = await getUserOrdersWithRelations(userId, offset, pageSize); getUserOrderCount(userId),
getUserOrdersWithRelations(userId, offset, pageSize),
]);
const mappedOrders = await Promise.all( const mappedOrders = await Promise.all(
userOrders.map(async (order) => { userOrders.map(async (order) => {

View file

@ -327,6 +327,9 @@ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => {
const fx = await createCatalogOrderFixture({ price: 100 }) const fx = await createCatalogOrderFixture({ price: 100 })
const orderId = await placeOne(fx) const orderId = await placeOne(fx)
const before: any = await admin.admin.order.getOrderDetails.query({ orderId })
expect(before.items[0].packagedAt).toBeNull()
const packed: any = await admin.admin.order.updatePackaged.mutate({ const packed: any = await admin.admin.order.updatePackaged.mutate({
orderId: String(orderId), orderId: String(orderId),
isPackaged: true, isPackaged: true,
@ -336,9 +339,17 @@ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => {
expect(afterPacked.deliveryStatus).toBe('packaged') expect(afterPacked.deliveryStatus).toBe('packaged')
expect(afterPacked.orderStatus).toBe('success') expect(afterPacked.orderStatus).toBe('success')
// Every item is stamped with the packaging moment.
const packedDetail: any = await admin.admin.order.getOrderDetails.query({ orderId })
expect(typeof packedDetail.items[0].packagedAt).toBe('string')
expect(Number.isNaN(new Date(packedDetail.items[0].packagedAt).getTime())).toBe(false)
await admin.admin.order.updatePackaged.mutate({ orderId: String(orderId), isPackaged: false }) await admin.admin.order.updatePackaged.mutate({ orderId: String(orderId), isPackaged: false })
const afterUnpacked: any = await detail(fx.user.token, orderId) const afterUnpacked: any = await detail(fx.user.token, orderId)
expect(afterUnpacked.deliveryStatus).toBe('pending') expect(afterUnpacked.deliveryStatus).toBe('pending')
const unpackedDetail: any = await admin.admin.order.getOrderDetails.query({ orderId })
expect(unpackedDetail.items[0].packagedAt).toBeNull()
}) })
it('AORD-14: updatePackaged on an unknown order is NOT_FOUND 404', async () => { it('AORD-14: updatePackaged on an unknown order is NOT_FOUND 404', async () => {
@ -363,6 +374,9 @@ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => {
const fx = await createCatalogOrderFixture({ price: 100 }) const fx = await createCatalogOrderFixture({ price: 100 })
const orderId = await placeOne(fx) const orderId = await placeOne(fx)
const before: any = await admin.admin.order.getOrderDetails.query({ orderId })
expect(before.deliveredAt).toBeNull()
const res: any = await admin.admin.order.updateDelivered.mutate({ const res: any = await admin.admin.order.updateDelivered.mutate({
orderId: String(orderId), orderId: String(orderId),
isDelivered: true, isDelivered: true,
@ -372,10 +386,21 @@ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => {
expect(delivered.orderStatus).toBe('success') expect(delivered.orderStatus).toBe('success')
expect(delivered.deliveryStatus).toBe('success') expect(delivered.deliveryStatus).toBe('success')
// The delivery moment is recorded and survives a repeat "delivered" call.
const deliveredDetail: any = await admin.admin.order.getOrderDetails.query({ orderId })
expect(typeof deliveredDetail.deliveredAt).toBe('string')
expect(Number.isNaN(new Date(deliveredDetail.deliveredAt).getTime())).toBe(false)
await admin.admin.order.updateDelivered.mutate({ orderId: String(orderId), isDelivered: true })
const repeat: any = await admin.admin.order.getOrderDetails.query({ orderId })
expect(repeat.deliveredAt).toBe(deliveredDetail.deliveredAt)
await admin.admin.order.updateDelivered.mutate({ orderId: String(orderId), isDelivered: false }) await admin.admin.order.updateDelivered.mutate({ orderId: String(orderId), isDelivered: false })
const pending: any = await detail(fx.user.token, orderId) const pending: any = await detail(fx.user.token, orderId)
expect(pending.orderStatus).toBe('success') expect(pending.orderStatus).toBe('success')
expect(pending.deliveryStatus).toBe('pending') expect(pending.deliveryStatus).toBe('pending')
const pendingDetail: any = await admin.admin.order.getOrderDetails.query({ orderId })
expect(pendingDetail.deliveredAt).toBeNull()
}) })
it('AORD-17: updateDelivered on an unknown order is NOT_FOUND 404', async () => { it('AORD-17: updateDelivered on an unknown order is NOT_FOUND 404', async () => {
@ -410,6 +435,15 @@ describe('admin.order.updateOrderItemPackaging (AORD-18..20)', () => {
const after: any = await admin.admin.order.getOrderDetails.query({ orderId }) const after: any = await admin.admin.order.getOrderDetails.query({ orderId })
expect(after.items[0].isPackaged).toBe(true) expect(after.items[0].isPackaged).toBe(true)
expect(after.items[0].isPackageVerified).toBe(true) expect(after.items[0].isPackageVerified).toBe(true)
expect(typeof after.items[0].packagedAt).toBe('string')
await admin.admin.order.updateOrderItemPackaging.mutate({
orderItemId: itemId,
isPackaged: false,
})
const unpacked: any = await admin.admin.order.getOrderDetails.query({ orderId })
expect(unpacked.items[0].isPackaged).toBe(false)
expect(unpacked.items[0].packagedAt).toBeNull()
}) })
it('AORD-19: an unknown order item is NOT_FOUND 404', async () => { it('AORD-19: an unknown order item is NOT_FOUND 404', async () => {

View file

@ -50,6 +50,11 @@ Use these names in the cases below so the expected values stay consistent.
| `CART_REG` | Chicken qty 2 in slot `S1`; line id 1 | cart/checkout | | `CART_REG` | Chicken qty 2 in slot `S1`; line id 1 | cart/checkout |
| `CART_FLASH` | Paneer qty 1 in slot 0; line id 1 | flash cart/checkout | | `CART_FLASH` | Paneer qty 1 in slot 0; line id 1 | flash cart/checkout |
| `AUTH_USER` | `{id:5,name:'Test User',email:'test@example.com',mobile:'9876543210'}` | all signed-in pages | | `AUTH_USER` | `{id:5,name:'Test User',email:'test@example.com',mobile:'9876543210'}` | all signed-in pages |
| `C_SKU2_PERCENT` | `C4` (`TARGET10`) as a catalogue offer: 10% max ₹40 on sku 2 → ₹215 becomes ₹194 | card, product detail |
| `C_SKU2_FLAT` | `SKU2FLAT` flat ₹100 on sku 2 | catalogue coupon comparison |
| `C_SKU2_MIN` | `SKU2MIN1000` flat ₹20 on sku 2 with `minOrder` 1000 (ignored on the catalogue) | catalogue coupon rules |
| `C_SKU8_FLASH` | `FLASH10` 10% max ₹20 on sku 8 → ₹90 regular, ₹75 flash | flash card/detail |
| `C_SKU2_FIRST` | `SKU2FIRST` first-order-only, flat ₹30 on sku 2 | catalogue coupon rules |
### Global reset rules ### Global reset rules
@ -60,10 +65,18 @@ Use these names in the cases below so the expected values stay consistent.
`region_carts_*`, `essential_consts_b*`). `region_carts_*`, `essential_consts_b*`).
3. Clear all Jest mocks and fake timers. Use real timers only for tests that do not depend on 3. Clear all Jest mocks and fake timers. Use real timers only for tests that do not depend on
debounce/countdown. debounce/countdown.
4. Mock router `push`, `replace`, `back`, `dismissTo`, `dismissAll`, `canGoBack`, `useLocalSearchParams`. 4. Catalogue pages read `useCentralProductStore`, not their own `useAllProducts()` call.
5. For page tests, mock `expo-router` only for navigation; keep `common-ui` components real. `renderWithProviders(ui, { withProductStore: true })` mounts the real producer so the mocked
6. Every case that presses a button which calls the API must assert the procedure name and the products JSON (payload, tags, pending, error) still drives the page. A first-load failure case
also clears the store with `seedEmptyCatalogue()`: `seedBoot()` seeds a *loaded* catalogue, and
a failed background refresh keeps it on purpose (“keep the last good catalogue”).
5. Mock router `push`, `replace`, `back`, `dismissTo`, `dismissAll`, `canGoBack`, `useLocalSearchParams`.
6. For page tests, mock `expo-router` only for navigation; keep `common-ui` components real.
7. Every case that presses a button which calls the API must assert the procedure name and the
exact input (use `lastProcedureInput`). exact input (use `lastProcedureInput`).
8. Catalogue coupon prices are seeded through the store, never through a request:
`useCentralProductStore.getState().setCouponOffers({ [skuId]: [offer] })`. `seedBoot()` seeds a
catalogue *without* offers, so the default for every existing case is “no coupon price”.
--- ---
@ -287,8 +300,8 @@ Mock `useAllProducts` via `common.essentialConsts` + versioned `products.json` a
| ID | Type | Case and setup | Assertion | | ID | Type | Case and setup | Assertion |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| HOME-01 | happy | products query pending | “Loading products...” | | HOME-01 | happy | products query pending | “Loading products...” |
| HOME-02 | error | products request rejects | “Oops!” + “Failed to load products” | | HOME-02 | error | products request rejects with an empty catalogue | “Oops!” + “Failed to load products” |
| HOME-03 | error | consts request rejects, products succeed | “Failed to load app settings” | | HOME-03 | error | consts request rejects, no catalogue | “Failed to load app settings” |
| HOME-04 | edge | products resolve with no products/tags | “No products available”; no tag strip | | HOME-04 | edge | products resolve with no products/tags | “No products available”; no tag strip |
| HOME-05 | edge | tag exists but `productIds` empty | “No products in this category yet” | | HOME-05 | edge | tag exists but `productIds` empty | “No products in this category yet” |
| HOME-06 | edge | products fetch empty while stores/slots load | page still renders stores/slots independently | | HOME-06 | edge | products fetch empty while stores/slots load | page still renders stores/slots independently |
@ -450,7 +463,7 @@ Mock `useAllProducts` via `common.essentialConsts` + versioned `products.json` a
| SEARCH-11 | edge | whitespace-only query | treated as empty | | SEARCH-11 | edge | whitespace-only query | treated as empty |
| SEARCH-12 | edge | special characters/quotes | no crash; escaped in header | | SEARCH-12 | edge | special characters/quotes | no crash; escaped in header |
| SEARCH-13 | happy | products pending | “Loading products...” empty component | | SEARCH-13 | happy | products pending | “Loading products...” empty component |
| SEARCH-14 | error | products request fails | current behavior: “No products found”, not an error screen | | SEARCH-14 | error | products request fails, no catalogue | current behavior: “No products found”, not an error screen |
| SEARCH-15 | edge | search input focused on mount | `requestAnimationFrame` focus called | | SEARCH-15 | edge | search input focused on mount | `requestAnimationFrame` focus called |
| SEARCH-16 | edge | pull to refresh | products refetch | | SEARCH-16 | edge | pull to refresh | products refetch |
| SEARCH-17 | edge | `useMarkDataFetchers` | products refetch | | SEARCH-17 | edge | `useMarkDataFetchers` | products refetch |
@ -510,7 +523,7 @@ This file covers the route wrapper, `SlotLayout`, `SlotProducts` and the flash p
| ID | Type | Case and setup | Assertion | | ID | Type | Case and setup | Assertion |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| FLASH-01 | happy | products pending | “Loading 1 Hr Delivery...” | | FLASH-01 | happy | products pending | “Loading 1 Hr Delivery...” |
| FLASH-02 | error | products fail, no cache | “Failed to load 1 Hr Delivery” | | FLASH-02 | error | products fail, no cache, no catalogue | “Failed to load 1 Hr Delivery” |
| FLASH-03 | happy | tag tabs | first tag selected; only non-empty tags get a tab | | FLASH-03 | happy | tag tabs | first tag selected; only non-empty tags get a tab |
| FLASH-04 | happy | data | only flash-available + in-stock products of the tag | | FLASH-04 | happy | data | only flash-available + in-stock products of the tag |
| FLASH-05 | happy | select another tag | feed swaps to that tag’s products | | FLASH-05 | happy | select another tag | feed swaps to that tag’s products |
@ -656,6 +669,10 @@ Use one shared component test file plus four route smoke files. Mock
| PD-49 | route | store variant | id passed; regular cart | | PD-49 | route | store variant | id passed; regular cart |
| PD-50 | route | offers variant | id passed; regular cart | | PD-50 | route | offers variant | id passed; regular cart |
| PD-51 | route | flash variant | id passed; `isFlashDelivery` true | | PD-51 | route | flash variant | id passed; `isFlashDelivery` true |
| PD-52 | happy | product-specific coupon in the store | `₹194` + “With Coupon” under the price block; listed price stays 30, coupon line 16 |
| PD-53 | edge | no coupon offer | no coupon line |
| PD-54 | edge | flash detail with a coupon | priced off `flashPrice` (₹75 → ₹68) |
| PD-55 | edge | out-of-stock product with a coupon offer | no coupon line |
--- ---
@ -1227,6 +1244,21 @@ Already covered by HOME-63..80; add:
| A2C-05 | edge | cart line with different SKU | not considered update | | A2C-05 | edge | cart line with different SKU | not considered update |
| A2C-06 | edge | `onClose` via backdrop | clears product | | A2C-06 | edge | `onClose` via backdrop | clears product |
### ProductCard coupon price (`tests/components/product-card-coupon.test.tsx`)
The card reads `couponOffers` from the central product store; no request of its own.
| ID | Type | Case and setup | Assertion |
| --- | --- | --- | --- |
| PCARD-01 | edge | no coupon offer for the sku | no coupon row |
| PCARD-02 | happy | 10% capped ₹40 on a ₹215 item | `₹194` + “With Coupon” |
| PCARD-03 | edge | coupon applied | listed price keeps `text-base` (16); struck price and coupon price both 12 |
| PCARD-04 | edge | coupon applied | coupon price in `brand500`, “With Coupon” in `gray400` |
| PCARD-05 | edge | no coupon | price unchanged: 16, struck 12 |
| PCARD-06 | edge | offer for a different sku | this card unaffected |
| PCARD-07 | edge | flash card, flash ₹75, 10% capped ₹20 | `₹68` (priced off `flashPrice`) |
| PCARD-08 | edge | out-of-stock product with an offer | no coupon row |
### FloatingCartBar ### FloatingCartBar
Covered by HOME-81..98, plus: Covered by HOME-81..98, plus:
@ -1238,6 +1270,9 @@ Covered by HOME-81..98, plus:
| FCB-03 | edge | flash cart | pink theme | | FCB-03 | edge | flash cart | pink theme |
| FCB-04 | edge | cart refetch after mutation | quantities state resets | | FCB-04 | edge | cart refetch after mutation | quantities state resets |
| FCB-05 | edge | no cart data | no crash | | FCB-05 | edge | no cart data | no crash |
| FCB-06 | happy | expanded sheet | “Apply Coupons at checkout” under the subtotal |
| FCB-07 | happy | coupon offer on the line's sku | `₹390` (₹430 line after the cap) + “With Coupon” |
| FCB-08 | edge | no offer for the sku | no coupon line |
### CouponBreakdownDialog ### CouponBreakdownDialog
@ -1595,6 +1630,29 @@ Covered by HOME-81..98, plus:
| STORE-10 | edge | centralProduct setProducts | products + map by id | | STORE-10 | edge | centralProduct setProducts | products + map by id |
| STORE-11 | edge | centralProduct refetch setter | callable | | STORE-11 | edge | centralProduct refetch setter | callable |
| STORE-12 | edge | centralSlot setSlotsData | map for all availability products; slots attached; flags | | STORE-12 | edge | centralSlot setSlotsData | map for all availability products; slots attached; flags |
| STORE-13 | edge | coupon offers set before the catalogue | products decorated (`isProductCouponApply`, `couponDiscountedPrice`) |
| STORE-14 | edge | coupon offers set after the catalogue | already-loaded products decorated |
| STORE-15 | edge | catalogue refresh / offers cleared | refresh keeps the fields; clearing strips them |
#### Catalogue coupon pricing (`src/lib/product-coupons.ts`, `tests/lib/product-coupons.test.ts`)
| ID | Type | Case and setup | Assertion |
| --- | --- | --- | --- |
| COUPON-01 | happy | targeted coupon | mapped onto its sku only |
| COUPON-02 | edge | cart-wide coupon (`skuIds: []`) | no offers |
| COUPON-03 | edge | `skuIds: null` | no offers |
| COUPON-04 | edge | coupon from another region | dropped unless the region matches |
| COUPON-05 | edge | coupon with no region | applies everywhere |
| COUPON-06 | edge | first-order-only coupon | dropped after the first order |
| COUPON-07 | edge | invalidated coupon | dropped |
| COUPON-08 | edge | targeted coupon carrying `minOrder` | advertised anyway (cart-level rule) |
| COUPON-09 | edge | two coupons on one sku | both kept for comparison |
| COUPON-10 | happy | 10% capped ₹40 on ₹215 | `₹194` (whole rupees, matches the cart) |
| COUPON-11 | edge | 10% vs flat ₹100 | the cheaper result wins |
| COUPON-12 | edge | same offer on ₹90 / flash ₹75 | `₹81` / `₹68` |
| COUPON-13 | edge | zero / null / non-numeric price | no coupon price |
| COUPON-14 | edge | coupon that discounts nothing | no coupon price |
| COUPON-15 | edge | unknown sku | no coupon price |
| STORE-13 | edge | centralSlot refetch setter | callable | | STORE-13 | edge | centralSlot refetch setter | callable |
| STORE-14 | edge | checkout notes | set | | STORE-14 | edge | checkout notes | set |
| STORE-15 | edge | region set | id/region/bound; generation bump | | STORE-15 | edge | region set | id/region/bound; generation bump |

View file

@ -11,7 +11,7 @@ import {
} from "common-ui"; } from "common-ui";
import MaterialIcons from "@expo/vector-icons/MaterialIcons"; import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import Fuse from "fuse.js"; import Fuse from "fuse.js";
import { useAllProducts } from "@/src/hooks/prominent-api-hooks"; import { useCentralProductStore } from "@/src/store/centralProductStore";
import ProductCard from "@/components/ProductCard"; import ProductCard from "@/components/ProductCard";
import FloatingCartBar from "@/components/floating-cart-bar"; import FloatingCartBar from "@/components/floating-cart-bar";
@ -77,9 +77,9 @@ export default function SearchResults() {
}); });
}, []); }, []);
const { data: productsData, isLoading, error, refetch } = useAllProducts(); const allProducts = useCentralProductStore((state) => state.products);
const isLoading = useCentralProductStore((state) => state.isLoading);
const allProducts = useMemo(() => productsData?.products ?? [], [productsData]); const refetchProducts = useCentralProductStore((state) => state.refetchProducts);
// Client-side search filtering using Fuse.js // Client-side search filtering using Fuse.js
const products = useMemo(() => { const products = useMemo(() => {
@ -100,11 +100,11 @@ export default function SearchResults() {
}, [allProducts, debouncedQuery]); }, [allProducts, debouncedQuery]);
useManualRefresh(() => { useManualRefresh(() => {
refetch(); refetchProducts?.();
}); });
useMarkDataFetchers(() => { useMarkDataFetchers(() => {
refetch(); refetchProducts?.();
}); });
const handleSearch = useCallback(() => { const handleSearch = useCallback(() => {

View file

@ -8,7 +8,7 @@ import { LinearGradient } from 'expo-linear-gradient';
import { Ionicons } from '@expo/vector-icons'; import { Ionicons } from '@expo/vector-icons';
import NextOrderGlimpse from '@/components/NextOrderGlimpse'; import NextOrderGlimpse from '@/components/NextOrderGlimpse';
import AddressSwitcherSheet from '@/src/components/location/AddressSwitcherSheet'; import AddressSwitcherSheet from '@/src/components/location/AddressSwitcherSheet';
import { useRegion } from '@/src/hooks/useRegion'; import { useRegionNeo } from '@/src/hooks/useRegionNeo';
import { useAuth } from '@/src/contexts/AuthContext'; import { useAuth } from '@/src/contexts/AuthContext';
import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget'; import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget';
import { useGetEssentialConsts } from '@/src/hooks/prominent-api-hooks'; import { useGetEssentialConsts } from '@/src/hooks/prominent-api-hooks';
@ -22,7 +22,7 @@ export default function Me() {
const { logout } = useAuth(); const { logout } = useAuth();
const { getNavigationTarget } = useNavigationTarget(); const { getNavigationTarget } = useNavigationTarget();
const [regionDialogOpen, setRegionDialogOpen] = useState(false); const [regionDialogOpen, setRegionDialogOpen] = useState(false);
const { region: selectedRegion } = useRegion(); const regionName = useRegionNeo().regionName;
// Same number the NextOrderGlimpse dials via tel: — Live Support opens it in WhatsApp. // Same number the NextOrderGlimpse dials via tel: — Live Support opens it in WhatsApp.
const { data: essentialConsts } = useGetEssentialConsts(); const { data: essentialConsts } = useGetEssentialConsts();
const supportMobile = essentialConsts?.supportMobile ?? null; const supportMobile = essentialConsts?.supportMobile ?? null;
@ -108,7 +108,7 @@ export default function Me() {
icon: 'globe-outline', icon: 'globe-outline',
color: '#0EA5E9', color: '#0EA5E9',
onPress: () => setRegionDialogOpen(true), onPress: () => setRegionDialogOpen(true),
subtitle: selectedRegion?.name ? `Delivering in ${selectedRegion.name}` : 'Choose or add an address' subtitle: regionName ? `Delivering in ${regionName}` : 'Choose or add an address'
}, },
{ {
title: 'Profile Settings', title: 'Profile Settings',

View file

@ -12,7 +12,7 @@ import {
import MaterialIcons from "@expo/vector-icons/MaterialIcons"; import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import type { OffersSectionProps } from '@packages/shared'; import type { OffersSectionProps } from '@packages/shared';
import ProductCard from "@/components/ProductCard"; import ProductCard from "@/components/ProductCard";
import { useAllProducts } from "@/src/hooks/prominent-api-hooks"; import { useCentralProductStore } from "@/src/store/centralProductStore";
import FloatingCartBar from "@/components/floating-cart-bar"; import FloatingCartBar from "@/components/floating-cart-bar";
import TabLayoutWrapper from "@/components/TabLayoutWrapper"; import TabLayoutWrapper from "@/components/TabLayoutWrapper";
import LocationBar from "@/src/components/LocationBar"; import LocationBar from "@/src/components/LocationBar";
@ -95,18 +95,20 @@ export default function Offers() {
const [expandedOffers, setExpandedOffers] = useState(false); const [expandedOffers, setExpandedOffers] = useState(false);
const [expandedCombos, setExpandedCombos] = useState(false); const [expandedCombos, setExpandedCombos] = useState(false);
const { data, isLoading, error, refetch } = useAllProducts(); const allProducts = useCentralProductStore((state) => state.products);
const isLoading = useCentralProductStore((state) => state.isLoading);
const error = useCentralProductStore((state) => state.error);
const refetchProducts = useCentralProductStore((state) => state.refetchProducts);
const allProducts = data?.products || [];
const combos = allProducts.filter((p) => p.productType === 'combo'); const combos = allProducts.filter((p) => p.productType === 'combo');
const offers = allProducts.filter((p) => p.isOffer); const offers = allProducts.filter((p) => p.isOffer);
useManualRefresh(() => { useManualRefresh(() => {
refetch(); refetchProducts?.();
}); });
useMarkDataFetchers(() => { useMarkDataFetchers(() => {
refetch(); refetchProducts?.();
}); });
if (isLoading) { if (isLoading) {

View file

@ -16,7 +16,8 @@ import FontAwesome5 from "@expo/vector-icons/FontAwesome5";
import ProductCard from "@/components/ProductCard"; import ProductCard from "@/components/ProductCard";
import FloatingCartBar from "@/components/floating-cart-bar"; import FloatingCartBar from "@/components/floating-cart-bar";
import { useStoreHeaderStore } from "@/src/store/storeHeaderStore"; import { useStoreHeaderStore } from "@/src/store/storeHeaderStore";
import { useAllProducts, useStoreWithProducts } from "@/src/hooks/prominent-api-hooks"; import { useCentralProductStore } from "@/src/store/centralProductStore";
import { useStoreWithProducts } from "@/src/hooks/prominent-api-hooks";
import type { StoreTag, TagChipProps } from "@packages/shared"; import type { StoreTag, TagChipProps } from "@packages/shared";
const { width: screenWidth } = Dimensions.get("window"); const { width: screenWidth } = Dimensions.get("window");
@ -55,22 +56,15 @@ export default function StoreDetail() {
const { data: storeData, isLoading, refetch, error } = const { data: storeData, isLoading, refetch, error } =
useStoreWithProducts(storeIdNum); useStoreWithProducts(storeIdNum);
const { data: productsData, isLoading: isProductsLoading } = useAllProducts(); const productsById = useCentralProductStore((state) => state.productsById);
const isProductsLoading = useCentralProductStore((state) => state.isLoading);
const productById = useMemo(() => {
const map = new Map<number, any>();
productsData?.products?.forEach((product) => {
map.set(product.id, product);
});
return map;
}, [productsData]);
const storeProducts = useMemo(() => { const storeProducts = useMemo(() => {
if (!storeData?.products) return []; if (!storeData?.products) return [];
return storeData.products return storeData.products
.map((product) => productById.get(product.id)) .map((product) => productsById[product.id])
.filter(Boolean); .filter(Boolean);
}, [storeData, productById]); }, [storeData, productsById]);
// Filter products based on selected tag // Filter products based on selected tag
const filteredProducts = selectedTagId const filteredProducts = selectedTagId

View file

@ -29,7 +29,9 @@ import BackHandlerWrapper from "@/components/BackHandler";
import AddToCartDialog from "@/src/components/AddToCartDialog"; import AddToCartDialog from "@/src/components/AddToCartDialog";
import PendingAddressSync from "@/src/components/PendingAddressSync"; import PendingAddressSync from "@/src/components/PendingAddressSync";
import NotifRegionSync from "@/src/components/NotifRegionSync"; import NotifRegionSync from "@/src/components/NotifRegionSync";
import LocationTestWrapper from "@/components/LocationTestWrapper"; // Old region gate — superseded by LocationWrapperNeo. Kept for reference.
// import LocationTestWrapper from "@/components/LocationTestWrapper";
import LocationWrapperNeo from "@/components/LocationWrapperNeo";
import React from "react"; import React from "react";
import { GestureHandlerRootView } from "react-native-gesture-handler"; import { GestureHandlerRootView } from "react-native-gesture-handler";
import NotifChecker from "@/services/notif-service/notif-checker"; import NotifChecker from "@/services/notif-service/notif-checker";
@ -76,7 +78,7 @@ export default function RootLayout() {
<FirstUserWrapper> <FirstUserWrapper>
<AuthProvider> <AuthProvider>
<PendingAddressSync /> <PendingAddressSync />
<LocationTestWrapper> <LocationWrapperNeo>
<NotificationProvider> <NotificationProvider>
<NotifChecker /> <NotifChecker />
<NotifRegionSync /> <NotifRegionSync />
@ -93,7 +95,7 @@ export default function RootLayout() {
</RefreshProvider> </RefreshProvider>
</PaperProvider> </PaperProvider>
</NotificationProvider> </NotificationProvider>
</LocationTestWrapper> </LocationWrapperNeo>
</AuthProvider> </AuthProvider>
</FirstUserWrapper> </FirstUserWrapper>
</WebViewWrapper> </WebViewWrapper>

View file

@ -4,6 +4,10 @@ import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui' import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui'
import AddressForm from '@/src/components/AddressForm' import AddressForm from '@/src/components/AddressForm'
import { useLocationStore } from '@/src/store/locationStore' import { useLocationStore } from '@/src/store/locationStore'
import { useRegionNeo } from '@/src/hooks/useRegionNeo'
import { trpc } from '@/src/trpc-client'
import { toNeoAddress } from '@/src/lib/neo-address'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
// How often to re-check the device location while we still have no fix. // How often to re-check the device location while we still have no fix.
const LOCATION_POLL_MS = 3000 const LOCATION_POLL_MS = 3000
@ -21,7 +25,11 @@ interface CartAddressGateProps {
* first address they save becomes their default, and we then show the cart. * first address they save becomes their default, and we then show the cart.
*/ */
const CartAddressGate: React.FC<CartAddressGateProps> = ({ onDone, onBack }) => { const CartAddressGate: React.FC<CartAddressGateProps> = ({ onDone, onBack }) => {
const coords = useLocationStore((state) => state.coords) const neo = useRegionNeo()
const coords = neo.coords
const selectAddress = neo.selectAddress
const utils = trpc.useUtils()
const setAddresses = useNeoRegionStore((state) => state.setAddresses)
const probeLocation = useLocationStore((state) => state.probe) const probeLocation = useLocationStore((state) => state.probe)
const refreshPosition = useLocationStore((state) => state.refresh) const refreshPosition = useLocationStore((state) => state.refresh)
const [mode, setMode] = useState<'none' | 'current' | 'other'>('none') const [mode, setMode] = useState<'none' | 'current' | 'other'>('none')
@ -107,7 +115,7 @@ const CartAddressGate: React.FC<CartAddressGateProps> = ({ onDone, onBack }) =>
animationType="slide" animationType="slide"
onRequestClose={() => setMode('none')} onRequestClose={() => setMode('none')}
> >
<View style={tw`flex-1 bg-white`}> <View style={tw`flex-1 bg-white pb-4`}>
<AddressForm <AddressForm
// "Current location" prefills the device coordinates; "another // "Current location" prefills the device coordinates; "another
// location" starts empty so the user picks on the map. // location" starts empty so the user picks on the map.
@ -118,7 +126,7 @@ const CartAddressGate: React.FC<CartAddressGateProps> = ({ onDone, onBack }) =>
phone: '', phone: '',
addressLine1: '', addressLine1: '',
addressLine2: '', addressLine2: '',
city: 'Mahabubnagar', city: neo.regionName,
state: 'Telangana', state: 'Telangana',
isDefault: true, isDefault: true,
latitude: coords.latitude, latitude: coords.latitude,
@ -126,9 +134,20 @@ const CartAddressGate: React.FC<CartAddressGateProps> = ({ onDone, onBack }) =>
} }
: undefined : undefined
} }
onSuccess={() => { onSuccess={(addressId) => {
setMode('none') void (async () => {
onDone() if (addressId != null) {
try {
const response = await utils.user.address.getUserAddresses.fetch(undefined)
if (response.data) setAddresses(response.data.map(toNeoAddress))
} catch {
// The form's invalidation will refresh it.
}
await selectAddress(addressId)
}
setMode('none')
onDone()
})()
}} }}
/> />
</View> </View>

View file

@ -2,28 +2,17 @@ import React from 'react'
import { View } from 'react-native' import { View } from 'react-native'
import MaterialIcons from '@expo/vector-icons/MaterialIcons' import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { tw, MyText } from 'common-ui' import { tw, MyText } from 'common-ui'
import { trpc } from '@/src/trpc-client' import { useRegionNeo } from '@/src/hooks/useRegionNeo'
import { useAuth } from '@/src/contexts/AuthContext' import { addressIconName } from '@/src/lib/neo-address'
import { useAddressStore } from '@/src/store/addressStore'
/** /**
* Read-only delivery address card for the checkout page. The address is chosen * Read-only delivery address card for the checkout page. The address is chosen
* on the cart page (CheckoutAddressSelector); checkout only shows it. * on the cart page (CheckoutAddressSelector); checkout only shows it.
*/ */
const CheckoutAddressDisplay: React.FC = () => { const CheckoutAddressDisplay: React.FC = () => {
const { isAuthenticated } = useAuth() // The hook guarantees the selection belongs to the current region, so this
const selectedAddressId = useAddressStore((state) => state.selectedAddressId) // is the one address the order will use.
const address = useRegionNeo().selectedAddress
const { data: addressesData, isLoading } = trpc.user.address.getUserAddresses.useQuery(
undefined,
{ enabled: isAuthenticated }
)
const addresses = addressesData?.data ?? []
const address =
addresses.find((candidate) => candidate.id === selectedAddressId) ??
addresses.find((candidate) => candidate.isDefault) ??
null
return ( return (
<View testID="checkout-address" style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}> <View testID="checkout-address" style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
@ -34,22 +23,10 @@ const CheckoutAddressDisplay: React.FC = () => {
<MyText style={tw`text-base font-bold text-gray-900`}>Delivery Address</MyText> <MyText style={tw`text-base font-bold text-gray-900`}>Delivery Address</MyText>
</View> </View>
{isLoading ? ( {address ? (
<MyText testID="checkout-address-loading" style={tw`text-gray-500`}>Loading address...</MyText>
) : address ? (
<View style={tw`bg-gray-50 p-4 rounded-xl border border-gray-200`}> <View style={tw`bg-gray-50 p-4 rounded-xl border border-gray-200`}>
<View style={tw`flex-row items-center mb-2`}> <View style={tw`flex-row items-center mb-2`}>
<MaterialIcons <MaterialIcons name={addressIconName(address.name)} size={20} color="#6B7280" />
name={
address.name.toLowerCase().includes('home')
? 'home'
: address.name.toLowerCase().includes('work')
? 'work'
: 'location-on'
}
size={20}
color="#6B7280"
/>
<MyText testID="checkout-address-name" style={tw`font-bold ml-2 text-gray-900`}>{address.name}</MyText> <MyText testID="checkout-address-name" style={tw`font-bold ml-2 text-gray-900`}>{address.name}</MyText>
</View> </View>
<MyText style={tw`text-gray-600 text-sm leading-5 mb-1`} numberOfLines={2}> <MyText style={tw`text-gray-600 text-sm leading-5 mb-1`} numberOfLines={2}>

View file

@ -1,4 +1,4 @@
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useRef } from 'react';
import { View, Text, TouchableOpacity, ScrollView, Alert, NativeSyntheticEvent, NativeScrollEvent } from 'react-native'; import { View, Text, TouchableOpacity, ScrollView, Alert, NativeSyntheticEvent, NativeScrollEvent } from 'react-native';
import { useRouter } from 'expo-router'; import { useRouter } from 'expo-router';
import { tw, BottomDialog, RawBottomDialog, MyText } from 'common-ui'; import { tw, BottomDialog, RawBottomDialog, MyText } from 'common-ui';
@ -8,21 +8,18 @@ import LocationAttacher from '@/src/components/LocationAttacher';
import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { trpc } from '@/src/trpc-client'; import { trpc } from '@/src/trpc-client';
import { useAuth } from '@/src/contexts/AuthContext'; import { useAuth } from '@/src/contexts/AuthContext';
import { useRegion } from '@/src/hooks/useRegion'; import { useRegionNeo } from '@/src/hooks/useRegionNeo';
import { confirmRegionSwitch } from '@/src/lib/region-switch'; import { addressIconName, toNeoAddress } from '@/src/lib/neo-address';
import { useNeoRegionStore } from '@/src/store/neoRegionStore';
import * as Location from 'expo-location'; import * as Location from 'expo-location';
interface AddressSelectorProps {
selectedAddress: number | null;
onAddressSelect: (addressId: number) => void;
}
const CARD_WIDTH = 300; // 288 (w-72) + 12 (mr-3) const CARD_WIDTH = 300; // 288 (w-72) + 12 (mr-3)
const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({ const CheckoutAddressSelector: React.FC = () => {
selectedAddress, const neo = useRegionNeo();
onAddressSelect, const selectedAddress = neo.selectedAddressId;
}) => { const selectAddress = neo.selectAddress;
const setAddresses = useNeoRegionStore((state) => state.setAddresses);
const [showAddAddress, setShowAddAddress] = useState(false); const [showAddAddress, setShowAddAddress] = useState(false);
const [editingLocationAddressId, setEditingLocationAddressId] = useState<number | null>(null); const [editingLocationAddressId, setEditingLocationAddressId] = useState<number | null>(null);
const [locationLoading, setLocationLoading] = useState(false); const [locationLoading, setLocationLoading] = useState(false);
@ -31,13 +28,16 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
const utils = trpc.useUtils(); const utils = trpc.useUtils();
const router = useRouter(); const router = useRouter();
const scrollViewRef = useRef<ScrollView>(null); const scrollViewRef = useRef<ScrollView>(null);
// The region the add-address form resolved to, so a cross-region save can be
// confirmed before it switches (and clears the cart).
const resolvedRegionRef = useRef<{ regionId: number; boundId: number | null } | null>(null);
const { isAuthenticated } = useAuth(); const { isAuthenticated } = useAuth();
const { regionId: selectedRegionId } = useRegion(); const selectedRegionId = neo.regionId;
const { data: addresses } = trpc.user.address.getUserAddresses.useQuery( const { data: addresses } = trpc.user.address.getUserAddresses.useQuery(
undefined, undefined,
{ enabled: isAuthenticated } { enabled: isAuthenticated }
); );
const { data: regions } = trpc.common.listRegions.useQuery(); const regions = useNeoRegionStore((state) => state.regions);
const updateAddressMutation = trpc.user.address.updateAddress.useMutation({ const updateAddressMutation = trpc.user.address.updateAddress.useMutation({
onSuccess: () => { onSuccess: () => {
@ -68,21 +68,6 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
}); });
}, [addresses?.data, selectedAddress]); }, [addresses?.data, selectedAddress]);
// Auto-select default address when addresses are loaded and none is selected
useEffect(() => {
if (sortedAddresses.length > 0 && selectedAddress === null) {
const defaultAddress = sortedAddresses.find(addr => addr.isDefault);
// 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, selectedRegionId]);
// Reset scroll to left when address is selected // Reset scroll to left when address is selected
const resetScrollToLeft = () => { const resetScrollToLeft = () => {
setCurrentIndex(0); setCurrentIndex(0);
@ -94,8 +79,29 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
setCurrentIndex(index); setCurrentIndex(index);
}; };
// Selecting an address from another region requires an explicit confirmation // Every cross-region selection goes through this confirmation, because the
// because it clears the cart and changes the browsing region. // switch clears the cart for the current region.
// Adding or editing an address is the caller's job to refresh the list.
const refreshAddresses = async () => {
try {
const response = await utils.user.address.getUserAddresses.fetch(undefined);
if (response.data) setAddresses(response.data.map(toNeoAddress));
} catch {
// The form's mutation invalidation will refresh it.
}
};
const confirmSwitch = (regionName: string, onConfirm: () => void) => {
Alert.alert(
'Switch region?',
`This address is in ${regionName}. Switching will clear your entire cart and take you home.`,
[
{ text: 'Cancel', style: 'cancel' },
{ text: 'Switch & clear cart', style: 'destructive', onPress: onConfirm },
]
);
};
const handleAddressPress = (address: any) => { const handleAddressPress = (address: any) => {
if (selectedRegionId && address.regionId && address.regionId !== selectedRegionId) { if (selectedRegionId && address.regionId && address.regionId !== selectedRegionId) {
const targetRegion = (regions ?? []).find((region) => region.id === address.regionId); const targetRegion = (regions ?? []).find((region) => region.id === address.regionId);
@ -103,27 +109,16 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
Alert.alert('Unavailable region', 'This address belongs to a region that is not currently available.'); Alert.alert('Unavailable region', 'This address belongs to a region that is not currently available.');
return; return;
} }
Alert.alert( confirmSwitch(targetRegion.name, () => {
'Switch region?', void (async () => {
`This address is in ${targetRegion.name}. Switching will clear your entire cart and take you home.`, await selectAddress(address.id);
[ router.replace('/(drawer)/(tabs)/home');
{ text: 'Cancel', style: 'cancel' }, })();
{ });
text: 'Switch & clear cart',
style: 'destructive',
onPress: () => {
void (async () => {
await confirmRegionSwitch(targetRegion, queryClient, address.boundId ?? targetRegion.effectiveBoundId ?? null);
router.replace('/(drawer)/(tabs)/home');
})();
},
},
]
);
return; return;
} }
onAddressSelect(address.id); void selectAddress(address.id);
resetScrollToLeft(); resetScrollToLeft();
}; };
@ -217,7 +212,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
<View style={tw`flex-row justify-between items-start mb-2`}> <View style={tw`flex-row justify-between items-start mb-2`}>
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
<MaterialIcons <MaterialIcons
name={address.name.toLowerCase().includes('home') ? 'home' : address.name.toLowerCase().includes('work') ? 'work' : 'location-on'} name={addressIconName(address.name)}
size={20} size={20}
color={selectedAddress === address.id ? '#EC4899' : '#6B7280'} color={selectedAddress === address.id ? '#EC4899' : '#6B7280'}
/> />
@ -286,17 +281,50 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
{/* <BottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}> */} {/* <BottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}> */}
<RawBottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}> <RawBottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}>
{/* pb-4 keeps the form off the bottom edge of the sheet (16px). */}
<View style={tw`flex-1 bg-white pb-4`}>
<AddressForm
onResolvedRegion={(info) => {
resolvedRegionRef.current = info;
}}
onSuccess={(addressId) => {
setShowAddAddress(false);
queryClient.invalidateQueries();
if (addressId == null) return;
<AddressForm const resolved = resolvedRegionRef.current;
onSuccess={(addressId) => { if (
setShowAddAddress(false); resolved != null &&
// Auto-select the newly added address selectedRegionId != null &&
if (addressId) { resolved.regionId !== selectedRegionId
onAddressSelect(addressId); ) {
} const targetRegion = (regions ?? []).find((region) => region.id === resolved.regionId);
queryClient.invalidateQueries(); if (!targetRegion) {
}} Alert.alert(
/> 'Unavailable region',
'This address belongs to a region that is not currently available.'
);
return;
}
// The address has been saved; only selecting it is destructive.
confirmSwitch(targetRegion.name, () => {
void (async () => {
await refreshAddresses();
await selectAddress(addressId);
router.replace('/(drawer)/(tabs)/home');
})();
});
return;
}
// Auto-select the newly added address.
void (async () => {
await refreshAddresses();
await selectAddress(addressId);
})();
}}
/>
</View>
</RawBottomDialog> </RawBottomDialog>
{/* </BottomDialog> */} {/* </BottomDialog> */}
</> </>

View file

@ -0,0 +1,34 @@
import React from 'react'
import type { ReactParentComponent } from '@packages/shared'
import { useNeoRegionBootstrap } from '@/src/hooks/useRegionNeo'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import NeoAddressFlow from '@/src/components/location/neo/NeoAddressFlow'
import NeoConfirmLocation from '@/src/components/location/neo/NeoConfirmLocation'
import NeoLoadingScreen from '@/src/components/location/neo/NeoLoadingScreen'
/**
* The neo region gate. It runs the launch decision and watches the store
* directly — it never calls `useRegionNeo`, because that hook is only valid for
* components behind this gate. Children appear once the store holds a complete
* region; the two flow flags take over when the decision needs input.
*/
const LocationWrapperNeo: React.FC<ReactParentComponent> = ({ children }) => {
useNeoRegionBootstrap()
const regionId = useNeoRegionStore((state) => state.regionId)
const boundId = useNeoRegionStore((state) => state.boundId)
const regionName = useNeoRegionStore((state) => state.regionName)
const coords = useNeoRegionStore((state) => state.coords)
const needsAddressFormFlow = useNeoRegionStore((state) => state.needsAddressFormFlow)
const needsAddressConfirmation = useNeoRegionStore((state) => state.needsAddressConfirmation)
if (needsAddressFormFlow) return <NeoAddressFlow />
if (regionId == null || boundId == null || regionName == null || coords == null) {
return <NeoLoadingScreen />
}
if (needsAddressConfirmation) return <NeoConfirmLocation />
return <>{children}</>
}
export default LocationWrapperNeo

View file

@ -6,7 +6,7 @@ import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { trpc } from '@/src/trpc-client'; import { trpc } from '@/src/trpc-client';
import { useCentralProductStore } from '@/src/store/centralProductStore'; import { useCentralProductStore } from '@/src/store/centralProductStore';
import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore';
import { useRegion } from '@/src/hooks/useRegion'; import { useRegionNeo } from '@/src/hooks/useRegionNeo';
import { useCheckoutStore } from '@/src/store/checkoutStore'; import { useCheckoutStore } from '@/src/store/checkoutStore';
import { clearLocalCart } from '@/hooks/cart-query-hooks'; import { clearLocalCart } from '@/hooks/cart-query-hooks';
import { useQueryClient } from '@tanstack/react-query'; import { useQueryClient } from '@tanstack/react-query';
@ -64,7 +64,9 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
const products = useCentralProductStore((state) => state.products); const products = useCentralProductStore((state) => state.products);
const productsById = useCentralProductStore((state) => state.productsById); const productsById = useCentralProductStore((state) => state.productsById);
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
const { regionId: selectedRegionId, boundId: activeBoundId } = useRegion(); const neo = useRegionNeo();
const selectedRegionId = neo.regionId;
const activeBoundId = neo.boundId;
// Memoized flash-eligible product IDs // Memoized flash-eligible product IDs
const flashEligibleProductIds = useMemo(() => { const flashEligibleProductIds = useMemo(() => {

View file

@ -15,6 +15,8 @@ import {
import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier'; import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier';
import { useCartStore } from '@/src/store/cartStore'; import { useCartStore } from '@/src/store/cartStore';
import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore';
import { useCentralProductStore } from '@/src/store/centralProductStore';
import { couponPriceFor } from '@/src/lib/product-coupons';
import { useRenderProbe } from '@/src/lib/render-probe' import { useRenderProbe } from '@/src/lib/render-probe'
@ -133,6 +135,14 @@ const ProductCard: React.FC<ProductCardProps> = ({
// Flash products carry their own promo price. // Flash products carry their own promo price.
const displayPrice = isFlash ? item.flashPrice ?? item.price : item.price; const displayPrice = isFlash ? item.flashPrice ?? item.price : item.price;
// Product-specific coupons land in the catalogue store; the price is derived
// from the price the card actually shows, so a flash card discounts flashPrice.
// Out-of-stock cards stay plain: there is nothing to buy.
const couponOffers = useCentralProductStore((state) =>
item.id != null ? state.couponOffers[item.id] : undefined
);
const couponPrice = displayIsOutOfStock ? null : couponPriceFor(couponOffers, displayPrice);
// if(item.name.startsWith('Mutton Curry Cut')) { // if(item.name.startsWith('Mutton Curry Cut')) {
// console.log({slotId, displayIsOutOfStock}) // console.log({slotId, displayIsOutOfStock})
// } // }
@ -249,6 +259,15 @@ const ProductCard: React.FC<ProductCardProps> = ({
<MyText style={isHero ? tw`text-gray-400 text-[10px] ml-1.5 line-through` : tw`text-gray-400 text-xs ml-2 line-through`}>₹{item.marketPrice}</MyText> <MyText style={isHero ? tw`text-gray-400 text-[10px] ml-1.5 line-through` : tw`text-gray-400 text-xs ml-2 line-through`}>₹{item.marketPrice}</MyText>
)} )}
</View> </View>
{couponPrice != null && (
<View
testID={`product-coupon-price-${item.id}`}
style={isHero ? tw`flex-row items-baseline mb-1` : tw`flex-row items-baseline mb-2`}
>
<MyText style={isHero ? tw`text-brand500 font-bold text-[10px]` : tw`text-brand500 font-bold text-xs`}>₹{couponPrice}</MyText>
<MyText style={tw`text-gray-400 text-[10px] ml-1.5`}>With Coupon</MyText>
</View>
)}
<View style={isHero ? tw`flex-row items-center mb-1` : tw`flex-row items-center mb-2`}> <View style={isHero ? tw`flex-row items-center mb-1` : tw`flex-row items-center mb-2`}>
{item.productType !== 'combo' && ( {item.productType !== 'combo' && (
<MyText style={isHero ? tw`text-gray-500 text-[10px] font-medium` : tw`text-gray-500 text-xs font-medium`}>Quantity: <MyText style={tw`text-[#f81260] font-semibold`}>{item.unitNotation}</MyText></MyText> <MyText style={isHero ? tw`text-gray-500 text-[10px] font-medium` : tw`text-gray-500 text-xs font-medium`}>Quantity: <MyText style={tw`text-[#f81260] font-semibold`}>{item.unitNotation}</MyText></MyText>

View file

@ -14,11 +14,13 @@ import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from '
import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier'; import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier';
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'; import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore';
import { useSlots } from '@/src/hooks/prominent-api-hooks'; import { useSlots } from '@/src/hooks/prominent-api-hooks';
import { useRegion } from '@/src/hooks/useRegion'; import { useRegionNeo } from '@/src/hooks/useRegionNeo';
import FloatingCartBar from './floating-cart-bar'; import FloatingCartBar from './floating-cart-bar';
import { useStoreHeaderStore } from '@/src/store/storeHeaderStore'; import { useStoreHeaderStore } from '@/src/store/storeHeaderStore';
import { useCartStore } from '@/src/store/cartStore'; import { useCartStore } from '@/src/store/cartStore';
import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore';
import { useCentralProductStore } from '@/src/store/centralProductStore';
import { couponPriceFor } from '@/src/lib/product-coupons';
const { width: screenWidth } = Dimensions.get("window"); const { width: screenWidth } = Dimensions.get("window");
const carouselWidth = screenWidth; const carouselWidth = screenWidth;
@ -51,7 +53,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
const [hasMore, setHasMore] = useState(true); const [hasMore, setHasMore] = useState(true);
const [reviewsOffset, setReviewsOffset] = useState(0); const [reviewsOffset, setReviewsOffset] = useState(0);
const [refreshing, setRefreshing] = useState(false); const [refreshing, setRefreshing] = useState(false);
const { regionId: activeRegionId } = useRegion(); const activeRegionId = useRegionNeo().regionId;
// The region is required (a global SKU has none of its own), so the query // The region is required (a global SKU has none of its own), so the query
// waits for it and the screen stays in its loading state until then. // waits for it and the screen stays in its loading state until then.
const { data: productDetail, isLoading, error, refetch } = trpc.user.product.getProductDetails.useQuery( const { data: productDetail, isLoading, error, refetch } = trpc.user.product.getProductDetails.useQuery(
@ -75,6 +77,20 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
return productSlotsMap[productDetail.id]; return productSlotsMap[productDetail.id];
}, [productDetail, productSlotsMap]); }, [productDetail, productSlotsMap]);
// The coupon comes from the catalogue store, so the detail price matches the
// card that sent the customer here. Flash detail prices the flash price.
const couponOffers = useCentralProductStore((state) =>
productDetail ? state.couponOffers[productDetail.id] : undefined
);
const couponPrice = useMemo(() => {
if (!productDetail || productAvailability?.isOutOfStock) return null;
const flashPrice = Number(productDetail.flashPrice);
const price = isFlashDelivery && Number.isFinite(flashPrice) && flashPrice > 0
? flashPrice
: productDetail.price;
return couponPriceFor(couponOffers, price);
}, [productDetail, productAvailability?.isOutOfStock, couponOffers, isFlashDelivery]);
const sortedDeliverySlots = useMemo(() => { const sortedDeliverySlots = useMemo(() => {
if (!slotsData?.slots || !productDetail) return [] if (!slotsData?.slots || !productDetail) return []
@ -194,8 +210,8 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
const onRefresh = async () => { const onRefresh = async () => {
setRefreshing(true); setRefreshing(true);
await refetch(); // Refetch product details // Product details and reviews are independent: refresh them together.
await loadReviews(true); // Reset and reload reviews await Promise.all([refetch(), loadReviews(true)]);
setRefreshing(false); setRefreshing(false);
}; };
@ -311,6 +327,14 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
</MyText> </MyText>
</View> </View>
)} )}
{/* Product-specific coupon, same figure the card advertised */}
{couponPrice != null && (
<View testID="product-coupon-price" style={tw`mt-2 flex-row items-baseline`}>
<MyText style={tw`text-brand500 text-base font-bold`}>₹{couponPrice}</MyText>
<MyText style={tw`text-gray-400 text-xs ml-1.5`}>With Coupon</MyText>
</View>
)}
</View> </View>

View file

@ -1,14 +1,11 @@
import React, { useState, useMemo } from 'react'; import React, { useState, useMemo } from 'react';
import { View, ScrollView, Dimensions, Alert } from 'react-native'; import { View, ScrollView, Dimensions, Alert } from 'react-native';
import { useRouter } from 'expo-router'; import { useRouter } from 'expo-router';
import { useQueryClient } from '@tanstack/react-query';
import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { BottomDialog, MyTouchableOpacity, MyText, tw, theme } from 'common-ui'; import { BottomDialog, MyTouchableOpacity, MyText, tw, theme } from 'common-ui';
import { useAuth } from '@/src/contexts/AuthContext'; import { useAuth } from '@/src/contexts/AuthContext';
import { trpc } from '@/src/trpc-client'; import { trpc } from '@/src/trpc-client';
import { useAddressStore } from '@/src/store/addressStore'; import { useRegionNeo } from '@/src/hooks/useRegionNeo';
import { useRegion } from '@/src/hooks/useRegion';
import { confirmRegionSwitch } from '@/src/lib/region-switch';
import { useSlots } from '@/src/hooks/prominent-api-hooks'; import { useSlots } from '@/src/hooks/prominent-api-hooks';
import LocationBar from '@/src/components/LocationBar'; import LocationBar from '@/src/components/LocationBar';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
@ -30,7 +27,10 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
const [dialogOpen, setDialogOpen] = useState(false); const [dialogOpen, setDialogOpen] = useState(false);
const { isAuthenticated } = useAuth(); const { isAuthenticated } = useAuth();
const { selectedAddressId, setSelectedAddressId } = useAddressStore(); const neo = useRegionNeo();
const selectedAddressId = neo.selectedAddressId;
const selectedRegionId = neo.regionId;
const selectAddress = neo.selectAddress;
const { data: defaultAddressData } = trpc.user.address.getDefaultAddress.useQuery(); const { data: defaultAddressData } = trpc.user.address.getDefaultAddress.useQuery();
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, { const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
@ -41,8 +41,6 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
const defaultAddress = defaultAddressData?.data; const defaultAddress = defaultAddressData?.data;
const addresses = addressesData?.data || []; const addresses = addressesData?.data || [];
const queryClient = useQueryClient();
const { regionId: selectedRegionId } = useRegion();
const { data: regions } = trpc.common.listRegions.useQuery(); const { data: regions } = trpc.common.listRegions.useQuery();
// An address (selected or default) that belongs to another region than the // An address (selected or default) that belongs to another region than the
@ -73,7 +71,7 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
style: 'destructive', style: 'destructive',
onPress: () => { onPress: () => {
void (async () => { void (async () => {
await confirmRegionSwitch(targetRegion, queryClient, foreignAddress.boundId ?? targetRegion.effectiveBoundId ?? null); await neo.selectAddress(foreignAddress.id);
router.replace('/(drawer)/(tabs)/home'); router.replace('/(drawer)/(tabs)/home');
})(); })();
}, },
@ -318,7 +316,7 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
address.id === (selectedAddressId || defaultAddress?.id) ? 'bg-brand50 border-brand500' : 'bg-white' address.id === (selectedAddressId || defaultAddress?.id) ? 'bg-brand50 border-brand500' : 'bg-white'
}`} }`}
onPress={() => { onPress={() => {
setSelectedAddressId(address.id); void selectAddress?.(address.id);
setAddressDialogOpen(false); setAddressDialogOpen(false);
}} }}
activeOpacity={0.7} activeOpacity={0.7}

View file

@ -7,7 +7,7 @@ import { useRouter, usePathname, Slot } from 'expo-router';
import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { tw, theme, MyText, MyTouchableOpacity, MyFlatList, AppContainer, MiniQuantifier, SearchBar } from 'common-ui'; import { tw, theme, MyText, MyTouchableOpacity, MyFlatList, AppContainer, MiniQuantifier, SearchBar } from 'common-ui';
import { trpc } from '@/src/trpc-client'; import { trpc } from '@/src/trpc-client';
import { useAllProducts, useStores, useSlots } from '@/src/hooks/prominent-api-hooks'; import { useStores, useSlots } from '@/src/hooks/prominent-api-hooks';
import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore'; import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore';
import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore';
import { useCentralProductStore } from '@/src/store/centralProductStore'; import { useCentralProductStore } from '@/src/store/centralProductStore';
@ -806,7 +806,11 @@ export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsP
const [isRefreshing, setIsRefreshing] = useState(false); const [isRefreshing, setIsRefreshing] = useState(false);
const router = useRouter(); const router = useRouter();
const productsQuery = useAllProducts(); const products = useCentralProductStore((state) => state.products);
const catalogueTags = useCentralProductStore((state) => state.tags);
const isProductsLoading = useCentralProductStore((state) => state.isLoading);
const productsError = useCentralProductStore((state) => state.error);
const refetchProducts = useCentralProductStore((state) => state.refetchProducts);
const { data: storesData, refetch: refetchStores } = useStores(); const { data: storesData, refetch: refetchStores } = useStores();
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
@ -822,8 +826,6 @@ export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsP
productsByStoreId, productsByStoreId,
flashProducts, flashProducts,
} = React.useMemo(() => { } = React.useMemo(() => {
const products = productsQuery?.data?.products || [];
const tags = productsQuery?.data?.tags || [];
const stores = storesData?.stores || []; const stores = storesData?.stores || [];
const flashProducts = products.filter((product: any) => { const flashProducts = products.filter((product: any) => {
@ -836,7 +838,7 @@ export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsP
// A tab only exists if it has at least one in-stock flash product; empty // A tab only exists if it has at least one in-stock flash product; empty
// tags and stores are not shown at all. // tags and stores are not shown at all.
const tagTabs = tags.filter((tag: any) => const tagTabs = catalogueTags.filter((tag: any) =>
((tag.productIds || []) as number[]).some((id) => flashProductIds.has(id)) ((tag.productIds || []) as number[]).some((id) => flashProductIds.has(id))
); );
const storeTabs = stores.filter((store: any) => flashStoreIds.has(store.id)); const storeTabs = stores.filter((store: any) => flashStoreIds.has(store.id));
@ -866,7 +868,7 @@ export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsP
productsByStoreId, productsByStoreId,
flashProducts, flashProducts,
}; };
}, [productsQuery?.data, storesData, productSlotsMap]); }, [products, catalogueTags, storesData, productSlotsMap]);
// Stable so FlashProductItem/FlashProductGrid memos survive a re-render. // Stable so FlashProductItem/FlashProductGrid memos survive a re-render.
const handleProductPress = React.useCallback( const handleProductPress = React.useCallback(
@ -880,7 +882,6 @@ export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsP
[onProductPress, router] [onProductPress, router]
); );
const refetchProducts = productsQuery?.refetch;
const handleRefresh = React.useCallback(async () => { const handleRefresh = React.useCallback(async () => {
setIsRefreshing(true); setIsRefreshing(true);
try { try {
@ -903,7 +904,7 @@ export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsP
[isRefreshing, handleRefresh] [isRefreshing, handleRefresh]
); );
if (productsQuery?.isLoading) { if (isProductsLoading) {
return ( return (
<AppContainer> <AppContainer>
<View style={tw`flex-1 justify-center items-center bg-gray-50`}> <View style={tw`flex-1 justify-center items-center bg-gray-50`}>
@ -913,7 +914,7 @@ export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsP
); );
} }
if (productsQuery?.error && !productsQuery?.data) { if (productsError && products.length === 0) {
return ( return (
<AppContainer> <AppContainer>
<View style={tw`flex-1 justify-center items-center bg-gray-50`}> <View style={tw`flex-1 justify-center items-center bg-gray-50`}>

View file

@ -29,12 +29,12 @@ import { useCentralProductStore, type Product } from '@/src/store/centralProduct
import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore';
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks'; import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks';
import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks'; import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
import { useRegion } from '@/src/hooks/useRegion'; import { useRegionNeo } from '@/src/hooks/useRegionNeo';
import CheckoutAddressSelector from '@/components/CheckoutAddressSelector'; import CheckoutAddressSelector from '@/components/CheckoutAddressSelector';
import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog'; import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog';
import LoginWall from '@/components/LoginWall'; import LoginWall from '@/components/LoginWall';
import CartAddressGate from '@/components/CartAddressGate'; import CartAddressGate from '@/components/CartAddressGate';
import { useAddressStore } from '@/src/store/addressStore';
import { useCheckoutStore } from '@/src/store/checkoutStore'; import { useCheckoutStore } from '@/src/store/checkoutStore';
import type { FlashDeliveryProps } from '@packages/shared'; import type { FlashDeliveryProps } from '@packages/shared';
import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } from '@packages/shared'; import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } from '@packages/shared';
@ -278,8 +278,9 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
const { isAuthenticated, isLoading: isAuthLoading } = useAuth(); const { isAuthenticated, isLoading: isAuthLoading } = useAuth();
const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular"; const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular";
const { selectedAddressId, setSelectedAddressId } = useAddressStore(); const neo = useRegionNeo();
const { regionId } = useRegion(); const selectedAddressId = neo.selectedAddressId;
const regionId = neo.regionId;
// First-address gate: the region can exist (from the location) with no address yet. // First-address gate: the region can exist (from the location) with no address yet.
const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, { const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, {
enabled: isAuthenticated, enabled: isAuthenticated,
@ -879,7 +880,9 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
</View> </View>
); );
} }
if ((addressesQuery.data?.data?.length ?? 0) === 0) { // No active address for the current region. Addresses that live in another
// region do not count: the neo store never selects them across regions.
if (selectedAddressId == null) {
return ( return (
<CartAddressGate <CartAddressGate
onDone={() => { onDone={() => {
@ -1447,10 +1450,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
</View> </View>
{/* Delivery Address */} {/* Delivery Address */}
<CheckoutAddressSelector <CheckoutAddressSelector />
selectedAddress={selectedAddressId}
onAddressSelect={setSelectedAddressId}
/>
{/* Bottom Checkout Bar - Now Static */} {/* Bottom Checkout Bar - Now Static */}
{hasAvailableItems && ( {hasAvailableItems && (

View file

@ -12,11 +12,11 @@ import { useCentralProductStore } from '@/src/store/centralProductStore';
import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore';
import { useGetCart } from '@/hooks/cart-query-hooks'; import { useGetCart } from '@/hooks/cart-query-hooks';
import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks'; import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
import { useRegion } from '@/src/hooks/useRegion'; import { useRegionNeo } from '@/src/hooks/useRegionNeo';
import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent'; import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent';
import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay'; import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay';
import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog'; import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog';
import { useAddressStore } from '@/src/store/addressStore';
import type { FlashDeliveryProps } from '@packages/shared'; import type { FlashDeliveryProps } from '@packages/shared';
import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } from '@packages/shared'; import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } from '@packages/shared';
@ -27,7 +27,8 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
// Slots are per-region and the order is placed with this same region // Slots are per-region and the order is placed with this same region
// (see PaymentAndOrderComponent), so scope the query to it. // (see PaymentAndOrderComponent), so scope the query to it.
const { regionId } = useRegion(); const neo = useRegionNeo();
const regionId = neo.regionId;
// Protect checkout route and preserve query params // Protect checkout route and preserve query params
useAuthenticatedRoute({ useAuthenticatedRoute({
@ -57,7 +58,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
refetchSlots(); refetchSlots();
}); });
const { selectedAddressId } = useAddressStore(); const selectedAddressId = neo.selectedAddressId;
const [selectedCouponIds, setSelectedCouponIds] = useState<number[]>([]); const [selectedCouponIds, setSelectedCouponIds] = useState<number[]>([]);
// Coupon whose per-product discount split is open (product-specific coupons only). // Coupon whose per-product discount split is open (product-specific coupons only).
const [breakdownCouponId, setBreakdownCouponId] = useState<number | null>(null); const [breakdownCouponId, setBreakdownCouponId] = useState<number | null>(null);

View file

@ -25,6 +25,7 @@ import { useRegionalConsts, useSlots } from "@/src/hooks/prominent-api-hooks"
import { useRenderProbe } from "@/src/lib/render-probe" import { useRenderProbe } from "@/src/lib/render-probe"
import { useProductSlotIdentifier } from "@/hooks/useProductSlotIdentifier"; import { useProductSlotIdentifier } from "@/hooks/useProductSlotIdentifier";
import { useCentralProductStore } from "@/src/store/centralProductStore"; import { useCentralProductStore } from "@/src/store/centralProductStore";
import { couponPriceFor } from "@/src/lib/product-coupons";
import dayjs from "dayjs"; import dayjs from "dayjs";
import { LinearGradient } from "expo-linear-gradient"; import { LinearGradient } from "expo-linear-gradient";
@ -107,6 +108,7 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
const constsData = useRegionalConsts(); const constsData = useRegionalConsts();
const { data: slotsData } = useSlots(); const { data: slotsData } = useSlots();
const productsById = useCentralProductStore((state) => state.productsById); const productsById = useCentralProductStore((state) => state.productsById);
const couponOffers = useCentralProductStore((state) => state.couponOffers);
const { productSlotsMap } = useProductSlotIdentifier(); const { productSlotsMap } = useProductSlotIdentifier();
const cartItems = cartData?.items || []; const cartItems = cartData?.items || [];
const itemCount = cartItems.length; const itemCount = cartItems.length;
@ -177,6 +179,18 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
freeDeliveryThreshold - totalCartValue freeDeliveryThreshold - totalCartValue
); );
/**
* What one line costs after the best product coupon, priced on the line total
* like the cart does (a flat coupon comes off the whole line, not each unit).
* Flash lines use the flash price. Null when no coupon beats the listed price.
*/
const couponLineTotal = (item: any): number | null => {
const product = productsById[item.skuId];
const basePrice = product?.price ?? 0;
const unitPrice = isFlashDelivery ? (product?.flashPrice ?? basePrice) : basePrice;
return couponPriceFor(couponOffers[item.skuId], unitPrice * item.quantity);
};
return ( return (
<> <>
<View <View
@ -287,7 +301,9 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
style={{ flexBasis: 'auto', flexShrink: 1 }} style={{ flexBasis: 'auto', flexShrink: 1 }}
contentContainerStyle={tw`px-6 py-4`} contentContainerStyle={tw`px-6 py-4`}
> >
{cartItems.map((item, index) => ( {cartItems.map((item, index) => {
const couponLine = couponLineTotal(item);
return (
<React.Fragment key={item.id}> <React.Fragment key={item.id}>
<View style={tw`py-4`}> <View style={tw`py-4`}>
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
@ -367,14 +383,25 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
)} )}
/> />
)} )}
<MyText style={tw`text-slate-900 text-sm font-bold`}> <View style={tw`items-end`}>
₹{(() => { <MyText style={tw`text-slate-900 text-sm font-bold`}>
const product = productsById[item.skuId]; ₹{(() => {
const basePrice = product?.price ?? 0; const product = productsById[item.skuId];
const price = isFlashDelivery ? (product?.flashPrice ?? basePrice) : basePrice; const basePrice = product?.price ?? 0;
return price * item.quantity; const price = isFlashDelivery ? (product?.flashPrice ?? basePrice) : basePrice;
})()} return price * item.quantity;
</MyText> })()}
</MyText>
{couponLine != null && (
<View
testID={`cart-item-coupon-price-${item.id}`}
style={tw`flex-row items-center mt-0.5`}
>
<MyText style={tw`text-emerald-600 text-xs font-bold`}>₹{couponLine}</MyText>
<MyText style={tw`text-gray-400 text-[9px] ml-1`}>With Coupon</MyText>
</View>
)}
</View>
</View> </View>
</View> </View>
</View> </View>
@ -385,7 +412,8 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
<View style={tw`h-px bg-slate-200 w-full`} /> <View style={tw`h-px bg-slate-200 w-full`} />
)} )}
</React.Fragment> </React.Fragment>
))} );
})}
</ScrollView> </ScrollView>
{/* Fancy Footer */} {/* Fancy Footer */}
@ -403,6 +431,14 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
)} )}
</View> </View>
{/* The cart screens have no coupon picker; checkout does. */}
<MyText
testID="apply-coupons-hint"
style={tw`text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-4`}
>
Apply Coupons at checkout
</MyText>
<MyTouchableOpacity <MyTouchableOpacity
onPress={() => router.push( onPress={() => router.push(
isFlashDelivery isFlashDelivery

View file

@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useState } from 'react' import { useCallback, useEffect, useMemo, useState } from 'react'
import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier' import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier'
import { useAllProducts } from '@/src/hooks/prominent-api-hooks' import { useCentralProductStore } from '@/src/store/centralProductStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore'
/** Rows per page, same as the "Show More" step on the home catalogue. */ /** Rows per page, same as the "Show More" step on the home catalogue. */
@ -15,28 +15,31 @@ export const HOME_CATALOG_PAGE_SIZE = 21
* file in the folder and left the sort effect reading `getQuickestSlot` and * file in the folder and left the sort effect reading `getQuickestSlot` and
* `isSlotsLoaded` without listing them. Keeping it here leaves the screen with * `isSlotsLoaded` without listing them. Keeping it here leaves the screen with
* just its layout concerns, and the effect lists every value it reads. * just its layout concerns, and the effect lists every value it reads.
*
* The catalogue itself comes from the central product store — the only place
* that reads the products document — so every product field (price flags,
* coupon price, ...) has one source across the app.
*/ */
export function useHomeCatalog() { export function useHomeCatalog() {
const { data: productsData, isLoading, error } = useAllProducts() const products = useCentralProductStore((state) => state.products)
const dashboardTags = useCentralProductStore((state) => state.tags)
const isLoading = useCentralProductStore((state) => state.isLoading)
const error = useCentralProductStore((state) => state.error)
const { getQuickestSlot } = useProductSlotIdentifier() const { getQuickestSlot } = useProductSlotIdentifier()
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap) const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap)
const isSlotsLoaded = useCentralSlotStore((state) => state.isSlotsLoaded) const isSlotsLoaded = useCentralSlotStore((state) => state.isSlotsLoaded)
// Single source of truth for the catalogue: `products` and `dashboardTags` // Single source of truth for the catalogue rows: the per-tag rows are derived
// come out of this memo together with the per-tag rows, so the screen never // from the same products list the "All Products" feed pages through, so the
// holds two views of the same payload that can drift apart. // screen never holds two views of the same payload that can drift apart.
const { dashboardTags, products, productsByTagId } = useMemo(() => { const productsByTagId = useMemo(() => {
const tags = productsData?.tags ?? []
const allProducts = productsData?.products ?? []
// Hoisted: the old version rebuilt this Map once per tag.
const productById = new Map<number, any>() const productById = new Map<number, any>()
for (const product of allProducts) { for (const product of products) {
productById.set(product.id, product) productById.set(product.id, product)
} }
const map: Record<number, any[]> = {} const map: Record<number, any[]> = {}
for (const tag of tags) { for (const tag of dashboardTags) {
// Respect the admin-curated order — tag.productIds is already ordered by // Respect the admin-curated order — tag.productIds is already ordered by
// the tag's sortOrder (backend reorders it when building the cache). // the tag's sortOrder (backend reorders it when building the cache).
// Unknown ids are skipped and a repeated id only renders once. // Unknown ids are skipped and a repeated id only renders once.
@ -62,8 +65,8 @@ export function useHomeCatalog() {
map[tag.id] = [...inStock, ...outOfStock] map[tag.id] = [...inStock, ...outOfStock]
} }
return { dashboardTags: tags, products: allProducts, productsByTagId: map } return map
}, [productsData, productSlotsMap, isSlotsLoaded, getQuickestSlot]) }, [products, dashboardTags, productSlotsMap, isSlotsLoaded, getQuickestSlot])
// Tag selection/expansion live in homeTagStore (subscribed by TagTabStrip and // Tag selection/expansion live in homeTagStore (subscribed by TagTabStrip and
// TagScene), so a tap does not re-render Dashboard or rebuild the list below. // TagScene), so a tap does not re-render Dashboard or rebuild the list below.

View file

@ -1,14 +1,14 @@
import React, { useCallback, useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import { View, Modal, ScrollView, KeyboardAvoidingView, Platform, Keyboard } from 'react-native'; import { View, Modal, ScrollView, KeyboardAvoidingView, Platform, Keyboard, StyleSheet, ActivityIndicator } from 'react-native';
import { Formik } from 'formik'; import { Formik } from 'formik';
import * as Yup from 'yup'; import * as Yup from 'yup';
import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , LoadingDialog , BottomDialog , BottomDropdown } from 'common-ui'; import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , BottomDialog , BottomDropdown } from 'common-ui';
import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { trpc } from '../trpc-client'; import { trpc } from '../trpc-client';
import LocationMapStep from './location/LocationMapStep'; import LocationMapStep from './location/LocationMapStep';
import type { AddressFormProps, RegionSummary } from '@packages/shared'; import type { AddressFormProps, RegionSummary } from '@packages/shared';
import { savePendingAddress } from '@/src/lib/pending-address'; import { savePendingAddress } from '@/src/lib/pending-address';
import { useRegion } from '@/src/hooks/useRegion'; import { useNeoRegionStore } from '@/src/store/neoRegionStore';
import { useLocationStore } from '@/src/store/locationStore'; import { useLocationStore } from '@/src/store/locationStore';
type Coords = { latitude: number; longitude: number }; type Coords = { latitude: number; longitude: number };
@ -19,6 +19,12 @@ type LocationSource = 'device' | 'map';
const AddressForm: React.FC<AddressFormProps & { const AddressForm: React.FC<AddressFormProps & {
/** Reported so a bottom sheet can size itself to the form when idle. */ /** Reported so a bottom sheet can size itself to the form when idle. */
onContentHeightChange?: (height: number) => void; onContentHeightChange?: (height: number) => void;
/**
* Called immediately before a create/update is submitted. Returning false
* aborts the submission. The neo flow uses it to confirm a region switch;
* the other mounts leave it unset.
*/
onBeforeSubmit?: () => boolean | Promise<boolean>;
}> = ({ }> = ({
onSuccess, onSuccess,
initialValues, initialValues,
@ -26,8 +32,12 @@ const AddressForm: React.FC<AddressFormProps & {
draftMode = false, draftMode = false,
onResolvedRegion, onResolvedRegion,
onContentHeightChange, onContentHeightChange,
onBeforeSubmit,
}) => { }) => {
const { regionId: browsingRegionId, boundId: browsingBoundId } = useRegion(); // The form is also shown before a region exists (the fallback), so it reads
// the store directly rather than using the ready-only hook.
const browsingRegionId = useNeoRegionStore((state) => state.regionId);
const browsingBoundId = useNeoRegionStore((state) => state.boundId);
const deviceCoords = useLocationStore((state) => state.coords); const deviceCoords = useLocationStore((state) => state.coords);
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null); const [submitError, setSubmitError] = useState<string | null>(null);
@ -205,6 +215,10 @@ const AddressForm: React.FC<AddressFormProps & {
const createAddressMutation = trpc.user.address.createAddress.useMutation({ const createAddressMutation = trpc.user.address.createAddress.useMutation({
onSuccess: (data) => { onSuccess: (data) => {
setIsSubmitting(false); setIsSubmitting(false);
// Keep the neo store's address list (and the default) in sync; the
// location flow selects the new id after this resolves.
void utils.user.address.getUserAddresses.invalidate();
void utils.user.address.getDefaultAddress.invalidate();
const addressId = data?.data?.id; const addressId = data?.data?.id;
// Delay to allow modal to close animation // Delay to allow modal to close animation
setTimeout(() => onSuccess(addressId), 350); setTimeout(() => onSuccess(addressId), 350);
@ -218,6 +232,8 @@ const AddressForm: React.FC<AddressFormProps & {
const updateAddressMutation = trpc.user.address.updateAddress.useMutation({ const updateAddressMutation = trpc.user.address.updateAddress.useMutation({
onSuccess: () => { onSuccess: () => {
setIsSubmitting(false); setIsSubmitting(false);
void utils.user.address.getUserAddresses.invalidate();
void utils.user.address.getDefaultAddress.invalidate();
// Delay to allow modal to close animation // Delay to allow modal to close animation
setTimeout(() => onSuccess(), 350); setTimeout(() => onSuccess(), 350);
}, },
@ -242,6 +258,9 @@ const AddressForm: React.FC<AddressFormProps & {
// not be saveable. // not be saveable.
const isLocationServiceable = const isLocationServiceable =
currentLocation != null && resolvedRegion != null && !locationError && !isCheckingLocation; currentLocation != null && resolvedRegion != null && !locationError && !isCheckingLocation;
const actionLabel = isEdit ? 'Update Address' : 'Add Address';
const progressingLabel = isEdit ? 'Updating...' : 'Adding...';
const submitLabel = isSubmitting ? progressingLabel : actionLabel;
return ( return (
<KeyboardAvoidingView <KeyboardAvoidingView
@ -287,6 +306,10 @@ const AddressForm: React.FC<AddressFormProps & {
setSubmitError(locationError || 'Please choose a town and a location inside it.'); setSubmitError(locationError || 'Please choose a town and a location inside it.');
return; return;
} }
if (onBeforeSubmit) {
const allowed = await onBeforeSubmit();
if (!allowed) return;
}
setIsSubmitting(true); setIsSubmitting(true);
setSubmitError(null); setSubmitError(null);
const payload = { const payload = {
@ -455,7 +478,7 @@ const AddressForm: React.FC<AddressFormProps & {
disabled={isSubmitting || !isLocationServiceable} disabled={isSubmitting || !isLocationServiceable}
> >
<MyText style={tw`text-white text-center font-bold`}> <MyText style={tw`text-white text-center font-bold`}>
{isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')} {submitLabel}
</MyText> </MyText>
</MyTouchableOpacity> </MyTouchableOpacity>
@ -469,10 +492,27 @@ const AddressForm: React.FC<AddressFormProps & {
)} )}
</Formik> </Formik>
<LoadingDialog {/*
open={isSubmitting} The submit loader is an in-tree overlay, NOT a LoadingDialog Modal.
message={isEdit ? "Updating address..." : "Adding address..."} This form is itself rendered inside a Modal (cart/me sheets, the location
/> flow). Dismissing a nested Modal and then the hosting Modal in quick
succession leaves an invisible native layer that blocks every touch on
iOS (react-native#50152). Keeping the loader inline removes the second
Modal entirely, so closing the sheet can never strand that layer.
*/}
{isSubmitting && (
<View
testID="address-submit-overlay"
style={[StyleSheet.absoluteFill, tw`bg-black bg-opacity-40 justify-center items-center`]}
>
<View style={tw`bg-white rounded-xl p-8 items-center justify-center min-w-50 min-h-37.5 shadow-lg`}>
<ActivityIndicator size="large" color="#3B82F6" style={tw`mb-4`} />
<MyText style={tw`text-base text-gray-500 text-center`}>
{isEdit ? "Updating address..." : "Adding address..."}
</MyText>
</View>
</View>
)}
{/* Region picker: the map opens focused on whichever region is chosen. */} {/* Region picker: the map opens focused on whichever region is chosen. */}
<BottomDialog open={mapRegionPickerOpen} onClose={closeMapRegionPicker}> <BottomDialog open={mapRegionPickerOpen} onClose={closeMapRegionPicker}>

View file

@ -2,20 +2,10 @@ import React, { useState } from 'react'
import { View } from 'react-native' import { View } from 'react-native'
import MaterialIcons from '@expo/vector-icons/MaterialIcons' import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui' import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui'
import { useRegion } from '@/src/hooks/useRegion' import { useRegionNeo } from '@/src/hooks/useRegionNeo'
import { useAddressStore } from '@/src/store/addressStore'
import { useAuthOptional } from '@/src/contexts/AuthContext'
import { trpc } from '@/src/trpc-client'
import AddressSwitcherSheet from '@/src/components/location/AddressSwitcherSheet' import AddressSwitcherSheet from '@/src/components/location/AddressSwitcherSheet'
import { useRenderProbe } from '@/src/lib/render-probe' import { useRenderProbe } from '@/src/lib/render-probe'
const formatAddress = (address: {
addressLine1: string
addressLine2?: string | null
city: string
}) =>
`${address.addressLine1}${address.addressLine2 ? `, ${address.addressLine2}` : ''}, ${address.city}`
/** /**
* Location bar shown at the top of every top-level tab screen. * Location bar shown at the top of every top-level tab screen.
* Rendered INSIDE the scroll content (first item / ListHeaderComponent) so it * Rendered INSIDE the scroll content (first item / ListHeaderComponent) so it
@ -28,27 +18,20 @@ const formatAddress = (address: {
const LocationBar: React.FC = () => { const LocationBar: React.FC = () => {
useRenderProbe('component:LocationBar') useRenderProbe('component:LocationBar')
const [sheetOpen, setSheetOpen] = useState(false) const [sheetOpen, setSheetOpen] = useState(false)
const { region } = useRegion() const neo = useRegionNeo()
const regionName = neo.regionName
const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false const fullAddress = neo.fullAddress
const selectedAddressId = useAddressStore((state) => state.selectedAddressId)
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
enabled: isAuthenticated,
})
const addresses = addressesData?.data ?? []
// Prefer the address the user selected at checkout, else their default.
const activeAddress =
addresses.find((address) => address.id === selectedAddressId) ??
addresses.find((address) => address.isDefault) ??
null
return ( return (
<View style={tw`px-4 pt-3 pb-1`}> <View style={tw`px-4 pt-3 pb-1`}>
<MyTouchableOpacity <MyTouchableOpacity
testID="location-bar" testID="location-bar"
activeOpacity={0.85} activeOpacity={0.85}
onPress={() => setSheetOpen(true)} onPress={() => {
console.log('clicked bar')
setSheetOpen(true)
}}
style={tw`flex-row items-center bg-white border border-gray-100 rounded-2xl px-4 py-3 shadow-sm`} style={tw`flex-row items-center bg-white border border-gray-100 rounded-2xl px-4 py-3 shadow-sm`}
> >
<View style={tw`w-9 h-9 rounded-full bg-blue-50 items-center justify-center mr-3`}> <View style={tw`w-9 h-9 rounded-full bg-blue-50 items-center justify-center mr-3`}>
@ -57,7 +40,7 @@ const LocationBar: React.FC = () => {
<View style={tw`flex-1`}> <View style={tw`flex-1`}>
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
<MyText style={tw`text-xs text-gray-500 mr-2`}>Deliver to</MyText> <MyText style={tw`text-xs text-gray-500 mr-2`}>Deliver to</MyText>
{region ? ( {regionName ? (
// The active region gets a tinted pill so it reads at a glance; the // The active region gets a tinted pill so it reads at a glance; the
// pill shrinks (flex-shrink) so a long name truncates instead of // pill shrinks (flex-shrink) so a long name truncates instead of
// pushing the chevron out of the row. // pushing the chevron out of the row.
@ -68,7 +51,7 @@ const LocationBar: React.FC = () => {
numberOfLines={1} numberOfLines={1}
ellipsizeMode="tail" ellipsizeMode="tail"
> >
{region.name} {regionName}
</MyText> </MyText>
</View> </View>
) : ( ) : (
@ -77,7 +60,7 @@ const LocationBar: React.FC = () => {
</MyText> </MyText>
)} )}
</View> </View>
{activeAddress ? ( {fullAddress ? (
<MyText <MyText
style={tw`text-xs text-gray-500 mt-1`} style={tw`text-xs text-gray-500 mt-1`}
// Exactly one address line: anything longer ellipsises with "…" // Exactly one address line: anything longer ellipsises with "…"
@ -85,7 +68,7 @@ const LocationBar: React.FC = () => {
numberOfLines={1} numberOfLines={1}
ellipsizeMode="tail" ellipsizeMode="tail"
> >
{formatAddress(activeAddress)} {fullAddress}
</MyText> </MyText>
) : null} ) : null}
</View> </View>

View file

@ -1,6 +1,7 @@
import React, { useEffect, useRef } from 'react' import React, { useEffect, useRef } from 'react'
import { trpc } from '@/src/trpc-client' import { trpc } from '@/src/trpc-client'
import { useRegion } from '@/src/hooks/useRegion' import { useRegionNeo } from '@/src/hooks/useRegionNeo'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import { useNotification } from '@/services/notif-service/notif-context' import { useNotification } from '@/services/notif-service/notif-context'
/** /**
@ -10,8 +11,7 @@ import { useNotification } from '@/services/notif-service/notif-context'
* It renders inside NotificationProvider (see app/_layout.tsx), which is the * It renders inside NotificationProvider (see app/_layout.tsx), which is the
* only place the push token is available. Both ways a region becomes known land * only place the push token is available. Both ways a region becomes known land
* here: * here:
* - a tracked device location — useRegion resolves it (and `bound` is set only * - a tracked device location — useRegionNeo resolves it (origin === 'device'), or
* for that path), or
* - an added address (incl. the signed-out local draft) — the location * - an added address (incl. the signed-out local draft) — the location
* fallback switches the region, which clears the gate and mounts this * fallback switches the region, which clears the gate and mounts this
* component with the new region already in place. * component with the new region already in place.
@ -24,7 +24,8 @@ import { useNotification } from '@/services/notif-service/notif-context'
*/ */
const NotifRegionSync: React.FC = () => { const NotifRegionSync: React.FC = () => {
const { expoPushToken, notifPermission } = useNotification() const { expoPushToken, notifPermission } = useNotification()
const { regionId, bound } = useRegion() const regionId = useRegionNeo().regionId
const origin = useNeoRegionStore((state) => state.origin)
// Both calls are best-effort telemetry for notifications: a failure is logged // Both calls are best-effort telemetry for notifications: a failure is logged
// and ignored, never surfaced or retried. // and ignored, never surfaced or retried.
const savePushToken = trpc.user.user.savePushToken.useMutation({ const savePushToken = trpc.user.user.savePushToken.useMutation({
@ -45,19 +46,18 @@ const NotifRegionSync: React.FC = () => {
useEffect(() => { useEffect(() => {
if (!expoPushToken || notifPermission !== 'granted' || regionId == null) return if (!expoPushToken || notifPermission !== 'granted' || regionId == null) return
const fromLocation = bound != null const fromLocation = origin === 'device'
const key = `${expoPushToken}:${regionId}:${fromLocation ? 'loc' : 'addr'}` const key = `${expoPushToken}:${regionId}:${fromLocation ? 'loc' : 'addr'}`
if (lastSynced.current === key) return if (lastSynced.current === key) return
lastSynced.current = key lastSynced.current = key
savePushTokenMutate({ token: expoPushToken, regionId }) savePushTokenMutate({ token: expoPushToken, regionId })
// `bound` is set only when the region came from the device fix, so this is // `origin === 'device'` is exactly the "location was tracked" case.
// exactly the "location was tracked" case.
if (fromLocation) { if (fromLocation) {
recordTrackedRegionMutate({ regionId }) recordTrackedRegionMutate({ regionId })
} }
}, [expoPushToken, notifPermission, regionId, bound, savePushTokenMutate, recordTrackedRegionMutate]) }, [expoPushToken, notifPermission, regionId, origin, savePushTokenMutate, recordTrackedRegionMutate])
return null return null
} }

View file

@ -2,6 +2,8 @@ import { useEffect, useRef } from 'react'
import { trpc } from '@/src/trpc-client' import { trpc } from '@/src/trpc-client'
import { useAuth } from '@/src/contexts/AuthContext' import { useAuth } from '@/src/contexts/AuthContext'
import { clearPendingAddress, getPendingAddress } from '@/src/lib/pending-address' import { clearPendingAddress, getPendingAddress } from '@/src/lib/pending-address'
import { toNeoAddress } from '@/src/lib/neo-address'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
/** /**
* Posts a locally-drafted address (created while signed out in the location * Posts a locally-drafted address (created while signed out in the location
@ -26,10 +28,25 @@ const PendingAddressSync: React.FC = () => {
isSyncing.current = true isSyncing.current = true
try { try {
await createAddress.mutateAsync(pending) const created = await createAddress.mutateAsync(pending)
await clearPendingAddress() // The address is saved; clear the draft and refresh both lists together.
await utils.user.address.getUserAddresses.invalidate() await Promise.all([
await utils.user.address.getDefaultAddress.invalidate() clearPendingAddress(),
utils.user.address.getUserAddresses.invalidate(),
utils.user.address.getDefaultAddress.invalidate(),
])
// The draft was the address the user was checking out with; make it the
// active selection as soon as the list is available.
try {
const response = await utils.user.address.getUserAddresses.fetch(undefined)
useNeoRegionStore.getState().setAddresses(response.data.map(toNeoAddress))
const createdId = created?.data?.id
if (createdId != null) {
await useNeoRegionStore.getState().selectAddress(createdId)
}
} catch {
// The subscription will refresh the list; the decision selects the default.
}
} catch { } catch {
// Leave the draft in place; a later authenticated mount retries it. // Leave the draft in place; a later authenticated mount retries it.
} finally { } finally {

View file

@ -1,7 +1,7 @@
import React from 'react' import React from 'react'
import { Modal, View } from 'react-native' import { Modal, View } from 'react-native'
import { tw } from 'common-ui' import { tw } from 'common-ui'
import LocationFallbackFlow from './LocationFallbackFlow' import NeoAddressFlow from './neo/NeoAddressFlow'
interface AddressSwitcherSheetProps { interface AddressSwitcherSheetProps {
open: boolean open: boolean
@ -16,7 +16,7 @@ interface AddressSwitcherSheetProps {
const AddressSwitcherSheet: React.FC<AddressSwitcherSheetProps> = ({ open, onClose }) => ( const AddressSwitcherSheet: React.FC<AddressSwitcherSheetProps> = ({ open, onClose }) => (
<Modal visible={open} animationType="slide" onRequestClose={onClose}> <Modal visible={open} animationType="slide" onRequestClose={onClose}>
<View style={tw`flex-1 bg-white`}> <View style={tw`flex-1 bg-white`}>
<LocationFallbackFlow onClose={onClose} /> <NeoAddressFlow onClose={onClose} />
</View> </View>
</Modal> </Modal>
) )

View file

@ -0,0 +1,230 @@
import React, { useEffect, useRef, useState } from 'react'
import { ScrollView, View } from 'react-native'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { MyButton, MyText, MyTouchableOpacity, tw } from 'common-ui'
import Login from '@/app/(auth)/login'
import { useAuthOptional } from '@/src/contexts/AuthContext'
import { useLocationStore } from '@/src/store/locationStore'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import { formatNeoAddress } from '@/src/lib/neo-address'
import NeoAddressForm from './NeoAddressForm'
import NeoLocationNotice, { type NeoLocationNoticeKind } from './NeoLocationNotice'
interface NeoAddressFlowProps {
/** Present when hosted in the location-bar sheet. */
onClose?: () => void
}
/** Location statuses that explain the flow in the notice card. */
const STATUS_NOTICE_KIND: Partial<Record<string, NeoLocationNoticeKind>> = {
denied: 'denied',
'services-off': 'services-off',
unavailable: 'unavailable',
error: 'unavailable',
}
/**
* The whole address fallback: choose a saved address, add one, or sign in.
* Used both by the wrapper (no usable region) and by the location bar sheet.
*/
const NeoAddressFlow: React.FC<NeoAddressFlowProps> = ({ onClose }) => {
const auth = useAuthOptional()
const isAuthenticated = auth?.isAuthenticated ?? false
const regionId = useNeoRegionStore((state) => state.regionId)
const addresses = useNeoRegionStore((state) => state.addresses)
const selectedAddressId = useNeoRegionStore((state) => state.selectedAddressId)
const closeAddressFlow = useNeoRegionStore((state) => state.closeAddressFlow)
const selectAddress = useNeoRegionStore((state) => state.selectAddress)
const deviceOutOfService = useNeoRegionStore((state) => state.deviceOutOfService)
const locationStatus = useLocationStore((state) => state.status)
const [mode, setMode] = useState<'choose' | 'add' | 'login'>('choose')
const autoOpened = useRef(false)
useEffect(() => {
if (mode === 'login' && isAuthenticated) setMode('choose')
}, [mode, isAuthenticated])
// With exactly one saved address the startup gate can open it without making
// the user tap a one-item list. Only the gate: when this flow is the
// location-bar sheet (onClose) the user opened it to look at or change the
// address, so auto-selecting would flash the sheet open and closed — which
// reads as a dead tap. A published region also means the gate is not showing
// the startup chooser (e.g. "add an address here" from the confirmation).
useEffect(() => {
if (onClose != null || regionId != null) return
if (mode !== 'choose' || !isAuthenticated || autoOpened.current) return
if (addresses.length !== 1) return
autoOpened.current = true
void selectAddress(addresses[0].id).then(() => {
// Its region may no longer be serviceable; closing would strand the
// loading screen, so keep the chooser up instead.
if (useNeoRegionStore.getState().regionId == null) return
closeAddressFlow()
})
}, [onClose, regionId, mode, isAuthenticated, addresses, selectAddress, closeAddressFlow])
const pick = async (id: number) => {
await selectAddress(id)
closeAddressFlow()
onClose?.()
}
// An out-of-area device fix is worth explaining even when a cached region is
// already published (the sheet case). A live permission/services notice is
// more current, so it wins while there is no region.
let noticeKind: NeoLocationNoticeKind | null = null
if (regionId == null && STATUS_NOTICE_KIND[locationStatus] != null) {
noticeKind = STATUS_NOTICE_KIND[locationStatus] ?? null
} else if (deviceOutOfService) {
noticeKind = 'out-of-area'
}
if (mode === 'add') {
return (
<View style={tw`flex-1 bg-white`}>
<MyTouchableOpacity
testID="neo-add-back"
onPress={() => setMode('choose')}
activeOpacity={0.7}
style={tw`px-5 pt-12 pb-2 flex-row items-center`}
>
<MaterialIcons name="arrow-back" size={22} color="#4B5563" />
<MyText style={tw`text-gray-600 ml-1`}>Back</MyText>
</MyTouchableOpacity>
{noticeKind != null && (
<NeoLocationNotice kind={noticeKind} style={tw`mx-5 mb-2`} />
)}
<NeoAddressForm
onDone={() => {
closeAddressFlow()
onClose?.()
}}
/>
</View>
)
}
if (mode === 'login') {
return (
<View style={tw`flex-1 bg-white`}>
<Login />
<MyTouchableOpacity
testID="neo-location-login-back"
onPress={() => setMode('choose')}
activeOpacity={0.7}
style={tw`absolute left-4 top-14 w-10 h-10 rounded-full bg-white/90 items-center justify-center shadow`}
>
<MaterialIcons name="arrow-back" size={22} color="#374151" />
</MyTouchableOpacity>
</View>
)
}
return (
<View testID="neo-address-flow" style={tw`flex-1 bg-white`}>
<ScrollView contentContainerStyle={tw`px-5 pt-12 pb-10`}>
<View style={tw`flex-row items-start justify-between`}>
<View style={tw`flex-1`}>
<MyText style={tw`text-3xl font-extrabold text-gray-900`}>
Delivery Address
</MyText>
<MyText style={tw`text-gray-500 mt-2`}>
Choose a saved address, or add a new one. Your region follows the address.
</MyText>
</View>
{onClose != null && (
<MyTouchableOpacity
testID="neo-location-close"
onPress={onClose}
activeOpacity={0.7}
style={tw`p-1`}
>
<MaterialIcons name="close" size={24} color="#9CA3AF" />
</MyTouchableOpacity>
)}
</View>
{noticeKind != null && (
<NeoLocationNotice kind={noticeKind} style={tw`mt-4`} />
)}
<View style={tw`mt-6`}>
{addresses.map((address) => {
const isSelected = address.id === selectedAddressId
return (
<MyTouchableOpacity
key={address.id}
testID={`neo-address-${address.id}`}
onPress={() => void pick(address.id)}
activeOpacity={0.85}
style={tw`border ${
isSelected ? 'border-indigo-500 bg-indigo-50' : 'border-gray-200 bg-white'
} rounded-2xl p-4 mb-3`}
>
<View style={tw`flex-row items-center mb-1`}>
<MaterialIcons
name="location-on"
size={20}
color={isSelected ? '#4F46E5' : '#6B7280'}
/>
<MyText style={tw`font-bold text-gray-900 ml-2`}>{address.name}</MyText>
{address.isDefault && (
<MyText style={tw`text-xs text-gray-400 ml-2`}>Default</MyText>
)}
{isSelected && (
<MyText style={tw`text-xs text-indigo-600 ml-2`}>Selected</MyText>
)}
</View>
<MyText style={tw`text-gray-600 text-sm`} numberOfLines={2}>
{formatNeoAddress(address)}
</MyText>
<MyText style={tw`text-gray-400 text-xs mt-1`}>{address.phone}</MyText>
</MyTouchableOpacity>
)
})}
{addresses.length === 0 && (
<MyText style={tw`text-gray-500 text-sm mb-4`}>
{isAuthenticated
? 'You have no saved addresses yet.'
: 'Sign in to use a saved address, or add one now.'}
</MyText>
)}
</View>
<MyButton
testID="neo-add-address"
fillColor="brand500"
textColor="white1"
fullWidth
onPress={() => setMode('add')}
style={tw`mt-2`}
>
<MyText weight="bold" color="white1">Add new address</MyText>
</MyButton>
{!isAuthenticated && (
<>
<MyButton
testID="neo-location-login"
fillColor="white1"
textColor="brand600"
borderColor="brand200"
fullWidth
onPress={() => setMode('login')}
style={tw`mt-3`}
>
<MyText weight="bold" color="brand600">Sign In</MyText>
</MyButton>
<MyText style={tw`mt-2 text-center text-xs text-gray-400`}>
Sign in to use saved addresses
</MyText>
</>
)}
</ScrollView>
</View>
)
}
export default NeoAddressFlow

View file

@ -0,0 +1,122 @@
import React, { useCallback, useRef, useState } from 'react'
import { View } from 'react-native'
import { BottomDialog, MyText, MyTouchableOpacity, tw } from 'common-ui'
import AddressForm from '@/src/components/AddressForm'
import { useAuthOptional } from '@/src/contexts/AuthContext'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import { trpc } from '@/src/trpc-client'
import { toNeoAddress } from '@/src/lib/neo-address'
type ResolvedRegion = { regionId: number; boundId: number | null }
interface NeoAddressFormProps {
onDone?: () => void
}
/**
* Adapter around the existing AddressForm. The form itself already implements
* the add-address chart (device fix prefilled, map picker, serviceability gate,
* "outside the area -> pick on the map"). This wrapper only:
* - writes the result into the neo store,
* - warns before an address in another region switches the browsing region.
*/
const NeoAddressForm: React.FC<NeoAddressFormProps> = ({ onDone }) => {
const auth = useAuthOptional()
const isAuthenticated = auth?.isAuthenticated ?? false
const utils = trpc.useUtils()
const currentRegionId = useNeoRegionStore((state) => state.regionId)
const currentRegionName = useNeoRegionStore((state) => state.regionName) ?? 'your current region'
const regions = useNeoRegionStore((state) => state.regions)
const setAddresses = useNeoRegionStore((state) => state.setAddresses)
const changeRegion = useNeoRegionStore((state) => state.changeRegion)
const selectAddress = useNeoRegionStore((state) => state.selectAddress)
const [resolved, setResolved] = useState<ResolvedRegion | null>(null)
const [warningOpen, setWarningOpen] = useState(false)
const warningResolver = useRef<((ok: boolean) => void) | null>(null)
const targetRegionName =
resolved != null
? regions.find((region) => region.id === resolved.regionId)?.name ?? 'another region'
: 'another region'
const onBeforeSubmit = useCallback((): boolean | Promise<boolean> => {
if (resolved == null || currentRegionId == null) return true
if (resolved.regionId === currentRegionId) return true
return new Promise<boolean>((resolve) => {
warningResolver.current = resolve
setWarningOpen(true)
})
}, [currentRegionId, resolved])
const finishWarning = (ok: boolean) => {
setWarningOpen(false)
warningResolver.current?.(ok)
warningResolver.current = null
}
const handleSuccess = async (addressId?: number) => {
// The server has the address now; refresh the store before selecting it.
if (addressId != null) {
try {
const response = await utils.user.address.getUserAddresses.fetch(undefined)
setAddresses(response.data.map(toNeoAddress))
} catch {
// The subscription will refresh the list on the next fetch.
}
await selectAddress(addressId)
onDone?.()
return
}
// Signed-out draft: the address is stored locally and posted after login.
// The browsing region still follows the chosen location now.
if (resolved != null) {
await changeRegion(resolved.regionId, resolved.boundId)
}
onDone?.()
}
return (
<View style={tw`flex-1 bg-white`}>
<AddressForm
draftMode={!isAuthenticated}
onResolvedRegion={setResolved}
onBeforeSubmit={onBeforeSubmit}
onSuccess={(addressId) => {
void handleSuccess(addressId)
}}
/>
<BottomDialog open={warningOpen} onClose={() => finishWarning(false)}>
<View style={tw`p-6`}>
<MyText style={tw`text-xl font-bold text-gray-900 mb-2`}>Switch region?</MyText>
<MyText style={tw`text-gray-600 mb-5`}>
This address is in {targetRegionName}. Saving it will switch you from{' '}
{currentRegionName} and clear your cart for that region.
</MyText>
<MyTouchableOpacity
testID="neo-region-warning-cancel"
onPress={() => finishWarning(false)}
activeOpacity={0.85}
style={tw`border border-gray-200 py-3.5 rounded-xl items-center mb-3`}
>
<MyText style={tw`text-gray-700 font-bold`}>Cancel</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="neo-region-warning-continue"
onPress={() => finishWarning(true)}
activeOpacity={0.85}
style={tw`bg-indigo-600 py-3.5 rounded-xl items-center`}
>
<MyText style={tw`text-white font-bold`}>Switch and save</MyText>
</MyTouchableOpacity>
</View>
</BottomDialog>
</View>
)
}
export default NeoAddressForm

View file

@ -0,0 +1,82 @@
import React from 'react'
import { View } from 'react-native'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { BottomDropdown, MyText, MyTouchableOpacity, tw } from 'common-ui'
import { formatNeoAddress } from '@/src/lib/neo-address'
import { useRegionNeo } from '@/src/hooks/useRegionNeo'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import NeoFixedPinMap from './NeoFixedPinMap'
/**
* Shown only when the device put the app in a region where none of the user's
* saved addresses live. The region is already active (there is no pending
* candidate); this screen offers a way back to one of those addresses, or to
* add a new one, or to keep the device region.
*/
const NeoConfirmLocation: React.FC = () => {
const data = useRegionNeo()
const addresses = useNeoRegionStore((state) => state.addresses)
const selectedAddressId = useNeoRegionStore((state) => state.selectedAddressId)
const setNeedsConfirmation = useNeoRegionStore((state) => state.setNeedsConfirmation)
const openAddressFlow = useNeoRegionStore((state) => state.openAddressFlow)
const options = addresses.map((address) => ({
label: formatNeoAddress(address) || address.name,
value: address.id,
}))
return (
<View style={tw`flex-1 bg-white`}>
<View style={tw`flex-1`}>
<NeoFixedPinMap coords={data.coords} />
</View>
<View style={tw`bg-white px-5 pt-5 pb-8 rounded-t-3xl -mt-4 shadow-lg`}>
<View style={tw`flex-row items-center mb-2`}>
<MaterialIcons name="my-location" size={20} color="#2563EB" />
<MyText style={tw`text-lg font-bold text-gray-900 ml-2`}>
You are in {data.regionName}
</MyText>
</View>
<MyText style={tw`text-gray-500 text-sm mb-4`}>
None of your saved addresses are in this region. Pick one to switch back, add a new
address here, or keep this location.
</MyText>
{options.length > 0 && (
<BottomDropdown
testID="neo-confirm-address"
topLabel="Saved addresses"
label="Switch to a saved address"
placeholder="Select an address"
value={selectedAddressId ?? ''}
options={options}
onValueChange={(value) => {
void data.selectAddress(Number(value))
}}
/>
)}
<MyTouchableOpacity
testID="neo-confirm-add-address"
onPress={() => openAddressFlow()}
activeOpacity={0.85}
style={tw`mt-4 border border-indigo-200 bg-indigo-50 py-3.5 rounded-xl items-center`}
>
<MyText style={tw`text-indigo-700 font-bold`}>Add a new address here</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="neo-confirm-keep"
onPress={() => setNeedsConfirmation(false)}
activeOpacity={0.85}
style={tw`mt-3 bg-indigo-600 py-3.5 rounded-xl items-center`}
>
<MyText style={tw`text-white font-bold`}>Keep this location</MyText>
</MyTouchableOpacity>
</View>
</View>
)
}
export default NeoConfirmLocation

View file

@ -0,0 +1,47 @@
import React, { useState } from 'react'
import { ActivityIndicator, View } from 'react-native'
import { WebView } from 'react-native-webview'
import { MyText, theme, tw } from 'common-ui'
import constants from '@/src/constants'
import type { NeoCoords } from '@/src/lib/neo-address'
interface NeoFixedPinMapProps {
coords: NeoCoords
}
/**
* Read-only map for the confirmation screen: the pin is already the resolved
* location and must not move ("no cursor movement" in the flow chart).
* `/location-selector?fixed=1` renders the page with a non-draggable marker.
*/
const NeoFixedPinMap: React.FC<NeoFixedPinMapProps> = ({ coords }) => {
const [isLoading, setIsLoading] = useState(true)
const url =
`${constants.WEB_UI_BASE_URL}/location-selector` +
`?lat=${coords.latitude}&lng=${coords.longitude}&fixed=1`
return (
<View style={tw`flex-1 bg-white`}>
<WebView
source={{ uri: url }}
style={tw`flex-1`}
originWhitelist={['*']}
javaScriptEnabled
domStorageEnabled
onLoadEnd={() => setIsLoading(false)}
startInLoadingState
scrollEnabled={false}
geolocationEnabled
/>
{isLoading && (
<View style={tw`absolute inset-0 items-center justify-center bg-white`}>
<ActivityIndicator size="large" color={theme.colors.brand500} />
<MyText style={tw`text-gray-500 mt-3`}>Loading map...</MyText>
</View>
)}
</View>
)
}
export default NeoFixedPinMap

View file

@ -0,0 +1,12 @@
import React from 'react'
import { ActivityIndicator, View } from 'react-native'
import { MyText, theme, tw } from 'common-ui'
const NeoLoadingScreen: React.FC<{ label?: string }> = ({ label = 'Finding your region...' }) => (
<View testID="neo-location-loading" style={tw`flex-1 justify-center items-center bg-white`}>
<ActivityIndicator size="large" color={theme.colors.brand500} />
<MyText style={tw`text-gray-500 mt-4`}>{label}</MyText>
</View>
)
export default NeoLoadingScreen

View file

@ -0,0 +1,146 @@
import React from 'react'
import type { StyleProp, ViewStyle } from 'react-native'
import { View } from 'react-native'
import Svg, { Circle, Path } from 'react-native-svg'
import { MyText, tw } from 'common-ui'
/** Why the address flow is asking for an address instead of using the device. */
export type NeoLocationNoticeKind =
| 'out-of-area'
| 'denied'
| 'services-off'
| 'unavailable'
interface NeoLocationNoticeProps {
kind: NeoLocationNoticeKind
style?: StyleProp<ViewStyle>
}
const COPY: Record<NeoLocationNoticeKind, { title: string; message: string }> = {
'out-of-area': {
title: 'Outside delivery area',
message:
'Your current location is outside our delivery area. Choose a saved address, or add one inside a serviceable area.',
},
denied: {
title: 'Location access is off',
message:
'Location access is not granted. Allow it for accurate delivery, or add an address below.',
},
'services-off': {
title: 'Device location is off',
message: 'Your device location is turned off. Turn it on, or add an address below.',
},
unavailable: {
title: 'Location unavailable',
message: 'We could not get your location. Try again, or add an address below.',
},
}
const AMBER_100 = '#FEF3C7'
const AMBER_300 = '#FCD34D'
const AMBER_600 = '#D97706'
const AMBER_700 = '#B45309'
/**
* The badge on the pin carries the reason: a cross for "outside the area", a
* slash for "permission/services", an exclamation for "couldn't get a fix".
*/
function NoticeBadge({ kind }: { kind: NeoLocationNoticeKind }) {
if (kind === 'denied' || kind === 'services-off') {
return (
<Path
d="M46.6 54.4 55.4 41.6"
stroke={AMBER_700}
strokeWidth={2.2}
strokeLinecap="round"
/>
)
}
if (kind === 'unavailable') {
return (
<>
<Path d="M51 43.5v6" stroke={AMBER_700} strokeWidth={2.2} strokeLinecap="round" />
<Circle cx={51} cy={53} r={1.4} fill={AMBER_700} />
</>
)
}
return (
<>
<Path
d="M48 45l6 6"
stroke={AMBER_700}
strokeWidth={2.2}
strokeLinecap="round"
/>
<Path
d="M54 45l-6 6"
stroke={AMBER_700}
strokeWidth={2.2}
strokeLinecap="round"
/>
</>
)
}
/** Inline illustration: a map pin with a dashed coverage ring and a reason badge. */
function LocationNoticeArtwork({ kind }: { kind: NeoLocationNoticeKind }) {
return (
<Svg width={64} height={64} viewBox="0 0 72 72" fill="none">
<Circle cx={36} cy={33} r={30} fill={AMBER_100} />
<Circle
cx={36}
cy={33}
r={24}
stroke={AMBER_300}
strokeWidth={1.5}
strokeDasharray="3 5"
/>
{/* The pin itself: white body, amber outline, amber dot. */}
<Path
d="M36 13.5c-7.9 0-14.3 6.3-14.3 14.1 0 10 11.2 20.4 13.4 22.3a1.4 1.4 0 0 0 1.8 0c2.2-1.9 13.4-12.3 13.4-22.3 0-7.8-6.4-14.1-14.3-14.1Z"
fill="#FFFFFF"
stroke={AMBER_600}
strokeWidth={2.2}
/>
<Circle cx={36} cy={27.6} r={4.6} fill={AMBER_600} />
{/* Reason badge, bottom-right. */}
<Circle cx={51} cy={48} r={9.5} fill="#FFFFFF" stroke={AMBER_600} strokeWidth={1.8} />
<NoticeBadge kind={kind} />
</Svg>
)
}
/**
* The reason the address flow is up, as a graphic card: an inline SVG
* illustration plus a title and the supporting sentence.
*/
const NeoLocationNotice: React.FC<NeoLocationNoticeProps> = ({ kind, style }) => {
const copy = COPY[kind]
return (
<View
testID="neo-location-notice"
accessibilityRole="alert"
style={[tw`bg-amber-50 border border-amber-200 rounded-2xl p-4`, style]}
>
<View style={tw`flex-row items-center`}>
<View style={tw`-ml-1`}>
<LocationNoticeArtwork kind={kind} />
</View>
<View style={tw`flex-1 ml-2`}>
<MyText weight="bold" style={tw`text-amber-900 text-base`}>
{copy.title}
</MyText>
<MyText style={tw`text-amber-800 text-sm mt-1 leading-5`}>{copy.message}</MyText>
</View>
</View>
</View>
)
}
export default NeoLocationNotice

View file

@ -198,8 +198,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
try { try {
setAuthState(prev => ({ ...prev, isLoading: true })); setAuthState(prev => ({ ...prev, isLoading: true }));
await saveAuthToken(token); await Promise.all([
await saveUserId(user.id.toString()); saveAuthToken(token),
saveUserId(user.id.toString()),
]);
setAuthState({ setAuthState({
user: { user: {
@ -232,8 +234,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
// const response = loginMutation.mutate(credentials); // const response = loginMutation.mutate(credentials);
const { token, user } = response.data; const { token, user } = response.data;
await saveAuthToken(token); await Promise.all([
await saveUserId(user.id.toString()); saveAuthToken(token),
saveUserId(user.id.toString()),
]);
setAuthState({ setAuthState({
user: { user: {
@ -266,8 +270,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
const response = await registerMutation.mutateAsync(data); const response = await registerMutation.mutateAsync(data);
const { token, user } = response; const { token, user } = response;
await saveAuthToken(token); await Promise.all([
await saveUserId(user.id.toString()); saveAuthToken(token),
saveUserId(user.id.toString()),
]);
setAuthState({ setAuthState({
user: { user: {

View file

@ -6,8 +6,7 @@ import type { ProductPriceFlags } from '@packages/shared'
import { AllProductsApiType, StoresApiType, SlotsApiType, EssentialConstsApiType, StoreWithProductsApiType, AvailabilityApiType } from "@backend/trpc/router"; import { AllProductsApiType, StoresApiType, SlotsApiType, EssentialConstsApiType, StoreWithProductsApiType, AvailabilityApiType } from "@backend/trpc/router";
import { CACHE_FILENAMES, availabilityCacheUrl, cachedFileUrl, regionCacheUrl, slotsCacheUrl, storeDetailCacheUrl } from "@packages/shared"; import { CACHE_FILENAMES, availabilityCacheUrl, cachedFileUrl, regionCacheUrl, slotsCacheUrl, storeDetailCacheUrl } from "@packages/shared";
import { StorageServiceCasual } from 'common-ui'; import { StorageServiceCasual } from 'common-ui';
import { useRegion } from '@/src/hooks/useRegion' import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import { useAddressStore } from '@/src/store/addressStore'
import { useAuthOptional } from '@/src/contexts/AuthContext' import { useAuthOptional } from '@/src/contexts/AuthContext'
// Discovery payload: the flat per-bound consts object (global + region + bound // Discovery payload: the flat per-bound consts object (global + region + bound
@ -19,12 +18,13 @@ export type DiscoveryData = EssentialConstsApiType
const essentialConstsKey = (boundId: number) => `essential_consts_b${boundId}` const essentialConstsKey = (boundId: number) => `essential_consts_b${boundId}`
export const useGetEssentialConsts = () => { export const useGetEssentialConsts = () => {
// The active bound (least-priority bound among the user's addresses in the // The active bound drives the constants. This hook runs above the location
// region, else the region's effective bound) drives the constants; at checkout // wrapper (UpdateChecker / HealthTestWrapper), so it reads the store directly
// the selected address's bound overrides it. // and tolerates an empty store instead of calling useRegionNeo.
const { boundId: activeBoundId, coords, regionId } = useRegion() const activeBoundId = useNeoRegionStore((state) => state.boundId)
const regionId = useNeoRegionStore((state) => state.regionId)
const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false
const selectedAddressId = useAddressStore((state) => state.selectedAddressId) const selectedAddressId = useNeoRegionStore((state) => state.selectedAddressId)
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, { const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
enabled: isAuthenticated && selectedAddressId != null, enabled: isAuthenticated && selectedAddressId != null,
@ -117,7 +117,7 @@ export type MergedProduct = BaseProduct & ProductPriceFlags & {
} }
function useDiscoveryRegionId(essentialConsts: unknown): number | null { function useDiscoveryRegionId(essentialConsts: unknown): number | null {
const { regionId: selectedRegionId } = useRegion() const selectedRegionId = useNeoRegionStore((state) => state.regionId)
const discovery = essentialConsts as DiscoveryData | undefined const discovery = essentialConsts as DiscoveryData | undefined
return discovery?.regionId ?? selectedRegionId return discovery?.regionId ?? selectedRegionId
} }

View file

@ -0,0 +1,430 @@
import { useEffect, useRef, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import type { RegionSummary } from '@packages/shared'
import { trpc } from '@/src/trpc-client'
import { useAuthOptional } from '@/src/contexts/AuthContext'
import { useLocationStore } from '@/src/store/locationStore'
import {
bindNeoRegionQueryClient,
useNeoRegionStore,
type NeoRegionData,
} from '@/src/store/neoRegionStore'
import {
decideNeoRegion,
type NeoCachedSnapshot,
type NeoResolvedRegion,
} from '@/src/lib/neo-region-decision'
import { readNeoRegionSnapshot } from '@/src/lib/neo-region-cache'
import { applyRegionSwitch } from '@/src/lib/neo-region-switch'
import {
formatNeoAddress,
toNeoAddress,
type NeoAddress,
type NeoCoords,
} from '@/src/lib/neo-address'
export type { NeoRegionData }
// One launch decision per app launch. The recovery poll resets it deliberately.
let decisionStarted = false
let snapshotRead: Promise<Awaited<ReturnType<typeof readNeoRegionSnapshot>>> | null = null
const LOCATION_POLL_MS = 3000
const LOCATION_TIMEOUT_MS = 8000
function regionCoords(region: RegionSummary | undefined | null): NeoCoords | null {
if (region?.center == null) return null
return { latitude: region.center.lat, longitude: region.center.lng }
}
const TERMINAL_LOCATION_STATUSES = [
'granted',
'denied',
'services-off',
'unavailable',
'error',
] as const
/**
* Runs the chart's decision once per launch:
* persisted snapshot -> one device fix -> resolve -> decide -> publish.
*
* Mounted by LocationWrapperNeo, which is always present inside AuthProvider.
* It writes the store; it does not expose data.
*/
export function useNeoRegionBootstrap(): void {
const auth = useAuthOptional()
const hasAuthContext = auth != null
const isAuthenticated = auth?.isAuthenticated ?? false
const isAuthLoading = auth?.isLoading ?? false
const userId = auth?.user?.id ?? null
const queryClient = useQueryClient()
const utils = trpc.useUtils()
const state = useNeoRegionStore()
const coords = useLocationStore((store) => store.coords)
const locationStatus = useLocationStore((store) => store.status)
const startTracking = useLocationStore((store) => store.start)
const probeLocation = useLocationStore((store) => store.probe)
const refreshLocation = useLocationStore((store) => store.refresh)
const [timedOut, setTimedOut] = useState(false)
const [decisionTick, setDecisionTick] = useState(0)
const lastAuthRef = useRef<boolean | null>(null)
// The recovery poll below is torn down by the status flip it causes, so its
// own `cancelled` flag cannot guard the re-arm. This tracks a real unmount.
const mountedRef = useRef(true)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
}
}, [])
const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, {
enabled: isAuthenticated,
})
// Starts on mount, in parallel with the device fix. The decision waits for it
// instead of fetching regions inside `run`.
const regionsQuery = trpc.common.listRegions.useQuery()
useEffect(() => {
bindNeoRegionQueryClient(queryClient)
}, [queryClient])
// One device fix per launch. The store is a singleton and start() is idempotent.
useEffect(() => {
startTracking()
}, [startTracking])
// Publish the persisted snapshot immediately; the decision may switch later.
useEffect(() => {
if (snapshotRead == null) snapshotRead = readNeoRegionSnapshot()
let cancelled = false
void snapshotRead.then((snapshot) => {
if (cancelled || snapshot == null) return
const current = useNeoRegionStore.getState()
if (current.regionId != null) return
const cachedAddress =
snapshot.selectedAddress != null &&
snapshot.selectedAddress.regionId === snapshot.regionId
? snapshot.selectedAddress
: null
if (cachedAddress != null) {
// Provisional: the live list replaces this entry, and validation clears
// the selection if the address no longer exists.
current.setAddresses([cachedAddress])
}
current.applyRegion({
regionId: snapshot.regionId,
boundId: snapshot.boundId,
regionName: snapshot.regionName,
coords: snapshot.coords,
origin: 'cache',
selectedAddressId: cachedAddress?.id ?? null,
})
})
return () => {
cancelled = true
}
}, [])
// Keep the store's address list in sync with the live query. Re-applying the
// selected address keeps its coords/bound fresh after an edit (e.g. attach
// current location), and is a no-op when nothing changed.
useEffect(() => {
if (!addressesQuery.data) return
const store = useNeoRegionStore.getState()
store.setAddresses(addressesQuery.data.data.map(toNeoAddress))
const selectedId = useNeoRegionStore.getState().selectedAddressId
if (selectedId != null) void useNeoRegionStore.getState().selectAddress(selectedId)
}, [addressesQuery.data])
useEffect(() => {
if (isAuthenticated) return
useNeoRegionStore.getState().setAddresses([])
}, [isAuthenticated])
// A hanging location read must not strand the first launch.
useEffect(() => {
if (!hasAuthContext) return
const timer = setTimeout(() => setTimedOut(true), LOCATION_TIMEOUT_MS)
return () => clearTimeout(timer)
}, [hasAuthContext])
// Logging in or out changes the address anchor; re-run the decision once.
useEffect(() => {
if (!hasAuthContext || isAuthLoading) return
if (lastAuthRef.current == null) {
lastAuthRef.current = isAuthenticated
return
}
if (lastAuthRef.current !== isAuthenticated) {
lastAuthRef.current = isAuthenticated
decisionStarted = false
setDecisionTick((tick) => tick + 1)
}
}, [hasAuthContext, isAuthLoading, isAuthenticated])
useEffect(() => {
if (!hasAuthContext || isAuthLoading) return
if (decisionStarted) return
const settled =
coords != null ||
(TERMINAL_LOCATION_STATUSES as readonly string[]).includes(locationStatus)
if (!settled && !timedOut) return
// These queries start on mount / when auth settles; wait for them rather
// than fetching them sequentially here.
const regionsReady = regionsQuery.isFetched || regionsQuery.isError
const addressesReady =
!isAuthenticated || addressesQuery.isFetched || addressesQuery.isError
if (!regionsReady || !addressesReady) return
decisionStarted = true
const run = async () => {
const fix = useLocationStore.getState().coords
// The snapshot read and the coordinate resolve are independent. A network
// failure is not "out of area", so it is tracked separately: only a
// successful resolve that returns no region means the fix is unserviceable.
let resolveFailed = false
const [snapshot, resolveResult] = await Promise.all([
snapshotRead ?? readNeoRegionSnapshot(),
fix != null
? utils.common.resolveRegionByLocation
.fetch({ lat: fix.latitude, lng: fix.longitude })
.catch(() => {
resolveFailed = true
return null
})
: Promise.resolve(null),
])
const store = useNeoRegionStore.getState()
let cached: NeoCachedSnapshot | null = null
if (
store.regionId != null &&
store.boundId != null &&
store.regionName != null &&
store.coords != null
) {
cached = {
regionId: store.regionId,
boundId: store.boundId,
regionName: store.regionName,
coords: store.coords,
}
} else if (snapshot != null) {
cached = {
regionId: snapshot.regionId,
boundId: snapshot.boundId,
regionName: snapshot.regionName,
coords: snapshot.coords,
}
}
const regions = regionsQuery.data ?? store.regions
useNeoRegionStore.getState().setRegions(regions)
if (cached != null && !regions.some((region) => region.id === cached?.regionId)) {
useNeoRegionStore.getState().clearRegion()
cached = null
}
let addresses: NeoAddress[] = []
if (isAuthenticated) {
addresses =
addressesQuery.data != null
? addressesQuery.data.data.map(toNeoAddress)
: useNeoRegionStore.getState().addresses
}
useNeoRegionStore.getState().setAddresses(addresses)
// Read after setAddresses: it clears the selection if the cached address
// is no longer in the live list.
const selectedAddressId = useNeoRegionStore.getState().selectedAddressId
let resolved: NeoResolvedRegion | null = null
if (resolveResult != null) {
const region = regions.find((candidate) => candidate.id === resolveResult.region.id)
const boundId = resolveResult.bound?.id ?? region?.effectiveBoundId ?? null
if (boundId != null) {
resolved = { regionId: resolveResult.region.id, boundId }
}
}
// A fix that resolves to nothing is "outside the delivery area": the
// address flow says why instead of only asking for an address. A failed
// resolve (offline) leaves it unknown.
useNeoRegionStore
.getState()
.setDeviceOutOfService(fix != null && !resolveFailed && resolveResult == null)
const decision = decideNeoRegion({
cached,
fix,
resolved,
isAuthenticated,
addresses,
selectedAddressId,
})
if (decision.action === 'needs-address-flow') {
useNeoRegionStore.getState().openAddressFlow()
return
}
const region = regions.find((candidate) => candidate.id === decision.regionId)
const boundId = decision.boundId ?? region?.effectiveBoundId ?? null
const decisionCoords = decision.action === 'ready' ? decision.coords : null
const targetCoords = decisionCoords ?? regionCoords(region) ?? cached?.coords ?? fix
if (region == null || boundId == null || targetCoords == null) {
useNeoRegionStore.getState().openAddressFlow()
return
}
// A decision that moves away from the published region is a real switch:
// stash/clear the carts and invalidate the region-scoped caches, exactly
// like an explicit changeRegion.
const previousRegionId = useNeoRegionStore.getState().regionId
if (previousRegionId != null && previousRegionId !== decision.regionId) {
await applyRegionSwitch(previousRegionId, decision.regionId, queryClient)
}
useNeoRegionStore.getState().applyRegion({
regionId: decision.regionId,
boundId,
regionName: region.name,
coords: targetCoords,
origin: decision.action === 'needs-confirmation' ? 'device' : decision.origin,
selectedAddressId:
decision.action === 'needs-confirmation' ? null : decision.selectedAddressId,
})
if (decision.action === 'needs-confirmation') {
useNeoRegionStore.getState().setNeedsConfirmation(true)
}
}
void run().catch(() => {
// A failed decision must not strand the loading screen forever.
useNeoRegionStore.getState().openAddressFlow()
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
hasAuthContext,
isAuthLoading,
isAuthenticated,
coords,
locationStatus,
timedOut,
decisionTick,
userId,
regionsQuery.data,
regionsQuery.isFetched,
regionsQuery.isError,
addressesQuery.data,
addressesQuery.isFetched,
addressesQuery.isError,
])
// If the user leaves for the OS settings and turns location on, recover
// without a restart while the address flow is up. Only poll when the location
// is actually unusable: when the flow is up because the user has no address,
// the fix already exists and re-deciding would just flicker the screen.
const locationIsUnusable =
locationStatus === 'denied' ||
locationStatus === 'services-off' ||
locationStatus === 'unavailable' ||
locationStatus === 'error'
useEffect(() => {
if (!state.needsAddressFormFlow || !locationIsUnusable) return
let cancelled = false
let busy = false
const check = async () => {
if (busy) return
busy = true
try {
const usable = await probeLocation()
if (cancelled || !usable) return
await refreshLocation()
// Do NOT gate this on `cancelled`: refresh() flips the status to
// 'locating', which makes locationIsUnusable false and runs this
// effect's cleanup while the fix is still being read. Only a real
// unmount (or a fix that still isn't there) should skip the re-arm.
if (!mountedRef.current) return
if (useLocationStore.getState().coords == null) return
decisionStarted = false
useNeoRegionStore.getState().closeAddressFlow()
setDecisionTick((tick) => tick + 1)
} finally {
busy = false
}
}
void check()
const timer = setInterval(() => void check(), LOCATION_POLL_MS)
return () => {
cancelled = true
clearInterval(timer)
}
}, [state.needsAddressFormFlow, locationIsUnusable, probeLocation, refreshLocation])
}
/**
* The region/address data, never null.
*
* Only call this from components that LocationWrapperNeo renders — the wrapper
* guarantees the store holds a complete region before children appear. Calling
* it earlier is a bug, so it throws rather than handing out a half-answer.
*/
export function useRegionNeo(): NeoRegionData {
const state = useNeoRegionStore()
const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false
const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, {
enabled: isAuthenticated,
})
const { regionId, boundId, regionName, coords, origin, selectedAddressId } = state
if (regionId == null || boundId == null || regionName == null || coords == null) {
throw new Error(
'useRegionNeo() called before LocationWrapperNeo published a region. ' +
'It may only be used by components rendered inside the wrapper.'
)
}
// Live query data wins; the store is the fallback while the query loads (it
// also carries the provisional cached address from the snapshot).
const liveAddresses = addressesQuery.data?.data.map(toNeoAddress) ?? null
const addresses = liveAddresses ?? state.addresses
const selected =
selectedAddressId != null
? addresses.find((address) => address.id === selectedAddressId) ?? null
: null
return {
regionId,
boundId,
regionName,
coords,
selectedAddressId: selected?.id ?? null,
selectedAddress: selected,
fullAddress: selected != null ? formatNeoAddress(selected) : null,
isCache: origin === 'cache',
changeRegion: state.changeRegion,
// Async only because a cross-region selection awaits the cart switch.
// Never performs an address API call; the caller refreshes after mutations.
selectAddress: state.selectAddress,
}
}

View file

@ -0,0 +1,79 @@
import type { UserAddress } from '@packages/shared'
/** Coordinates as the app stores them (the shared DTO uses lat/lng on region centres). */
export interface NeoCoords {
latitude: number
longitude: number
}
/**
* The address shape the neo region store works with. Deliberately a small,
* serializable projection of `UserAddress`: the fields the region decision and
* the checkout surfaces actually read.
*/
export interface NeoAddress {
id: number
regionId: number | null
boundId: number | null
name: string
phone: string
addressLine1: string
addressLine2: string | null
city: string
state: string
isDefault: boolean
latitude: number | null
longitude: number | null
googleMapsUrl: string | null
}
type AddressLike = Pick<
UserAddress,
'id' | 'name' | 'phone' | 'addressLine1' | 'city' | 'state' | 'isDefault'
> & {
regionId?: number | null
boundId?: number | null
addressLine2?: string | null
latitude?: number | null
longitude?: number | null
googleMapsUrl?: string | null
}
/** Normalize a `UserAddress` (or a serialized copy of one) into `NeoAddress`. */
export function toNeoAddress(address: AddressLike): NeoAddress {
return {
id: address.id,
regionId: address.regionId ?? null,
boundId: address.boundId ?? null,
name: address.name,
phone: address.phone,
addressLine1: address.addressLine1,
addressLine2: address.addressLine2 ?? null,
city: address.city,
state: address.state,
isDefault: address.isDefault,
latitude: address.latitude ?? null,
longitude: address.longitude ?? null,
googleMapsUrl: address.googleMapsUrl ?? null,
}
}
export function addressCoords(address: NeoAddress): NeoCoords | null {
if (address.latitude == null || address.longitude == null) return null
return { latitude: address.latitude, longitude: address.longitude }
}
/** Icon name for the address card, based on the address label. */
export function addressIconName(name: string): 'home' | 'work' | 'location-on' {
const normalized = name.toLowerCase()
if (normalized.includes('home')) return 'home'
if (normalized.includes('work')) return 'work'
return 'location-on'
}
/** One-line delivery address used by the location bar and the checkout card. */
export function formatNeoAddress(address: NeoAddress): string {
return [address.addressLine1, address.addressLine2, address.city]
.filter((part): part is string => typeof part === 'string' && part.trim().length > 0)
.join(', ')
}

View file

@ -0,0 +1,63 @@
import { StorageServiceCasual } from 'common-ui'
import type { NeoAddress, NeoCoords } from '@/src/lib/neo-address'
const NEO_REGION_KEY = 'freshyo_neo_region_v1'
/** The last published region, so the next launch renders before the fix lands. */
export interface NeoRegionSnapshot {
regionId: number
boundId: number
regionName: string
coords: NeoCoords
/** The address that was active when the snapshot was written. */
selectedAddress: NeoAddress | null
}
function isSnapshot(value: unknown): value is NeoRegionSnapshot {
if (value == null || typeof value !== 'object') return false
const candidate = value as Record<string, unknown>
const coords = candidate.coords as Record<string, unknown> | null | undefined
const selected = candidate.selectedAddress as Record<string, unknown> | null | undefined
const selectedOk =
selected == null ||
(typeof selected === 'object' && typeof selected.id === 'number')
return (
typeof candidate.regionId === 'number' &&
typeof candidate.boundId === 'number' &&
typeof candidate.regionName === 'string' &&
coords != null &&
typeof coords === 'object' &&
typeof coords.latitude === 'number' &&
typeof coords.longitude === 'number' &&
selectedOk
)
}
export async function readNeoRegionSnapshot(): Promise<NeoRegionSnapshot | null> {
try {
const raw = await StorageServiceCasual.getItem(NEO_REGION_KEY)
if (!raw) return null
const parsed = JSON.parse(raw) as unknown
if (!isSnapshot(parsed)) return null
// Snapshots written before the address was cached have no field.
return { ...parsed, selectedAddress: parsed.selectedAddress ?? null }
} catch {
return null
}
}
export async function writeNeoRegionSnapshot(snapshot: NeoRegionSnapshot): Promise<void> {
try {
await StorageServiceCasual.setItem(NEO_REGION_KEY, JSON.stringify(snapshot))
} catch {
// Persistence is best-effort; the live decision still corrects the region.
}
}
export async function clearNeoRegionSnapshot(): Promise<void> {
try {
await StorageServiceCasual.removeItem(NEO_REGION_KEY)
} catch {
// ignore
}
}

View file

@ -0,0 +1,183 @@
import { addressCoords, type NeoAddress, type NeoCoords } from '@/src/lib/neo-address'
export type NeoOrigin = 'device' | 'cache' | 'address' | 'manual'
export interface NeoCachedSnapshot {
regionId: number
boundId: number
regionName: string
coords: NeoCoords
}
export interface NeoResolvedRegion {
regionId: number
boundId: number
}
/**
* The outcome of one launch decision. `coords` / `boundId` may be null when the
* chosen address has no coordinates and no cached fix exists; the hook fills
* them from the region's centre / effective bound before publishing.
*/
export type NeoDecision =
| {
action: 'ready'
regionId: number
boundId: number | null
coords: NeoCoords | null
origin: NeoOrigin
selectedAddressId: number | null
}
| { action: 'needs-address-flow' }
| { action: 'needs-confirmation'; regionId: number; boundId: number | null }
export interface DecideNeoRegionInput {
cached: NeoCachedSnapshot | null
fix: NeoCoords | null
resolved: NeoResolvedRegion | null
isAuthenticated: boolean
addresses: NeoAddress[]
/** The currently active address (restored from the persisted snapshot). */
selectedAddressId?: number | null
}
function defaultAddress(addresses: NeoAddress[]): NeoAddress | null {
return addresses.find((address) => address.isDefault) ?? addresses[0] ?? null
}
/**
* The active address inside a region: the persisted selection first, then the
* default, then the first one there.
*/
function preferredInRegion(
addresses: NeoAddress[],
regionId: number,
selectedAddressId: number | null
): NeoAddress | null {
const inRegion = addresses.filter((address) => address.regionId === regionId)
return (
inRegion.find((address) => address.id === selectedAddressId) ??
inRegion.find((address) => address.isDefault) ??
inRegion[0] ??
null
)
}
/** The persisted selection anywhere, else the default, else the first. */
function bestAddress(
addresses: NeoAddress[],
selectedAddressId: number | null
): NeoAddress | null {
return (
addresses.find((address) => address.id === selectedAddressId) ??
defaultAddress(addresses)
)
}
function readyWithAddress(address: NeoAddress): NeoDecision {
return {
action: 'ready',
regionId: address.regionId as number,
boundId: address.boundId,
coords: addressCoords(address),
origin: 'address',
selectedAddressId: address.id,
}
}
/**
* The chart, as a pure function.
*
* - no cached region -> a saved address always wins (decision 2); only a
* user with no address at all follows the device fix;
* - cached region + same region -> keep it (and select an address there);
* - cached region + different region -> the address in the new region wins;
* with no such address, an address-owning user is asked to confirm, while a
* guest / address-less user simply follows the device.
*/
export function decideNeoRegion(input: DecideNeoRegionInput): NeoDecision {
// Addresses without a region can never anchor a decision.
const addresses = input.isAuthenticated
? input.addresses.filter((address) => address.regionId != null)
: []
const cached = input.cached
const fix = input.fix
const resolved = input.resolved
const selectedAddressId = input.selectedAddressId ?? null
// No usable device answer: keep the persisted region, or fall back to the
// user's default address, or ask for an address.
if (resolved == null) {
if (cached != null) {
const selected = preferredInRegion(addresses, cached.regionId, selectedAddressId)
return {
action: 'ready',
regionId: cached.regionId,
boundId: selected?.boundId ?? cached.boundId,
coords: selected ? addressCoords(selected) ?? cached.coords : cached.coords,
origin: selected ? 'address' : 'cache',
selectedAddressId: selected?.id ?? null,
}
}
const fallback = bestAddress(addresses, selectedAddressId)
if (fallback != null && fallback.regionId != null) {
return readyWithAddress(fallback)
}
return { action: 'needs-address-flow' }
}
// The device resolved to a serviceable region.
if (cached != null) {
if (cached.regionId === resolved.regionId) {
const selected = preferredInRegion(addresses, resolved.regionId, selectedAddressId)
return {
action: 'ready',
regionId: resolved.regionId,
boundId: selected?.boundId ?? resolved.boundId,
coords: selected ? addressCoords(selected) ?? fix : fix,
origin: selected ? 'address' : 'device',
selectedAddressId: selected?.id ?? null,
}
}
const inNewRegion = preferredInRegion(addresses, resolved.regionId, selectedAddressId)
if (inNewRegion != null) {
return readyWithAddress(inNewRegion)
}
// Saved addresses exist, but none of them is in the region the device is in.
if (addresses.length > 0) {
return {
action: 'needs-confirmation',
regionId: resolved.regionId,
boundId: resolved.boundId,
}
}
return {
action: 'ready',
regionId: resolved.regionId,
boundId: resolved.boundId,
coords: fix,
origin: 'device',
selectedAddressId: null,
}
}
// No cached region: the saved address is the anchor.
const anchor = bestAddress(addresses, selectedAddressId)
if (anchor != null && anchor.regionId != null) {
return readyWithAddress(anchor)
}
return {
action: 'ready',
regionId: resolved.regionId,
boundId: resolved.boundId,
coords: fix,
origin: 'device',
selectedAddressId: null,
}
}

View file

@ -0,0 +1,64 @@
import type { QueryClient } from '@tanstack/react-query'
import { clearLocalCart, restoreRegionCarts, stashRegionCarts } from '@/hooks/cart-query-hooks'
import { useCartStore } from '@/src/store/cartStore'
import { useFlashCartStore } from '@/src/store/flashCartStore'
import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore'
import { useCentralProductStore } from '@/src/store/centralProductStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import { useSlotStore } from '@/components/stores/slotStore'
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
import { useHomeTagStore } from '@/src/store/homeTagStore'
import { useFlashTabStore } from '@/src/store/flashTabStore'
/**
* The destructive half of a region switch, lifted from `region-switch.ts` so the
* neo store can own the write. Carts are stashed per region and restored when
* the user comes back; everything scoped to the old region is cleared.
*
* The caller (the neo store) has already decided to switch; confirmation for a
* manual switch is the caller's responsibility.
*/
export async function applyRegionSwitch(
fromRegionId: number | null,
toRegionId: number,
queryClient: QueryClient
): Promise<void> {
const isSameRegion = fromRegionId === toRegionId
if (!isSameRegion) {
if (fromRegionId != null) {
await stashRegionCarts(fromRegionId)
}
await Promise.all([clearLocalCart('regular'), clearLocalCart('flash')])
}
// Drop in-memory checkout / quick-delivery selections.
useQuickDeliveryStore.getState().setSelectedSlotId(null)
useSlotStore.getState().setSlotId(undefined)
useSlotStore.getState().setStoreId(undefined)
useCartStore.getState().clearAddedToCartProduct()
useFlashCartStore.getState().clearAddedFlashProduct()
useFlashNavigationStore.getState().reset()
// Tag ids belong to the outgoing region.
useHomeTagStore.getState().resetHomeTags()
useFlashTabStore.getState().resetFlashTabs()
// Drop cached regional catalog/slot snapshots so they cannot leak across.
const productStore = useCentralProductStore.getState()
productStore.setProducts([])
productStore.setRefetchProducts(null)
useCentralSlotStore.getState().setSlotsData([], [], [])
queryClient.removeQueries({ queryKey: ['all-products'] })
queryClient.removeQueries({ queryKey: ['stores'] })
queryClient.removeQueries({ queryKey: ['slots'] })
queryClient.removeQueries({ queryKey: ['availability'] })
queryClient.removeQueries({ queryKey: ['store-with-products'] })
if (!isSameRegion) {
await restoreRegionCarts(toRegionId)
}
await queryClient.invalidateQueries()
}

View file

@ -0,0 +1,110 @@
import { computeCouponDiscount } from '@packages/shared'
import type { ProductCouponOffer } from '@packages/shared'
/**
* Coupon money for the catalogue (product cards + product detail).
*
* Invariants:
* - Only product-specific coupons are advertised: `skuIds` must be a non-empty
* array containing the sku. A cart-wide coupon is not a product offer and is
* left to the cart screen.
* - `minOrder` is ignored here: it is measured on the whole cart, so a single
* product cannot know whether the customer will reach it. The cart already
* explains eligibility.
* - Expiry, invalidation and per-user usage limits are dropped server-side by
* `user.coupon.getEligible`; region and first-order-only are checked here
* because the endpoint returns those coupons on purpose.
* - The discount is the shared `computeCouponDiscount`, so a card price can
* never disagree with the cart's line math.
*/
/** The coupon fields the catalogue cares about (a structural slice of the API row). */
export interface CatalogueCoupon {
id: number
couponCode: string
discountPercent?: string | number | null
flatDiscount?: string | number | null
maxValue?: string | number | null
skuIds?: number[] | null
regionId?: number | null
isFirstOrderOnly?: boolean | null
isInvalidated?: boolean | null
}
export interface CouponOfferContext {
/** The region the catalogue is showing, or null when it is not known yet. */
regionId: number | null
/** Whether the customer can still use first-order-only coupons. */
isFirstOrder: boolean
}
/**
* Map every product-specific coupon onto the skus it targets.
*
* A sku can be targeted by more than one coupon (they stack in the cart), so the
* value is a list. Which one a card advertises depends on the unit price — a
* percentage beats a flat discount on an expensive item and loses on a cheap one
* — so the choice is deferred to `couponPriceFor` with the price in hand.
*/
export function buildCouponOffers(
coupons: CatalogueCoupon[] | null | undefined,
context: CouponOfferContext
): Record<number, ProductCouponOffer[]> {
const offers: Record<number, ProductCouponOffer[]> = {}
if (!Array.isArray(coupons)) return offers
for (const coupon of coupons) {
if (coupon.isInvalidated) continue
if (
coupon.regionId != null &&
context.regionId != null &&
coupon.regionId !== context.regionId
) {
continue
}
if (coupon.isFirstOrderOnly && !context.isFirstOrder) continue
const targets = Array.isArray(coupon.skuIds) ? coupon.skuIds : []
if (targets.length === 0) continue
const offer: ProductCouponOffer = {
couponId: coupon.id,
couponCode: coupon.couponCode,
discountPercent: coupon.discountPercent ?? null,
flatDiscount: coupon.flatDiscount ?? null,
maxValue: coupon.maxValue ?? null,
}
for (const skuId of targets) {
if (!Number.isFinite(skuId)) continue
if (!offers[skuId]) offers[skuId] = []
offers[skuId].push(offer)
}
}
return offers
}
/**
* The unit price a coupon leaves behind for one sku, or null when no offer beats
* the listed price. Whole rupees, matching how the cart rounds a coupon's share.
*/
export function couponPriceFor(
offers: ProductCouponOffer[] | undefined | null,
unitPrice: number | string | null | undefined
): number | null {
const price = typeof unitPrice === 'number' ? unitPrice : parseFloat(String(unitPrice ?? ''))
if (!Number.isFinite(price) || price <= 0) return null
if (!Array.isArray(offers) || offers.length === 0) return null
let best: number | null = null
for (const offer of offers) {
const discount = computeCouponDiscount(price, offer)
if (!(discount > 0)) continue
const discounted = Math.max(0, Math.round(price - discount))
if (discounted >= price) continue
if (best == null || discounted < best) best = discounted
}
return best
}

View file

@ -64,6 +64,8 @@ export async function confirmRegionSwitch(
// 3. Drop cached regional catalog/slot snapshots so they cannot leak across. // 3. Drop cached regional catalog/slot snapshots so they cannot leak across.
const productStore = useCentralProductStore.getState() const productStore = useCentralProductStore.getState()
productStore.setProducts([]) productStore.setProducts([])
productStore.setTags([])
productStore.setCouponOffers({})
productStore.setRefetchProducts(null) productStore.setRefetchProducts(null)
useCentralSlotStore.getState().setSlotsData([], [], []) useCentralSlotStore.getState().setSlotsData([], [], [])

View file

@ -1,38 +1,170 @@
import { create } from 'zustand' import { create } from 'zustand'
import { useEffect } from 'react' import { useEffect } from 'react'
import { useAllProducts, type MergedProduct } from '@/src/hooks/prominent-api-hooks' import { useAllProducts, type MergedProduct } from '@/src/hooks/prominent-api-hooks'
import type { CentralProductState as CentralProductsState } from '@packages/shared' import type { AllProductsApiType } from '@backend/trpc/router'
import type { CentralProductState as CentralProductsState, ProductCouponOffer } from '@packages/shared'
import { trpc } from '@/src/trpc-client'
import { useAuthOptional } from '@/src/contexts/AuthContext'
import { useRegion } from '@/src/hooks/useRegion'
import { buildCouponOffers, couponPriceFor } from '@/src/lib/product-coupons'
export type Product = MergedProduct /** Catalogue fields the store adds on top of the parsed products document. */
export interface ProductCouponFields {
/** True when a product-specific coupon makes this product cheaper. */
isProductCouponApply: boolean
/** The unit price after that coupon (whole rupees). */
couponDiscountedPrice: number
}
type CentralProductState = CentralProductsState<Product> export type Product = MergedProduct & Partial<ProductCouponFields>
/** One dashboard tag strip; the catalogue payload's own tag shape. */
export type CatalogueTag = AllProductsApiType['tags'][number]
export const useCentralProductStore = create<CentralProductState>((set) => ({ type CentralProductState = CentralProductsState<Product, CatalogueTag>
const EMPTY_OFFERS: Record<number, ProductCouponOffer[]> = {}
/**
* Stamp the coupon fields onto a product. Only products that actually change get
* a new object, so a coupon arriving does not re-render every card in the list.
*/
function withCouponFields(
product: Product,
offers: Record<number, ProductCouponOffer[]>
): Product {
const discounted = couponPriceFor(offers[product.id], product.price)
if (discounted == null) {
if (!product.isProductCouponApply) return product
const { isProductCouponApply, couponDiscountedPrice, ...rest } = product
return rest
}
if (
product.isProductCouponApply &&
product.couponDiscountedPrice === discounted
) {
return product
}
return {
...product,
isProductCouponApply: true,
couponDiscountedPrice: discounted,
}
}
function buildProductsById(products: Product[]): Record<number, Product> {
const productsById: Record<number, Product> = {}
for (const product of products) {
productsById[product.id] = product
}
return productsById
}
/**
* Single frontend source of product data. `useInitializeCentralProductStore` is
* the only reader of the catalogue JSON; every screen selects from here, so a
* product field (price flags, coupon price, ...) is authoritative in one place.
*
* `isLoading` starts true: the root initializer mounts before the screens paint,
* and a cold start must show the loading copy rather than an empty catalogue.
*/
export const useCentralProductStore = create<CentralProductState>((set, get) => ({
products: [], products: [],
productsById: {}, productsById: {},
tags: [],
isLoading: true,
error: null,
couponOffers: EMPTY_OFFERS,
refetchProducts: null, refetchProducts: null,
setProducts: (products) => { setProducts: (products) => {
const productsById: Record<number, Product> = {} const { couponOffers } = get()
const decorated =
products.forEach((product) => { Object.keys(couponOffers).length === 0
productsById[product.id] = product ? products
: products.map((product) => withCouponFields(product, couponOffers))
set({ products: decorated, productsById: buildProductsById(decorated) })
},
setTags: (tags) => set({ tags }),
setCatalogMeta: (meta) =>
set((state) => ({
isLoading: meta.isLoading ?? state.isLoading,
error: meta.error !== undefined ? meta.error : state.error,
})),
setCouponOffers: (offers) => {
const state = get()
// The coupon effect rebuilds the same map on unrelated re-renders; skip the
// whole catalogue walk when nothing moved.
if (offers === state.couponOffers) return
let changed = false
const products = state.products.map((product) => {
const next = withCouponFields(product, offers)
if (next !== product) changed = true
return next
})
// An empty (or equally empty) offer map must not churn the catalogue array:
// the home feed pages off it and would reset "Show More".
if (!changed) {
set({ couponOffers: offers })
return
}
set({
couponOffers: offers,
products,
productsById: buildProductsById(products),
}) })
set({ products, productsById })
}, },
setRefetchProducts: (refetchProducts) => set({ refetchProducts }), setRefetchProducts: (refetchProducts) => set({ refetchProducts }),
})) }))
export function useInitializeCentralProductStore() { export function useInitializeCentralProductStore() {
const { data: productsData, refetch } = useAllProducts() const { data: productsData, refetch, isLoading, error } = useAllProducts()
const { regionId } = useRegion()
const auth = useAuthOptional()
const isAuthenticated = Boolean(auth?.isAuthenticated)
// Fire-and-forget: a second, independent leg next to the catalogue. Nothing
// reads its loading state, so a slow or failing call never blocks a screen.
// Held until the region is known: the same region decides the catalogue URL,
// and a coupon from another region must never price a card, even briefly.
const { data: couponsData } = trpc.user.coupon.getEligible.useQuery(
{ regionId: regionId ?? undefined },
{ enabled: isAuthenticated && regionId != null }
)
const setProducts = useCentralProductStore((state) => state.setProducts) const setProducts = useCentralProductStore((state) => state.setProducts)
const setTags = useCentralProductStore((state) => state.setTags)
const setCatalogMeta = useCentralProductStore((state) => state.setCatalogMeta)
const setCouponOffers = useCentralProductStore((state) => state.setCouponOffers)
const setRefetchProducts = useCentralProductStore((state) => state.setRefetchProducts) const setRefetchProducts = useCentralProductStore((state) => state.setRefetchProducts)
useEffect(() => { useEffect(() => {
// Products and tags land together so the tag strips never render a catalogue
// they don't belong to. Undefined data (version bump still in flight, failed
// refresh) deliberately keeps the previous catalogue on screen.
if (productsData?.products) { if (productsData?.products) {
setProducts(productsData.products) setProducts(productsData.products)
setTags(productsData.tags ?? [])
} }
}, [productsData, setProducts]) }, [productsData, setProducts, setTags])
useEffect(() => {
setCatalogMeta({ isLoading, error: error ?? null })
}, [isLoading, error, setCatalogMeta])
useEffect(() => {
if (!isAuthenticated || !couponsData || regionId == null) {
setCouponOffers(EMPTY_OFFERS)
return
}
setCouponOffers(
buildCouponOffers(couponsData.data, {
regionId,
// The endpoint counts the customer's orders; a missing flag means
// "still first-order eligible" for a brand-new session.
isFirstOrder: couponsData.isFirstOrder ?? true,
})
)
}, [couponsData, isAuthenticated, regionId, setCouponOffers])
useEffect(() => { useEffect(() => {
setRefetchProducts(async () => { setRefetchProducts(async () => {

View file

@ -0,0 +1,243 @@
import { create } from 'zustand'
import type { QueryClient } from '@tanstack/react-query'
import type { RegionSummary } from '@packages/shared'
import { applyRegionSwitch } from '@/src/lib/neo-region-switch'
import { writeNeoRegionSnapshot } from '@/src/lib/neo-region-cache'
import { addressCoords, type NeoAddress, type NeoCoords } from '@/src/lib/neo-address'
import type { NeoOrigin } from '@/src/lib/neo-region-decision'
export interface NeoRegionData {
regionId: number
boundId: number
regionName: string
coords: NeoCoords
selectedAddressId: number | null
/** The full selected address object (null when the region has no address). */
selectedAddress: NeoAddress | null
/** The selected address formatted as one line. */
fullAddress: string | null
isCache: boolean
changeRegion: (regionId: number, boundId?: number | null) => Promise<void>
selectAddress: (id: number) => Promise<void>
}
interface ApplyRegionInput {
regionId: number
boundId: number
regionName: string
coords: NeoCoords
origin: NeoOrigin
selectedAddressId: number | null
}
interface NeoRegionState {
regionId: number | null
boundId: number | null
regionName: string | null
coords: NeoCoords | null
origin: NeoOrigin | null
regions: RegionSummary[]
addresses: NeoAddress[]
selectedAddressId: number | null
needsAddressFormFlow: boolean
needsAddressConfirmation: boolean
/** A device fix exists but resolves outside every serviceable bound. */
deviceOutOfService: boolean
applyRegion: (data: ApplyRegionInput) => void
setRegions: (regions: RegionSummary[]) => void
setAddresses: (addresses: NeoAddress[]) => void
clearRegion: () => void
openAddressFlow: () => void
closeAddressFlow: () => void
setNeedsConfirmation: (value: boolean) => void
setDeviceOutOfService: (value: boolean) => void
resetForLogout: () => void
changeRegion: (regionId: number, boundId?: number | null) => Promise<void>
selectAddress: (id: number) => Promise<void>
}
// The cart/cache side of a region switch needs the app's query client. The hook
// binds it once; every other consumer only uses the actions below.
let boundQueryClient: QueryClient | null = null
export function bindNeoRegionQueryClient(queryClient: QueryClient): void {
boundQueryClient = queryClient
}
function regionCoords(region: RegionSummary | undefined | null): NeoCoords | null {
if (region?.center == null) return null
return { latitude: region.center.lat, longitude: region.center.lng }
}
export const useNeoRegionStore = create<NeoRegionState>((set, get) => ({
regionId: null,
boundId: null,
regionName: null,
coords: null,
origin: null,
regions: [],
addresses: [],
selectedAddressId: null,
needsAddressFormFlow: false,
needsAddressConfirmation: false,
deviceOutOfService: false,
/**
* The only writer of the region fields. The selection is validated against
* the region here, so `selectedAddressId != null` always means "the active
* address belongs to the active region".
*/
applyRegion: (data) => {
const state = get()
const selection =
data.selectedAddressId != null
? state.addresses.find((address) => address.id === data.selectedAddressId) ?? null
: null
const validSelection =
selection != null && selection.regionId === data.regionId ? selection : null
const regionName =
state.regions.find((region) => region.id === data.regionId)?.name ?? data.regionName
const coords = (validSelection ? addressCoords(validSelection) : null) ?? data.coords
const boundId = validSelection?.boundId ?? data.boundId
set({
regionId: data.regionId,
boundId,
regionName,
coords,
origin: validSelection != null ? 'address' : data.origin,
selectedAddressId: validSelection?.id ?? null,
needsAddressFormFlow: false,
needsAddressConfirmation: false,
})
void writeNeoRegionSnapshot({
regionId: data.regionId,
boundId,
regionName,
coords,
selectedAddress: validSelection,
})
},
setRegions: (regions) => {
const state = get()
const current = state.regionId != null
? regions.find((region) => region.id === state.regionId) ?? null
: null
set({
regions,
regionName: current?.name ?? state.regionName,
})
},
setAddresses: (addresses) => {
const usable = addresses.filter((address) => address.regionId != null)
const state = get()
if (state.selectedAddressId == null) {
set({ addresses: usable })
return
}
const selected = usable.find((address) => address.id === state.selectedAddressId) ?? null
const stillValid =
selected != null &&
selected.regionId === state.regionId &&
(selected.boundId == null || state.boundId == null || selected.boundId === state.boundId)
set({
addresses: usable,
selectedAddressId: stillValid ? state.selectedAddressId : null,
})
},
clearRegion: () => {
set({
regionId: null,
boundId: null,
regionName: null,
coords: null,
origin: null,
selectedAddressId: null,
needsAddressFormFlow: false,
needsAddressConfirmation: false,
})
},
openAddressFlow: () => set({ needsAddressFormFlow: true, needsAddressConfirmation: false }),
closeAddressFlow: () => set({ needsAddressFormFlow: false }),
setNeedsConfirmation: (value) =>
set({
needsAddressConfirmation: value,
...(value ? { needsAddressFormFlow: false } : null),
}),
setDeviceOutOfService: (value) => set({ deviceOutOfService: value }),
resetForLogout: () =>
set({
addresses: [],
selectedAddressId: null,
needsAddressFormFlow: false,
needsAddressConfirmation: false,
}),
changeRegion: async (regionId, boundId) => {
const state = get()
const region = state.regions.find((candidate) => candidate.id === regionId)
if (region == null) return
const nextBoundId = boundId ?? region.effectiveBoundId ?? null
if (nextBoundId == null) return
if (state.regionId !== regionId && boundQueryClient != null) {
await applyRegionSwitch(state.regionId, regionId, boundQueryClient)
}
const coords = regionCoords(region) ?? state.coords
if (coords == null) return
get().applyRegion({
regionId,
boundId: nextBoundId,
regionName: region.name,
coords,
origin: 'manual',
selectedAddressId: null,
})
},
selectAddress: async (id) => {
const state = get()
const address = state.addresses.find((candidate) => candidate.id === id)
if (address == null || address.regionId == null) return
const region = state.regions.find((candidate) => candidate.id === address.regionId)
if (region == null) return
const boundId = address.boundId ?? region.effectiveBoundId ?? null
if (boundId == null) return
if (state.regionId !== address.regionId && boundQueryClient != null) {
await applyRegionSwitch(state.regionId, address.regionId, boundQueryClient)
}
const coords = addressCoords(address) ?? regionCoords(region) ?? state.coords
if (coords == null) return
get().applyRegion({
regionId: address.regionId,
boundId,
regionName: region.name,
coords,
origin: 'address',
selectedAddressId: address.id,
})
},
}))

View file

@ -87,12 +87,23 @@ Rules:
| Helper | Effect | | Helper | Effect |
| --- | --- | | --- | --- |
| `seedJsonCache(overrides)` | products/availability/slots/stores/store-detail CDN docs | | `seedJsonCache(overrides)` | products/availability/slots/stores/store-detail CDN docs |
| `seedCentralStores(overrides)` | central product + slot stores (needed by `useGetCart`) | | `seedCentralStores(overrides)` | central product + slot stores, with `tags` and a loaded (`isLoading: false`) catalogue state |
| `seedEmptyCatalogue()` | clears the central product store — a cold start, for first-load loading/error cases |
| `seedRegion(region, boundId)` | selects the browsing region without the location flow | | `seedRegion(region, boundId)` | selects the browsing region without the location flow |
| `seedSelectedAddress(id)` | sets `addressStore.selectedAddressId` | | `seedSelectedAddress(id)` | sets `addressStore.selectedAddressId` |
| `seedBoot({auth,addressId})` | the usual home/cart boot state | | `seedBoot({auth,addressId})` | the usual home/cart boot state |
| `seedAuthStorage('in' | 'out')` | token/userId in the storage mock | | `seedAuthStorage('in' | 'out')` | token/userId in the storage mock |
Catalogue coupon prices are seeded through the store, never through a request:
`useCentralProductStore.getState().setCouponOffers({ [skuId]: [offer] })`.
`seedBoot()` seeds a catalogue without offers, so the default everywhere is "no
coupon price".
Catalogue pages render from `useCentralProductStore`, not from their own
`useAllProducts()` call. `renderWithProviders(ui, { withProductStore: true })`
mounts the real producer, so the mocked products JSON still drives what the page
shows (loading, error, tags and payload overrides included).
Storage: `import { __set, __delete, __snapshot } from '../../mocks/secure-store-mock'`. Storage: `import { __set, __delete, __snapshot } from '../../mocks/secure-store-mock'`.
Cart lines live under `cart_items` / `flash_cart_items` (`CART_REG`, `CART_FLASH`). Cart lines live under `cart_items` / `flash_cart_items` (`CART_REG`, `CART_FLASH`).

View file

@ -14,6 +14,7 @@
import * as React from 'react' import * as React from 'react'
import { fireEvent, waitFor, within, act } from '@testing-library/react-native' import { fireEvent, waitFor, within, act } from '@testing-library/react-native'
import AddressForm from '@/src/components/AddressForm' import AddressForm from '@/src/components/AddressForm'
import { useLocationStore } from '@/src/store/locationStore'
import LocationMapStep from '@/src/components/location/LocationMapStep' import LocationMapStep from '@/src/components/location/LocationMapStep'
import constants from '@/src/constants' import constants from '@/src/constants'
import { renderWithProviders, seedRegion, flush } from '../helpers/test-utils' import { renderWithProviders, seedRegion, flush } from '../helpers/test-utils'
@ -62,6 +63,7 @@ function grantLocation(latitude = 12.34, longitude = 56.78) {
servicesEnabled: true, servicesEnabled: true,
position: { coords: { latitude, longitude, accuracy: 5 }, timestamp: 1 }, position: { coords: { latitude, longitude, accuracy: 5 }, timestamp: 1 },
}) })
useLocationStore.getState().start()
return { latitude, longitude } return { latitude, longitude }
} }

View file

@ -14,7 +14,7 @@ import CheckoutAddressSelector from '@/components/CheckoutAddressSelector'
import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay' import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay'
import AddressForm from '@/src/components/AddressForm' import AddressForm from '@/src/components/AddressForm'
import { useRegionStore } from '@/src/store/regionStore' import { useRegionStore } from '@/src/store/regionStore'
import { useAddressStore } from '@/src/store/addressStore' import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
@ -30,8 +30,8 @@ import { router } from '../mocks/expo-router-mock'
import { A1, A2, A3, REGION_1, REGION_2 } from '../fixtures' import { A1, A2, A3, REGION_1, REGION_2 } from '../fixtures'
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
jest.mock('@/src/hooks/useRegion', () => ({ jest.mock('@/src/hooks/useRegionNeo', () => ({
useRegion: () => (globalThis as any).__regionHook, useRegionNeo: () => (globalThis as any).__neoHook,
})) }))
const ser = (address: any) => ({ const ser = (address: any) => ({
@ -47,24 +47,35 @@ const S3 = ser(A3) // NoRegion
function setRegionHook(overrides: Record<string, any> = {}) { function setRegionHook(overrides: Record<string, any> = {}) {
const state: any = { const state: any = {
region: null, regionId: 1,
regionId: null, boundId: 7,
boundId: null, regionName: 'Mahabubnagar',
bound: null, coords: { latitude: 16.7488, longitude: 77.9851 },
regionGeneration: 0, selectedAddressId: null,
hydrated: true, selectedAddress: null,
coords: null, fullAddress: null,
locationStatus: 'idle', isCache: false,
isResolvingRegion: false, changeRegion: jest.fn(),
setRegion: jest.fn(), selectAddress: jest.fn(),
clearRegion: jest.fn(),
refreshLocation: jest.fn(),
...overrides, ...overrides,
} }
;(globalThis as any).__regionHook = state ;(globalThis as any).__neoHook = state
return state return state
} }
function selector(selectedAddress: number | null, onAddressSelect = jest.fn()) {
setRegionHook({ selectedAddressId: selectedAddress, selectAddress: onAddressSelect })
return renderWithProviders(<CheckoutAddressSelector />, { auth: false })
}
function seedNeo(addresses: any[], selectedAddressId: number | null) {
useNeoRegionStore.setState({ addresses, selectedAddressId })
setRegionHook({
selectedAddressId,
selectedAddress: addresses.find((address) => address.id === selectedAddressId) ?? null,
})
}
function signIn() { function signIn() {
__setAuthState({ isAuthenticated: true, isLoading: false }) __setAuthState({ isAuthenticated: true, isLoading: false })
} }
@ -84,10 +95,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
it('CAS-01: the selected address is sorted first', async () => { it('CAS-01: the selected address is sorted first', async () => {
signIn() signIn()
setAddresses([S1, S2, S3]) setAddresses([S1, S2, S3])
const { getByTestId } = renderWithProviders( const { getByTestId } = selector(12, jest.fn())
<CheckoutAddressSelector selectedAddress={12} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2) await flush(2)
expect(within(getByTestId('address-option-0')).getByText('Work')).toBeTruthy() expect(within(getByTestId('address-option-0')).getByText('Work')).toBeTruthy()
}) })
@ -95,10 +103,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
it('CAS-02: the default address is sorted after the selected one', async () => { it('CAS-02: the default address is sorted after the selected one', async () => {
signIn() signIn()
setAddresses([S1, S2, S3]) setAddresses([S1, S2, S3])
const { getByTestId } = renderWithProviders( const { getByTestId } = selector(13, jest.fn())
<CheckoutAddressSelector selectedAddress={13} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2) await flush(2)
const optionOne = getByTestId('address-option-1') const optionOne = getByTestId('address-option-1')
expect(within(optionOne).getByText('Home')).toBeTruthy() expect(within(optionOne).getByText('Home')).toBeTruthy()
@ -111,60 +116,29 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
{ ...S1, isDefault: false }, { ...S1, isDefault: false },
{ ...S2, isDefault: false }, { ...S2, isDefault: false },
]) ])
const { getByTestId } = renderWithProviders( const { getByTestId } = selector(null, jest.fn())
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2) await flush(2)
expect(within(getByTestId('address-option-0')).getByText('Home')).toBeTruthy() expect(within(getByTestId('address-option-0')).getByText('Home')).toBeTruthy()
expect(within(getByTestId('address-option-1')).getByText('Work')).toBeTruthy() expect(within(getByTestId('address-option-1')).getByText('Work')).toBeTruthy()
expect(within(getByTestId('address-option-2')).getByText('NoRegion')).toBeTruthy() expect(within(getByTestId('address-option-2')).getByText('NoRegion')).toBeTruthy()
}) })
it('CAS-04: no selection auto-selects a default in the current region', async () => {
signIn()
setAddresses([S1, S2])
const onAddressSelect = jest.fn()
renderWithProviders(
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
{ auth: false }
)
await flush(2)
expect(onAddressSelect).toHaveBeenCalledWith(11)
})
it('CAS-05: a default in another region is never auto-selected', async () => { it('CAS-05: a default in another region is never auto-selected', async () => {
signIn() signIn()
setAddresses([S2, S3]) setAddresses([S2, S3])
const onAddressSelect = jest.fn() const onAddressSelect = jest.fn()
renderWithProviders( selector(null, onAddressSelect)
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
{ auth: false }
)
await flush(2) await flush(2)
expect(onAddressSelect).not.toHaveBeenCalled() expect(onAddressSelect).not.toHaveBeenCalled()
}) })
it('CAS-06: a default without a region is auto-selected', async () => {
signIn()
setAddresses([{ ...S1, regionId: null }])
const onAddressSelect = jest.fn()
renderWithProviders(
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
{ auth: false }
)
await flush(2)
expect(onAddressSelect).toHaveBeenCalledWith(11)
})
it('CAS-07: tapping an address in another region opens the confirm dialog', async () => { it('CAS-07: tapping an address in another region opens the confirm dialog', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
signIn() signIn()
setAddresses([S1, S2]) setAddresses([S1, S2])
const { getByTestId } = renderWithProviders( const { getByTestId } = selector(11, jest.fn())
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2) await flush(2)
fireEvent.press(getByTestId('address-option-1')) fireEvent.press(getByTestId('address-option-1'))
expect(alertSpy).toHaveBeenCalled() expect(alertSpy).toHaveBeenCalled()
@ -178,10 +152,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
useRegionStore.getState().setRegion(REGION_1, 7) useRegionStore.getState().setRegion(REGION_1, 7)
setAddresses([S1, S2]) setAddresses([S1, S2])
const onAddressSelect = jest.fn() const onAddressSelect = jest.fn()
const { getByTestId } = renderWithProviders( const { getByTestId } = selector(11, onAddressSelect)
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={onAddressSelect} />,
{ auth: false }
)
await flush(2) await flush(2)
fireEvent.press(getByTestId('address-option-1')) fireEvent.press(getByTestId('address-option-1'))
const buttons = alertSpy.mock.calls[0][2] as any[] const buttons = alertSpy.mock.calls[0][2] as any[]
@ -198,10 +169,8 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
signIn() signIn()
useRegionStore.getState().setRegion(REGION_1, 7) useRegionStore.getState().setRegion(REGION_1, 7)
setAddresses([S1, S2]) setAddresses([S1, S2])
const { getByTestId } = renderWithProviders( const selectAddress = jest.fn()
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />, const { getByTestId } = selector(11, selectAddress)
{ auth: false }
)
await flush(2) await flush(2)
fireEvent.press(getByTestId('address-option-1')) fireEvent.press(getByTestId('address-option-1'))
const buttons = alertSpy.mock.calls[0][2] as any[] const buttons = alertSpy.mock.calls[0][2] as any[]
@ -209,9 +178,9 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
await act(async () => { await act(async () => {
await confirm.onPress() await confirm.onPress()
}) })
// `confirmRegionSwitch` awaits the cart clear before navigating. // `selectAddress` performs the switch in the neo store before navigating.
await flush() await flush()
expect(useRegionStore.getState().selectedRegionId).toBe(2) expect(selectAddress).toHaveBeenCalledWith(12)
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home') expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
alertSpy.mockRestore() alertSpy.mockRestore()
}) })
@ -220,10 +189,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
signIn() signIn()
setAddresses([S1, { ...S2, id: 31, regionId: 99 }]) setAddresses([S1, { ...S2, id: 31, regionId: 99 }])
const { getByTestId } = renderWithProviders( const { getByTestId } = selector(11, jest.fn())
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2) await flush(2)
fireEvent.press(getByTestId('address-option-1')) fireEvent.press(getByTestId('address-option-1'))
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
@ -237,10 +203,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
signIn() signIn()
setAddresses([S1, S2]) setAddresses([S1, S2])
const onAddressSelect = jest.fn() const onAddressSelect = jest.fn()
const { getByTestId } = renderWithProviders( const { getByTestId } = selector(null, onAddressSelect)
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
{ auth: false }
)
await flush(2) await flush(2)
fireEvent.scroll(getByTestId('address-scroll'), { fireEvent.scroll(getByTestId('address-scroll'), {
@ -261,10 +224,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
it('CAS-12: one pagination dot per address reflects the scroll index', async () => { it('CAS-12: one pagination dot per address reflects the scroll index', async () => {
signIn() signIn()
setAddresses([S1, S2, S3]) setAddresses([S1, S2, S3])
const { getAllByTestId, getByTestId } = renderWithProviders( const { getAllByTestId, getByTestId } = selector(null, jest.fn())
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2) await flush(2)
expect(getAllByTestId(/address-dot-/)).toHaveLength(3) expect(getAllByTestId(/address-dot-/)).toHaveLength(3)
@ -283,10 +243,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
it('CAS-13: with no addresses the empty card offers adding one', async () => { it('CAS-13: with no addresses the empty card offers adding one', async () => {
signIn() signIn()
setAddresses([]) setAddresses([])
const { getByText, getByTestId } = renderWithProviders( const { getByText, getByTestId } = selector(null, jest.fn())
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2) await flush(2)
expect(getByText('No addresses found')).toBeTruthy() expect(getByText('No addresses found')).toBeTruthy()
expect(getByTestId('add-address-empty')).toBeTruthy() expect(getByTestId('add-address-empty')).toBeTruthy()
@ -296,10 +253,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
signIn() signIn()
setAddresses([{ ...S1, latitude: null, longitude: null }]) setAddresses([{ ...S1, latitude: null, longitude: null }])
configureLocation({ permission: 'granted' }) configureLocation({ permission: 'granted' })
const { getByTestId } = renderWithProviders( const { getByTestId } = selector(11, jest.fn())
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2) await flush(2)
expect(getByTestId('attach-location')).toBeTruthy() expect(getByTestId('attach-location')).toBeTruthy()
fireEvent.press(getByTestId('attach-location')) fireEvent.press(getByTestId('attach-location'))
@ -316,10 +270,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
signIn() signIn()
setAddresses([{ ...S1, latitude: null, longitude: null }]) setAddresses([{ ...S1, latitude: null, longitude: null }])
configureLocation({ permission: 'denied' }) configureLocation({ permission: 'denied' })
const { getByTestId } = renderWithProviders( const { getByTestId } = selector(11, jest.fn())
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2) await flush(2)
fireEvent.press(getByTestId('attach-location')) fireEvent.press(getByTestId('attach-location'))
await flush(2) await flush(2)
@ -336,10 +287,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
signIn() signIn()
setAddresses([{ ...S1, latitude: null, longitude: null }]) setAddresses([{ ...S1, latitude: null, longitude: null }])
configureLocation({ permission: 'granted', throwOnPosition: true }) configureLocation({ permission: 'granted', throwOnPosition: true })
const { getByTestId, getByText } = renderWithProviders( const { getByTestId, getByText } = selector(11, jest.fn())
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2) await flush(2)
fireEvent.press(getByTestId('attach-location')) fireEvent.press(getByTestId('attach-location'))
await flush(2) await flush(2)
@ -355,10 +303,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
signIn() signIn()
setAddresses([S1]) setAddresses([S1])
const onAddressSelect = jest.fn() const onAddressSelect = jest.fn()
const { getByTestId, UNSAFE_getByType, queryClient } = renderWithProviders( const { getByTestId, UNSAFE_getByType, queryClient } = selector(null, onAddressSelect)
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
{ auth: false }
)
await flush(2) await flush(2)
const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries') const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries')
fireEvent.press(getByTestId('add-new-address')) fireEvent.press(getByTestId('add-new-address'))
@ -374,46 +319,36 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
it('CAS-18: the display shows the selected address', async () => { it('CAS-18: the display shows the selected address', async () => {
signIn() signIn()
setAddresses([S1, S2, S3]) setAddresses([S1, S2, S3])
useAddressStore.getState().setSelectedAddressId(12) seedNeo([S1, S2, S3], 12)
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false }) const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2) await flush(2)
expect(getByText('Work')).toBeTruthy() expect(getByText('Work')).toBeTruthy()
}) })
it('CAS-19: the display falls back to the default address', async () => { it('CAS-19: the display never falls back to a default from another region', async () => {
signIn() signIn()
setAddresses([S1, S2, S3]) setAddresses([S1, S2, S3])
useAddressStore.getState().setSelectedAddressId(null) seedNeo([S1, S2, S3], null)
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false }) const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2) await flush(2)
expect(getByText('Home')).toBeTruthy() expect(getByText('No address selected')).toBeTruthy()
}) })
it('CAS-20: the display shows an empty state with no address', async () => { it('CAS-20: the display shows an empty state with no address', async () => {
signIn() signIn()
setAddresses([]) setAddresses([])
seedNeo([], null)
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false }) const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2) await flush(2)
expect(getByText('No address selected')).toBeTruthy() expect(getByText('No address selected')).toBeTruthy()
}) })
it('CAS-21: the display shows a loading state while addresses load', () => { it('CAS-22: the display does not query addresses when signed out', async () => {
signIn()
setProcedure('user.address.getUserAddresses', { mode: 'pending' })
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
expect(getByText('Loading address...')).toBeTruthy()
})
it('CAS-22: the display is query-disabled when signed out and does not crash', async () => {
__setAuthState({ isAuthenticated: false, isLoading: false }) __setAuthState({ isAuthenticated: false, isLoading: false })
// The real batch link schedules requests on a timer; drain one left over
// from the previous case and clear its record before asserting this render
// issued none.
await flush() await flush()
resetAllMocks() resetAllMocks()
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false }) const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2) await flush(2)
expect(getByText('No address selected')).toBeTruthy() expect(getByText('No address selected')).toBeTruthy()
expect(procedureQueryCalls('user.address.getUserAddresses')).toHaveLength(0)
}) })
}) })

View file

@ -11,11 +11,21 @@ import { StyleSheet, View } from 'react-native'
import { QueryClient } from '@tanstack/react-query' import { QueryClient } from '@tanstack/react-query'
import { fireEvent, waitFor } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import FloatingCartBar from '@/components/floating-cart-bar' import FloatingCartBar from '@/components/floating-cart-bar'
import { useCentralProductStore } from '@/src/store/centralProductStore'
import { renderWithProviders, seedBoot, flush } from '../helpers/test-utils' import { renderWithProviders, seedBoot, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { __set, __snapshot } from '../mocks/secure-store-mock' import { __set, __snapshot } from '../mocks/secure-store-mock'
import { CART_REG, CART_FLASH } from '../fixtures' import { CART_REG, CART_FLASH } from '../fixtures'
/** 10% capped ₹40 on Chicken Breast (sku 2). */
const CHICKEN_OFFER = {
couponId: 24,
couponCode: 'TARGET10',
discountPercent: '10',
flatDiscount: null,
maxValue: 40,
}
/** /**
* Same defaults as the shared harness client, except mutations use `gcTime: 0`: * Same defaults as the shared harness client, except mutations use `gcTime: 0`:
* React Query otherwise schedules a 5-minute GC timeout on unmount, which keeps * React Query otherwise schedules a 5-minute GC timeout on unmount, which keeps
@ -97,4 +107,32 @@ describe('FloatingCartBar', () => {
expect(getByText('No Items In Cart')).toBeTruthy() expect(getByText('No Items In Cart')).toBeTruthy()
expect(getByTestId('go-to-cart')).toBeTruthy() expect(getByTestId('go-to-cart')).toBeTruthy()
}) })
it('FCB-06: the expanded sheet points at the checkout coupon step', async () => {
__set('cart_items', CART_REG)
const { getByTestId, getByText } = await renderBar({ isExpanded: true })
expect(getByTestId('apply-coupons-hint')).toBeTruthy()
expect(getByText('Apply Coupons at checkout')).toBeTruthy()
})
it('FCB-07: a couponed line shows its price after the coupon, with the label', async () => {
__set('cart_items', CART_REG)
const { getByTestId, getByText } = await renderBar({ isExpanded: true })
useCentralProductStore.getState().setCouponOffers({ 2: [CHICKEN_OFFER] })
// Chicken qty 2 at ₹215 = ₹430; 10% capped ₹40 = ₹390.
await waitFor(() => expect(getByTestId('cart-item-coupon-price-1')).toBeTruthy())
expect(getByTestId('cart-item-coupon-price-1')).toHaveTextContent('₹390')
expect(getByText('With Coupon')).toBeTruthy()
})
it('FCB-08: a line with no coupon shows only its price', async () => {
__set('cart_items', CART_REG)
const { queryByTestId, queryByText } = await renderBar({ isExpanded: true })
expect(queryByTestId('cart-item-coupon-price-1')).toBeNull()
expect(queryByText('With Coupon')).toBeNull()
})
}) })

View file

@ -27,10 +27,11 @@ import LocationFallbackFlow from '@/src/components/location/LocationFallbackFlow
import AddressForm from '@/src/components/AddressForm' import AddressForm from '@/src/components/AddressForm'
import constants from '@/src/constants' import constants from '@/src/constants'
import { useRegionStore } from '@/src/store/regionStore' import { useRegionStore } from '@/src/store/regionStore'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import { useAddressStore } from '@/src/store/addressStore' import { useAddressStore } from '@/src/store/addressStore'
import { useLocationStore } from '@/src/store/locationStore' import { useLocationStore } from '@/src/store/locationStore'
import { renderWithProviders, flush, seedJsonCache } from '../helpers/test-utils' import { renderWithProviders, flush, seedJsonCache, seedSelectedAddress } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
setProcedure, setProcedure,
@ -431,7 +432,7 @@ describe('Location components (LOC)', () => {
it('LOC-20: the active address prefers the selection over the default (and is off at startup)', async () => { it('LOC-20: the active address prefers the selection over the default (and is off at startup)', async () => {
signIn() signIn()
setAddresses([S1, S2]) setAddresses([S1, S2])
useAddressStore.getState().setSelectedAddressId(12) seedSelectedAddress(12)
const first = renderWithProviders(<LocationFallbackFlow />, { auth: false }) const first = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2) await flush(2)
expect(within(first.getByTestId('location-address-12')).getByTestId('location-address-active')).toBeTruthy() expect(within(first.getByTestId('location-address-12')).getByTestId('location-address-active')).toBeTruthy()
@ -577,7 +578,7 @@ describe('Location components (LOC)', () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 }) setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn() signIn()
setAddresses([S1, S2]) setAddresses([S1, S2])
useAddressStore.getState().setSelectedAddressId(11) seedSelectedAddress(11)
const { getByTestId, getByText } = renderWithProviders(<LocationBar />, { auth: false }) const { getByTestId, getByText } = renderWithProviders(<LocationBar />, { auth: false })
await flush(2) await flush(2)
expect(getByText('Mahabubnagar')).toBeTruthy() expect(getByText('Mahabubnagar')).toBeTruthy()
@ -587,16 +588,12 @@ describe('Location components (LOC)', () => {
expect(getByText('Delivery Address')).toBeTruthy() expect(getByText('Delivery Address')).toBeTruthy()
}) })
it('LOC-31: LocationBar without a region shows "Choose your address"', () => {
const { getByText } = renderWithProviders(<LocationBar />, { auth: false })
expect(getByText('Choose your address')).toBeTruthy()
})
it('LOC-32: LocationBar prefers the selected address over the default', async () => { it('LOC-32: LocationBar prefers the selected address over the default', async () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 }) setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn() signIn()
setAddresses([S1, S2]) setAddresses([S1, S2])
useAddressStore.getState().setSelectedAddressId(12) seedSelectedAddress(12)
const { getByText } = renderWithProviders(<LocationBar />, { auth: false }) const { getByText } = renderWithProviders(<LocationBar />, { auth: false })
await flush(2) await flush(2)
expect(getByText('45 Office Street, Hyderabad')).toBeTruthy() expect(getByText('45 Office Street, Hyderabad')).toBeTruthy()
@ -616,7 +613,7 @@ describe('Location components (LOC)', () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 }) setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn() signIn()
setAddresses([S1, S2]) setAddresses([S1, S2])
useAddressStore.getState().setSelectedAddressId(11) seedSelectedAddress(11)
const { getByText } = renderWithProviders(<LocationBar />, { auth: false }) const { getByText } = renderWithProviders(<LocationBar />, { auth: false })
await flush(2) await flush(2)
@ -780,6 +777,7 @@ describe('Location components (LOC)', () => {
it('LOC-46: CartAddressGate enables the current-location option and shows the coordinates', () => { it('LOC-46: CartAddressGate enables the current-location option and shows the coordinates', () => {
useLocationStore.setState({ coords: { latitude: 17.1, longitude: 78.2 }, status: 'granted' }) useLocationStore.setState({ coords: { latitude: 17.1, longitude: 78.2 }, status: 'granted' })
useNeoRegionStore.setState({ coords: { latitude: 17.1, longitude: 78.2 } })
const { getByTestId, getByText } = renderWithProviders( const { getByTestId, getByText } = renderWithProviders(
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />, <CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
{ auth: false } { auth: false }
@ -788,37 +786,11 @@ describe('Location components (LOC)', () => {
expect(getByText('Use your current location (17.10000, 78.20000)')).toBeTruthy() expect(getByText('Use your current location (17.10000, 78.20000)')).toBeTruthy()
}) })
it('LOC-47: CartAddressGate disables the current-location option without coordinates', () => {
const { getByTestId, getByText } = renderWithProviders(
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
{ auth: false }
)
expect(getByTestId('cart-address-current')).toBeDisabled()
expect(getByText('Turn on location to use this option')).toBeTruthy()
})
it('LOC-48: CartAddressGate polls and takes a fix once the location turns usable', async () => {
jest.useFakeTimers()
configureLocation({ permission: 'granted' })
renderWithProviders(<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />, {
auth: false,
})
await act(async () => {
jest.advanceTimersByTime(3000)
await Promise.resolve()
})
await act(async () => {
await Promise.resolve()
})
await act(async () => {
await Promise.resolve()
})
expect(useLocationStore.getState().coords).not.toBeNull()
jest.useRealTimers()
})
it('LOC-49: the cart gate current-location mode prefills the device coordinates', async () => { it('LOC-49: the cart gate current-location mode prefills the device coordinates', async () => {
useLocationStore.setState({ coords: { latitude: 17.1, longitude: 78.2 }, status: 'granted' }) useLocationStore.setState({ coords: { latitude: 17.1, longitude: 78.2 }, status: 'granted' })
useNeoRegionStore.setState({ coords: { latitude: 17.1, longitude: 78.2 } })
const { getByTestId, UNSAFE_getByType } = renderWithProviders( const { getByTestId, UNSAFE_getByType } = renderWithProviders(
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />, <CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
{ auth: false } { auth: false }

View file

@ -0,0 +1,66 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* NeoAddressFlow (`tests/components/neo-address-flow.test.tsx`).
*
* Covers the notice area above the address choices: an out-of-area device fix,
* the permission notices, and the "nothing to say" case. The chooser itself is
* the real component; the add form and the inline login screen are stubbed
* because they have their own suites and would pull in the map / auth stack.
*/
import * as React from 'react'
import { resetAllMocks } from '../helpers/reset'
import { renderWithProviders } from '../helpers/test-utils'
import { useLocationStore } from '@/src/store/locationStore'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
jest.mock('@/src/components/location/neo/NeoAddressForm', () => ({
__esModule: true,
default: () => null,
}))
jest.mock('@/app/(auth)/login', () => ({
__esModule: true,
default: () => null,
}))
import NeoAddressFlow from '@/src/components/location/neo/NeoAddressFlow'
describe('NeoAddressFlow — location notices', () => {
beforeEach(() => resetAllMocks())
it('NEOFLOW-01: an out-of-area fix is explained above the address choices', () => {
useNeoRegionStore.setState({ deviceOutOfService: true })
const { getByTestId, getByText } = renderWithProviders(<NeoAddressFlow />, { auth: false })
expect(getByTestId('neo-location-notice')).toBeTruthy()
expect(getByText('Outside delivery area')).toBeTruthy()
expect(getByText(/outside our delivery area/)).toBeTruthy()
})
it('NEOFLOW-02: no out-of-area notice when the fix is serviceable', () => {
useNeoRegionStore.setState({ deviceOutOfService: false })
const { queryByText } = renderWithProviders(<NeoAddressFlow />, { auth: false })
expect(queryByText(/outside our delivery area/)).toBeNull()
})
it('NEOFLOW-03: the permission notice still shows when there is no region', () => {
useNeoRegionStore.setState({
regionId: null,
boundId: null,
regionName: null,
coords: null,
deviceOutOfService: false,
})
useLocationStore.setState({ status: 'denied' })
const { getByText } = renderWithProviders(<NeoAddressFlow />, { auth: false })
expect(getByText('Location access is off')).toBeTruthy()
expect(getByText(/Location access is not granted/)).toBeTruthy()
})
})

View file

@ -0,0 +1,96 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* LocationWrapperNeo's four render branches: loading, address flow,
* confirmation, children. The wrapper reads the store directly; only the
* bootstrap hook and the two flow screens are mocked.
*/
import * as React from 'react'
import { Text } from 'react-native'
import LocationWrapperNeo from '@/components/LocationWrapperNeo'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import { renderWithProviders } from '../helpers/test-utils'
jest.mock('@/src/hooks/useRegionNeo', () => ({
useNeoRegionBootstrap: () => undefined,
useRegionNeo: () => (globalThis as any).__neoHook,
}))
jest.mock('@/src/components/location/neo/NeoAddressFlow', () => {
const ReactLib = require('react')
const { View } = require('react-native')
return {
__esModule: true,
default: () => ReactLib.createElement(View, { testID: 'mock-neo-flow' }),
}
})
jest.mock('@/src/components/location/neo/NeoConfirmLocation', () => {
const ReactLib = require('react')
const { View } = require('react-native')
return {
__esModule: true,
default: () => ReactLib.createElement(View, { testID: 'mock-neo-confirm' }),
}
})
function readyStore(overrides: Record<string, any> = {}) {
useNeoRegionStore.setState({
regionId: 1,
boundId: 7,
regionName: 'Region A',
coords: { latitude: 16.7, longitude: 77.9 },
origin: 'manual',
regions: [],
addresses: [],
selectedAddressId: null,
needsAddressFormFlow: false,
needsAddressConfirmation: false,
...overrides,
})
}
function tree() {
return (
<LocationWrapperNeo>
<Text>children</Text>
</LocationWrapperNeo>
)
}
describe('LocationWrapperNeo', () => {
beforeEach(() => {
readyStore()
})
it('shows the loading screen until the store has a complete region', () => {
readyStore({ regionId: null, boundId: null, regionName: null, coords: null })
const { getByTestId } = renderWithProviders(tree())
expect(getByTestId('neo-location-loading')).toBeTruthy()
})
it('renders the address flow when needsAddressFormFlow is set', () => {
readyStore({ needsAddressFormFlow: true })
const { getByTestId } = renderWithProviders(tree())
expect(getByTestId('mock-neo-flow')).toBeTruthy()
})
it('renders the confirmation when needsAddressConfirmation is set', () => {
readyStore({ needsAddressConfirmation: true })
const { getByTestId } = renderWithProviders(tree())
expect(getByTestId('mock-neo-confirm')).toBeTruthy()
})
it('renders children once the store holds a region', () => {
const { getByText, queryByTestId } = renderWithProviders(tree())
expect(getByText('children')).toBeTruthy()
expect(queryByTestId('neo-location-loading')).toBeNull()
})
it('the address flow wins if both flags are somehow set', () => {
readyStore({ needsAddressFormFlow: true, needsAddressConfirmation: true })
const { getByTestId, queryByTestId } = renderWithProviders(tree())
expect(getByTestId('mock-neo-flow')).toBeTruthy()
expect(queryByTestId('mock-neo-confirm')).toBeNull()
})
})

View file

@ -0,0 +1,120 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Section 26 — ProductCard coupon price (PCARD-01..08).
*
* The card reads `couponOffers` from the central product store (written by the
* catalogue initializer when `user.coupon.getEligible` lands) and derives the
* coupon price from the price it actually shows — `price` on the regular card,
* `flashPrice` on the 1 Hr Delivery card. Nothing here is fetched by the card.
*
* Fixtures: Chicken Breast (sku 2) is ₹215, Paneer (sku 8) is ₹90 with a ₹75
* flash price, Mutton (sku 6) is out of stock.
*/
import * as React from 'react'
import { StyleSheet } from 'react-native'
import { waitFor } from '@testing-library/react-native'
import { theme } from 'common-ui'
import ProductCard from '@/components/ProductCard'
import { useCentralProductStore } from '@/src/store/centralProductStore'
import { renderWithProviders, seedBoot, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { P_CHICKEN, P_CUCUMBER, P_FLASH, P_OUT } from '../fixtures'
/** 10% capped ₹40 (sku 2): ₹215 → ₹194. */
const CHICKEN_OFFER = {
couponId: 24,
couponCode: 'TARGET10',
discountPercent: '10',
flatDiscount: null,
maxValue: 40,
}
/** 10% capped ₹20 (sku 8): ₹90 → ₹81, flash ₹75 → ₹68. */
const PANEER_OFFER = {
couponId: 31,
couponCode: 'FLASH10',
discountPercent: '10',
flatDiscount: null,
maxValue: 20,
}
async function renderCard(item: any, props: Record<string, any> = {}) {
seedBoot()
const utils = renderWithProviders(
<ProductCard item={item} itemWidth={180} {...props} />,
{ auth: false }
)
await flush(2)
return utils
}
const fontSizeOf = (node: any) => StyleSheet.flatten(node.props.style)?.fontSize
const colorOf = (node: any) => StyleSheet.flatten(node.props.style)?.color
describe('ProductCard coupon price', () => {
beforeEach(() => resetAllMocks())
it('PCARD-01: no coupon — no coupon row', async () => {
const { queryByTestId } = await renderCard(P_CHICKEN)
expect(queryByTestId('product-coupon-price-2')).toBeNull()
})
it('PCARD-02: a product coupon shows the discounted price with a "With Coupon" label', async () => {
useCentralProductStore.getState().setCouponOffers({ 2: [CHICKEN_OFFER] })
const { getByTestId, getByText } = await renderCard(P_CHICKEN)
await waitFor(() => expect(getByTestId('product-coupon-price-2')).toBeTruthy())
expect(getByTestId('product-coupon-price-2')).toHaveTextContent('₹194')
expect(getByText('With Coupon')).toBeTruthy()
})
it('PCARD-03: the listed price keeps its size, the coupon price matches the struck price', async () => {
useCentralProductStore.getState().setCouponOffers({ 2: [CHICKEN_OFFER] })
const { getByText } = await renderCard(P_CHICKEN)
// The coupon must not outshine the price: text-base stays text-base (16),
// the struck price is untouched (12), and the coupon price sits at 12 too.
expect(fontSizeOf(getByText('₹215'))).toBe(16)
expect(fontSizeOf(getByText('₹220'))).toBe(12)
expect(fontSizeOf(getByText('₹194'))).toBe(12)
})
it('PCARD-04: the coupon price is in the brand colour, the label stays muted', async () => {
useCentralProductStore.getState().setCouponOffers({ 2: [CHICKEN_OFFER] })
const { getByText } = await renderCard(P_CHICKEN)
expect(colorOf(getByText('₹194'))).toBe(theme.colors.brand500)
expect(colorOf(getByText('With Coupon'))).toBe(theme.colors.gray400)
})
it('PCARD-05: without a coupon the price is unchanged', async () => {
const { getByText } = await renderCard(P_CHICKEN)
expect(fontSizeOf(getByText('₹215'))).toBe(16)
expect(fontSizeOf(getByText('₹220'))).toBe(12)
})
it('PCARD-06: a coupon for another sku leaves this card alone', async () => {
useCentralProductStore.getState().setCouponOffers({ 2: [CHICKEN_OFFER] })
const { queryByTestId } = await renderCard(P_CUCUMBER)
expect(queryByTestId('product-coupon-price-5')).toBeNull()
})
it('PCARD-07: a flash card discounts the flash price it displays', async () => {
useCentralProductStore.getState().setCouponOffers({ 8: [PANEER_OFFER] })
const { getByTestId } = await renderCard(P_FLASH, { cartType: 'flash' })
await waitFor(() => expect(getByTestId('product-coupon-price-8')).toBeTruthy())
// ₹75 flash - 10% (capped ₹20) = ₹67.5 -> ₹68
expect(getByTestId('product-coupon-price-8')).toHaveTextContent('₹68')
})
it('PCARD-08: an out-of-stock card shows no coupon price', async () => {
useCentralProductStore.getState().setCouponOffers({ 6: [CHICKEN_OFFER] })
const { queryByTestId } = await renderCard(P_OUT)
expect(queryByTestId('product-coupon-price-6')).toBeNull()
})
})

View file

@ -13,7 +13,6 @@ import dayjs from 'dayjs'
import QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector' import QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector'
import { useRegionStore } from '@/src/store/regionStore' import { useRegionStore } from '@/src/store/regionStore'
import { useAddressStore } from '@/src/store/addressStore'
import { renderWithProviders, flush, seedJsonCache } from '../helpers/test-utils' import { renderWithProviders, flush, seedJsonCache } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
@ -25,8 +24,8 @@ import { router } from '../mocks/expo-router-mock'
import { A1, A2, A3, REGION_1, REGION_2, SLOTS, CART_REG, slotsCacheUrl } from '../fixtures' import { A1, A2, A3, REGION_1, REGION_2, SLOTS, CART_REG, slotsCacheUrl } from '../fixtures'
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
jest.mock('@/src/hooks/useRegion', () => ({ jest.mock('@/src/hooks/useRegionNeo', () => ({
useRegion: () => (globalThis as any).__regionHook, useRegionNeo: () => (globalThis as any).__neoHook,
})) }))
const ser = (address: any) => ({ const ser = (address: any) => ({
@ -42,21 +41,18 @@ const S3 = ser(A3) // NoRegion
function setRegionHook(overrides: Record<string, any> = {}) { function setRegionHook(overrides: Record<string, any> = {}) {
const state: any = { const state: any = {
region: null, regionId: 1,
regionId: null, boundId: 7,
boundId: null, regionName: 'Mahabubnagar',
bound: null, coords: { latitude: 16.7488, longitude: 77.9851 },
regionGeneration: 0, selectedAddressId: null,
hydrated: true, fullAddress: null,
coords: null, isCache: false,
locationStatus: 'idle', changeRegion: jest.fn(),
isResolvingRegion: false, selectAddress: jest.fn(),
setRegion: jest.fn(),
clearRegion: jest.fn(),
refreshLocation: jest.fn(),
...overrides, ...overrides,
} }
;(globalThis as any).__regionHook = state ;(globalThis as any).__neoHook = state
return state return state
} }
@ -96,9 +92,9 @@ describe('QuickDeliveryAddressSelector (SLOTQ)', () => {
it('SLOTQ-01: a foreign address warns, confirms the switch and clears the cart/home', async () => { it('SLOTQ-01: a foreign address warns, confirms the switch and clears the cart/home', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
useRegionStore.getState().setRegion(REGION_1, 7) useRegionStore.getState().setRegion(REGION_1, 7)
useAddressStore.getState().setSelectedAddressId(12)
__set('cart_items', CART_REG) __set('cart_items', CART_REG)
setup() setup()
;(globalThis as any).__neoHook.selectedAddressId = 12
const { getByTestId, getByText } = renderWithProviders(<QuickDeliveryAddressSelector />, { const { getByTestId, getByText } = renderWithProviders(<QuickDeliveryAddressSelector />, {
auth: false, auth: false,
}) })
@ -117,8 +113,7 @@ describe('QuickDeliveryAddressSelector (SLOTQ)', () => {
await switchButton.onPress() await switchButton.onPress()
}) })
expect(useRegionStore.getState().selectedRegionId).toBe(2) expect((globalThis as any).__neoHook.selectAddress).toHaveBeenCalledWith(12)
expect(__snapshot().cart_items).toBe('[]')
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home') expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
alertSpy.mockRestore() alertSpy.mockRestore()
}) })
@ -126,8 +121,8 @@ describe('QuickDeliveryAddressSelector (SLOTQ)', () => {
it('SLOTQ-02: an address in an unavailable region alerts instead of switching', async () => { it('SLOTQ-02: an address in an unavailable region alerts instead of switching', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
useRegionStore.getState().setRegion(REGION_1, 7) useRegionStore.getState().setRegion(REGION_1, 7)
useAddressStore.getState().setSelectedAddressId(31)
setup({ addresses: [S1, { ...S1, id: 31, regionId: 99 }] }) setup({ addresses: [S1, { ...S1, id: 31, regionId: 99 }] })
;(globalThis as any).__neoHook.selectedAddressId = 31
const { getByTestId } = renderWithProviders(<QuickDeliveryAddressSelector />, { const { getByTestId } = renderWithProviders(<QuickDeliveryAddressSelector />, {
auth: false, auth: false,
}) })

View file

@ -469,6 +469,22 @@ export const C6 = { id: 26, couponCode: 'USED', discountPercent: '10', maxValue:
export const C7 = { id: 27, couponCode: 'OTHERREGION', discountPercent: '10', maxValue: 30, minOrder: null, flatDiscount: null, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [], applicableUsers: [], isExclusive: false, firstOrderOnly: false, regionId: 2 } export const C7 = { id: 27, couponCode: 'OTHERREGION', discountPercent: '10', maxValue: 30, minOrder: null, flatDiscount: null, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [], applicableUsers: [], isExclusive: false, firstOrderOnly: false, regionId: 2 }
export const C8 = { id: 28, couponCode: 'FIRST', discountPercent: null, maxValue: null, minOrder: null, flatDiscount: 40, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [], applicableUsers: [], isExclusive: false, firstOrderOnly: true, regionId: 1 } export const C8 = { id: 28, couponCode: 'FIRST', discountPercent: null, maxValue: null, minOrder: null, flatDiscount: 40, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [], applicableUsers: [], isExclusive: false, firstOrderOnly: true, regionId: 1 }
/*
* Product-specific coupons for the catalogue (card + product detail). Kept out of
* `COUPONS` on purpose: that array is the default `getEligible` payload and the
* cart/checkout suites count and price against it.
*/
/** 10% capped ₹40 on Chicken Breast (sku 2): ₹215 -> ₹194. */
export const C_SKU2_PERCENT = C4
/** Flat ₹100 on the same sku — beats the percentage above. */
export const C_SKU2_FLAT = { id: 29, couponCode: 'SKU2FLAT', discountPercent: null, maxValue: null, minOrder: null, flatDiscount: 100, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [2], applicableUsers: [], exclusiveApply: false, isFirstOrderOnly: false, regionId: 1 }
/** Targeted coupon that also carries a cart minimum: the catalogue ignores minOrder. */
export const C_SKU2_MIN = { id: 30, couponCode: 'SKU2MIN1000', discountPercent: null, maxValue: null, minOrder: 1000, flatDiscount: 20, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [2], applicableUsers: [], exclusiveApply: false, isFirstOrderOnly: false, regionId: 1 }
/** 10% capped ₹20 on Paneer (sku 8): price 90 -> 81, flashPrice 75 -> 68. */
export const C_SKU8_FLASH = { id: 31, couponCode: 'FLASH10', discountPercent: '10', maxValue: 20, minOrder: null, flatDiscount: null, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [8], applicableUsers: [], exclusiveApply: false, isFirstOrderOnly: false, regionId: 1 }
/** First-order-only, product-specific. */
export const C_SKU2_FIRST = { id: 32, couponCode: 'SKU2FIRST', discountPercent: null, maxValue: null, minOrder: null, flatDiscount: 30, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [2], applicableUsers: [], exclusiveApply: false, isFirstOrderOnly: true, regionId: 1 }
export const COUPONS = [C1, C2, C3, C4, C5, C6, C7, C8] export const COUPONS = [C1, C2, C3, C4, C5, C6, C7, C8]
export const ELIGIBLE_COUPONS_RESPONSE = { data: COUPONS, isFirstOrder: true } export const ELIGIBLE_COUPONS_RESPONSE = { data: COUPONS, isFirstOrder: true }
export const MY_COUPONS_RESPONSE = { export const MY_COUPONS_RESPONSE = {

View file

@ -11,6 +11,7 @@ import { __reset as resetNotifications } from '../mocks/expo-notifications-mock'
import { __resetRouterMock } from '../mocks/expo-router-mock' import { __resetRouterMock } from '../mocks/expo-router-mock'
import { __resetAuthState } from '../mocks/auth-context' import { __resetAuthState } from '../mocks/auth-context'
import { REGIONS } from '../fixtures'
import { useAppStore } from '@/src/store/appStore' import { useAppStore } from '@/src/store/appStore'
import { useAddressStore } from '@/src/store/addressStore' import { useAddressStore } from '@/src/store/addressStore'
import { useCartStore } from '@/src/store/cartStore' import { useCartStore } from '@/src/store/cartStore'
@ -22,6 +23,7 @@ import { useCheckoutStore } from '@/src/store/checkoutStore'
import { useCentralProductStore } from '@/src/store/centralProductStore' import { useCentralProductStore } from '@/src/store/centralProductStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import { useRegionStore } from '@/src/store/regionStore' import { useRegionStore } from '@/src/store/regionStore'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import { useLocationStore } from '@/src/store/locationStore' import { useLocationStore } from '@/src/store/locationStore'
import { useSlotStore } from '@/components/stores/slotStore' import { useSlotStore } from '@/components/stores/slotStore'
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
@ -37,7 +39,15 @@ export function resetStores() {
useQuickDeliveryStore.setState({ isDrawerHidden: false, selectedSlotId: null }) useQuickDeliveryStore.setState({ isDrawerHidden: false, selectedSlotId: null })
useStoreHeaderStore.setState({ title: '' }) useStoreHeaderStore.setState({ title: '' })
useCheckoutStore.setState({ userNotes: '' }) useCheckoutStore.setState({ userNotes: '' })
useCentralProductStore.setState({ products: [], productsById: {}, refetchProducts: null }) useCentralProductStore.setState({
products: [],
productsById: {},
tags: [],
isLoading: true,
error: null,
couponOffers: {},
refetchProducts: null,
})
useCentralSlotStore.setState({ useCentralSlotStore.setState({
slots: [], slots: [],
productSlotsMap: {}, productSlotsMap: {},
@ -54,6 +64,21 @@ export function resetStores() {
// flip this back to false). // flip this back to false).
hydrated: true, hydrated: true,
}) })
// Most component tests mount a screen directly (no LocationWrapperNeo), so
// the store starts ready. No-region cases call clearNeoRegion() explicitly.
useNeoRegionStore.setState({
regionId: 1,
boundId: 7,
regionName: 'Mahabubnagar',
coords: { latitude: 16.7488, longitude: 77.9851 },
origin: 'manual',
regions: REGIONS as any,
addresses: [],
selectedAddressId: null,
needsAddressFormFlow: false,
needsAddressConfirmation: false,
deviceOutOfService: false,
})
useSlotStore.setState({ slotId: undefined, storeId: undefined }) useSlotStore.setState({ slotId: undefined, storeId: undefined })
useFlashNavigationStore.setState({ shouldNavigateToCart: false }) useFlashNavigationStore.setState({ shouldNavigateToCart: false })
useHomeTagStore.setState({ selectedTagId: null, expandedByTagId: {} }) useHomeTagStore.setState({ selectedTagId: null, expandedByTagId: {} })

View file

@ -17,6 +17,7 @@ import {
STORES_RESPONSE, STORES_RESPONSE,
STORE_DETAIL_1, STORE_DETAIL_1,
MERGED_PRODUCTS, MERGED_PRODUCTS,
TAGS,
AVAILABILITY, AVAILABILITY,
TEST_JWT, TEST_JWT,
availabilityCacheUrl, availabilityCacheUrl,
@ -25,11 +26,18 @@ import {
storeDetailCacheUrl, storeDetailCacheUrl,
storesCacheUrl, storesCacheUrl,
A1, A1,
A2,
A3,
REGION_1, REGION_1,
REGION_2,
} from '../fixtures' } from '../fixtures'
import { useCentralProductStore } from '@/src/store/centralProductStore' import {
useCentralProductStore,
useInitializeCentralProductStore,
} from '@/src/store/centralProductStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import { useRegionStore } from '@/src/store/regionStore' import { useRegionStore } from '@/src/store/regionStore'
import { bindNeoRegionQueryClient, useNeoRegionStore } from '@/src/store/neoRegionStore'
import { useAddressStore } from '@/src/store/addressStore' import { useAddressStore } from '@/src/store/addressStore'
export function createTestQueryClient(): QueryClient { export function createTestQueryClient(): QueryClient {
@ -62,10 +70,23 @@ export interface RenderOptions {
queryClient?: QueryClient queryClient?: QueryClient
auth?: AuthMode auth?: AuthMode
withRefresh?: boolean withRefresh?: boolean
/**
* Mount the real catalogue producer (`useInitializeCentralProductStore`) so
* the mocked products JSON flows into the central product store exactly like
* production. Catalogue screens read the store now, so the page suites that
* drive them through `setJsonResponse(productsCacheUrl(), …)` opt in here.
*/
withProductStore?: boolean
userId?: string userId?: string
token?: string token?: string
} }
/** Production's only catalogue reader: JSON -> central product store. */
function ProductStoreSync() {
useInitializeCentralProductStore()
return null
}
export function seedAuthStorage(mode: AuthMode, userId = '5', token = TEST_JWT) { export function seedAuthStorage(mode: AuthMode, userId = '5', token = TEST_JWT) {
if (mode === 'in') { if (mode === 'in') {
setSecureItem('authToken', token) setSecureItem('authToken', token)
@ -85,8 +106,10 @@ export function renderWithProviders(
options: RenderOptions = {} options: RenderOptions = {}
): RenderWithProvidersResult { ): RenderWithProvidersResult {
const queryClient = options.queryClient ?? createTestQueryClient() const queryClient = options.queryClient ?? createTestQueryClient()
bindNeoRegionQueryClient(queryClient)
const auth = options.auth ?? 'out' const auth = options.auth ?? 'out'
const withRefresh = options.withRefresh ?? true const withRefresh = options.withRefresh ?? true
const withProductStore = options.withProductStore ?? false
if (auth !== false) { if (auth !== false) {
// Synchronous seeding so AuthProvider's bootstrap effect reads the token. // Synchronous seeding so AuthProvider's bootstrap effect reads the token.
@ -95,6 +118,14 @@ export function renderWithProviders(
const Wrapper = ({ children }: { children: React.ReactNode }) => { const Wrapper = ({ children }: { children: React.ReactNode }) => {
let tree: React.ReactElement = React.createElement(React.Fragment, null, children) let tree: React.ReactElement = React.createElement(React.Fragment, null, children)
if (withProductStore) {
tree = React.createElement(
React.Fragment,
null,
React.createElement(ProductStoreSync),
tree
)
}
if (auth !== false) { if (auth !== false) {
tree = React.createElement(AuthProvider, null, tree) tree = React.createElement(AuthProvider, null, tree)
} }
@ -155,9 +186,14 @@ export function seedJsonCache(overrides: {
} }
/** Populate the central product/slot stores so `useGetCart` can enrich lines. */ /** Populate the central product/slot stores so `useGetCart` can enrich lines. */
export function seedCentralStores(options: { products?: any[]; slots?: any[] } = {}) { export function seedCentralStores(options: { products?: any[]; tags?: any[]; slots?: any[] } = {}) {
const products = options.products ?? MERGED_PRODUCTS const products = options.products ?? MERGED_PRODUCTS
useCentralProductStore.getState().setProducts(products) const productStore = useCentralProductStore.getState()
productStore.setProducts(products)
// Catalogue metadata travels with the products: screens select both from the
// store, so a seeded store must look like a loaded one.
productStore.setTags((options.tags ?? TAGS) as any)
productStore.setCatalogMeta({ isLoading: false, error: null })
useCentralSlotStore useCentralSlotStore
.getState() .getState()
.setSlotsData((options.slots ?? SLOTS) as any, PRODUCT_AVAILABILITY as any, AVAILABILITY as any) .setSlotsData((options.slots ?? SLOTS) as any, PRODUCT_AVAILABILITY as any, AVAILABILITY as any)
@ -166,18 +202,136 @@ export function seedCentralStores(options: { products?: any[]; slots?: any[] } =
/** Select a browsing region (+ bound) without going through the location flow. */ /** Select a browsing region (+ bound) without going through the location flow. */
export function seedRegion(region = REGION_1, boundId: number | null = 7) { export function seedRegion(region = REGION_1, boundId: number | null = 7) {
useRegionStore.getState().setRegion(region as any, boundId) useRegionStore.getState().setRegion(region as any, boundId)
const center = (region as any).center
seedNeoRegion({
regionId: region.id,
boundId: boundId ?? (region as any).effectiveBoundId ?? 7,
regionName: region.name,
coords: center ? { latitude: center.lat, longitude: center.lng } : undefined,
})
} }
export function seedSelectedAddress(addressId: number | null = A1.id) { export function seedSelectedAddress(addressId: number | null = A1.id) {
useAddressStore.getState().setSelectedAddressId(addressId) useAddressStore.getState().setSelectedAddressId(addressId)
useNeoRegionStore.setState({ selectedAddressId: addressId })
}
/** Clear the neo region for the tests that assert the no-region state. */
export function clearNeoRegion() {
useNeoRegionStore.setState({
regionId: null,
boundId: null,
regionName: null,
coords: null,
origin: null,
regions: [],
addresses: [],
selectedAddressId: null,
needsAddressFormFlow: false,
needsAddressConfirmation: false,
})
}
/** Seed the neo region store (the post-migration source of truth). */
export function seedNeoRegion(options: {
regionId?: number
boundId?: number
regionName?: string
coords?: { latitude: number; longitude: number }
addresses?: any[]
selectedAddressId?: number | null
} = {}) {
const regionId = options.regionId ?? REGION_1.id
useNeoRegionStore.setState({
regionId,
boundId: options.boundId ?? 7,
regionName: options.regionName ?? REGION_1.name,
coords: options.coords ?? { latitude: 16.7488, longitude: 77.9851 },
origin: 'manual',
regions: [REGION_1 as any, REGION_2 as any],
addresses: (options.addresses ?? []) as any,
selectedAddressId: options.selectedAddressId ?? null,
needsAddressFormFlow: false,
needsAddressConfirmation: false,
})
} }
/** Convenience: the usual home/cart boot state (region + catalogue + cache). */ /** Convenience: the usual home/cart boot state (region + catalogue + cache). */
const NEO_A2 = {
id: A2.id,
regionId: A2.regionId,
boundId: A2.boundId,
name: A2.name,
phone: A2.mobile,
addressLine1: A2.line1,
addressLine2: A2.line2,
city: A2.city,
state: A2.state,
isDefault: A2.isDefault,
latitude: A2.latitude,
longitude: A2.longitude,
googleMapsUrl: A2.googleMapsUrl,
}
const NEO_A3 = {
id: A3.id,
regionId: A3.regionId,
boundId: A3.boundId,
name: A3.name,
phone: A3.mobile,
addressLine1: A3.line1,
addressLine2: A3.line2,
city: A3.city,
state: A3.state,
isDefault: A3.isDefault,
latitude: A3.latitude,
longitude: A3.longitude,
googleMapsUrl: A3.googleMapsUrl,
}
const NEO_A1 = {
id: A1.id,
regionId: A1.regionId,
boundId: A1.boundId,
name: A1.name,
phone: A1.mobile,
addressLine1: A1.line1,
addressLine2: A1.line2,
city: A1.city,
state: A1.state,
isDefault: A1.isDefault,
latitude: A1.latitude,
longitude: A1.longitude,
googleMapsUrl: A1.googleMapsUrl,
}
export function seedBoot(options: { auth?: AuthMode; addressId?: number | null } = {}) { export function seedBoot(options: { auth?: AuthMode; addressId?: number | null } = {}) {
// Mirror the launch decision: a default address exists, so A1 is selected
// unless the caller explicitly asks for no address (addressId: null).
const selectedId = options.addressId === undefined ? A1.id : options.addressId
seedJsonCache() seedJsonCache()
seedCentralStores() seedCentralStores()
seedRegion() seedRegion()
seedSelectedAddress(options.addressId ?? null) seedSelectedAddress(selectedId)
// The post-migration components read the neo store; seed a ready region so no
// test renders them outside LocationWrapperNeo with an empty store.
seedNeoRegion({
addresses: [NEO_A1, NEO_A2, NEO_A3],
selectedAddressId: selectedId,
})
}
/**
* Simulate a cold start: nothing in the catalogue yet. Catalogue screens pick
* their loading/error copy from the store, so a first-load failure test needs an
* empty store — `seedBoot` seeds a *loaded* catalogue (that is what cart
* enrichment needs), and a failed background refresh keeps it on purpose.
*/
export function seedEmptyCatalogue() {
const store = useCentralProductStore.getState()
store.setProducts([])
store.setTags([])
store.setCatalogMeta({ isLoading: true, error: null })
} }
export function setConsoleErrorMock() { export function setConsoleErrorMock() {

View file

@ -68,7 +68,6 @@ module.exports = {
'^expo-router$': '<rootDir>/mocks/native/expo-router.tsx', '^expo-router$': '<rootDir>/mocks/native/expo-router.tsx',
'^expo-router/(.*)$': '<rootDir>/mocks/native/expo-router.tsx', '^expo-router/(.*)$': '<rootDir>/mocks/native/expo-router.tsx',
'^expo-image$': '<rootDir>/mocks/native/common.tsx', '^expo-image$': '<rootDir>/mocks/native/common.tsx',
'^expo-file-system$': '<rootDir>/mocks/native/common.tsx',
'^expo-linear-gradient$': '<rootDir>/mocks/native/common.tsx', '^expo-linear-gradient$': '<rootDir>/mocks/native/common.tsx',
'^expo-blur$': '<rootDir>/mocks/native/common.tsx', '^expo-blur$': '<rootDir>/mocks/native/common.tsx',
'^expo-status-bar$': '<rootDir>/mocks/native/common.tsx', '^expo-status-bar$': '<rootDir>/mocks/native/common.tsx',

View file

@ -0,0 +1,276 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* The launch decision as a table. Each case maps to one row of the
* docs/neo-region-refactor.md decision table.
*/
import { decideNeoRegion } from '@/src/lib/neo-region-decision'
import type { NeoAddress } from '@/src/lib/neo-address'
const CACHED_A = {
regionId: 1,
boundId: 7,
regionName: 'Region A',
coords: { latitude: 16.7, longitude: 77.9 },
}
const FIX_A = { latitude: 16.71, longitude: 77.91 }
const FIX_B = { latitude: 18.0, longitude: 79.0 }
const RESOLVED_A = { regionId: 1, boundId: 7 }
const RESOLVED_B = { regionId: 2, boundId: 8 }
function address(overrides: Partial<NeoAddress> = {}): NeoAddress {
return {
id: 11,
regionId: 1,
boundId: 7,
name: 'Home',
phone: '9876543210',
addressLine1: '12 Main Road',
addressLine2: null,
city: 'Mahabubnagar',
state: 'Telangana',
isDefault: true,
latitude: 16.7,
longitude: 77.9,
googleMapsUrl: null,
...overrides,
}
}
const A_IN_A = address()
const A_IN_B = address({
id: 12,
regionId: 2,
boundId: 8,
isDefault: false,
name: 'Work',
latitude: 18.0,
longitude: 79.0,
})
describe('decideNeoRegion', () => {
it('1. no cache, no fix, default address exists -> use the address', () => {
const decision = decideNeoRegion({
cached: null,
fix: null,
resolved: null,
isAuthenticated: true,
addresses: [A_IN_A],
})
expect(decision).toMatchObject({
action: 'ready',
regionId: 1,
boundId: 7,
origin: 'address',
selectedAddressId: 11,
})
})
it('2. no cache, no fix, no address -> address flow', () => {
const decision = decideNeoRegion({
cached: null,
fix: null,
resolved: null,
isAuthenticated: true,
addresses: [],
})
expect(decision).toEqual({ action: 'needs-address-flow' })
})
it('3. no cache, device in B, address in A -> address wins', () => {
const decision = decideNeoRegion({
cached: null,
fix: FIX_B,
resolved: RESOLVED_B,
isAuthenticated: true,
addresses: [A_IN_A],
})
expect(decision).toMatchObject({
action: 'ready',
regionId: 1,
origin: 'address',
selectedAddressId: 11,
})
})
it('4. no cache, device in B, no address -> use B', () => {
const decision = decideNeoRegion({
cached: null,
fix: FIX_B,
resolved: RESOLVED_B,
isAuthenticated: true,
addresses: [],
})
expect(decision).toMatchObject({
action: 'ready',
regionId: 2,
boundId: 8,
origin: 'device',
selectedAddressId: null,
coords: FIX_B,
})
})
it('5. cached A, no fix, address in A -> keep A with the address', () => {
const decision = decideNeoRegion({
cached: CACHED_A,
fix: null,
resolved: null,
isAuthenticated: true,
addresses: [A_IN_A],
})
expect(decision).toMatchObject({
action: 'ready',
regionId: 1,
origin: 'address',
selectedAddressId: 11,
})
})
it('6. cached A, no fix, no address -> keep the cached region', () => {
const decision = decideNeoRegion({
cached: CACHED_A,
fix: null,
resolved: null,
isAuthenticated: true,
addresses: [],
})
expect(decision).toMatchObject({
action: 'ready',
regionId: 1,
boundId: 7,
origin: 'cache',
selectedAddressId: null,
})
})
it('7. cached A, device in A, no address in A -> device keeps the region', () => {
const decision = decideNeoRegion({
cached: CACHED_A,
fix: FIX_A,
resolved: RESOLVED_A,
isAuthenticated: true,
addresses: [A_IN_B],
})
expect(decision).toMatchObject({
action: 'ready',
regionId: 1,
origin: 'device',
selectedAddressId: null,
})
})
it('8. cached A, device in B, address in B -> use that address', () => {
const decision = decideNeoRegion({
cached: CACHED_A,
fix: FIX_B,
resolved: RESOLVED_B,
isAuthenticated: true,
addresses: [A_IN_A, A_IN_B],
})
expect(decision).toMatchObject({
action: 'ready',
regionId: 2,
boundId: 8,
origin: 'address',
selectedAddressId: 12,
})
})
it('9. cached A, device in B, addresses only in A -> confirmation', () => {
const decision = decideNeoRegion({
cached: CACHED_A,
fix: FIX_B,
resolved: RESOLVED_B,
isAuthenticated: true,
addresses: [A_IN_A],
})
expect(decision).toEqual({
action: 'needs-confirmation',
regionId: 2,
boundId: 8,
})
})
it('10. cached A, device in B, no addresses -> go ahead with B', () => {
const decision = decideNeoRegion({
cached: CACHED_A,
fix: FIX_B,
resolved: RESOLVED_B,
isAuthenticated: true,
addresses: [],
})
expect(decision).toMatchObject({
action: 'ready',
regionId: 2,
origin: 'device',
selectedAddressId: null,
})
})
it('11. cached A, device in B, guest with address data -> go ahead with B', () => {
const decision = decideNeoRegion({
cached: CACHED_A,
fix: FIX_B,
resolved: RESOLVED_B,
isAuthenticated: false,
addresses: [A_IN_A],
})
expect(decision).toMatchObject({
action: 'ready',
regionId: 2,
origin: 'device',
selectedAddressId: null,
})
})
it('13. cached A keeps the persisted selection over the default', () => {
const office = address({ id: 14, isDefault: false, name: 'Office' })
const decision = decideNeoRegion({
cached: CACHED_A,
fix: null,
resolved: null,
isAuthenticated: true,
addresses: [A_IN_A, office],
selectedAddressId: 14,
})
expect(decision).toMatchObject({
action: 'ready',
regionId: 1,
origin: 'address',
selectedAddressId: 14,
})
})
it('14. a persisted selection outside the cached region is ignored', () => {
const decision = decideNeoRegion({
cached: CACHED_A,
fix: null,
resolved: null,
isAuthenticated: true,
addresses: [A_IN_A, A_IN_B],
selectedAddressId: A_IN_B.id,
})
expect(decision).toMatchObject({
action: 'ready',
regionId: 1,
selectedAddressId: A_IN_A.id,
})
})
it('12. cached A, device in A, address in A -> the address is selected', () => {
const decision = decideNeoRegion({
cached: CACHED_A,
fix: FIX_A,
resolved: RESOLVED_A,
isAuthenticated: true,
addresses: [A_IN_A],
})
expect(decision).toMatchObject({
action: 'ready',
regionId: 1,
origin: 'address',
selectedAddressId: 11,
})
})
})

View file

@ -0,0 +1,193 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Neo region store invariants: the selection always belongs to the active
* region, a region change clears it, and the two flow flags are exclusive.
*/
import type { RegionSummary } from '@packages/shared'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import type { NeoAddress } from '@/src/lib/neo-address'
const R1: RegionSummary = {
id: 1,
name: 'Region A',
description: null,
effectiveBoundId: 7,
center: { lat: 16.7, lng: 77.9 },
}
const R2: RegionSummary = {
id: 2,
name: 'Region B',
description: null,
effectiveBoundId: 8,
center: { lat: 18.0, lng: 79.0 },
}
function address(overrides: Partial<NeoAddress> = {}): NeoAddress {
return {
id: 12,
regionId: 2,
boundId: 8,
name: 'Work',
phone: '9876543211',
addressLine1: '45 Office Street',
addressLine2: null,
city: 'Hyderabad',
state: 'Telangana',
isDefault: false,
latitude: 18.1,
longitude: 79.1,
googleMapsUrl: null,
...overrides,
}
}
const A_IN_B = address()
function reset() {
useNeoRegionStore.setState({
regionId: null,
boundId: null,
regionName: null,
coords: null,
origin: null,
regions: [],
addresses: [],
selectedAddressId: null,
needsAddressFormFlow: false,
needsAddressConfirmation: false,
})
}
describe('neoRegionStore', () => {
beforeEach(reset)
it('applyRegion keeps a selection that belongs to the region', () => {
useNeoRegionStore.setState({ addresses: [A_IN_B], regions: [R2] })
useNeoRegionStore.getState().applyRegion({
regionId: 2,
boundId: 8,
regionName: 'Region B',
coords: { latitude: 18, longitude: 79 },
origin: 'device',
selectedAddressId: 12,
})
const state = useNeoRegionStore.getState()
expect(state.selectedAddressId).toBe(12)
expect(state.origin).toBe('address')
expect(state.boundId).toBe(8)
expect(state.coords).toEqual({ latitude: 18.1, longitude: 79.1 })
})
it('applyRegion drops a selection that belongs to another region', () => {
useNeoRegionStore.setState({ addresses: [A_IN_B], regions: [R1] })
useNeoRegionStore.getState().applyRegion({
regionId: 1,
boundId: 7,
regionName: 'Region A',
coords: { latitude: 16.7, longitude: 77.9 },
origin: 'device',
selectedAddressId: 12,
})
const state = useNeoRegionStore.getState()
expect(state.selectedAddressId).toBeNull()
expect(state.origin).toBe('device')
})
it('changeRegion switches without an address and clears the selection', async () => {
useNeoRegionStore.setState({
regionId: 1,
boundId: 7,
regionName: 'Region A',
coords: { latitude: 16.7, longitude: 77.9 },
regions: [R1, R2],
addresses: [A_IN_B],
selectedAddressId: 12,
})
await useNeoRegionStore.getState().changeRegion(2)
const state = useNeoRegionStore.getState()
expect(state.regionId).toBe(2)
expect(state.boundId).toBe(8)
expect(state.regionName).toBe('Region B')
expect(state.selectedAddressId).toBeNull()
expect(state.origin).toBe('manual')
})
it('selectAddress adopts the address region, bound and coords', async () => {
useNeoRegionStore.setState({
regionId: 1,
boundId: 7,
regionName: 'Region A',
coords: { latitude: 16.7, longitude: 77.9 },
regions: [R1, R2],
addresses: [A_IN_B],
})
await useNeoRegionStore.getState().selectAddress(12)
const state = useNeoRegionStore.getState()
expect(state.regionId).toBe(2)
expect(state.boundId).toBe(8)
expect(state.selectedAddressId).toBe(12)
expect(state.origin).toBe('address')
expect(state.coords).toEqual({ latitude: 18.1, longitude: 79.1 })
})
it('setAddresses clears a selection that vanished from the list', () => {
useNeoRegionStore.setState({
regionId: 2,
boundId: 8,
addresses: [A_IN_B],
selectedAddressId: 12,
})
useNeoRegionStore.getState().setAddresses([])
expect(useNeoRegionStore.getState().selectedAddressId).toBeNull()
})
it('setAddresses filters addresses without a region', () => {
useNeoRegionStore.getState().setAddresses([
A_IN_B,
address({ id: 13, regionId: null, boundId: null }),
])
expect(useNeoRegionStore.getState().addresses.map((item) => item.id)).toEqual([12])
})
it('logout clears addresses and selection but keeps the region', () => {
useNeoRegionStore.setState({
regionId: 2,
boundId: 8,
regionName: 'Region B',
coords: { latitude: 18, longitude: 79 },
addresses: [A_IN_B],
selectedAddressId: 12,
})
useNeoRegionStore.getState().resetForLogout()
const state = useNeoRegionStore.getState()
expect(state.regionId).toBe(2)
expect(state.addresses).toEqual([])
expect(state.selectedAddressId).toBeNull()
})
it('the two flow flags are mutually exclusive', () => {
useNeoRegionStore.getState().openAddressFlow()
expect(useNeoRegionStore.getState().needsAddressFormFlow).toBe(true)
expect(useNeoRegionStore.getState().needsAddressConfirmation).toBe(false)
useNeoRegionStore.getState().setNeedsConfirmation(true)
expect(useNeoRegionStore.getState().needsAddressConfirmation).toBe(true)
expect(useNeoRegionStore.getState().needsAddressFormFlow).toBe(false)
useNeoRegionStore.getState().setNeedsConfirmation(false)
expect(useNeoRegionStore.getState().needsAddressConfirmation).toBe(false)
})
})

View file

@ -0,0 +1,144 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue coupon pricing (`src/lib/product-coupons.ts`).
*
* The card and the product detail screen both read `couponOffers` from the
* central product store and turn them into a price with `couponPriceFor`. These
* cases pin the rules that decide *which* coupons are advertised at all and how
* the money is rounded, because the figure has to match what the cart charges.
*
* Fixtures (see tests/fixtures): Chicken Breast (sku 2) is ₹215, Paneer (sku 8)
* is ₹90 with a ₹75 flash price.
*/
import { buildCouponOffers, couponPriceFor } from '@/src/lib/product-coupons'
import {
C1,
C4,
C7,
C_SKU2_FIRST,
C_SKU2_FLAT,
C_SKU2_MIN,
C_SKU8_FLASH,
} from '../fixtures'
const priceOf = (offers: Record<number, any[]>, skuId: number, price: number) =>
couponPriceFor(offers[skuId], price)
describe('catalogue coupon pricing', () => {
it('COUPON-01: a product-specific coupon is mapped onto the sku it targets', () => {
const offers = buildCouponOffers([C4 as any], { regionId: 1, isFirstOrder: false })
expect(offers[2]).toHaveLength(1)
expect(offers[2][0]).toMatchObject({ couponId: 24, couponCode: 'TARGET10' })
expect(offers[5]).toBeUndefined()
})
it('COUPON-02: a cart-wide coupon (no skuIds) is not a product offer', () => {
const offers = buildCouponOffers([C1 as any], { regionId: 1, isFirstOrder: true })
expect(offers).toEqual({})
})
it('COUPON-03: a null skuIds list is treated as cart-wide, not as a target', () => {
const offers = buildCouponOffers(
[{ ...C4, skuIds: null } as any],
{ regionId: 1, isFirstOrder: true }
)
expect(offers).toEqual({})
})
it('COUPON-04: a coupon from another region is not advertised', () => {
expect(buildCouponOffers([{ ...C7, skuIds: [2] } as any], { regionId: 1, isFirstOrder: true })).toEqual({})
expect(buildCouponOffers([{ ...C7, skuIds: [2] } as any], { regionId: 2, isFirstOrder: true })[2]).toHaveLength(1)
})
it('COUPON-05: a coupon with no region applies in every region', () => {
const offers = buildCouponOffers(
[{ ...C4, regionId: null } as any],
{ regionId: 7, isFirstOrder: true }
)
expect(offers[2]).toHaveLength(1)
})
it('COUPON-06: first-order-only coupons are dropped once the customer has ordered', () => {
expect(buildCouponOffers([C_SKU2_FIRST as any], { regionId: 1, isFirstOrder: false })).toEqual({})
expect(buildCouponOffers([C_SKU2_FIRST as any], { regionId: 1, isFirstOrder: true })[2]).toHaveLength(1)
})
it('COUPON-07: an invalidated coupon is never advertised', () => {
const offers = buildCouponOffers(
[{ ...C4, isInvalidated: true } as any],
{ regionId: 1, isFirstOrder: true }
)
expect(offers).toEqual({})
})
it('COUPON-08: minOrder is ignored on the catalogue (it is a cart-level rule)', () => {
// C_SKU2_MIN needs a ₹1000 cart, but a single ₹215 item is still advertised.
const offers = buildCouponOffers([C_SKU2_MIN as any], { regionId: 1, isFirstOrder: true })
expect(offers[2]).toHaveLength(1)
expect(priceOf(offers, 2, 215)).toBe(195)
})
it('COUPON-09: every coupon targeting the same sku is kept for price comparison', () => {
const offers = buildCouponOffers(
[C4 as any, C_SKU2_FLAT as any],
{ regionId: 1, isFirstOrder: true }
)
expect(offers[2]).toHaveLength(2)
})
it('COUPON-10: a 10% coupon rounds to whole rupees, matching the cart', () => {
const offers = buildCouponOffers([C4 as any], { regionId: 1, isFirstOrder: true })
// 215 - min(21.5, 40) = 193.5 -> 194
expect(priceOf(offers, 2, 215)).toBe(194)
})
it('COUPON-11: the best of several coupons wins for the price shown', () => {
const offers = buildCouponOffers(
[C4 as any, C_SKU2_FLAT as any],
{ regionId: 1, isFirstOrder: true }
)
// ₹100 flat beats 10% of ₹215.
expect(priceOf(offers, 2, 215)).toBe(115)
})
it('COUPON-12: the same offer prices a flash item from its flash price', () => {
const offers = buildCouponOffers([C_SKU8_FLASH as any], { regionId: 1, isFirstOrder: true })
expect(priceOf(offers, 8, 90)).toBe(81)
// 75 - 7.5 = 67.5 -> 68
expect(priceOf(offers, 8, 75)).toBe(68)
})
it('COUPON-13: a missing or unknown price yields no coupon price', () => {
const offers = buildCouponOffers([C4 as any], { regionId: 1, isFirstOrder: true })
expect(couponPriceFor(offers[2], 0)).toBeNull()
expect(couponPriceFor(offers[2], null)).toBeNull()
expect(couponPriceFor(offers[2], undefined)).toBeNull()
expect(couponPriceFor(offers[2], 'not-a-number')).toBeNull()
})
it('COUPON-14: a coupon that discounts nothing yields no coupon price', () => {
const offers = buildCouponOffers(
[{ ...C4, discountPercent: '0', maxValue: null } as any],
{ regionId: 1, isFirstOrder: true }
)
expect(priceOf(offers, 2, 215)).toBeNull()
})
it('COUPON-15: an unknown sku has no offers', () => {
const offers = buildCouponOffers([C4 as any], { regionId: 1, isFirstOrder: true })
expect(couponPriceFor(offers[999], 215)).toBeNull()
})
})

View file

@ -12,11 +12,14 @@
import * as React from 'react' import * as React from 'react'
import { act, waitFor } from '@testing-library/react-native' import { act, waitFor } from '@testing-library/react-native'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import { import {
renderWithProviders, renderWithProviders,
flush, flush,
seedRegion, seedRegion,
seedNeoRegion,
seedSelectedAddress, seedSelectedAddress,
clearNeoRegion,
} from '../helpers/test-utils' } from '../helpers/test-utils'
import { import {
setJsonResponse, setJsonResponse,
@ -85,6 +88,7 @@ describe('prominent API hooks', () => {
resetAllMocks() resetAllMocks()
configureLocation({ permission: 'denied' }) configureLocation({ permission: 'denied' })
seedRegion(REGION_1 as any, 7) seedRegion(REGION_1 as any, 7)
seedNeoRegion({ regionId: REGION_1.id, boundId: 7 })
}) })
it('API-01: queries essential consts for the active bound and reads the threshold', async () => { it('API-01: queries essential consts for the active bound and reads the threshold', async () => {
@ -100,6 +104,7 @@ describe('prominent API hooks', () => {
it('API-02: a same-region selected address bound overrides the active bound', async () => { it('API-02: a same-region selected address bound overrides the active bound', async () => {
__setAuthState({ isAuthenticated: true, isLoading: false }) __setAuthState({ isAuthenticated: true, isLoading: false })
seedSelectedAddress(A1.id) seedSelectedAddress(A1.id)
useNeoRegionStore.setState({ selectedAddressId: A1.id })
setProcedure('user.address.getUserAddresses', { data: { data: [{ ...A1, boundId: 8 }] } }) setProcedure('user.address.getUserAddresses', { data: { data: [{ ...A1, boundId: 8 }] } })
const { element, result } = makeProbe(() => useGetEssentialConsts()) const { element, result } = makeProbe(() => useGetEssentialConsts())
@ -112,6 +117,7 @@ describe('prominent API hooks', () => {
it('API-03: a selected address in another region is ignored', async () => { it('API-03: a selected address in another region is ignored', async () => {
__setAuthState({ isAuthenticated: true, isLoading: false }) __setAuthState({ isAuthenticated: true, isLoading: false })
seedSelectedAddress(A2.id) seedSelectedAddress(A2.id)
useNeoRegionStore.setState({ selectedAddressId: A2.id })
const { element, result } = makeProbe(() => useGetEssentialConsts()) const { element, result } = makeProbe(() => useGetEssentialConsts())
renderWithProviders(element, { auth: false }) renderWithProviders(element, { auth: false })
@ -122,6 +128,7 @@ describe('prominent API hooks', () => {
}) })
it('API-04: with no region/bound the consts query stays disabled', async () => { it('API-04: with no region/bound the consts query stays disabled', async () => {
clearNeoRegion()
useRegionStore.getState().clearRegion() useRegionStore.getState().clearRegion()
const { element, result } = makeProbe(() => useGetEssentialConsts()) const { element, result } = makeProbe(() => useGetEssentialConsts())
@ -159,6 +166,7 @@ describe('prominent API hooks', () => {
setSecureItem('essential_consts_b7', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 111 })) setSecureItem('essential_consts_b7', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 111 }))
setSecureItem('essential_consts_b8', JSON.stringify({ ...CONSTS, boundId: 8, freeDeliveryThreshold: 222 })) setSecureItem('essential_consts_b8', JSON.stringify({ ...CONSTS, boundId: 8, freeDeliveryThreshold: 222 }))
seedRegion(REGION_1 as any, 8) seedRegion(REGION_1 as any, 8)
seedNeoRegion({ regionId: REGION_1.id, boundId: 8 })
const { element, result } = makeProbe(() => useGetEssentialConsts()) const { element, result } = makeProbe(() => useGetEssentialConsts())
renderWithProviders(element, { auth: false }) renderWithProviders(element, { auth: false })
@ -196,6 +204,7 @@ describe('prominent API hooks', () => {
JSON.stringify({ ...CONSTS, boundId: 7, freeDeliveryThreshold: 111 }) JSON.stringify({ ...CONSTS, boundId: 7, freeDeliveryThreshold: 111 })
) )
seedRegion(REGION_1 as any, 8) seedRegion(REGION_1 as any, 8)
seedNeoRegion({ regionId: REGION_1.id, boundId: 8 })
const { element, result } = makeProbe(() => useGetEssentialConsts()) const { element, result } = makeProbe(() => useGetEssentialConsts())
renderWithProviders(element, { auth: false }) renderWithProviders(element, { auth: false })
@ -369,7 +378,7 @@ describe('prominent API hooks', () => {
it('API-18: a region change produces a new CDN URL / query key', async () => { it('API-18: a region change produces a new CDN URL / query key', async () => {
setProcedure('common.essentialConsts', { setProcedure('common.essentialConsts', {
impl: () => { impl: () => {
const regionId = useRegionStore.getState().selectedRegionId ?? 1 const regionId = useNeoRegionStore.getState().regionId ?? 1
return { return {
...CONSTS, ...CONSTS,
regionId, regionId,
@ -397,7 +406,7 @@ describe('prominent API hooks', () => {
await waitFor(() => expect(jsonCallsFor(productsCacheUrl(1))).toHaveLength(1)) await waitFor(() => expect(jsonCallsFor(productsCacheUrl(1))).toHaveLength(1))
await act(async () => { await act(async () => {
useRegionStore.getState().setRegion(REGION_2 as any, 8) seedRegion(REGION_2 as any, 8)
}) })
await waitFor(() => expect(jsonCallsFor(productsCacheUrl(2))).toHaveLength(1)) await waitFor(() => expect(jsonCallsFor(productsCacheUrl(2))).toHaveLength(1))

View file

@ -196,6 +196,53 @@ describe('stores', () => {
expect(refetch).toHaveBeenCalledTimes(1) expect(refetch).toHaveBeenCalledTimes(1)
}) })
/*
* Catalogue coupons. The store holds the offers and stamps the two product
* fields the cards read, in whichever order the two legs of the boot land.
*/
const CHICKEN_OFFER = {
couponId: 24,
couponCode: 'TARGET10',
discountPercent: '10',
flatDiscount: null,
maxValue: 40,
}
it('STORE-13: coupon offers decorate a catalogue that arrives afterwards', () => {
useCentralProductStore.getState().setCouponOffers({ 2: [CHICKEN_OFFER] })
useCentralProductStore.getState().setProducts(MERGED_PRODUCTS as any)
const state = useCentralProductStore.getState()
// 215 - min(21.5, 40) = 193.5 -> 194
expect(state.productsById[2].isProductCouponApply).toBe(true)
expect(state.productsById[2].couponDiscountedPrice).toBe(194)
// Untouched products keep their identity and carry no coupon fields.
expect(state.productsById[5].isProductCouponApply).toBeUndefined()
})
it('STORE-14: a catalogue already in the store is decorated when the coupon call lands', () => {
useCentralProductStore.getState().setProducts(MERGED_PRODUCTS as any)
expect(useCentralProductStore.getState().productsById[2].isProductCouponApply).toBeUndefined()
useCentralProductStore.getState().setCouponOffers({ 2: [CHICKEN_OFFER] })
const state = useCentralProductStore.getState()
expect(state.productsById[2].isProductCouponApply).toBe(true)
expect(state.productsById[2].couponDiscountedPrice).toBe(194)
})
it('STORE-15: a catalogue refresh keeps the coupon price, clearing the offers drops it', () => {
useCentralProductStore.getState().setCouponOffers({ 2: [CHICKEN_OFFER] })
// products.json is refetched every minute; the fields must survive it.
useCentralProductStore.getState().setProducts(MERGED_PRODUCTS as any)
expect(useCentralProductStore.getState().productsById[2].couponDiscountedPrice).toBe(194)
useCentralProductStore.getState().setCouponOffers({})
expect(useCentralProductStore.getState().productsById[2].isProductCouponApply).toBeUndefined()
expect(useCentralProductStore.getState().productsById[2].couponDiscountedPrice).toBeUndefined()
})
it('STORE-12: centralSlotStore builds a slot map for every product with flags', () => { it('STORE-12: centralSlotStore builds a slot map for every product with flags', () => {
useCentralSlotStore.getState().setSlotsData(SLOTS as any, PRODUCT_AVAILABILITY as any, AVAILABILITY as any) useCentralSlotStore.getState().setSlotsData(SLOTS as any, PRODUCT_AVAILABILITY as any, AVAILABILITY as any)
const state = useCentralSlotStore.getState() const state = useCentralSlotStore.getState()

View file

@ -784,49 +784,6 @@ describe('useRegion', () => {
}) })
}) })
it('REGION-31: a live "no serviceable region" clears a region adopted from the cache', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, BOUND_1 } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: false, isLoading: false })
ctx.locationMock.__configure({ permission: 'granted' })
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1] })
ctx.trpc.setProcedure('common.resolveRegionByLocation', { data: null })
ctx.secure.__set(
ctx.regionCache.LOCATION_RESOLUTION_CACHE_KEY,
JSON.stringify({ lat: 17.00012, lng: 78.00034, result: { region: REGION_1, bound: BOUND_1 } })
)
// Hold the live resolve so the cached answer settles first.
const networkMock = (global as any).fetch
let releaseResolve!: () => void
const resolveGate = new Promise<void>((resolve) => {
releaseResolve = resolve
})
;(global as any).fetch = jest.fn(async (input: any, init: any) => {
const response = await networkMock(input, init)
if (String(input).includes('common.resolveRegionByLocation')) await resolveGate
return response
})
try {
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(5)
expect(result.current.regionId).toBe(1)
await ctx.rtl.act(async () => {
releaseResolve()
})
await ctx.testUtils.flush(8)
expect(result.current.regionId).toBeNull()
expect(result.current.isResolvingRegion).toBe(false)
view.unmount()
} finally {
;(global as any).fetch = networkMock
}
})
})
it('REGION-32: a persisted region/bound is hydrated before the launch decision', async () => { it('REGION-32: a persisted region/bound is hydrated before the launch decision', async () => {
await withFreshModules(async (ctx) => { await withFreshModules(async (ctx) => {
@ -880,177 +837,8 @@ describe('useRegion', () => {
describe('Home region integration (REGION-16..18)', () => { describe('Home region integration (REGION-16..18)', () => {
it('REGION-16: a default address and a location in its region open Home in that region', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, BOUND_1, A1, A2, productsCacheUrl } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.locationMock.__configure({ permission: 'granted' })
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
data: { region: REGION_1, bound: BOUND_1 },
})
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: A1 } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
ctx.testUtils.seedJsonCache({ regionId: 1 })
ctx.testUtils.seedJsonCache({ regionId: 2 })
ctx.testUtils.seedCentralStores()
ctx.testUtils.seedSelectedAddress(A1.id)
const Home = require('@/app/(drawer)/(tabs)/home/index').default
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
await ctx.testUtils.flush(8)
expect(ctx.regionStore.getState().selectedRegionId).toBe(1)
expect(ctx.regionStore.getState().selectedBoundId).toBe(7)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1)).length).toBeGreaterThan(0)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0)
expect(view.getByText('Mahabubnagar')).toBeTruthy()
view.unmount()
})
})
it('REGION-17: a location in another region clears the default region and opens the chooser', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, A1, A2, productsCacheUrl } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.locationMock.__configure({ permission: 'granted' })
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
data: {
region: REGION_2,
bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' },
},
})
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: A1 } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
ctx.testUtils.seedJsonCache({ regionId: 1 })
ctx.testUtils.seedJsonCache({ regionId: 2 })
ctx.testUtils.seedCentralStores()
const Home = require('@/app/(drawer)/(tabs)/home/index').default
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
await ctx.testUtils.flush(8)
expect(ctx.regionStore.getState().selectedRegionId).toBeNull()
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1))).toHaveLength(0)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0)
expect(view.getByText('Choose your address')).toBeTruthy()
view.unmount()
})
})
it('REGION-18: without a default address, the location alone opens its region', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, A1, A2, productsCacheUrl } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.locationMock.__configure({ permission: 'granted' })
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
data: {
region: REGION_2,
bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' },
},
})
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
ctx.trpc.setProcedure('common.essentialConsts', {
data: {
...ctx.fixtures.CONSTS,
regionId: 2,
boundId: 8,
// Published URLs must follow the payload's own region, exactly like the
// backend builds them.
essentialUrls: buildEssentialUrls({
assetsDomain: ctx.fixtures.CACHE_BASE,
apiCacheKey: ctx.fixtures.API_CACHE_KEY,
regionId: 2,
versions: {
products: ctx.fixtures.PRODUCTS_VERSION_NUM,
availability: ctx.fixtures.AVAILABILITY_VERSION_NUM,
slots: ctx.fixtures.SLOTS_VERSION_NUM,
},
}),
},
})
ctx.testUtils.seedJsonCache({ regionId: 1 })
ctx.testUtils.seedJsonCache({ regionId: 2 })
ctx.testUtils.seedCentralStores()
const Home = require('@/app/(drawer)/(tabs)/home/index').default
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
await ctx.testUtils.flush(8)
expect(ctx.regionStore.getState().selectedRegionId).toBe(2)
expect(ctx.regionStore.getState().selectedBoundId).toBe(8)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2)).length).toBeGreaterThan(0)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1))).toHaveLength(0)
expect(view.getByText('Hyderabad')).toBeTruthy()
view.unmount()
})
})
it('REGION-21: a sole non-default address opens Home with location off', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, A1, productsCacheUrl } = ctx.fixtures
const sole = { ...A1, isDefault: false }
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.locationMock.__configure({ permission: 'denied' })
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [sole] } })
ctx.testUtils.seedJsonCache({ regionId: 1 })
ctx.testUtils.seedJsonCache({ regionId: 2 })
ctx.testUtils.seedCentralStores()
const Home = require('@/app/(drawer)/(tabs)/home/index').default
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
await ctx.testUtils.flush(8)
expect(ctx.regionStore.getState().selectedRegionId).toBe(1)
expect(ctx.regionStore.getState().selectedBoundId).toBe(7)
expect(ctx.addressStore.getState().selectedAddressId).toBe(sole.id)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1)).length).toBeGreaterThan(0)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0)
expect(view.getByText('Mahabubnagar')).toBeTruthy()
view.unmount()
})
})
it('REGION-22: a sole non-default address opens Home even when location is elsewhere', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, A1, productsCacheUrl } = ctx.fixtures
const sole = { ...A1, isDefault: false }
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.locationMock.__configure({ permission: 'granted' })
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
data: {
region: REGION_2,
bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' },
},
})
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [sole] } })
ctx.testUtils.seedJsonCache({ regionId: 1 })
ctx.testUtils.seedJsonCache({ regionId: 2 })
ctx.testUtils.seedCentralStores()
const Home = require('@/app/(drawer)/(tabs)/home/index').default
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
await ctx.testUtils.flush(8)
expect(ctx.regionStore.getState().selectedRegionId).toBe(1)
expect(ctx.regionStore.getState().selectedBoundId).toBe(7)
expect(ctx.addressStore.getState().selectedAddressId).toBe(sole.id)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1)).length).toBeGreaterThan(0)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0)
expect(view.getByText('Mahabubnagar')).toBeTruthy()
view.unmount()
})
})
}) })

View file

@ -29,6 +29,7 @@ import constants from '@/src/constants'
import { useAddressStore } from '@/src/store/addressStore' import { useAddressStore } from '@/src/store/addressStore'
import { useCheckoutStore } from '@/src/store/checkoutStore' import { useCheckoutStore } from '@/src/store/checkoutStore'
import { useRegionStore } from '@/src/store/regionStore' import { useRegionStore } from '@/src/store/regionStore'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import { import {
renderWithProviders, renderWithProviders,
@ -265,17 +266,6 @@ describe('Cart (scheduled) — CART-01..110', () => {
expect(getByText('Loading cart...')).toBeTruthy() expect(getByText('Loading cart...')).toBeTruthy()
}) })
it('CART-07: pending slots in a flash cart do not gate on slots', async () => {
configureLocation({ permission: 'denied', position: null })
seedJsonCache()
seedCentralStores()
seedSelectedAddress(A1.id)
seedCart([line(1, 8, 1, 0)], FLASH_KEY)
setProcedure('user.cart.getCartSlots', { mode: 'pending' })
const { getByText, queryByText } = await enableRegionAfterMount(<FlashCart />)
expect(queryByText('Loading cart...')).toBeNull()
expect(getByText('1 Hr Delivery Cart')).toBeTruthy()
})
it('CART-08: a failing cart query shows "Failed to load your cart" with no retry', async () => { it('CART-08: a failing cart query shows "Failed to load your cart" with no retry', async () => {
seedBoot() seedBoot()
@ -286,15 +276,6 @@ describe('Cart (scheduled) — CART-01..110', () => {
expect(queryByText('Retry')).toBeNull() expect(queryByText('Retry')).toBeNull()
}) })
it('CART-09: pending addresses show "Loading..."', async () => {
seedBoot()
seedCart([line(1, 2, 2, 1849)])
setProcedure('user.address.getUserAddresses', { mode: 'pending' })
const { getByText, queryByTestId } = renderWithProviders(<Cart />, { auth: 'in' })
await flush(4)
expect(getByText('Loading...')).toBeTruthy()
expect(queryByTestId('login-wall')).toBeNull()
})
it('CART-10: no addresses show the CartAddressGate even when the cart is empty', async () => { it('CART-10: no addresses show the CartAddressGate even when the cart is empty', async () => {
seedBoot() seedBoot()
@ -1208,16 +1189,6 @@ describe('Cart (scheduled) — CART-01..110', () => {
expect(useAddressStore.getState().selectedAddressId).toBe(A1.id) expect(useAddressStore.getState().selectedAddressId).toBe(A1.id)
}) })
it('CART-90: a default address in another region is never auto-selected', async () => {
await mount({
lines: [],
setup: () =>
setProcedure('user.address.getUserAddresses', {
data: { data: [{ ...A2, isDefault: true }] },
}),
})
expect(useAddressStore.getState().selectedAddressId).toBeNull()
})
it('CART-91: tapping a cross-region address asks to confirm; Cancel changes nothing', async () => { it('CART-91: tapping a cross-region address asks to confirm; Cancel changes nothing', async () => {
const alertSpy = spyAlert() const alertSpy = spyAlert()
@ -1244,7 +1215,7 @@ describe('Cart (scheduled) — CART-01..110', () => {
}) })
fireEvent.press(getByTestId('address-option-1')) fireEvent.press(getByTestId('address-option-1'))
await tapAlert(alertSpy, 'Switch & clear cart') await tapAlert(alertSpy, 'Switch & clear cart')
expect(useRegionStore.getState().selectedRegionId).toBe(2) expect(useNeoRegionStore.getState().regionId).toBe(2)
expect(storedLines()).toEqual([]) expect(storedLines()).toEqual([])
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home') expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
alertSpy.mockRestore() alertSpy.mockRestore()
@ -1267,18 +1238,6 @@ describe('Cart (scheduled) — CART-01..110', () => {
alertSpy.mockRestore() alertSpy.mockRestore()
}) })
it('CART-94: adding an address opens the form; success auto-selects and invalidates', async () => {
const { getByTestId, UNSAFE_getByType, queryClient } = await mount({ lines: [] })
const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries')
fireEvent.press(getByTestId('add-new-address'))
await flush(2)
await act(async () => {
UNSAFE_getByType(AddressForm).props.onSuccess(55)
})
await flush(2)
expect(useAddressStore.getState().selectedAddressId).toBe(55)
expect(invalidateSpy).toHaveBeenCalled()
})
it('CART-95: attaching the current location updates the address with the coords', async () => { it('CART-95: attaching the current location updates the address with the coords', async () => {
const { getByTestId } = await mount({ const { getByTestId } = await mount({

View file

@ -254,12 +254,14 @@ describe('Checkout — CHECK-01..35', () => {
expect(first.getByTestId('checkout-address-name')).toHaveTextContent('Home') expect(first.getByTestId('checkout-address-name')).toHaveTextContent('Home')
first.unmount() first.unmount()
// The neo model has no read-time default fallback: no selection means no
// address card, even when the user has a saved default.
const second = await mount({ const second = await mount({
addressId: null, addressId: null,
lines: [line(1, 2, 2, 1849)], lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' }, params: { slots: '1849:1' },
}) })
expect(second.getByTestId('checkout-address-name')).toHaveTextContent('Home') expect(second.getByTestId('checkout-address-empty')).toBeTruthy()
second.unmount() second.unmount()
const third = await mount({ const third = await mount({
@ -270,14 +272,6 @@ describe('Checkout — CHECK-01..35', () => {
expect(third.getByTestId('checkout-address-empty')).toBeTruthy() expect(third.getByTestId('checkout-address-empty')).toBeTruthy()
}) })
it('CHECK-14: address loading shows "Loading address..."', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
setup: () => setProcedure('user.address.getUserAddresses', { mode: 'pending' }),
})
expect(getByTestId('checkout-address-loading')).toHaveTextContent('Loading address...')
})
it('CHECK-28: the flash checkout uses the flash price in items and totals', async () => { it('CHECK-28: the flash checkout uses the flash price in items and totals', async () => {
const { getByTestId } = await mount({ const { getByTestId } = await mount({

View file

@ -19,7 +19,7 @@ import { useFlashCartStore } from '@/src/store/flashCartStore'
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import { flush, renderWithProviders, seedBoot } from '../helpers/test-utils' import { flush, renderWithProviders, seedBoot, seedEmptyCatalogue } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
import { jsonCallsFor, setJsonError, setJsonPending, setJsonResponse } from '../mocks/fetch-json' import { jsonCallsFor, setJsonError, setJsonPending, setJsonResponse } from '../mocks/fetch-json'
@ -63,7 +63,7 @@ async function load() {
} }
function renderFlash(queryClient?: QueryClient) { function renderFlash(queryClient?: QueryClient) {
return renderWithProviders(<FlashDeliveryView />, { auth: false, queryClient }) return renderWithProviders(<FlashDeliveryView />, { auth: false, queryClient, withProductStore: true })
} }
type FlashView = ReturnType<typeof renderFlash> type FlashView = ReturnType<typeof renderFlash>
@ -106,6 +106,7 @@ describe('Flash products (FLASH)', () => {
}) })
it('FLASH-02: a failed request with no cache shows the flash failure state', async () => { it('FLASH-02: a failed request with no cache shows the flash failure state', async () => {
seedEmptyCatalogue()
setJsonError(productsCacheUrl(), new Error('offline')) setJsonError(productsCacheUrl(), new Error('offline'))
const { getByText } = renderFlash() const { getByText } = renderFlash()

View file

@ -35,7 +35,7 @@ import { useNavigationStore } from '@/src/store/navigationStore'
import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget' import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget'
import { StorageServiceCasual, tw } from 'common-ui' import { StorageServiceCasual, tw } from 'common-ui'
import { flush, renderWithProviders, seedBoot, seedSelectedAddress } from '../helpers/test-utils' import { flush, renderWithProviders, seedBoot, seedEmptyCatalogue, seedSelectedAddress } from '../helpers/test-utils'
import { buildEssentialUrls } from '@packages/shared' import { buildEssentialUrls } from '@packages/shared'
// The production list keeps only two pinned cells so the top sections can // The production list keeps only two pinned cells so the top sections can
@ -141,6 +141,7 @@ async function renderHome(options: { queryClient?: any } = {}) {
const utils = renderWithProviders(<Home />, { const utils = renderWithProviders(<Home />, {
auth: false, auth: false,
queryClient: createCartQueryClient(), queryClient: createCartQueryClient(),
withProductStore: true,
...options, ...options,
}) })
await flush(3) await flush(3)
@ -296,6 +297,7 @@ describe('Home (HOME)', () => {
}) })
it('HOME-02: a rejected products request shows the error state', async () => { it('HOME-02: a rejected products request shows the error state', async () => {
seedEmptyCatalogue()
setJsonError(productsCacheUrl(), new Error('offline')) setJsonError(productsCacheUrl(), new Error('offline'))
const { getByText } = await renderHome() const { getByText } = await renderHome()
@ -304,6 +306,7 @@ describe('Home (HOME)', () => {
}) })
it('HOME-03: a rejected consts request shows the settings error', async () => { it('HOME-03: a rejected consts request shows the settings error', async () => {
seedEmptyCatalogue()
setProcedure('common.essentialConsts', { mode: 'error', error: new Error('boom') }) setProcedure('common.essentialConsts', { mode: 'error', error: new Error('boom') })
const { getByText } = await renderHome() const { getByText } = await renderHome()
@ -928,65 +931,62 @@ describe('Home (HOME)', () => {
}) })
it('HOME-58: pull to refresh refetches products, slots and stores', async () => { it('HOME-58: pull to refresh refetches products, slots and stores', async () => {
const refetchProducts = jest.fn(async () => undefined)
const refetchSlots = jest.fn(async () => undefined) const refetchSlots = jest.fn(async () => undefined)
useCentralProductStore.setState({ refetchProducts })
useCentralSlotStore.setState({ refetchSlots }) useCentralSlotStore.setState({ refetchSlots })
await renderHome() await renderHome()
const productsBefore = jsonCallsFor(productsCacheUrl()).length
const storesBefore = jsonCallsFor(storesCacheUrl()).length const storesBefore = jsonCallsFor(storesCacheUrl()).length
await emitManualRefresh() await emitManualRefresh()
expect(refetchProducts).toHaveBeenCalled() // The refresh runs store -> products query -> the catalogue document.
expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(productsBefore)
expect(refetchSlots).toHaveBeenCalled() expect(refetchSlots).toHaveBeenCalled()
expect(jsonCallsFor(storesCacheUrl()).length).toBeGreaterThan(storesBefore) expect(jsonCallsFor(storesCacheUrl()).length).toBeGreaterThan(storesBefore)
}) })
it('HOME-59: a rejected refresh request still runs the rest and clears the spinner', async () => { it('HOME-59: a rejected refresh request still runs the rest and clears the spinner', async () => {
const refetchProducts = jest.fn(async () => undefined)
const refetchSlots = jest.fn(async () => undefined) const refetchSlots = jest.fn(async () => undefined)
useCentralProductStore.setState({ refetchProducts })
useCentralSlotStore.setState({ refetchSlots }) useCentralSlotStore.setState({ refetchSlots })
setJsonError(storesCacheUrl(), new Error('stores down')) setJsonError(storesCacheUrl(), new Error('stores down'))
const utils = await renderHome() const utils = await renderHome()
const productsBefore = jsonCallsFor(productsCacheUrl()).length
await emitManualRefresh() await emitManualRefresh()
expect(refetchProducts).toHaveBeenCalled() expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(productsBefore)
expect(refetchSlots).toHaveBeenCalled() expect(refetchSlots).toHaveBeenCalled()
const refreshControl = utils.UNSAFE_getByType(SectionList).props.refreshControl const refreshControl = utils.UNSAFE_getByType(SectionList).props.refreshControl
expect(refreshControl.props.refreshing).toBe(false) expect(refreshControl.props.refreshing).toBe(false)
}) })
it('HOME-60: a re-focus through useMarkDataFetchers runs the same refresh', async () => { it('HOME-60: a re-focus through useMarkDataFetchers runs the same refresh', async () => {
const refetchProducts = jest.fn(async () => undefined)
const refetchSlots = jest.fn(async () => undefined) const refetchSlots = jest.fn(async () => undefined)
useCentralProductStore.setState({ refetchProducts })
useCentralSlotStore.setState({ refetchSlots }) useCentralSlotStore.setState({ refetchSlots })
await renderHome() await renderHome()
const productsBefore = jsonCallsFor(productsCacheUrl()).length
const storesBefore = jsonCallsFor(storesCacheUrl()).length const storesBefore = jsonCallsFor(storesCacheUrl()).length
await emitFocus() await emitFocus()
await flush(2) await flush(2)
expect(refetchProducts).toHaveBeenCalled() expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(productsBefore)
expect(refetchSlots).toHaveBeenCalled() expect(refetchSlots).toHaveBeenCalled()
expect(jsonCallsFor(storesCacheUrl()).length).toBeGreaterThan(storesBefore) expect(jsonCallsFor(storesCacheUrl()).length).toBeGreaterThan(storesBefore)
}) })
it('HOME-61: refreshing while already refreshing does not corrupt the spinner', async () => { it('HOME-61: refreshing while already refreshing does not corrupt the spinner', async () => {
const refetchProducts = jest.fn(async () => undefined)
const refetchSlots = jest.fn(async () => undefined) const refetchSlots = jest.fn(async () => undefined)
useCentralProductStore.setState({ refetchProducts })
useCentralSlotStore.setState({ refetchSlots }) useCentralSlotStore.setState({ refetchSlots })
const utils = await renderHome() const utils = await renderHome()
const productsBefore = jsonCallsFor(productsCacheUrl()).length
await emitManualRefresh() await emitManualRefresh()
await emitManualRefresh() await emitManualRefresh()
const refreshControl = utils.UNSAFE_getByType(SectionList).props.refreshControl const refreshControl = utils.UNSAFE_getByType(SectionList).props.refreshControl
expect(refreshControl.props.refreshing).toBe(false) expect(refreshControl.props.refreshing).toBe(false)
expect(refetchProducts).toHaveBeenCalled() expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(productsBefore)
}) })
it('HOME-62: the location bar shows the region and active address and opens the switcher', async () => { it('HOME-62: the location bar shows the region and active address and opens the switcher', async () => {
@ -1407,12 +1407,15 @@ describe('Home (HOME)', () => {
it('HOME-96: a long product name is truncated in the bar', async () => { it('HOME-96: a long product name is truncated in the bar', async () => {
const longName = 'Super Extra Long Chicken Breast Family Pack' const longName = 'Super Extra Long Chicken Breast Family Pack'
__set('cart_items', CART_REG)
const { getByText } = await renderHome()
// Patch the catalogue AFTER mount: the page's producer overwrites the store
// from the products document on its first effect.
const current = useCentralProductStore.getState().productsById const current = useCentralProductStore.getState().productsById
useCentralProductStore.setState({ useCentralProductStore.setState({
productsById: { ...current, 2: { ...current[2], name: longName } }, productsById: { ...current, 2: { ...current[2], name: longName } },
}) })
__set('cart_items', CART_REG)
const { getByText } = await renderHome()
fireEvent.press(getByText(/1 Item/)) fireEvent.press(getByText(/1 Item/))
@ -1421,6 +1424,10 @@ describe('Home (HOME)', () => {
}) })
it('HOME-97: a combo product hides the unit suffix in the bar', async () => { it('HOME-97: a combo product hides the unit suffix in the bar', async () => {
__set('cart_items', cartLine(1, 2, 1, 1849))
const { getByText, queryByText } = await renderHome()
// Same as HOME-96: patch after the producer has seeded the store.
const current = useCentralProductStore.getState().productsById const current = useCentralProductStore.getState().productsById
useCentralProductStore.setState({ useCentralProductStore.setState({
productsById: { productsById: {
@ -1428,8 +1435,6 @@ describe('Home (HOME)', () => {
2: { ...current[2], name: 'Party Pack', unitNotation: '1 combo', productType: 'combo' }, 2: { ...current[2], name: 'Party Pack', unitNotation: '1 combo', productType: 'combo' },
}, },
}) })
__set('cart_items', cartLine(1, 2, 1, 1849))
const { getByText, queryByText } = await renderHome()
fireEvent.press(getByText(/1 Item/)) fireEvent.press(getByText(/1 Item/))

View file

@ -84,14 +84,6 @@ describe('Me hub (ME-01..ME-19)', () => {
expect(view.getByText(`Delivering in ${REGION_1.name}`)).toBeTruthy() expect(view.getByText(`Delivering in ${REGION_1.name}`)).toBeTruthy()
}) })
it('ME-03: without a region the Delivery Address subtitle asks to choose one', async () => {
// Signed out: `useRegion` has no default address to adopt, so the region
// stays unset.
const view = renderWithProviders(<Me />, { auth: 'out' })
await flush(2)
expect(view.getByText('Choose or add an address')).toBeTruthy()
})
it('ME-04: My Orders pushes the my-orders route', async () => { it('ME-04: My Orders pushes the my-orders route', async () => {
const view = await renderHub() const view = await renderHub()
@ -128,10 +120,10 @@ describe('Me hub (ME-01..ME-19)', () => {
it('ME-08: Delivery Address opens the address switcher sheet', async () => { it('ME-08: Delivery Address opens the address switcher sheet', async () => {
const view = await renderHub() const view = await renderHub()
expect(view.queryByTestId('location-add-address')).toBeNull() expect(view.queryByTestId('neo-add-address')).toBeNull()
fireEvent.press(view.getByTestId('me-menu-delivery-address')) fireEvent.press(view.getByTestId('me-menu-delivery-address'))
expect(view.getByTestId('location-add-address')).toBeTruthy() expect(view.getByTestId('neo-add-address')).toBeTruthy()
}) })
it('ME-09: Profile Settings and the settings icon both push edit-profile', async () => { it('ME-09: Profile Settings and the settings icon both push edit-profile', async () => {
@ -217,14 +209,14 @@ describe('Me hub (ME-01..ME-19)', () => {
expect(view.queryByTestId('location-bar')).toBeNull() expect(view.queryByTestId('location-bar')).toBeNull()
fireEvent.press(view.getByTestId('me-menu-delivery-address')) fireEvent.press(view.getByTestId('me-menu-delivery-address'))
expect(view.getByTestId('location-add-address')).toBeTruthy() expect(view.getByTestId('neo-add-address')).toBeTruthy()
}) })
it('ME-18: closing the address sheet dismisses it', async () => { it('ME-18: closing the address sheet dismisses it', async () => {
const view = await renderHub() const view = await renderHub()
fireEvent.press(view.getByTestId('me-menu-delivery-address')) fireEvent.press(view.getByTestId('me-menu-delivery-address'))
expect(view.getByTestId('location-add-address')).toBeTruthy() expect(view.getByTestId('neo-add-address')).toBeTruthy()
const modal = view.UNSAFE_getAllByType(Modal).find((candidate: any) => candidate.props.visible) const modal = view.UNSAFE_getAllByType(Modal).find((candidate: any) => candidate.props.visible)
expect(modal).toBeTruthy() expect(modal).toBeTruthy()
@ -232,7 +224,7 @@ describe('Me hub (ME-01..ME-19)', () => {
fireEvent(modal!, 'requestClose') fireEvent(modal!, 'requestClose')
}) })
expect(view.queryByTestId('location-add-address')).toBeNull() expect(view.queryByTestId('neo-add-address')).toBeNull()
}) })
it('ME-19: the footer shows the app version', async () => { it('ME-19: the footer shows the app version', async () => {

View file

@ -124,7 +124,7 @@ async function load() {
} }
function renderPage() { function renderPage() {
return renderWithProviders(<Offers />, { auth: false }) return renderWithProviders(<Offers />, { auth: false, withProductStore: true })
} }
describe('Offers / order again (OFFER)', () => { describe('Offers / order again (OFFER)', () => {

View file

@ -112,18 +112,6 @@ describe('PaymentAndOrder — PAY-01..29', () => {
expect(getByTestId('place-order-button')).toBeDisabled() expect(getByTestId('place-order-button')).toBeDisabled()
}) })
it('PAY-03: pressing with no region alerts "Please select a delivery region..."', async () => {
const alert = spyAlert()
const { getByTestId } = await mountPay({}, { noRegion: true })
fireEvent.press(getByTestId('place-order-button'))
await flush(1)
expect(alert).toHaveBeenCalledWith(
'Error',
'Please select a delivery region before placing an order'
)
expect(lastProcedureInput('user.order.placeOrder')).toBeUndefined()
})
it('PAY-04: no valid items alerts "No valid items to order"', async () => { it('PAY-04: no valid items alerts "No valid items to order"', async () => {
const alert = spyAlert() const alert = spyAlert()

View file

@ -13,7 +13,7 @@
* behaviour and say so in a comment. * behaviour and say so in a comment.
*/ */
import * as React from 'react' import * as React from 'react'
import { Alert, Image as RNImage, RefreshControl } from 'react-native' import { Alert, Image as RNImage, RefreshControl, StyleSheet } from 'react-native'
import { QueryClient } from '@tanstack/react-query' import { QueryClient } from '@tanstack/react-query'
import { fireEvent, waitFor } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import ProductDetail from '@/components/ProductDetail' import ProductDetail from '@/components/ProductDetail'
@ -21,6 +21,7 @@ import { useCartStore } from '@/src/store/cartStore'
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
import { useStoreHeaderStore } from '@/src/store/storeHeaderStore' import { useStoreHeaderStore } from '@/src/store/storeHeaderStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import { useCentralProductStore } from '@/src/store/centralProductStore'
import { renderWithProviders, seedBoot, flush } from '../helpers/test-utils' import { renderWithProviders, seedBoot, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
@ -44,6 +45,26 @@ import {
slotsResponse, slotsResponse,
} from '../fixtures' } from '../fixtures'
/** 10% capped ₹40 on Chicken Breast (sku 2): ₹215 -> ₹194. */
const CHICKEN_OFFER = {
couponId: 24,
couponCode: 'TARGET10',
discountPercent: '10',
flatDiscount: null,
maxValue: 40,
}
/** 10% capped ₹20 on Paneer (sku 8): flash ₹75 -> ₹68. */
const PANEER_OFFER = {
couponId: 31,
couponCode: 'FLASH10',
discountPercent: '10',
flatDiscount: null,
maxValue: 20,
}
const fontSizeOf = (node: any) => StyleSheet.flatten(node.props.style)?.fontSize
const HOUR = 60 * 60 * 1000 const HOUR = 60 * 60 * 1000
const iso = (offsetMs: number) => new Date(Date.now() + offsetMs).toISOString() const iso = (offsetMs: number) => new Date(Date.now() + offsetMs).toISOString()
@ -90,13 +111,6 @@ const cartLine = (id: number, skuId: number, quantity: number, slotId: number) =
describe('ProductDetail', () => { describe('ProductDetail', () => {
beforeEach(() => resetAllMocks()) beforeEach(() => resetAllMocks())
it('PD-01: with no region the loading copy shows and the product query never runs', async () => {
configureLocation({ permission: 'denied', position: null })
const { getByText } = await renderDetail('2')
expect(getByText('Loading product details...')).toBeTruthy()
expect(procedureQueryCalls('user.product.getProductDetails')).toHaveLength(0)
})
it('PD-02: a pending product query keeps the loading copy', async () => { it('PD-02: a pending product query keeps the loading copy', async () => {
seedBoot() seedBoot()
@ -627,4 +641,50 @@ describe('ProductDetail', () => {
const flash = await renderDetail('8', { isFlashDelivery: true }) const flash = await renderDetail('8', { isFlashDelivery: true })
expect(flash.getByText('No Flash Items')).toBeTruthy() expect(flash.getByText('No Flash Items')).toBeTruthy()
}) })
/*
* Catalogue coupons: the detail screen reads the offer from the central product
* store, so the figure matches the card the customer tapped.
*/
it('PD-52: a product coupon adds the coupon price under the price block', async () => {
seedDetail()
useCentralProductStore.getState().setCouponOffers({ 2: [CHICKEN_OFFER] })
const { getByTestId, getByText } = await renderDetail('2')
await waitFor(() => expect(getByTestId('product-coupon-price')).toBeTruthy())
// ₹215 - min(21.5, 40) = ₹193.5 -> ₹194
expect(getByTestId('product-coupon-price')).toHaveTextContent('₹194')
expect(getByText('With Coupon')).toBeTruthy()
// The price block stays the hero number (text-3xl); the coupon line is
// text-base, i.e. the struck price's size, and never outshines it.
expect(fontSizeOf(getByText('₹215'))).toBe(30)
expect(fontSizeOf(getByText('₹220'))).toBe(16)
expect(fontSizeOf(getByText('₹194'))).toBe(16)
})
it('PD-53: without a coupon there is no coupon line', async () => {
seedDetail()
const { queryByTestId } = await renderDetail('2')
expect(queryByTestId('product-coupon-price')).toBeNull()
})
it('PD-54: the flash detail prices the coupon off the flash price', async () => {
seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' })
useCentralProductStore.getState().setCouponOffers({ 8: [PANEER_OFFER] })
const { getByTestId } = await renderDetail('8', { isFlashDelivery: true })
await waitFor(() => expect(getByTestId('product-coupon-price')).toBeTruthy())
// ₹75 flash - 10% (capped ₹20) = ₹67.5 -> ₹68
expect(getByTestId('product-coupon-price')).toHaveTextContent('₹68')
})
it('PD-55: an out-of-stock product shows no coupon line', async () => {
seedDetail(P_OUT)
useCentralProductStore.getState().setCouponOffers({ 6: [CHICKEN_OFFER] })
const { queryByTestId } = await renderDetail('6')
expect(queryByTestId('product-coupon-price')).toBeNull()
})
}) })

View file

@ -18,7 +18,7 @@ import { act, fireEvent, waitFor } from '@testing-library/react-native'
import SearchResults from '@/app/(drawer)/(tabs)/home/search-results/index' import SearchResults from '@/app/(drawer)/(tabs)/home/search-results/index'
import { useCartStore } from '@/src/store/cartStore' import { useCartStore } from '@/src/store/cartStore'
import { flush, renderWithProviders, seedBoot } from '../helpers/test-utils' import { flush, renderWithProviders, seedBoot, seedEmptyCatalogue } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { router, __setParams } from '../mocks/expo-router-mock' import { router, __setParams } from '../mocks/expo-router-mock'
import { jsonCallsFor, setJsonError, setJsonPending } from '../mocks/fetch-json' import { jsonCallsFor, setJsonError, setJsonPending } from '../mocks/fetch-json'
@ -69,7 +69,7 @@ const ALL_NAMES = [
function renderPage(params: Record<string, any> = {}) { function renderPage(params: Record<string, any> = {}) {
__setParams(params) __setParams(params)
return renderWithProviders(<SearchResults />, { auth: false }) return renderWithProviders(<SearchResults />, { auth: false, withProductStore: true })
} }
/** /**
@ -243,6 +243,7 @@ describe('Search results (SEARCH)', () => {
}) })
it('SEARCH-14: a failed products request falls back to the empty state', async () => { it('SEARCH-14: a failed products request falls back to the empty state', async () => {
seedEmptyCatalogue()
setJsonError(productsCacheUrl(), new Error('offline')) setJsonError(productsCacheUrl(), new Error('offline'))
const { getByText } = renderPage() const { getByText } = renderPage()

View file

@ -67,7 +67,7 @@ async function load() {
} }
function renderPage() { function renderPage() {
return renderWithProviders(<StoreDetail />, { auth: false }) return renderWithProviders(<StoreDetail />, { auth: false, withProductStore: true })
} }
function seedDetail(detail: any) { function seedDetail(detail: any) {

View file

@ -2,13 +2,34 @@ import { useEffect } from 'react'
import { useAllProducts } from './prominent-api-hooks' import { useAllProducts } from './prominent-api-hooks'
import { useCentralProductStore } from '../lib/stores/central-product-store' import { useCentralProductStore } from '../lib/stores/central-product-store'
/**
* The only reader of the catalogue document. Every catalogue screen selects
* from the store afterwards, so a product field has one source across the app.
* Mounted by the pages that render a catalogue (web-ui has no root initializer).
*/
export function usePopulateCentralProductStore() { export function usePopulateCentralProductStore() {
const { data: productsData } = useAllProducts() const { data: productsData, refetch, isLoading, error } = useAllProducts()
const setProducts = useCentralProductStore((state) => state.setProducts) const setProducts = useCentralProductStore((state) => state.setProducts)
const setTags = useCentralProductStore((state) => state.setTags)
const setCatalogMeta = useCentralProductStore((state) => state.setCatalogMeta)
const setRefetchProducts = useCentralProductStore((state) => state.setRefetchProducts)
useEffect(() => { useEffect(() => {
// Undefined data (version bump in flight, failed refresh) keeps the previous
// catalogue on screen instead of blanking it.
if (productsData?.products) { if (productsData?.products) {
setProducts(productsData.products) setProducts(productsData.products)
setTags(productsData.tags ?? [])
} }
}, [productsData, setProducts]) }, [productsData, setProducts, setTags])
useEffect(() => {
setCatalogMeta({ isLoading, error: error ?? null })
}, [isLoading, error, setCatalogMeta])
useEffect(() => {
setRefetchProducts(async () => {
await refetch()
})
}, [refetch, setRefetchProducts])
} }

View file

@ -61,6 +61,7 @@ export async function confirmRegionSwitch(
// 3. Drop cached regional catalog/slot snapshots so they cannot leak across. // 3. Drop cached regional catalog/slot snapshots so they cannot leak across.
const productStore = useCentralProductStore.getState() const productStore = useCentralProductStore.getState()
productStore.setProducts([]) productStore.setProducts([])
productStore.setTags([])
productStore.setRefetchProducts(null) productStore.setRefetchProducts(null)
const slotStore = useCentralSlotStore.getState() const slotStore = useCentralSlotStore.getState()
slotStore.setSlots([]) slotStore.setSlots([])

View file

@ -1,16 +1,28 @@
import { create } from 'zustand' import { create } from 'zustand'
import type { CentralProductState as CentralProductsState } from '@packages/shared' import type { CentralProductState as CentralProductsState, ProductCouponOffer } from '@packages/shared'
import type { AllProductsApiType } from '@backend/trpc/router'
import type { MergedProduct } from '../../hooks/prominent-api-hooks' import type { MergedProduct } from '../../hooks/prominent-api-hooks'
// Central cache holds the API product (MergedProduct) — single product shape // Central cache holds the API product (MergedProduct) — single product shape
// across the app (numeric pricing, string images). // across the app (numeric pricing, string images).
type Product = MergedProduct type Product = MergedProduct
/** One dashboard tag strip; the catalogue payload's own tag shape. */
export type CatalogueTag = AllProductsApiType['tags'][number]
type CentralProductStore = CentralProductsState<Product> type CentralProductStore = CentralProductsState<Product, CatalogueTag>
export const useCentralProductStore = create<CentralProductStore>((set) => ({ export const useCentralProductStore = create<CentralProductStore>((set) => ({
products: [], products: [],
productsById: {}, productsById: {},
tags: [],
// Starts true so a cold start shows the loading copy instead of an empty
// catalogue; the populator mirrors the query's flags afterwards.
isLoading: true,
error: null,
// web-ui's cart/checkout cannot apply coupons, so this stays empty: no coupon
// price is ever shown here. The members exist because the store contract is
// shared with the native app.
couponOffers: {},
setProducts: (products) => { setProducts: (products) => {
const productsById: Record<number, Product> = {} const productsById: Record<number, Product> = {}
products.forEach((p) => { products.forEach((p) => {
@ -18,6 +30,14 @@ export const useCentralProductStore = create<CentralProductStore>((set) => ({
}) })
set({ products, productsById }) set({ products, productsById })
}, },
setTags: (tags) => set({ tags }),
setCatalogMeta: (meta) =>
set((state) => ({
isLoading: meta.isLoading ?? state.isLoading,
error: meta.error !== undefined ? meta.error : state.error,
})),
setCouponOffers: (couponOffers: Record<number, ProductCouponOffer[]>) =>
set({ couponOffers }),
refetchProducts: null, refetchProducts: null,
setRefetchProducts: (fn) => set({ refetchProducts: fn }), setRefetchProducts: (fn) => set({ refetchProducts: fn }),
})) }))

View file

@ -1,7 +1,7 @@
import { createFileRoute, useNavigate } from '@tanstack/react-router' import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { MiniQuantifier } from 'web-components' import { MiniQuantifier } from 'web-components'
import { useAllProducts, useStores } from '../hooks/prominent-api-hooks' import { useStores } from '../hooks/prominent-api-hooks'
import { useCentralProductStore } from '../lib/stores/central-product-store' import { useCentralProductStore } from '../lib/stores/central-product-store'
import { useCentralSlotStore } from '../lib/stores/central-slot-store' import { useCentralSlotStore } from '../lib/stores/central-slot-store'
import { useFlashTabStore } from '../lib/stores/flash-tab-store' import { useFlashTabStore } from '../lib/stores/flash-tab-store'
@ -279,9 +279,9 @@ function FlashDeliveryPage() {
usePopulateCentralStores() usePopulateCentralStores()
usePopulateCentralProductStore() usePopulateCentralProductStore()
const { data: productsData } = useAllProducts()
const { data: storesData } = useStores() const { data: storesData } = useStores()
const { productsById } = useCentralProductStore() const productsById = useCentralProductStore((state) => state.productsById)
const catalogueTags = useCentralProductStore((state) => state.tags)
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap) const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap)
const addToCart = useAddToCart('flash') const addToCart = useAddToCart('flash')
@ -299,7 +299,7 @@ function FlashDeliveryPage() {
productsByStoreId, productsByStoreId,
allFlashProducts, allFlashProducts,
} = useMemo(() => { } = useMemo(() => {
const tags = productsData?.tags || [] const tags = catalogueTags || []
const stores = storesData?.stores || [] const stores = storesData?.stores || []
const allFlashProducts = Object.values(productsById).filter( const allFlashProducts = Object.values(productsById).filter(
@ -345,7 +345,7 @@ function FlashDeliveryPage() {
productsByStoreId, productsByStoreId,
allFlashProducts, allFlashProducts,
} }
}, [productsData, storesData, productsById, productSlotsMap]) }, [catalogueTags, storesData, productsById, productSlotsMap])
// Stable so FlashProductItem memos survive a section re-render. // Stable so FlashProductItem memos survive a section re-render.
const handleAddToCart = useCallback( const handleAddToCart = useCallback(

View file

@ -2,7 +2,6 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useState, useEffect, useMemo, useRef } from 'react' import { useState, useEffect, useMemo, useRef } from 'react'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import { import {
useAllProducts,
useStores, useStores,
useBanners, useBanners,
useSlots, useSlots,
@ -16,6 +15,8 @@ import AddToCartDialog from '../components/AddToCartDialog'
import { useProductSlotIdentifier } from '../hooks/useProductSlotIdentifier' import { useProductSlotIdentifier } from '../hooks/useProductSlotIdentifier'
import { useHomeTagStore } from '../lib/stores/home-tag-store' import { useHomeTagStore } from '../lib/stores/home-tag-store'
import { usePopulateCentralStores } from '../hooks/usePopulateCentralStores' import { usePopulateCentralStores } from '../hooks/usePopulateCentralStores'
import { usePopulateCentralProductStore } from '../hooks/usePopulateCentralProductStore'
import { useCentralProductStore } from '../lib/stores/central-product-store'
import { Store, ImageOff, Loader2, Clock, Truck } from 'lucide-react' import { Store, ImageOff, Loader2, Clock, Truck } from 'lucide-react'
// Scroll Indicator Component // Scroll Indicator Component
@ -80,7 +81,9 @@ function SectionSpinner({ label }: { label?: string }) {
function HomePage() { function HomePage() {
const navigate = useNavigate() const navigate = useNavigate()
const { data: productsData, isLoading: isProductsLoading } = useAllProducts() const products = useCentralProductStore((state) => state.products)
const catalogueTags = useCentralProductStore((state) => state.tags)
const isProductsLoading = useCentralProductStore((state) => state.isLoading)
const { data: storesData, isLoading: isStoresLoading } = useStores() const { data: storesData, isLoading: isStoresLoading } = useStores()
const { data: bannersData } = useBanners() const { data: bannersData } = useBanners()
const { data: slotsData, isLoading: isSlotsLoading } = useSlots() const { data: slotsData, isLoading: isSlotsLoading } = useSlots()
@ -100,6 +103,8 @@ function HomePage() {
// Populate central stores with slots and product data // Populate central stores with slots and product data
usePopulateCentralStores() usePopulateCentralStores()
// The catalogue lands in the product store; this page only selects from it.
usePopulateCentralProductStore()
const stores = storesData?.stores || [] const stores = storesData?.stores || []
// const banners = bannersData?.banners || [] // const banners = bannersData?.banners || []
@ -108,8 +113,8 @@ function HomePage() {
// Single source of truth for the catalogue (mirrors user-ui home): the tags, // Single source of truth for the catalogue (mirrors user-ui home): the tags,
// the full product list and the per-tag rows all come out of one memo. // the full product list and the per-tag rows all come out of one memo.
const { dashboardTags, allProducts, productsByTagId } = useMemo(() => { const { dashboardTags, allProducts, productsByTagId } = useMemo(() => {
const dashboardTags = productsData?.tags || [] const dashboardTags = catalogueTags || []
const allProducts = productsData?.products || [] const allProducts = products || []
// Hoisted: the old version rebuilt this Map once per tag. // Hoisted: the old version rebuilt this Map once per tag.
const productById = new Map<number, any>() const productById = new Map<number, any>()
@ -143,7 +148,7 @@ function HomePage() {
} }
return { dashboardTags, allProducts, productsByTagId: map } return { dashboardTags, allProducts, productsByTagId: map }
}, [productsData, productSlotsMap, getQuickestSlot]) }, [catalogueTags, products, productSlotsMap, getQuickestSlot])
// Explore Products tabs — tags in tagsOrder, products in per-tag sortOrder. // Explore Products tabs — tags in tagsOrder, products in per-tag sortOrder.
// Selection/expansion live in the shared store (mirrors user-ui) so the state // Selection/expansion live in the shared store (mirrors user-ui) so the state

View file

@ -1,7 +1,8 @@
import { createFileRoute, useNavigate, useSearch } from '@tanstack/react-router' import { createFileRoute, useNavigate, useSearch } from '@tanstack/react-router'
import { useState, useEffect, useMemo, useRef, useCallback } from 'react' import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
import Fuse from 'fuse.js' import Fuse from 'fuse.js'
import { useAllProducts } from '../hooks/prominent-api-hooks' import { usePopulateCentralProductStore } from '../hooks/usePopulateCentralProductStore'
import { useCentralProductStore } from '../lib/stores/central-product-store'
import { SearchBar } from 'web-components' import { SearchBar } from 'web-components'
import { ProductCard } from '../components/ProductCard' import { ProductCard } from '../components/ProductCard'
import { SearchX, Loader2, ChevronLeft } from 'lucide-react' import { SearchX, Loader2, ChevronLeft } from 'lucide-react'
@ -34,6 +35,9 @@ function useDebounce<T>(value: T, delay: number): T {
} }
function SearchPage() { function SearchPage() {
// The catalogue lands in the product store; this page only selects from it.
usePopulateCentralProductStore()
const navigate = useNavigate() const navigate = useNavigate()
const { q } = useSearch({ from: '/home/search' }) const { q } = useSearch({ from: '/home/search' })
const [inputQuery, setInputQuery] = useState(q) const [inputQuery, setInputQuery] = useState(q)
@ -50,8 +54,10 @@ function SearchPage() {
}) })
}, []) }, [])
const { data: productsData, isLoading, error, refetch } = useAllProducts() const allProducts = useCentralProductStore((state) => state.products)
const allProducts = productsData?.products || [] const isLoading = useCentralProductStore((state) => state.isLoading)
const error = useCentralProductStore((state) => state.error)
const refetchProducts = useCentralProductStore((state) => state.refetchProducts)
// Client-side search filtering using Fuse.js // Client-side search filtering using Fuse.js
const products = useMemo(() => { const products = useMemo(() => {
@ -106,7 +112,7 @@ function SearchPage() {
<SearchX className="h-16 w-16 text-gray-300" /> <SearchX className="h-16 w-16 text-gray-300" />
<p className="mt-4 text-lg font-medium text-gray-900">Failed to load products</p> <p className="mt-4 text-lg font-medium text-gray-900">Failed to load products</p>
<button <button
onClick={() => refetch()} onClick={() => refetchProducts?.()}
className="mt-4 rounded-lg bg-brand-600 px-4 py-2 font-medium text-white transition-colors hover:bg-brand-700" className="mt-4 rounded-lg bg-brand-600 px-4 py-2 font-medium text-white transition-colors hover:bg-brand-700"
> >
Retry Retry

View file

@ -17,10 +17,15 @@ export const Route = createFileRoute('/location-selector')({
const parsed = Number(value) const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : undefined return Number.isFinite(parsed) ? parsed : undefined
} }
// `fixed=1` renders the pin read-only (the neo confirmation screen). The
// search parser may hand it back as a number, a string, or a boolean.
const flag = (value: unknown): boolean =>
value === true || value === 1 || value === '1' || value === 'true'
return { return {
lat: num(search.lat), lat: num(search.lat),
lng: num(search.lng), lng: num(search.lng),
zoom: num(search.zoom), zoom: num(search.zoom),
fixed: flag(search.fixed),
} }
}, },
component: LocationSelectorPage, component: LocationSelectorPage,
@ -188,6 +193,7 @@ function LocationSelectorPage() {
const [pendingCoords, setPendingCoords] = useState<LatLngLiteral | null>(null) const [pendingCoords, setPendingCoords] = useState<LatLngLiteral | null>(null)
const search = Route.useSearch() const search = Route.useSearch()
const isFixed = search.fixed === true
useEffect(() => { useEffect(() => {
if (!GOOGLE_MAPS_API_KEY) { if (!GOOGLE_MAPS_API_KEY) {
@ -224,36 +230,40 @@ function LocationSelectorPage() {
}) })
mapRef.current = map mapRef.current = map
// The pin is on the map from the start, at the map centre. Continue is // The pin is on the map from the start, at the map centre. In the normal
// disabled until the user touches it (tap anywhere on the map, tap the // mode Continue stays disabled until the user touches it (tap the map,
// pin, or drag the pin), which is what writes `pendingCoords`. // tap the pin, or drag the pin), which writes `pendingCoords`. In
// `fixed=1` mode the point is already decided: the pin cannot move and
// there is nothing to confirm.
const marker = new maps.Marker({ const marker = new maps.Marker({
map, map,
position: center, position: center,
draggable: true, draggable: !isFixed,
}) })
const chooseMarkerPosition = () => { if (!isFixed) {
const position = marker.getPosition() const chooseMarkerPosition = () => {
if (!position) return const position = marker.getPosition()
setPendingCoords({ lat: position.lat(), lng: position.lng() }) if (!position) return
setPendingCoords({ lat: position.lat(), lng: position.lng() })
}
// `dragstart` enables Continue as soon as the pin is grabbed; `dragend`
// stores the final position. A plain tap on the pin also selects it.
marker.addListener('dragstart', chooseMarkerPosition)
marker.addListener('dragend', chooseMarkerPosition)
marker.addListener('click', chooseMarkerPosition)
map.addListener('click', (event) => {
const latLng = event.latLng
if (!latLng) return
const coords = { lat: latLng.lat(), lng: latLng.lng() }
marker.setPosition(coords)
setPendingCoords(coords)
})
} }
// `dragstart` enables Continue as soon as the pin is grabbed; `dragend`
// stores the final position. A plain tap on the pin also selects it.
marker.addListener('dragstart', chooseMarkerPosition)
marker.addListener('dragend', chooseMarkerPosition)
marker.addListener('click', chooseMarkerPosition)
map.addListener('click', (event) => {
const latLng = event.latLng
if (!latLng) return
const coords = { lat: latLng.lat(), lng: latLng.lng() }
marker.setPosition(coords)
setPendingCoords(coords)
})
setIsLoading(false) setIsLoading(false)
}) })
.catch((error: unknown) => { .catch((error: unknown) => {
@ -265,7 +275,7 @@ function LocationSelectorPage() {
return () => { return () => {
cancelled = true cancelled = true
} }
}, []) }, [isFixed])
const handleConfirm = useCallback(() => { const handleConfirm = useCallback(() => {
if (!pendingCoords) return if (!pendingCoords) return
@ -327,7 +337,7 @@ function LocationSelectorPage() {
</div> </div>
)} )}
{!isLoading && !loadError && ( {!isLoading && !loadError && !isFixed && (
<div <div
className="absolute inset-x-0 bottom-0 z-10 border-t border-gray-100 bg-white px-4 pt-3 shadow-[0_-2px_10px_rgba(0,0,0,0.06)]" className="absolute inset-x-0 bottom-0 z-10 border-t border-gray-100 bg-white px-4 pt-3 shadow-[0_-2px_10px_rgba(0,0,0,0.06)]"
style={{ paddingBottom: 'max(1rem, env(safe-area-inset-bottom))' }} style={{ paddingBottom: 'max(1rem, env(safe-area-inset-bottom))' }}

Some files were not shown because too many files have changed in this diff Show more