Compare commits
6 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d528d164b4 | ||
|
|
9daf724075 | ||
|
|
92987a1c3f | ||
|
|
f5e5818e64 | ||
|
|
5e658c8d3a | ||
|
|
176e3eea9d |
68 changed files with 3249 additions and 666 deletions
6
apps/admin-ui/.expo/types/router.d.ts
vendored
6
apps/admin-ui/.expo/types/router.d.ts
vendored
File diff suppressed because one or more lines are too long
|
|
@ -895,6 +895,9 @@ Use these fixture names in the cases below.
|
|||
| AOD-23 | happy | Back to orders | 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-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
|
||||
|
||||
|
|
|
|||
|
|
@ -182,6 +182,17 @@ export default function OrderDetails() {
|
|||
Placed on {dayjs(order.createdAt).format("MMM DD, YYYY • h:mm A")}
|
||||
</MyText>
|
||||
</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>
|
||||
|
||||
{/* Cancellation Reason */}
|
||||
|
|
@ -403,6 +414,14 @@ export default function OrderDetails() {
|
|||
</MyText>
|
||||
</TouchableOpacity>
|
||||
</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>
|
||||
<MyText style={tw`text-sm font-bold text-gray-900`}>
|
||||
₹{item.amount}
|
||||
|
|
|
|||
|
|
@ -196,8 +196,7 @@ export default function EditProduct() {
|
|||
newImageUrls: allUploadUrls,
|
||||
} as any)
|
||||
|
||||
await refetch()
|
||||
await refetchProducts()
|
||||
await Promise.all([refetch(), refetchProducts()])
|
||||
Alert.alert('Success', 'Product updated successfully!')
|
||||
productFormRef.current?.clearImages()
|
||||
} catch (error: any) {
|
||||
|
|
@ -241,8 +240,7 @@ export default function EditProduct() {
|
|||
deletedImageKeys: [],
|
||||
newImageUrls: [],
|
||||
} as any)
|
||||
await refetch()
|
||||
await refetchProducts()
|
||||
await Promise.all([refetch(), refetchProducts()])
|
||||
Alert.alert('Success', 'Market data updated for your region')
|
||||
} catch (error: any) {
|
||||
Alert.alert('Error', error.message || 'Failed to update product')
|
||||
|
|
|
|||
|
|
@ -61,8 +61,10 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
|
|||
{ name, password },
|
||||
{
|
||||
onSuccess: async (data) => {
|
||||
await saveJWT(data.token);
|
||||
await saveStaff(data.staff);
|
||||
await Promise.all([
|
||||
saveJWT(data.token),
|
||||
saveStaff(data.staff),
|
||||
]);
|
||||
setStaff(data.staff);
|
||||
setIsLoggedIn(true);
|
||||
// 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 () => {
|
||||
await deleteJWT();
|
||||
await deleteStaff();
|
||||
await Promise.all([
|
||||
deleteJWT(),
|
||||
deleteStaff(),
|
||||
]);
|
||||
setIsLoggedIn(false);
|
||||
setStaff(null);
|
||||
queryClient.clear();
|
||||
|
|
|
|||
|
|
@ -10,6 +10,10 @@ import { CreateCouponPayload } from 'common-ui/shared-types';
|
|||
import { ADMIN_LIST_VIRTUALIZATION } from '@/src/lib/list-virtualization';
|
||||
|
||||
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 {
|
||||
isReservedCoupon?: boolean;
|
||||
|
|
@ -79,6 +83,9 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
|||
|
||||
// User dropdown states
|
||||
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 [allUsers, setAllUsers] = useState<{ id: number; name: string; mobile: string | null }[]>([]);
|
||||
const [hasMoreUsers, setHasMoreUsers] = useState(true);
|
||||
|
|
@ -88,8 +95,16 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
|||
const [multiDialogOpen, setMultiDialogOpen] = useState(false);
|
||||
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(
|
||||
{ search: userSearchQuery, limit: USERS_PAGE_SIZE, offset: userOffset },
|
||||
{ search: debouncedUserSearch, limit: USERS_PAGE_SIZE, offset: userOffset },
|
||||
{ enabled: usersDropdownOpen }
|
||||
);
|
||||
|
||||
|
|
@ -115,6 +130,7 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
|||
setAllUsers([]);
|
||||
setHasMoreUsers(true);
|
||||
setUserSearchQuery('');
|
||||
setDebouncedUserSearch('');
|
||||
}
|
||||
}, [usersDropdownOpen]);
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,27 @@ import { getJWT } from '@/hooks/useJWT';
|
|||
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs';
|
||||
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
|
||||
export const trpc = createTRPCReact<AppRouter>();
|
||||
|
||||
|
|
@ -16,11 +37,52 @@ export const trpcClient = createTRPCProxyClient<AppRouter>({
|
|||
url: BASE_API_URL+'/api/trpc',
|
||||
headers: async () => {
|
||||
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}` } : {};
|
||||
},
|
||||
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);
|
||||
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(() => ({}));
|
||||
let code = '';
|
||||
if(data[0]?.error || data?.error) {
|
||||
|
|
|
|||
|
|
@ -68,6 +68,15 @@ async function openUsersWith(
|
|||
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 = {
|
||||
couponCodes: ['SAVE10'],
|
||||
isUserBased: false,
|
||||
|
|
@ -280,11 +289,11 @@ describe('CouponForm (ACOUPF-01..24)', () => {
|
|||
view.getByPlaceholderText('Search users by name or mobile...'),
|
||||
'Test'
|
||||
)
|
||||
await flush(2)
|
||||
// The query is debounced, so seed the response before the timer fires.
|
||||
setProcedure('admin.coupon.getUsersMiniInfo', {
|
||||
data: { users: [{ id: 5, name: 'Test User', mobile: '9876543210' }], count: 1 },
|
||||
})
|
||||
await flush(2)
|
||||
await waitForUserSearchDebounce()
|
||||
|
||||
expect(lastProcedureInput('admin.coupon.getUsersMiniInfo')).toEqual({
|
||||
search: 'Test',
|
||||
|
|
@ -308,6 +317,26 @@ describe('CouponForm (ACOUPF-01..24)', () => {
|
|||
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 () => {
|
||||
setProcedure('admin.coupon.getUsersMiniInfo', {
|
||||
data: {
|
||||
|
|
|
|||
3
apps/admin-ui/tests/fixtures/index.ts
vendored
3
apps/admin-ui/tests/fixtures/index.ts
vendored
|
|
@ -312,10 +312,11 @@ export const ORDER_DETAILS = {
|
|||
adminNotes: null,
|
||||
userNotes: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
deliveredAt: null,
|
||||
status: 'pending',
|
||||
isPackaged: 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,
|
||||
cancellationReviewed: false,
|
||||
couponData: null,
|
||||
|
|
|
|||
|
|
@ -357,4 +357,40 @@ describe('Order details (AOD-01..25)', () => {
|
|||
expect(view.getByTestId('order-details-cancel-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()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -26,6 +26,10 @@ export interface CreateCouponPayload {
|
|||
}
|
||||
|
||||
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 {
|
||||
isReservedCoupon?: boolean
|
||||
|
|
@ -93,6 +97,9 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
|||
|
||||
// User dropdown states
|
||||
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 [allUsers, setAllUsers] = useState<{ id: number; name: string; mobile: string | null }[]>([])
|
||||
const [hasMoreUsers, setHasMoreUsers] = useState(true)
|
||||
|
|
@ -102,8 +109,16 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
|||
const [multiDialogOpen, setMultiDialogOpen] = useState(false)
|
||||
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(
|
||||
{ search: userSearchQuery, limit: USERS_PAGE_SIZE, offset: userOffset },
|
||||
{ search: debouncedUserSearch, limit: USERS_PAGE_SIZE, offset: userOffset },
|
||||
{ enabled: usersDropdownOpen }
|
||||
)
|
||||
|
||||
|
|
@ -129,6 +144,7 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
|||
setAllUsers([])
|
||||
setHasMoreUsers(true)
|
||||
setUserSearchQuery('')
|
||||
setDebouncedUserSearch('')
|
||||
}
|
||||
}, [usersDropdownOpen])
|
||||
|
||||
|
|
|
|||
|
|
@ -10,6 +10,25 @@ import { BASE_API_URL as DEFAULT_API_URL } from '@packages/shared'
|
|||
export const BASE_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 function getTrpcClient() {
|
||||
|
|
@ -19,11 +38,52 @@ export function getTrpcClient() {
|
|||
url: `${BASE_API_URL}/api/trpc`,
|
||||
headers: async () => {
|
||||
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}` } : {}
|
||||
},
|
||||
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)
|
||||
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(() => ({}))
|
||||
let code = ''
|
||||
if (data[0]?.error || data?.error) {
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
Zap,
|
||||
CircleAlert,
|
||||
Check,
|
||||
CheckCircle,
|
||||
Package,
|
||||
Truck,
|
||||
ChevronRight,
|
||||
|
|
@ -192,6 +193,17 @@ function OrderDetails() {
|
|||
Placed on {dayjs(order.createdAt).format('MMM DD, YYYY • h:mm A')}
|
||||
</MyText>
|
||||
</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>
|
||||
|
||||
{/* Cancellation Reason */}
|
||||
|
|
@ -391,6 +403,14 @@ function OrderDetails() {
|
|||
</MyText>
|
||||
</button>
|
||||
</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>
|
||||
<MyText className="text-sm font-bold text-gray-900">
|
||||
₹{item.amount}
|
||||
|
|
|
|||
|
|
@ -189,8 +189,7 @@ function EditProduct() {
|
|||
newImageUrls: allUploadUrls,
|
||||
} as any)
|
||||
|
||||
await refetch()
|
||||
await refetchProducts()
|
||||
await Promise.all([refetch(), refetchProducts()])
|
||||
window.alert('Product updated successfully!')
|
||||
productFormRef.current?.clearImages()
|
||||
} catch (error: any) {
|
||||
|
|
@ -233,8 +232,7 @@ function EditProduct() {
|
|||
deletedImageKeys: [],
|
||||
newImageUrls: [],
|
||||
} as any)
|
||||
await refetch()
|
||||
await refetchProducts()
|
||||
await Promise.all([refetch(), refetchProducts()])
|
||||
window.alert('Market data updated for your region')
|
||||
} catch (error: any) {
|
||||
window.alert(error.message || 'Failed to update product')
|
||||
|
|
|
|||
|
|
@ -1187,12 +1187,12 @@ Covered by UCOMP-01..11. Add admin-side cases in section 7.
|
|||
| AORD-10 | happy | updateNotes | stored |
|
||||
| AORD-11 | error | unknown | error |
|
||||
| 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-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-18 | happy | updateOrderItemPackaging | flags |
|
||||
| AORD-18 | happy | updateOrderItemPackaging | flags; packagedAt follows the Packaged toggle |
|
||||
| AORD-19 | error | unknown item | 404 |
|
||||
| AORD-20 | edge | only one flag supplied | other preserved |
|
||||
| AORD-21 | happy | removeDeliveryCharge | 0; user sees |
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -40,15 +40,20 @@ export async function initializeProducts(regionId: number): Promise<void> {
|
|||
try {
|
||||
console.log('Initializing product store in Redis...')
|
||||
|
||||
// Fetch all products with full details (similar to productMega logic)
|
||||
const productsData = await getAllProductsForCache(regionId)
|
||||
// All five cache slices are independent: fetch them together.
|
||||
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]))
|
||||
|
||||
// Fetch all delivery slots (excluding full capacity slots)
|
||||
const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
|
||||
const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
|
||||
for (const slot of allDeliverySlots) {
|
||||
if (!deliverySlotsMap.has(slot.skuId))
|
||||
|
|
@ -56,8 +61,7 @@ export async function initializeProducts(regionId: number): Promise<void> {
|
|||
deliverySlotsMap.get(slot.skuId)!.push(slot)
|
||||
}
|
||||
|
||||
// Fetch all special deals
|
||||
const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
|
||||
// Special deals by sku
|
||||
const specialDealsMap = new Map<number, SpecialDealData[]>()
|
||||
for (const deal of allSpecialDeals) {
|
||||
if (!specialDealsMap.has(deal.skuId))
|
||||
|
|
@ -65,8 +69,7 @@ export async function initializeProducts(regionId: number): Promise<void> {
|
|||
specialDealsMap.get(deal.skuId)!.push(deal)
|
||||
}
|
||||
|
||||
// Fetch all product tags
|
||||
const allProductTags = await getAllProductTagsForCache(regionId)
|
||||
// Tag names by product
|
||||
const productTagsMap = new Map<number, string[]>()
|
||||
for (const tag of allProductTags) {
|
||||
if (!productTagsMap.has(tag.productId))
|
||||
|
|
@ -158,12 +161,25 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
|
|||
//
|
||||
// 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 allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
|
||||
const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
|
||||
for (const slot of allDeliverySlots) {
|
||||
if (!deliverySlotsMap.has(slot.skuId))
|
||||
|
|
@ -171,7 +187,6 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
|
|||
deliverySlotsMap.get(slot.skuId)!.push(slot)
|
||||
}
|
||||
|
||||
const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
|
||||
const specialDealsMap = new Map<number, SpecialDealData[]>()
|
||||
for (const deal of allSpecialDeals) {
|
||||
if (!specialDealsMap.has(deal.skuId))
|
||||
|
|
@ -179,7 +194,6 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
|
|||
specialDealsMap.get(deal.skuId)!.push(deal)
|
||||
}
|
||||
|
||||
const allProductTags = await getAllProductTagsForCache(regionId)
|
||||
const productTagsMap = new Map<number, string[]>()
|
||||
for (const tag of allProductTags) {
|
||||
if (!productTagsMap.has(tag.productId))
|
||||
|
|
@ -188,7 +202,6 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
|
|||
}
|
||||
|
||||
const products: Product[] = []
|
||||
const allProductCombos = await getAllProductCombosForCache(regionId)
|
||||
const productCombosMap = new Map<number, ProductComboCacheData[]>()
|
||||
for (const comboItem of allProductCombos) {
|
||||
if (!productCombosMap.has(comboItem.comboSkuId))
|
||||
|
|
|
|||
|
|
@ -45,11 +45,11 @@ export async function initializeProductTagStore(regionId: number): Promise<void>
|
|||
try {
|
||||
console.log('Initializing product tag store in Redis...')
|
||||
|
||||
// Fetch all tags
|
||||
const tagsData = await getAllTagsForCache(regionId)
|
||||
|
||||
// Fetch product IDs for each tag
|
||||
const productTagsData = await getAllTagProductMappings(regionId)
|
||||
// The tags and their product mappings are independent reads.
|
||||
const [tagsData, productTagsData] = await Promise.all([
|
||||
getAllTagsForCache(regionId),
|
||||
getAllTagProductMappings(regionId),
|
||||
])
|
||||
|
||||
// Group product IDs by tag
|
||||
const productIdsByTag = new Map<number, number[]>()
|
||||
|
|
|
|||
|
|
@ -81,9 +81,17 @@ export async function getMultipleUserNegativityScores(
|
|||
//
|
||||
// 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> = {}
|
||||
for (const userId of userIds) {
|
||||
result[userId] = await getUserNegativityScoreFromDb(userId)
|
||||
for (const entry of entries) {
|
||||
result[entry.userId] = entry.score
|
||||
}
|
||||
return result
|
||||
} catch (error) {
|
||||
|
|
|
|||
|
|
@ -367,9 +367,11 @@ export const productRouter = router({
|
|||
skus: skuInputs,
|
||||
} as any, ctx.staffUser!.regionId)
|
||||
|
||||
await claimUploadUrls(allUploadUrls)
|
||||
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
// Both are post-write side effects and independent of each other.
|
||||
await Promise.all([
|
||||
claimUploadUrls(allUploadUrls),
|
||||
scheduleStoreInitialization(ctx.staffUser!.regionId),
|
||||
])
|
||||
|
||||
const productWithImageUrls = {
|
||||
...newProduct,
|
||||
|
|
@ -470,11 +472,12 @@ export const productRouter = router({
|
|||
throw new ApiError('Product not found', 404)
|
||||
}
|
||||
|
||||
if (uploadsToValidate.length > 0) {
|
||||
await claimUploadUrls(uploadsToValidate)
|
||||
}
|
||||
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
await Promise.all([
|
||||
uploadsToValidate.length > 0
|
||||
? claimUploadUrls(uploadsToValidate)
|
||||
: Promise.resolve(),
|
||||
scheduleStoreInitialization(ctx.staffUser!.regionId),
|
||||
])
|
||||
|
||||
const productWithImageUrls = {
|
||||
...updatedProduct,
|
||||
|
|
@ -712,9 +715,10 @@ export const productRouter = router({
|
|||
|
||||
await replaceTagProducts(ctx.staffUser!.regionId, createdTag.id, productIds)
|
||||
|
||||
await claimUploadUrls(uploadUrls)
|
||||
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
await Promise.all([
|
||||
claimUploadUrls(uploadUrls),
|
||||
scheduleStoreInitialization(ctx.staffUser!.regionId),
|
||||
])
|
||||
|
||||
const { products, ...createdTagInfo } = createdTag
|
||||
|
||||
|
|
@ -779,9 +783,10 @@ export const productRouter = router({
|
|||
await replaceTagProducts(ctx.staffUser!.regionId, id, productIds)
|
||||
}
|
||||
|
||||
await claimUploadUrls(uploadUrls)
|
||||
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
await Promise.all([
|
||||
claimUploadUrls(uploadUrls),
|
||||
scheduleStoreInitialization(ctx.staffUser!.regionId),
|
||||
])
|
||||
|
||||
const { products, ...updatedTagInfo } = updatedTag
|
||||
|
||||
|
|
|
|||
|
|
@ -51,9 +51,12 @@ export const userRouter = {
|
|||
// Get order stats for each user
|
||||
const userIds = usersToReturn.map((u: any) => u.id);
|
||||
|
||||
const orderCounts = await getOrderCountsByUserIds(ctx.staffUser!.regionId, userIds);
|
||||
const lastOrders = await getLastOrdersByUserIds(ctx.staffUser!.regionId, userIds);
|
||||
const suspensionStatuses = await getSuspensionStatusesByUserIds(ctx.staffUser!.regionId, userIds);
|
||||
// The three per-user stats are independent reads.
|
||||
const [orderCounts, lastOrders, suspensionStatuses] = await Promise.all([
|
||||
getOrderCountsByUserIds(ctx.staffUser!.regionId, userIds),
|
||||
getLastOrdersByUserIds(ctx.staffUser!.regionId, userIds),
|
||||
getSuspensionStatusesByUserIds(ctx.staffUser!.regionId, userIds),
|
||||
]);
|
||||
|
||||
// Create lookup maps
|
||||
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);
|
||||
}
|
||||
|
||||
// Get user suspension status
|
||||
const isSuspended = await getUserSuspensionStatus(userId);
|
||||
|
||||
// Get all orders for this user
|
||||
const userOrders = await getUserOrders(ctx.staffUser!.regionId, userId);
|
||||
// Suspension status and the order list are independent reads.
|
||||
const [isSuspended, userOrders] = await Promise.all([
|
||||
getUserSuspensionStatus(userId),
|
||||
getUserOrders(ctx.staffUser!.regionId, userId),
|
||||
]);
|
||||
|
||||
// Get order status for each order
|
||||
const orderIds = userOrders.map((o: any) => o.id);
|
||||
const orderStatuses = await getOrderStatusesByOrderIds(ctx.staffUser!.regionId, orderIds);
|
||||
|
||||
// Get item counts for each order
|
||||
const itemCounts = await getItemCountsByOrderIds(ctx.staffUser!.regionId, orderIds);
|
||||
// Order status and item counts both key off orderIds; run them together.
|
||||
const [orderStatuses, itemCounts] = await Promise.all([
|
||||
getOrderStatusesByOrderIds(ctx.staffUser!.regionId, orderIds),
|
||||
getItemCountsByOrderIds(ctx.staffUser!.regionId, orderIds),
|
||||
]);
|
||||
|
||||
// Create lookup maps
|
||||
const statusMap = new Map(orderStatuses.map(s => [s.orderId, s]));
|
||||
|
|
@ -163,10 +167,11 @@ export const userRouter = {
|
|||
.query(async ({ input, ctx }) => {
|
||||
const { search } = input;
|
||||
|
||||
const usersList = await searchUsers(ctx.staffUser!.regionId, search);
|
||||
|
||||
// Get eligible users (have notif_creds entry)
|
||||
const eligibleUsers = await getAllNotifCreds();
|
||||
// The user list and the notif_creds lookup are independent.
|
||||
const [usersList, eligibleUsers] = await Promise.all([
|
||||
searchUsers(ctx.staffUser!.regionId, search),
|
||||
getAllNotifCreds(),
|
||||
]);
|
||||
|
||||
const eligibleSet = new Set(eligibleUsers.map(u => u.userId));
|
||||
|
||||
|
|
@ -203,8 +208,10 @@ export const userRouter = {
|
|||
|
||||
if (userIds.length === 0) {
|
||||
// Send to all users - get tokens from both logged-in and unlogged users
|
||||
const loggedInTokens = await getAllNotifCreds();
|
||||
const unloggedTokens = await getAllUnloggedTokens();
|
||||
const [loggedInTokens, unloggedTokens] = await Promise.all([
|
||||
getAllNotifCreds(),
|
||||
getAllUnloggedTokens(),
|
||||
]);
|
||||
|
||||
tokens = [
|
||||
...loggedInTokens.map(t => t.token),
|
||||
|
|
|
|||
|
|
@ -450,8 +450,10 @@ export const orderRouter = router({
|
|||
const userId = ctx.user.userId;
|
||||
const offset = (page - 1) * pageSize;
|
||||
|
||||
const totalCount = await getUserOrderCount(userId);
|
||||
const userOrders = await getUserOrdersWithRelations(userId, offset, pageSize);
|
||||
const [totalCount, userOrders] = await Promise.all([
|
||||
getUserOrderCount(userId),
|
||||
getUserOrdersWithRelations(userId, offset, pageSize),
|
||||
]);
|
||||
|
||||
const mappedOrders = await Promise.all(
|
||||
userOrders.map(async (order) => {
|
||||
|
|
|
|||
|
|
@ -327,6 +327,9 @@ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => {
|
|||
const fx = await createCatalogOrderFixture({ price: 100 })
|
||||
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({
|
||||
orderId: String(orderId),
|
||||
isPackaged: true,
|
||||
|
|
@ -336,9 +339,17 @@ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => {
|
|||
expect(afterPacked.deliveryStatus).toBe('packaged')
|
||||
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 })
|
||||
const afterUnpacked: any = await detail(fx.user.token, orderId)
|
||||
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 () => {
|
||||
|
|
@ -363,6 +374,9 @@ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => {
|
|||
const fx = await createCatalogOrderFixture({ price: 100 })
|
||||
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({
|
||||
orderId: String(orderId),
|
||||
isDelivered: true,
|
||||
|
|
@ -372,10 +386,21 @@ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => {
|
|||
expect(delivered.orderStatus).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 })
|
||||
const pending: any = await detail(fx.user.token, orderId)
|
||||
expect(pending.orderStatus).toBe('success')
|
||||
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 () => {
|
||||
|
|
@ -410,6 +435,15 @@ describe('admin.order.updateOrderItemPackaging (AORD-18..20)', () => {
|
|||
const after: any = await admin.admin.order.getOrderDetails.query({ orderId })
|
||||
expect(after.items[0].isPackaged).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 () => {
|
||||
|
|
|
|||
|
|
@ -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_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 |
|
||||
| `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
|
||||
|
||||
|
|
@ -60,10 +65,18 @@ Use these names in the cases below so the expected values stay consistent.
|
|||
`region_carts_*`, `essential_consts_b*`).
|
||||
3. Clear all Jest mocks and fake timers. Use real timers only for tests that do not depend on
|
||||
debounce/countdown.
|
||||
4. Mock router `push`, `replace`, `back`, `dismissTo`, `dismissAll`, `canGoBack`, `useLocalSearchParams`.
|
||||
5. For page tests, mock `expo-router` only for navigation; keep `common-ui` components real.
|
||||
6. Every case that presses a button which calls the API must assert the procedure name and the
|
||||
4. Catalogue pages read `useCentralProductStore`, not their own `useAllProducts()` call.
|
||||
`renderWithProviders(ui, { withProductStore: true })` mounts the real producer so the mocked
|
||||
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`).
|
||||
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 |
|
||||
| --- | --- | --- | --- |
|
||||
| HOME-01 | happy | products query pending | “Loading products...” |
|
||||
| HOME-02 | error | products request rejects | “Oops!” + “Failed to load products” |
|
||||
| HOME-03 | error | consts request rejects, products succeed | “Failed to load app settings” |
|
||||
| HOME-02 | error | products request rejects with an empty catalogue | “Oops!” + “Failed to load products” |
|
||||
| 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-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 |
|
||||
|
|
@ -450,7 +463,7 @@ Mock `useAllProducts` via `common.essentialConsts` + versioned `products.json` a
|
|||
| SEARCH-11 | edge | whitespace-only query | treated as empty |
|
||||
| SEARCH-12 | edge | special characters/quotes | no crash; escaped in header |
|
||||
| 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-16 | edge | pull to refresh | 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 |
|
||||
| --- | --- | --- | --- |
|
||||
| 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-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 |
|
||||
|
|
@ -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-50 | route | offers variant | id passed; regular cart |
|
||||
| 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-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
|
||||
|
||||
Covered by HOME-81..98, plus:
|
||||
|
|
@ -1238,6 +1270,9 @@ Covered by HOME-81..98, plus:
|
|||
| FCB-03 | edge | flash cart | pink theme |
|
||||
| FCB-04 | edge | cart refetch after mutation | quantities state resets |
|
||||
| FCB-05 | edge | no cart data | no crash |
|
||||
| FCB-06 | happy | expanded sheet | “Apply Coupons at checkout” on the subtotal row, beside the amount |
|
||||
| FCB-07 | happy | coupon offer on the line's sku | `₹390` (₹430 line after the cap) + “With Coupon”, on its own row under the slot row |
|
||||
| FCB-08 | edge | no offer for the sku | no coupon line |
|
||||
|
||||
### CouponBreakdownDialog
|
||||
|
||||
|
|
@ -1595,6 +1630,29 @@ Covered by HOME-81..98, plus:
|
|||
| STORE-10 | edge | centralProduct setProducts | products + map by id |
|
||||
| STORE-11 | edge | centralProduct refetch setter | callable |
|
||||
| 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-14 | edge | checkout notes | set |
|
||||
| STORE-15 | edge | region set | id/region/bound; generation bump |
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import {
|
|||
} from "common-ui";
|
||||
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
|
||||
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 FloatingCartBar from "@/components/floating-cart-bar";
|
||||
|
||||
|
|
@ -77,9 +77,9 @@ export default function SearchResults() {
|
|||
});
|
||||
}, []);
|
||||
|
||||
const { data: productsData, isLoading, error, refetch } = useAllProducts();
|
||||
|
||||
const allProducts = useMemo(() => productsData?.products ?? [], [productsData]);
|
||||
const allProducts = useCentralProductStore((state) => state.products);
|
||||
const isLoading = useCentralProductStore((state) => state.isLoading);
|
||||
const refetchProducts = useCentralProductStore((state) => state.refetchProducts);
|
||||
|
||||
// Client-side search filtering using Fuse.js
|
||||
const products = useMemo(() => {
|
||||
|
|
@ -100,11 +100,11 @@ export default function SearchResults() {
|
|||
}, [allProducts, debouncedQuery]);
|
||||
|
||||
useManualRefresh(() => {
|
||||
refetch();
|
||||
refetchProducts?.();
|
||||
});
|
||||
|
||||
useMarkDataFetchers(() => {
|
||||
refetch();
|
||||
refetchProducts?.();
|
||||
});
|
||||
|
||||
const handleSearch = useCallback(() => {
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import {
|
|||
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
|
||||
import type { OffersSectionProps } from '@packages/shared';
|
||||
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 TabLayoutWrapper from "@/components/TabLayoutWrapper";
|
||||
import LocationBar from "@/src/components/LocationBar";
|
||||
|
|
@ -95,18 +95,20 @@ export default function Offers() {
|
|||
const [expandedOffers, setExpandedOffers] = 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 offers = allProducts.filter((p) => p.isOffer);
|
||||
|
||||
useManualRefresh(() => {
|
||||
refetch();
|
||||
refetchProducts?.();
|
||||
});
|
||||
|
||||
useMarkDataFetchers(() => {
|
||||
refetch();
|
||||
refetchProducts?.();
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
|
|
|
|||
|
|
@ -16,7 +16,8 @@ import FontAwesome5 from "@expo/vector-icons/FontAwesome5";
|
|||
import ProductCard from "@/components/ProductCard";
|
||||
import FloatingCartBar from "@/components/floating-cart-bar";
|
||||
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";
|
||||
|
||||
const { width: screenWidth } = Dimensions.get("window");
|
||||
|
|
@ -55,22 +56,15 @@ export default function StoreDetail() {
|
|||
const { data: storeData, isLoading, refetch, error } =
|
||||
useStoreWithProducts(storeIdNum);
|
||||
|
||||
const { data: productsData, isLoading: isProductsLoading } = useAllProducts();
|
||||
|
||||
const productById = useMemo(() => {
|
||||
const map = new Map<number, any>();
|
||||
productsData?.products?.forEach((product) => {
|
||||
map.set(product.id, product);
|
||||
});
|
||||
return map;
|
||||
}, [productsData]);
|
||||
const productsById = useCentralProductStore((state) => state.productsById);
|
||||
const isProductsLoading = useCentralProductStore((state) => state.isLoading);
|
||||
|
||||
const storeProducts = useMemo(() => {
|
||||
if (!storeData?.products) return [];
|
||||
return storeData.products
|
||||
.map((product) => productById.get(product.id))
|
||||
.map((product) => productsById[product.id])
|
||||
.filter(Boolean);
|
||||
}, [storeData, productById]);
|
||||
}, [storeData, productsById]);
|
||||
|
||||
// Filter products based on selected tag
|
||||
const filteredProducts = selectedTagId
|
||||
|
|
|
|||
|
|
@ -15,6 +15,8 @@ import {
|
|||
import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier';
|
||||
import { useCartStore } from '@/src/store/cartStore';
|
||||
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'
|
||||
|
||||
|
||||
|
|
@ -133,6 +135,14 @@ const ProductCard: React.FC<ProductCardProps> = ({
|
|||
// Flash products carry their own promo 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')) {
|
||||
// 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>
|
||||
)}
|
||||
</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`}>
|
||||
{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>
|
||||
|
|
|
|||
|
|
@ -19,6 +19,8 @@ import FloatingCartBar from './floating-cart-bar';
|
|||
import { useStoreHeaderStore } from '@/src/store/storeHeaderStore';
|
||||
import { useCartStore } from '@/src/store/cartStore';
|
||||
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 carouselWidth = screenWidth;
|
||||
|
|
@ -75,6 +77,20 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
|
|||
return productSlotsMap[productDetail.id];
|
||||
}, [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(() => {
|
||||
if (!slotsData?.slots || !productDetail) return []
|
||||
|
||||
|
|
@ -194,8 +210,8 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
|
|||
|
||||
const onRefresh = async () => {
|
||||
setRefreshing(true);
|
||||
await refetch(); // Refetch product details
|
||||
await loadReviews(true); // Reset and reload reviews
|
||||
// Product details and reviews are independent: refresh them together.
|
||||
await Promise.all([refetch(), loadReviews(true)]);
|
||||
setRefreshing(false);
|
||||
};
|
||||
|
||||
|
|
@ -311,6 +327,14 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
|
|||
</MyText>
|
||||
</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>
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { useRouter, usePathname, Slot } from 'expo-router';
|
|||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||
import { tw, theme, MyText, MyTouchableOpacity, MyFlatList, AppContainer, MiniQuantifier, SearchBar } from 'common-ui';
|
||||
import { trpc } from '@/src/trpc-client';
|
||||
import { 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 { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
||||
import { useCentralProductStore } from '@/src/store/centralProductStore';
|
||||
|
|
@ -806,7 +806,11 @@ export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsP
|
|||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
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 productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
||||
|
||||
|
|
@ -822,8 +826,6 @@ export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsP
|
|||
productsByStoreId,
|
||||
flashProducts,
|
||||
} = React.useMemo(() => {
|
||||
const products = productsQuery?.data?.products || [];
|
||||
const tags = productsQuery?.data?.tags || [];
|
||||
const stores = storesData?.stores || [];
|
||||
|
||||
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
|
||||
// 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))
|
||||
);
|
||||
const storeTabs = stores.filter((store: any) => flashStoreIds.has(store.id));
|
||||
|
|
@ -866,7 +868,7 @@ export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsP
|
|||
productsByStoreId,
|
||||
flashProducts,
|
||||
};
|
||||
}, [productsQuery?.data, storesData, productSlotsMap]);
|
||||
}, [products, catalogueTags, storesData, productSlotsMap]);
|
||||
|
||||
// Stable so FlashProductItem/FlashProductGrid memos survive a re-render.
|
||||
const handleProductPress = React.useCallback(
|
||||
|
|
@ -880,7 +882,6 @@ export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsP
|
|||
[onProductPress, router]
|
||||
);
|
||||
|
||||
const refetchProducts = productsQuery?.refetch;
|
||||
const handleRefresh = React.useCallback(async () => {
|
||||
setIsRefreshing(true);
|
||||
try {
|
||||
|
|
@ -903,7 +904,7 @@ export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsP
|
|||
[isRefreshing, handleRefresh]
|
||||
);
|
||||
|
||||
if (productsQuery?.isLoading) {
|
||||
if (isProductsLoading) {
|
||||
return (
|
||||
<AppContainer>
|
||||
<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 (
|
||||
<AppContainer>
|
||||
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ import { useRegionalConsts, useSlots } from "@/src/hooks/prominent-api-hooks"
|
|||
import { useRenderProbe } from "@/src/lib/render-probe"
|
||||
import { useProductSlotIdentifier } from "@/hooks/useProductSlotIdentifier";
|
||||
import { useCentralProductStore } from "@/src/store/centralProductStore";
|
||||
import { couponPriceFor } from "@/src/lib/product-coupons";
|
||||
import dayjs from "dayjs";
|
||||
import { LinearGradient } from "expo-linear-gradient";
|
||||
|
||||
|
|
@ -107,6 +108,7 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
const constsData = useRegionalConsts();
|
||||
const { data: slotsData } = useSlots();
|
||||
const productsById = useCentralProductStore((state) => state.productsById);
|
||||
const couponOffers = useCentralProductStore((state) => state.couponOffers);
|
||||
const { productSlotsMap } = useProductSlotIdentifier();
|
||||
const cartItems = cartData?.items || [];
|
||||
const itemCount = cartItems.length;
|
||||
|
|
@ -177,6 +179,18 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
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 (
|
||||
<>
|
||||
<View
|
||||
|
|
@ -287,7 +301,9 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
style={{ flexBasis: 'auto', flexShrink: 1 }}
|
||||
contentContainerStyle={tw`px-6 py-4`}
|
||||
>
|
||||
{cartItems.map((item, index) => (
|
||||
{cartItems.map((item, index) => {
|
||||
const couponLine = couponLineTotal(item);
|
||||
return (
|
||||
<React.Fragment key={item.id}>
|
||||
<View style={tw`py-4`}>
|
||||
<View style={tw`flex-row items-center`}>
|
||||
|
|
@ -376,6 +392,15 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
})()}
|
||||
</MyText>
|
||||
</View>
|
||||
{couponLine != null && (
|
||||
<View
|
||||
testID={`cart-item-coupon-price-${item.id}`}
|
||||
style={tw`flex-row items-center mt-1.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>
|
||||
|
||||
|
|
@ -385,7 +410,8 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
<View style={tw`h-px bg-slate-200 w-full`} />
|
||||
)}
|
||||
</React.Fragment>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
|
||||
{/* Fancy Footer */}
|
||||
|
|
@ -393,7 +419,17 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
<View style={tw`flex-row justify-between items-center mb-5`}>
|
||||
<View>
|
||||
<MyText style={tw`text-slate-400 text-[10px] font-black uppercase tracking-widest`}>Subtotal</MyText>
|
||||
<MyText style={tw`text-2xl font-black text-slate-900`}>₹{totalCartValue}</MyText>
|
||||
<View style={tw`flex-row items-baseline`}>
|
||||
<MyText style={tw`text-2xl font-black text-slate-900`}>₹{totalCartValue}</MyText>
|
||||
{/* The cart screens have no coupon picker; checkout does. */}
|
||||
<MyText
|
||||
testID="apply-coupons-hint"
|
||||
numberOfLines={1}
|
||||
style={tw`ml-2 text-[10px] font-bold text-slate-400 flex-shrink`}
|
||||
>
|
||||
Apply Coupons at checkout
|
||||
</MyText>
|
||||
</View>
|
||||
</View>
|
||||
{remainingForFreeDelivery === 0 && (
|
||||
<View style={tw`bg-emerald-50 px-3 py-1.5 rounded-xl border border-emerald-100 flex-row items-center`}>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
|
||||
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'
|
||||
|
||||
/** 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
|
||||
* `isSlotsLoaded` without listing them. Keeping it here leaves the screen with
|
||||
* 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() {
|
||||
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 productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap)
|
||||
const isSlotsLoaded = useCentralSlotStore((state) => state.isSlotsLoaded)
|
||||
|
||||
// Single source of truth for the catalogue: `products` and `dashboardTags`
|
||||
// come out of this memo together with the per-tag rows, so the screen never
|
||||
// holds two views of the same payload that can drift apart.
|
||||
const { dashboardTags, products, productsByTagId } = useMemo(() => {
|
||||
const tags = productsData?.tags ?? []
|
||||
const allProducts = productsData?.products ?? []
|
||||
|
||||
// Hoisted: the old version rebuilt this Map once per tag.
|
||||
// Single source of truth for the catalogue rows: the per-tag rows are derived
|
||||
// from the same products list the "All Products" feed pages through, so the
|
||||
// screen never holds two views of the same payload that can drift apart.
|
||||
const productsByTagId = useMemo(() => {
|
||||
const productById = new Map<number, any>()
|
||||
for (const product of allProducts) {
|
||||
for (const product of products) {
|
||||
productById.set(product.id, product)
|
||||
}
|
||||
|
||||
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
|
||||
// the tag's sortOrder (backend reorders it when building the cache).
|
||||
// Unknown ids are skipped and a repeated id only renders once.
|
||||
|
|
@ -62,8 +65,8 @@ export function useHomeCatalog() {
|
|||
map[tag.id] = [...inStock, ...outOfStock]
|
||||
}
|
||||
|
||||
return { dashboardTags: tags, products: allProducts, productsByTagId: map }
|
||||
}, [productsData, productSlotsMap, isSlotsLoaded, getQuickestSlot])
|
||||
return map
|
||||
}, [products, dashboardTags, productSlotsMap, isSlotsLoaded, getQuickestSlot])
|
||||
|
||||
// Tag selection/expansion live in homeTagStore (subscribed by TagTabStrip and
|
||||
// TagScene), so a tap does not re-render Dashboard or rebuild the list below.
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
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 * 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 { trpc } from '../trpc-client';
|
||||
import LocationMapStep from './location/LocationMapStep';
|
||||
|
|
@ -469,10 +469,27 @@ const AddressForm: React.FC<AddressFormProps & {
|
|||
)}
|
||||
</Formik>
|
||||
|
||||
<LoadingDialog
|
||||
open={isSubmitting}
|
||||
message={isEdit ? "Updating address..." : "Adding address..."}
|
||||
/>
|
||||
{/*
|
||||
The submit loader is an in-tree overlay, NOT a LoadingDialog Modal.
|
||||
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. */}
|
||||
<BottomDialog open={mapRegionPickerOpen} onClose={closeMapRegionPicker}>
|
||||
|
|
|
|||
|
|
@ -27,9 +27,12 @@ const PendingAddressSync: React.FC = () => {
|
|||
isSyncing.current = true
|
||||
try {
|
||||
await createAddress.mutateAsync(pending)
|
||||
await clearPendingAddress()
|
||||
await utils.user.address.getUserAddresses.invalidate()
|
||||
await utils.user.address.getDefaultAddress.invalidate()
|
||||
// The address is saved; clear the draft and refresh both lists together.
|
||||
await Promise.all([
|
||||
clearPendingAddress(),
|
||||
utils.user.address.getUserAddresses.invalidate(),
|
||||
utils.user.address.getDefaultAddress.invalidate(),
|
||||
])
|
||||
} catch {
|
||||
// Leave the draft in place; a later authenticated mount retries it.
|
||||
} finally {
|
||||
|
|
|
|||
|
|
@ -198,8 +198,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
|
|||
try {
|
||||
setAuthState(prev => ({ ...prev, isLoading: true }));
|
||||
|
||||
await saveAuthToken(token);
|
||||
await saveUserId(user.id.toString());
|
||||
await Promise.all([
|
||||
saveAuthToken(token),
|
||||
saveUserId(user.id.toString()),
|
||||
]);
|
||||
|
||||
setAuthState({
|
||||
user: {
|
||||
|
|
@ -232,8 +234,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
|
|||
// const response = loginMutation.mutate(credentials);
|
||||
const { token, user } = response.data;
|
||||
|
||||
await saveAuthToken(token);
|
||||
await saveUserId(user.id.toString());
|
||||
await Promise.all([
|
||||
saveAuthToken(token),
|
||||
saveUserId(user.id.toString()),
|
||||
]);
|
||||
|
||||
setAuthState({
|
||||
user: {
|
||||
|
|
@ -266,8 +270,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
|
|||
const response = await registerMutation.mutateAsync(data);
|
||||
const { token, user } = response;
|
||||
|
||||
await saveAuthToken(token);
|
||||
await saveUserId(user.id.toString());
|
||||
await Promise.all([
|
||||
saveAuthToken(token),
|
||||
saveUserId(user.id.toString()),
|
||||
]);
|
||||
|
||||
setAuthState({
|
||||
user: {
|
||||
|
|
|
|||
110
apps/user-ui/src/lib/product-coupons.ts
Normal file
110
apps/user-ui/src/lib/product-coupons.ts
Normal 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
|
||||
}
|
||||
|
|
@ -64,6 +64,8 @@ export async function confirmRegionSwitch(
|
|||
// 3. Drop cached regional catalog/slot snapshots so they cannot leak across.
|
||||
const productStore = useCentralProductStore.getState()
|
||||
productStore.setProducts([])
|
||||
productStore.setTags([])
|
||||
productStore.setCouponOffers({})
|
||||
productStore.setRefetchProducts(null)
|
||||
useCentralSlotStore.getState().setSlotsData([], [], [])
|
||||
|
||||
|
|
|
|||
|
|
@ -1,38 +1,170 @@
|
|||
import { create } from 'zustand'
|
||||
import { useEffect } from 'react'
|
||||
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: [],
|
||||
productsById: {},
|
||||
tags: [],
|
||||
isLoading: true,
|
||||
error: null,
|
||||
couponOffers: EMPTY_OFFERS,
|
||||
refetchProducts: null,
|
||||
setProducts: (products) => {
|
||||
const productsById: Record<number, Product> = {}
|
||||
|
||||
products.forEach((product) => {
|
||||
productsById[product.id] = product
|
||||
const { couponOffers } = get()
|
||||
const decorated =
|
||||
Object.keys(couponOffers).length === 0
|
||||
? 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 }),
|
||||
}))
|
||||
|
||||
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 setTags = useCentralProductStore((state) => state.setTags)
|
||||
const setCatalogMeta = useCentralProductStore((state) => state.setCatalogMeta)
|
||||
const setCouponOffers = useCentralProductStore((state) => state.setCouponOffers)
|
||||
const setRefetchProducts = useCentralProductStore((state) => state.setRefetchProducts)
|
||||
|
||||
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) {
|
||||
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(() => {
|
||||
setRefetchProducts(async () => {
|
||||
|
|
|
|||
|
|
@ -87,12 +87,23 @@ Rules:
|
|||
| Helper | Effect |
|
||||
| --- | --- |
|
||||
| `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 |
|
||||
| `seedSelectedAddress(id)` | sets `addressStore.selectedAddressId` |
|
||||
| `seedBoot({auth,addressId})` | the usual home/cart boot state |
|
||||
| `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'`.
|
||||
Cart lines live under `cart_items` / `flash_cart_items` (`CART_REG`, `CART_FLASH`).
|
||||
|
||||
|
|
|
|||
|
|
@ -11,11 +11,21 @@ import { StyleSheet, View } from 'react-native'
|
|||
import { QueryClient } from '@tanstack/react-query'
|
||||
import { fireEvent, waitFor } from '@testing-library/react-native'
|
||||
import FloatingCartBar from '@/components/floating-cart-bar'
|
||||
import { useCentralProductStore } from '@/src/store/centralProductStore'
|
||||
import { renderWithProviders, seedBoot, flush } from '../helpers/test-utils'
|
||||
import { resetAllMocks } from '../helpers/reset'
|
||||
import { __set, __snapshot } from '../mocks/secure-store-mock'
|
||||
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`:
|
||||
* 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(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()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
120
apps/user-ui/tests/components/product-card-coupon.test.tsx
Normal file
120
apps/user-ui/tests/components/product-card-coupon.test.tsx
Normal 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()
|
||||
})
|
||||
})
|
||||
16
apps/user-ui/tests/fixtures/index.ts
vendored
16
apps/user-ui/tests/fixtures/index.ts
vendored
|
|
@ -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 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 ELIGIBLE_COUPONS_RESPONSE = { data: COUPONS, isFirstOrder: true }
|
||||
export const MY_COUPONS_RESPONSE = {
|
||||
|
|
|
|||
|
|
@ -37,7 +37,15 @@ export function resetStores() {
|
|||
useQuickDeliveryStore.setState({ isDrawerHidden: false, selectedSlotId: null })
|
||||
useStoreHeaderStore.setState({ title: '' })
|
||||
useCheckoutStore.setState({ userNotes: '' })
|
||||
useCentralProductStore.setState({ products: [], productsById: {}, refetchProducts: null })
|
||||
useCentralProductStore.setState({
|
||||
products: [],
|
||||
productsById: {},
|
||||
tags: [],
|
||||
isLoading: true,
|
||||
error: null,
|
||||
couponOffers: {},
|
||||
refetchProducts: null,
|
||||
})
|
||||
useCentralSlotStore.setState({
|
||||
slots: [],
|
||||
productSlotsMap: {},
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import {
|
|||
STORES_RESPONSE,
|
||||
STORE_DETAIL_1,
|
||||
MERGED_PRODUCTS,
|
||||
TAGS,
|
||||
AVAILABILITY,
|
||||
TEST_JWT,
|
||||
availabilityCacheUrl,
|
||||
|
|
@ -27,7 +28,10 @@ import {
|
|||
A1,
|
||||
REGION_1,
|
||||
} from '../fixtures'
|
||||
import { useCentralProductStore } from '@/src/store/centralProductStore'
|
||||
import {
|
||||
useCentralProductStore,
|
||||
useInitializeCentralProductStore,
|
||||
} from '@/src/store/centralProductStore'
|
||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
||||
import { useRegionStore } from '@/src/store/regionStore'
|
||||
import { useAddressStore } from '@/src/store/addressStore'
|
||||
|
|
@ -62,10 +66,23 @@ export interface RenderOptions {
|
|||
queryClient?: QueryClient
|
||||
auth?: AuthMode
|
||||
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
|
||||
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) {
|
||||
if (mode === 'in') {
|
||||
setSecureItem('authToken', token)
|
||||
|
|
@ -87,6 +104,7 @@ export function renderWithProviders(
|
|||
const queryClient = options.queryClient ?? createTestQueryClient()
|
||||
const auth = options.auth ?? 'out'
|
||||
const withRefresh = options.withRefresh ?? true
|
||||
const withProductStore = options.withProductStore ?? false
|
||||
|
||||
if (auth !== false) {
|
||||
// Synchronous seeding so AuthProvider's bootstrap effect reads the token.
|
||||
|
|
@ -95,6 +113,14 @@ export function renderWithProviders(
|
|||
|
||||
const Wrapper = ({ children }: { children: React.ReactNode }) => {
|
||||
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) {
|
||||
tree = React.createElement(AuthProvider, null, tree)
|
||||
}
|
||||
|
|
@ -155,9 +181,14 @@ export function seedJsonCache(overrides: {
|
|||
}
|
||||
|
||||
/** 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
|
||||
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
|
||||
.getState()
|
||||
.setSlotsData((options.slots ?? SLOTS) as any, PRODUCT_AVAILABILITY as any, AVAILABILITY as any)
|
||||
|
|
@ -180,6 +211,19 @@ export function seedBoot(options: { auth?: AuthMode; addressId?: number | null }
|
|||
seedSelectedAddress(options.addressId ?? null)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
return jest.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
}
|
||||
|
|
|
|||
144
apps/user-ui/tests/lib/product-coupons.test.ts
Normal file
144
apps/user-ui/tests/lib/product-coupons.test.ts
Normal 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()
|
||||
})
|
||||
})
|
||||
|
|
@ -196,6 +196,53 @@ describe('stores', () => {
|
|||
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', () => {
|
||||
useCentralSlotStore.getState().setSlotsData(SLOTS as any, PRODUCT_AVAILABILITY as any, AVAILABILITY as any)
|
||||
const state = useCentralSlotStore.getState()
|
||||
|
|
|
|||
|
|
@ -898,7 +898,12 @@ describe('Home region integration (REGION-16..18)', () => {
|
|||
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 })
|
||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), {
|
||||
auth: false,
|
||||
// The catalogue comes from the product store; mount its producer so the
|
||||
// region's products document is still fetched by the screen.
|
||||
withProductStore: true,
|
||||
})
|
||||
await ctx.testUtils.flush(8)
|
||||
|
||||
expect(ctx.regionStore.getState().selectedRegionId).toBe(1)
|
||||
|
|
@ -930,7 +935,12 @@ describe('Home region integration (REGION-16..18)', () => {
|
|||
ctx.testUtils.seedCentralStores()
|
||||
|
||||
const Home = require('@/app/(drawer)/(tabs)/home/index').default
|
||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
|
||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), {
|
||||
auth: false,
|
||||
// The catalogue comes from the product store; mount its producer so the
|
||||
// region's products document is still fetched by the screen.
|
||||
withProductStore: true,
|
||||
})
|
||||
await ctx.testUtils.flush(8)
|
||||
|
||||
expect(ctx.regionStore.getState().selectedRegionId).toBeNull()
|
||||
|
|
@ -980,7 +990,12 @@ describe('Home region integration (REGION-16..18)', () => {
|
|||
ctx.testUtils.seedCentralStores()
|
||||
|
||||
const Home = require('@/app/(drawer)/(tabs)/home/index').default
|
||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
|
||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), {
|
||||
auth: false,
|
||||
// The catalogue comes from the product store; mount its producer so the
|
||||
// region's products document is still fetched by the screen.
|
||||
withProductStore: true,
|
||||
})
|
||||
await ctx.testUtils.flush(8)
|
||||
|
||||
expect(ctx.regionStore.getState().selectedRegionId).toBe(2)
|
||||
|
|
@ -1007,7 +1022,12 @@ describe('Home region integration (REGION-16..18)', () => {
|
|||
ctx.testUtils.seedCentralStores()
|
||||
|
||||
const Home = require('@/app/(drawer)/(tabs)/home/index').default
|
||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
|
||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), {
|
||||
auth: false,
|
||||
// The catalogue comes from the product store; mount its producer so the
|
||||
// region's products document is still fetched by the screen.
|
||||
withProductStore: true,
|
||||
})
|
||||
await ctx.testUtils.flush(8)
|
||||
|
||||
expect(ctx.regionStore.getState().selectedRegionId).toBe(1)
|
||||
|
|
@ -1041,7 +1061,12 @@ describe('Home region integration (REGION-16..18)', () => {
|
|||
ctx.testUtils.seedCentralStores()
|
||||
|
||||
const Home = require('@/app/(drawer)/(tabs)/home/index').default
|
||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
|
||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), {
|
||||
auth: false,
|
||||
// The catalogue comes from the product store; mount its producer so the
|
||||
// region's products document is still fetched by the screen.
|
||||
withProductStore: true,
|
||||
})
|
||||
await ctx.testUtils.flush(8)
|
||||
|
||||
expect(ctx.regionStore.getState().selectedRegionId).toBe(1)
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ import { useFlashCartStore } from '@/src/store/flashCartStore'
|
|||
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
|
||||
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 { router } from '../mocks/expo-router-mock'
|
||||
import { jsonCallsFor, setJsonError, setJsonPending, setJsonResponse } from '../mocks/fetch-json'
|
||||
|
|
@ -63,7 +63,7 @@ async function load() {
|
|||
}
|
||||
|
||||
function renderFlash(queryClient?: QueryClient) {
|
||||
return renderWithProviders(<FlashDeliveryView />, { auth: false, queryClient })
|
||||
return renderWithProviders(<FlashDeliveryView />, { auth: false, queryClient, withProductStore: true })
|
||||
}
|
||||
|
||||
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 () => {
|
||||
seedEmptyCatalogue()
|
||||
setJsonError(productsCacheUrl(), new Error('offline'))
|
||||
const { getByText } = renderFlash()
|
||||
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ import { useNavigationStore } from '@/src/store/navigationStore'
|
|||
import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget'
|
||||
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'
|
||||
|
||||
// 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 />, {
|
||||
auth: false,
|
||||
queryClient: createCartQueryClient(),
|
||||
withProductStore: true,
|
||||
...options,
|
||||
})
|
||||
await flush(3)
|
||||
|
|
@ -296,6 +297,7 @@ describe('Home (HOME)', () => {
|
|||
})
|
||||
|
||||
it('HOME-02: a rejected products request shows the error state', async () => {
|
||||
seedEmptyCatalogue()
|
||||
setJsonError(productsCacheUrl(), new Error('offline'))
|
||||
const { getByText } = await renderHome()
|
||||
|
||||
|
|
@ -304,6 +306,7 @@ describe('Home (HOME)', () => {
|
|||
})
|
||||
|
||||
it('HOME-03: a rejected consts request shows the settings error', async () => {
|
||||
seedEmptyCatalogue()
|
||||
setProcedure('common.essentialConsts', { mode: 'error', error: new Error('boom') })
|
||||
const { getByText } = await renderHome()
|
||||
|
||||
|
|
@ -928,65 +931,62 @@ describe('Home (HOME)', () => {
|
|||
})
|
||||
|
||||
it('HOME-58: pull to refresh refetches products, slots and stores', async () => {
|
||||
const refetchProducts = jest.fn(async () => undefined)
|
||||
const refetchSlots = jest.fn(async () => undefined)
|
||||
useCentralProductStore.setState({ refetchProducts })
|
||||
useCentralSlotStore.setState({ refetchSlots })
|
||||
await renderHome()
|
||||
|
||||
const productsBefore = jsonCallsFor(productsCacheUrl()).length
|
||||
const storesBefore = jsonCallsFor(storesCacheUrl()).length
|
||||
await emitManualRefresh()
|
||||
|
||||
expect(refetchProducts).toHaveBeenCalled()
|
||||
// The refresh runs store -> products query -> the catalogue document.
|
||||
expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(productsBefore)
|
||||
expect(refetchSlots).toHaveBeenCalled()
|
||||
expect(jsonCallsFor(storesCacheUrl()).length).toBeGreaterThan(storesBefore)
|
||||
})
|
||||
|
||||
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)
|
||||
useCentralProductStore.setState({ refetchProducts })
|
||||
useCentralSlotStore.setState({ refetchSlots })
|
||||
setJsonError(storesCacheUrl(), new Error('stores down'))
|
||||
const utils = await renderHome()
|
||||
|
||||
const productsBefore = jsonCallsFor(productsCacheUrl()).length
|
||||
await emitManualRefresh()
|
||||
|
||||
expect(refetchProducts).toHaveBeenCalled()
|
||||
expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(productsBefore)
|
||||
expect(refetchSlots).toHaveBeenCalled()
|
||||
const refreshControl = utils.UNSAFE_getByType(SectionList).props.refreshControl
|
||||
expect(refreshControl.props.refreshing).toBe(false)
|
||||
})
|
||||
|
||||
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)
|
||||
useCentralProductStore.setState({ refetchProducts })
|
||||
useCentralSlotStore.setState({ refetchSlots })
|
||||
await renderHome()
|
||||
|
||||
const productsBefore = jsonCallsFor(productsCacheUrl()).length
|
||||
const storesBefore = jsonCallsFor(storesCacheUrl()).length
|
||||
await emitFocus()
|
||||
await flush(2)
|
||||
|
||||
expect(refetchProducts).toHaveBeenCalled()
|
||||
expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(productsBefore)
|
||||
expect(refetchSlots).toHaveBeenCalled()
|
||||
expect(jsonCallsFor(storesCacheUrl()).length).toBeGreaterThan(storesBefore)
|
||||
})
|
||||
|
||||
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)
|
||||
useCentralProductStore.setState({ refetchProducts })
|
||||
useCentralSlotStore.setState({ refetchSlots })
|
||||
const utils = await renderHome()
|
||||
|
||||
const productsBefore = jsonCallsFor(productsCacheUrl()).length
|
||||
await emitManualRefresh()
|
||||
await emitManualRefresh()
|
||||
|
||||
const refreshControl = utils.UNSAFE_getByType(SectionList).props.refreshControl
|
||||
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 () => {
|
||||
|
|
@ -1407,12 +1407,15 @@ describe('Home (HOME)', () => {
|
|||
|
||||
it('HOME-96: a long product name is truncated in the bar', async () => {
|
||||
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
|
||||
useCentralProductStore.setState({
|
||||
productsById: { ...current, 2: { ...current[2], name: longName } },
|
||||
})
|
||||
__set('cart_items', CART_REG)
|
||||
const { getByText } = await renderHome()
|
||||
|
||||
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 () => {
|
||||
__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
|
||||
useCentralProductStore.setState({
|
||||
productsById: {
|
||||
|
|
@ -1428,8 +1435,6 @@ describe('Home (HOME)', () => {
|
|||
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/))
|
||||
|
||||
|
|
|
|||
|
|
@ -124,7 +124,7 @@ async function load() {
|
|||
}
|
||||
|
||||
function renderPage() {
|
||||
return renderWithProviders(<Offers />, { auth: false })
|
||||
return renderWithProviders(<Offers />, { auth: false, withProductStore: true })
|
||||
}
|
||||
|
||||
describe('Offers / order again (OFFER)', () => {
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@
|
|||
* behaviour and say so in a comment.
|
||||
*/
|
||||
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 { fireEvent, waitFor } from '@testing-library/react-native'
|
||||
import ProductDetail from '@/components/ProductDetail'
|
||||
|
|
@ -21,6 +21,7 @@ import { useCartStore } from '@/src/store/cartStore'
|
|||
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
|
||||
import { useStoreHeaderStore } from '@/src/store/storeHeaderStore'
|
||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
||||
import { useCentralProductStore } from '@/src/store/centralProductStore'
|
||||
import { renderWithProviders, seedBoot, flush } from '../helpers/test-utils'
|
||||
import { resetAllMocks } from '../helpers/reset'
|
||||
import {
|
||||
|
|
@ -44,6 +45,26 @@ import {
|
|||
slotsResponse,
|
||||
} 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 iso = (offsetMs: number) => new Date(Date.now() + offsetMs).toISOString()
|
||||
|
||||
|
|
@ -627,4 +648,50 @@ describe('ProductDetail', () => {
|
|||
const flash = await renderDetail('8', { isFlashDelivery: true })
|
||||
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()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ import { act, fireEvent, waitFor } from '@testing-library/react-native'
|
|||
import SearchResults from '@/app/(drawer)/(tabs)/home/search-results/index'
|
||||
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 { router, __setParams } from '../mocks/expo-router-mock'
|
||||
import { jsonCallsFor, setJsonError, setJsonPending } from '../mocks/fetch-json'
|
||||
|
|
@ -69,7 +69,7 @@ const ALL_NAMES = [
|
|||
|
||||
function renderPage(params: Record<string, any> = {}) {
|
||||
__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 () => {
|
||||
seedEmptyCatalogue()
|
||||
setJsonError(productsCacheUrl(), new Error('offline'))
|
||||
const { getByText } = renderPage()
|
||||
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ async function load() {
|
|||
}
|
||||
|
||||
function renderPage() {
|
||||
return renderWithProviders(<StoreDetail />, { auth: false })
|
||||
return renderWithProviders(<StoreDetail />, { auth: false, withProductStore: true })
|
||||
}
|
||||
|
||||
function seedDetail(detail: any) {
|
||||
|
|
|
|||
|
|
@ -2,13 +2,34 @@ import { useEffect } from 'react'
|
|||
import { useAllProducts } from './prominent-api-hooks'
|
||||
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() {
|
||||
const { data: productsData } = useAllProducts()
|
||||
const { data: productsData, refetch, isLoading, error } = useAllProducts()
|
||||
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(() => {
|
||||
// Undefined data (version bump in flight, failed refresh) keeps the previous
|
||||
// catalogue on screen instead of blanking it.
|
||||
if (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])
|
||||
}
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ export async function confirmRegionSwitch(
|
|||
// 3. Drop cached regional catalog/slot snapshots so they cannot leak across.
|
||||
const productStore = useCentralProductStore.getState()
|
||||
productStore.setProducts([])
|
||||
productStore.setTags([])
|
||||
productStore.setRefetchProducts(null)
|
||||
const slotStore = useCentralSlotStore.getState()
|
||||
slotStore.setSlots([])
|
||||
|
|
|
|||
|
|
@ -1,16 +1,28 @@
|
|||
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'
|
||||
|
||||
// Central cache holds the API product (MergedProduct) — single product shape
|
||||
// across the app (numeric pricing, string images).
|
||||
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) => ({
|
||||
products: [],
|
||||
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) => {
|
||||
const productsById: Record<number, Product> = {}
|
||||
products.forEach((p) => {
|
||||
|
|
@ -18,6 +30,14 @@ export const useCentralProductStore = create<CentralProductStore>((set) => ({
|
|||
})
|
||||
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,
|
||||
setRefetchProducts: (fn) => set({ refetchProducts: fn }),
|
||||
}))
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
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 { useCentralSlotStore } from '../lib/stores/central-slot-store'
|
||||
import { useFlashTabStore } from '../lib/stores/flash-tab-store'
|
||||
|
|
@ -279,9 +279,9 @@ function FlashDeliveryPage() {
|
|||
usePopulateCentralStores()
|
||||
usePopulateCentralProductStore()
|
||||
|
||||
const { data: productsData } = useAllProducts()
|
||||
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 addToCart = useAddToCart('flash')
|
||||
|
|
@ -299,7 +299,7 @@ function FlashDeliveryPage() {
|
|||
productsByStoreId,
|
||||
allFlashProducts,
|
||||
} = useMemo(() => {
|
||||
const tags = productsData?.tags || []
|
||||
const tags = catalogueTags || []
|
||||
const stores = storesData?.stores || []
|
||||
|
||||
const allFlashProducts = Object.values(productsById).filter(
|
||||
|
|
@ -345,7 +345,7 @@ function FlashDeliveryPage() {
|
|||
productsByStoreId,
|
||||
allFlashProducts,
|
||||
}
|
||||
}, [productsData, storesData, productsById, productSlotsMap])
|
||||
}, [catalogueTags, storesData, productsById, productSlotsMap])
|
||||
|
||||
// Stable so FlashProductItem memos survive a section re-render.
|
||||
const handleAddToCart = useCallback(
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
|||
import { useState, useEffect, useMemo, useRef } from 'react'
|
||||
import dayjs from 'dayjs'
|
||||
import {
|
||||
useAllProducts,
|
||||
useStores,
|
||||
useBanners,
|
||||
useSlots,
|
||||
|
|
@ -16,6 +15,8 @@ import AddToCartDialog from '../components/AddToCartDialog'
|
|||
import { useProductSlotIdentifier } from '../hooks/useProductSlotIdentifier'
|
||||
import { useHomeTagStore } from '../lib/stores/home-tag-store'
|
||||
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'
|
||||
|
||||
// Scroll Indicator Component
|
||||
|
|
@ -80,7 +81,9 @@ function SectionSpinner({ label }: { label?: string }) {
|
|||
|
||||
function HomePage() {
|
||||
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: bannersData } = useBanners()
|
||||
const { data: slotsData, isLoading: isSlotsLoading } = useSlots()
|
||||
|
|
@ -100,6 +103,8 @@ function HomePage() {
|
|||
|
||||
// Populate central stores with slots and product data
|
||||
usePopulateCentralStores()
|
||||
// The catalogue lands in the product store; this page only selects from it.
|
||||
usePopulateCentralProductStore()
|
||||
|
||||
const stores = storesData?.stores || []
|
||||
// const banners = bannersData?.banners || []
|
||||
|
|
@ -108,8 +113,8 @@ function HomePage() {
|
|||
// 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.
|
||||
const { dashboardTags, allProducts, productsByTagId } = useMemo(() => {
|
||||
const dashboardTags = productsData?.tags || []
|
||||
const allProducts = productsData?.products || []
|
||||
const dashboardTags = catalogueTags || []
|
||||
const allProducts = products || []
|
||||
|
||||
// Hoisted: the old version rebuilt this Map once per tag.
|
||||
const productById = new Map<number, any>()
|
||||
|
|
@ -143,7 +148,7 @@ function HomePage() {
|
|||
}
|
||||
|
||||
return { dashboardTags, allProducts, productsByTagId: map }
|
||||
}, [productsData, productSlotsMap, getQuickestSlot])
|
||||
}, [catalogueTags, products, productSlotsMap, getQuickestSlot])
|
||||
|
||||
// Explore Products tabs — tags in tagsOrder, products in per-tag sortOrder.
|
||||
// Selection/expansion live in the shared store (mirrors user-ui) so the state
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { createFileRoute, useNavigate, useSearch } from '@tanstack/react-router'
|
||||
import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
|
||||
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 { ProductCard } from '../components/ProductCard'
|
||||
import { SearchX, Loader2, ChevronLeft } from 'lucide-react'
|
||||
|
|
@ -34,6 +35,9 @@ function useDebounce<T>(value: T, delay: number): T {
|
|||
}
|
||||
|
||||
function SearchPage() {
|
||||
// The catalogue lands in the product store; this page only selects from it.
|
||||
usePopulateCentralProductStore()
|
||||
|
||||
const navigate = useNavigate()
|
||||
const { q } = useSearch({ from: '/home/search' })
|
||||
const [inputQuery, setInputQuery] = useState(q)
|
||||
|
|
@ -50,8 +54,10 @@ function SearchPage() {
|
|||
})
|
||||
}, [])
|
||||
|
||||
const { data: productsData, isLoading, error, refetch } = useAllProducts()
|
||||
const allProducts = productsData?.products || []
|
||||
const allProducts = useCentralProductStore((state) => state.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
|
||||
const products = useMemo(() => {
|
||||
|
|
@ -106,7 +112,7 @@ function SearchPage() {
|
|||
<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>
|
||||
<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"
|
||||
>
|
||||
Retry
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@ import { useState } from 'react'
|
|||
import { Tag, Loader2, AlertCircle } from 'lucide-react'
|
||||
import { ProductCard } from '../components/ProductCard'
|
||||
import { AppLayout } from '../components/AppLayout'
|
||||
import { useAllProducts } from '../hooks/prominent-api-hooks'
|
||||
import { usePopulateCentralProductStore } from '../hooks/usePopulateCentralProductStore'
|
||||
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
||||
import type { OffersSectionProps } from '@packages/shared'
|
||||
|
||||
export const Route = createFileRoute('/offers')({ component: OffersPage })
|
||||
|
|
@ -57,13 +58,16 @@ function OffersSection({ title, subtitle, products, expanded, onExpand, onProduc
|
|||
}
|
||||
|
||||
function OffersPage() {
|
||||
// The catalogue lands in the product store; this page only selects from it.
|
||||
usePopulateCentralProductStore()
|
||||
|
||||
const navigate = useNavigate()
|
||||
const [expandedOffers, setExpandedOffers] = useState(false)
|
||||
const [expandedCombos, setExpandedCombos] = useState(false)
|
||||
|
||||
const { data, isLoading, error } = useAllProducts()
|
||||
|
||||
const allProducts = data?.products || []
|
||||
const allProducts = useCentralProductStore((state) => state.products)
|
||||
const isLoading = useCentralProductStore((state) => state.isLoading)
|
||||
const error = useCentralProductStore((state) => state.error)
|
||||
const combos = allProducts.filter((p: any) => p.productType === 'combo')
|
||||
const offers = allProducts.filter((p: any) => p.isOffer)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
import { createFileRoute, useNavigate, useParams } from '@tanstack/react-router'
|
||||
import { useStoreWithProducts, useAllProducts } from '../hooks/prominent-api-hooks'
|
||||
import { useStoreWithProducts } from '../hooks/prominent-api-hooks'
|
||||
import { useState, useMemo } from 'react'
|
||||
import type { StoreTag, TagChipProps } from '@packages/shared'
|
||||
import { AppLayout } from '../components/AppLayout'
|
||||
import AddToCartDialog from '../components/AddToCartDialog'
|
||||
import { ProductCard } from '../components/ProductCard'
|
||||
import { usePopulateCentralStores } from '../hooks/usePopulateCentralStores'
|
||||
import { usePopulateCentralProductStore } from '../hooks/usePopulateCentralProductStore'
|
||||
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
||||
import { ArrowLeft, Store, X, Grid3X3 } from 'lucide-react'
|
||||
|
||||
export const Route = createFileRoute('/stores/$storeId')({
|
||||
|
|
@ -20,24 +22,19 @@ function StoreDetailPage() {
|
|||
|
||||
// Populate central stores with slots and product data for out-of-stock checking
|
||||
usePopulateCentralStores()
|
||||
// The catalogue lands in the product store; this page only selects from it.
|
||||
usePopulateCentralProductStore()
|
||||
|
||||
const { data: storeData, isLoading, error, refetch } = useStoreWithProducts(storeIdNum)
|
||||
const { data: productsData, isLoading: isProductsLoading } = useAllProducts()
|
||||
|
||||
const productById = useMemo(() => {
|
||||
const map = new Map<number, any>()
|
||||
productsData?.products?.forEach((product) => {
|
||||
map.set(product.id, product)
|
||||
})
|
||||
return map
|
||||
}, [productsData])
|
||||
const productsById = useCentralProductStore((state) => state.productsById)
|
||||
const isProductsLoading = useCentralProductStore((state) => state.isLoading)
|
||||
|
||||
const storeProducts = useMemo(() => {
|
||||
if (!storeData?.products) return []
|
||||
return storeData.products
|
||||
.map((product: any) => productById.get(product.id))
|
||||
.map((product: any) => productsById[product.id])
|
||||
.filter(Boolean)
|
||||
}, [storeData, productById])
|
||||
}, [storeData, productsById])
|
||||
|
||||
// Filter products based on selected tag
|
||||
const filteredProducts = selectedTagId
|
||||
|
|
|
|||
641
change-log.txt
641
change-log.txt
|
|
@ -867,3 +867,644 @@ never read the new switch. WebViewWrapper was a third surface (host-gated
|
|||
+ ROOT-34: closable store dialog renders Later and dismisses.
|
||||
--- apps/user-ui/JEST-TEST-CASES.md
|
||||
+ ROOT-33/ROOT-34 rows; ROOT-05/06 note the switch.
|
||||
|
||||
[2026-11-08 15:47:34 IST] cart add-address: fix the invisible touch-blocking layer after a successful save (ported from neo-region).
|
||||
|
||||
On iOS, a Modal dismissed while another Modal is presenting/dismissing can leave
|
||||
an empty native layer that swallows every touch (react-native#50152). The cart's
|
||||
add-address form is already inside RawBottomDialog/CartAddressGate's Modal, and
|
||||
AddressForm rendered its submit loader as a second Modal (LoadingDialog), then
|
||||
closed that loader and the host sheet in quick succession. After saving, the
|
||||
cart looked frozen.
|
||||
|
||||
--- apps/user-ui/src/components/AddressForm.tsx
|
||||
- submit <LoadingDialog> (nested Modal)
|
||||
+ inline absolute-fill overlay with the same spinner + message inside the form's
|
||||
KeyboardAvoidingView; no second native modal to leave behind
|
||||
|
||||
[2026-11-10 17:22:58 IST] admin orders: record packaging time and delivery time.
|
||||
|
||||
Both columns already exist on the SQLite schema (order_items.packaged_at from
|
||||
migration 0004/0005, orders.delivered_at from 0005) and were never written. No
|
||||
new migration is needed; this wires the writes and surfaces the values in the
|
||||
admin order-details screens (RN admin-ui + web admin-web).
|
||||
|
||||
--- packages/db_helper_sqlite/src/lib/date.ts
|
||||
+ export function nullableDate(value: Date | null | undefined): Date | null
|
||||
(timestampText's fromDriver maps NULL to new Date(0); treat epoch as null)
|
||||
|
||||
--- packages/db_helper_sqlite/src/admin-apis/order.ts
|
||||
updateOrderPackaged:
|
||||
- .set({ is_packaged: isPackaged })
|
||||
+ isPackaged true -> { is_packaged: true, packagedAt: COALESCE(packaged_at, now) }
|
||||
+ isPackaged false -> { is_packaged: false, packagedAt: null }
|
||||
+ !isPackaged also clears orders.deliveredAt (it already reset isDelivered)
|
||||
updateOrderDelivered:
|
||||
+ stamps orders.deliveredAt = now on the first delivered=true, keeps it on repeat
|
||||
+ calls, and clears it on delivered=false
|
||||
updateOrderItemPackaging:
|
||||
+ isPackaged true -> packaged_at = existing ?? now
|
||||
+ isPackaged false -> packaged_at = null
|
||||
getOrderDetails:
|
||||
+ deliveredAt (order) and packagedAt (per item), epoch-as-null
|
||||
|
||||
--- packages/db_helper_sqlite/src/lib/order-items-archive.ts
|
||||
- packagedAt: row.packagedAt ? row.packagedAt.toISOString() : null
|
||||
+ packagedAt: nullableDate(row.packagedAt)?.toISOString() ?? null
|
||||
(an unset timestamp was archived as 1970-01-01T00:00:00.000Z)
|
||||
|
||||
--- packages/shared/types/admin.ts
|
||||
+ AdminOrderDetails.deliveredAt: Date | null
|
||||
+ AdminOrderDetailsItem.packagedAt: Date | null
|
||||
|
||||
--- apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx
|
||||
+ testID "order-delivered-at" row in the header when order.deliveredAt
|
||||
+ testID `order-item-packaged-at-<id>` under each item when item.packagedAt
|
||||
|
||||
--- apps/admin-web/src/routes/dashboard.orders.$id.tsx
|
||||
+ same two blocks (web counterpart)
|
||||
|
||||
--- apps/backend/tests/api/admin-order.test.ts
|
||||
+ AORD-13: asserts packagedAt is stamped then cleared on un-pack
|
||||
+ AORD-16: asserts deliveredAt is stamped then cleared on un-deliver
|
||||
+ AORD-18: asserts the per-item packagedAt follows the Packaged toggle
|
||||
|
||||
--- apps/admin-ui/tests/fixtures/index.ts
|
||||
+ deliveredAt / packagedAt on ORDER_DETAILS and its items
|
||||
|
||||
--- apps/admin-ui/tests/pages/order-details.test.tsx
|
||||
+ AOD-26: delivered timestamp renders when order.deliveredAt is set
|
||||
+ AOD-27: no delivered timestamp before delivery
|
||||
+ AOD-28: per-item packed timestamp renders only when packagedAt is set
|
||||
|
||||
[2026-11-14 11:21:51 IST] intrv.java: print numbers 1 to 10 using Java streams.
|
||||
|
||||
--- intrv.java (new)
|
||||
+ class intrv with static printOneToTen() using IntStream.rangeClosed(1, 10).forEach(System.out::println)
|
||||
+ main() invoking printOneToTen()
|
||||
|
||||
[2026-11-14 11:27:23 IST] intrv.java: extract company name before the first hyphen.
|
||||
|
||||
--- intrv.java
|
||||
+ import java.util.Arrays
|
||||
+ static String extractCompany(String input): null/blank guard, input.split("-", 2)[0].trim()
|
||||
+ static String extractCompanyStream(String input): Arrays.stream(input.split("-", 2)).findFirst().orElse("")
|
||||
~ main() now also demos both on "Infosys-Interview 2028"
|
||||
|
||||
[2026-11-14 11:27:53 IST] intrv.java: company extraction now stream-only.
|
||||
|
||||
--- intrv.java
|
||||
- remove non-stream extractCompany
|
||||
~ extractCompanyStream renamed to extractCompany; body is a single Arrays.stream(...).findFirst().orElse("") pipeline
|
||||
~ main() calls extractCompany only
|
||||
|
||||
[2026-11-14 11:58:07 IST] intrv.java: extractCompany rewritten with an enhanced for loop.
|
||||
|
||||
--- intrv.java
|
||||
~ extractCompany: drop Arrays.stream/split pipeline; split once and walk the
|
||||
segments with a `for (String part : parts)` loop, returning the first non-blank
|
||||
trimmed segment ("" when none)
|
||||
- drop now-unused `import java.util.Arrays` (IntStream import stays for printOneToTen)
|
||||
|
||||
[2026-11-14 21:20:45 IST] perf: Promise.all for verified-independent sequential awaits.
|
||||
|
||||
Read-only waterfalls and independent storage/refetch pairs that the audit
|
||||
found. No ordering-dependent pair was changed (validate->write, write->read,
|
||||
mutate->refetch, fetch->reload stay sequential).
|
||||
|
||||
--- apps/backend/src/stores/product-store.ts
|
||||
initializeProducts: 5 cache reads -> one Promise.all
|
||||
- const productsData = await getAllProductsForCache(regionId)
|
||||
- const allStores = await getAllStoresForCache(regionId)
|
||||
- const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
|
||||
- const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
|
||||
- const allProductTags = await getAllProductTagsForCache(regionId)
|
||||
+ const [productsData, allStores, allDeliverySlots, allSpecialDeals, allProductTags] =
|
||||
+ await Promise.all([...same five calls...])
|
||||
getAllProducts: 6 cache reads -> one Promise.all (adds getAllProductCombosForCache)
|
||||
|
||||
--- apps/backend/src/stores/product-tag-store.ts
|
||||
- const tagsData = await getAllTagsForCache(regionId)
|
||||
- const productTagsData = await getAllTagProductMappings(regionId)
|
||||
+ const [tagsData, productTagsData] = await Promise.all([
|
||||
+ getAllTagsForCache(regionId),
|
||||
+ getAllTagProductMappings(regionId),
|
||||
+ ])
|
||||
|
||||
--- apps/backend/src/stores/user-negativity-store.ts
|
||||
loop of per-user awaits -> Promise.all over userIds, then fill the record.
|
||||
|
||||
--- apps/backend/src/trpc/apis/admin-apis/apis/user.ts
|
||||
getAllUsers: order counts / last orders / suspension -> Promise.all
|
||||
getUserDetails: suspension + orders -> Promise.all; statuses + item counts -> Promise.all
|
||||
getUsersForNotification: searchUsers + getAllNotifCreds -> Promise.all
|
||||
sendNotification: logged-in + unlogged tokens -> Promise.all
|
||||
|
||||
--- apps/backend/src/trpc/apis/user-apis/apis/order.ts
|
||||
- const totalCount = await getUserOrderCount(userId);
|
||||
- const userOrders = await getUserOrdersWithRelations(userId, offset, pageSize);
|
||||
+ const [totalCount, userOrders] = await Promise.all([...])
|
||||
|
||||
--- apps/backend/src/trpc/apis/admin-apis/apis/product.ts
|
||||
claimUploadUrls + scheduleStoreInitialization -> Promise.all at 4 sites
|
||||
(create product, update product, create tag, update tag). create/update and
|
||||
replaceTagProducts stay before the batch because the cache rebuild reads them.
|
||||
|
||||
--- apps/user-ui/src/contexts/AuthContext.tsx
|
||||
saveAuthToken + saveUserId -> Promise.all (3 sites: loginWithToken/login/register)
|
||||
|
||||
--- apps/admin-ui/components/context/staff-auth-context.tsx
|
||||
saveJWT + saveStaff, deleteJWT + deleteStaff -> Promise.all
|
||||
|
||||
--- apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx
|
||||
--- apps/admin-web/src/routes/dashboard.products.edit.tsx
|
||||
refetch() + refetchProducts() -> Promise.all (2 sites each; web counterpart)
|
||||
|
||||
--- apps/user-ui/components/ProductDetail.tsx
|
||||
onRefresh: refetch() + loadReviews(true) -> Promise.all
|
||||
|
||||
--- apps/user-ui/src/components/PendingAddressSync.tsx
|
||||
clearPendingAddress + getUserAddresses/getDefaultAddress invalidations -> Promise.all
|
||||
(the createAddress mutation still completes first)
|
||||
|
||||
Skipped on purpose:
|
||||
- write -> scheduleStoreInitialization pairs (store/banner/global-store CRUD):
|
||||
single enqueue after commit, negligible gain.
|
||||
- cloud_cache version bumpers: independent but D1 serializes writes anyway.
|
||||
- per-region loops (createAllCacheFiles, initializeAllStores, gen-store,
|
||||
flash cron): deliberate batching, not a missed parallel await.
|
||||
- getAuthToken + getCurrentUserId (AuthContext:70): getCurrentUserId re-reads
|
||||
the token; needs a refactor, not Promise.all.
|
||||
|
||||
[2026-11-16 00:36:38 IST] refactor catalogue: the central product store is the single
|
||||
source of product data (native + web).
|
||||
|
||||
Catalogue screens used to call useAllProducts() themselves — 6 hook instances in
|
||||
user-ui, 10 in web-ui — each rebuilding the merged products array, while cart,
|
||||
checkout and billing already read useCentralProductStore. The store now owns the
|
||||
whole catalogue snapshot (products, tags, loading, error, refetch) and every
|
||||
catalogue screen reads it.
|
||||
|
||||
--- packages/shared/types/app-common.types.ts
|
||||
CentralProductState<Product> -> CentralProductState<Product, Tag = unknown>
|
||||
+ tags: Tag[]
|
||||
+ isLoading: boolean
|
||||
+ error: unknown | null
|
||||
+ setTags(tags)
|
||||
+ setCatalogMeta({ isLoading?, error? })
|
||||
(second generic defaulted to unknown, so existing CentralProductState<Product>
|
||||
references still compile)
|
||||
|
||||
--- apps/user-ui/src/store/centralProductStore.ts
|
||||
initial state: tags [], isLoading true (cold start must not flash the empty
|
||||
catalogue), error null
|
||||
+ useInitializeCentralProductStore publishes products + tags in one effect and
|
||||
mirrors the query's isLoading / error into the store; products are never
|
||||
cleared when data is undefined (a version bump or a failed refresh keeps the
|
||||
last good catalogue, matching keepPreviousData)
|
||||
|
||||
--- apps/user-ui/src/lib/region-switch.ts
|
||||
+ clears tags alongside products when the region switches
|
||||
|
||||
--- apps/user-ui/hooks/useHomeCatalog.ts
|
||||
- const { data: productsData, isLoading, error } = useAllProducts()
|
||||
+ products / tags / isLoading / error from useCentralProductStore
|
||||
(return shape unchanged, so home/index.tsx needs no edit)
|
||||
|
||||
--- apps/user-ui/app/(drawer)/(tabs)/home/search-results/index.tsx
|
||||
products / isLoading / error from the store; manual refresh and the focus
|
||||
refetcher call the store's refetchProducts
|
||||
|
||||
--- apps/user-ui/app/(drawer)/(tabs)/order-again/index.tsx
|
||||
same swap (Offers tab: combos and isOffer rows)
|
||||
|
||||
--- apps/user-ui/app/(drawer)/(tabs)/stores/store-detail/[id].tsx
|
||||
- const { data: productsData, isLoading: isProductsLoading } = useAllProducts()
|
||||
- const productById = useMemo(...) // a second copy of the store's map
|
||||
+ productsById / isLoading from useCentralProductStore
|
||||
|
||||
--- apps/user-ui/components/SlotSpecificView.tsx
|
||||
FlashDeliveryProducts: products, tags, isLoading, error and refetchProducts
|
||||
from the store. SlotProducts in the same file already did.
|
||||
|
||||
--- apps/user-ui/tests/helpers/test-utils.tsx
|
||||
+ renderWithProviders({ withProductStore }) mounts the real producer
|
||||
(useInitializeCentralProductStore) so page tests keep driving the catalogue
|
||||
through the mocked products JSON instead of seeding the store by hand
|
||||
+ seedCentralStores seeds tags (TAGS fixture) and a refetchProducts stub
|
||||
|
||||
--- apps/user-ui/tests/helpers/reset.ts
|
||||
+ resets tags / isLoading / error
|
||||
|
||||
--- apps/user-ui/tests/pages/{home,flash-products,offers,search-results,store-detail}.test.tsx
|
||||
render helpers opt into withProductStore
|
||||
|
||||
--- apps/web-ui
|
||||
central-product-store + usePopulateCentralProductStore carry the same state;
|
||||
home.index / home.search / offers / stores.$storeId / flash read it
|
||||
(home.index, stores.$storeId and flash now also mount the product populator)
|
||||
+ tests/lib/use-region.test.tsx: the five Home renders opt into
|
||||
withProductStore so the region's products document is still fetched and the
|
||||
"only this region's catalogue is requested" assertions stay meaningful
|
||||
+ home.test.tsx: HOME-02/03 seed an empty catalogue (cold start); HOME-58..61
|
||||
assert the products document refetch instead of a store spy (the producer
|
||||
owns refetchProducts now); HOME-96/97 patch productsById after mount, since
|
||||
the producer seeds the store on its first effect
|
||||
+ flash-products FLASH-02 / search-results SEARCH-14 seed an empty catalogue
|
||||
for the first-load failure copy
|
||||
|
||||
[2026-11-16 00:52:09 IST] catalogue: show the coupon price on product cards and the
|
||||
product detail screen.
|
||||
|
||||
Product-specific coupons (coupons.sku_ids non-empty) already reach the client via
|
||||
user.coupon.getEligible, which cart/checkout use. The catalogue store now carries
|
||||
them too, so a card can say "₹194 with coupon" without a second request and
|
||||
without any screen owning the math.
|
||||
|
||||
Nothing waits on it: the coupon query runs in parallel with the products document
|
||||
inside the store's initializer; products render first, coupon prices fill in when
|
||||
the call lands. Cart-wide coupons (no sku_ids) are ignored here — they are not a
|
||||
product offer. minOrder is ignored too: it is a cart-level rule and the cart
|
||||
screen already explains eligibility.
|
||||
|
||||
--- packages/shared/types/app-common.types.ts
|
||||
+ interface ProductCouponOffer { couponId; couponCode; discountPercent; flatDiscount; maxValue }
|
||||
+ CentralProductState.couponOffers: Record<skuId, ProductCouponOffer>
|
||||
+ CentralProductState.setCouponOffers(offers)
|
||||
(price-independent params: the catalogue card prices a regular product and the
|
||||
flash card prices flashPrice, and both must use the same coupon)
|
||||
|
||||
--- apps/user-ui/src/lib/product-coupons.ts (new)
|
||||
+ buildCouponOffers(coupons, { regionId, isFirstOrder }) -> Record<skuId, offer>
|
||||
best single coupon per sku; skips region mismatch, first-order-only when the
|
||||
customer already ordered, and non-targeted coupons
|
||||
+ couponPriceFor(offer, unitPrice) -> number | null
|
||||
round(unitPrice - computeCouponDiscount(unitPrice, offer)); null when there is
|
||||
no discount (reuses the shared cart-pricing helper, so card and cart agree)
|
||||
|
||||
--- apps/user-ui/src/store/centralProductStore.ts
|
||||
+ couponOffers state; setCouponOffers decorates products/productsById with
|
||||
+ isProductCouponApply: true, couponDiscountedPrice: N
|
||||
+ setProducts re-applies the offers it holds (products.json refetches every
|
||||
+ minute and would otherwise drop the fields); clearing the offers strips them
|
||||
+ useInitializeCentralProductStore runs user.coupon.getEligible alongside the
|
||||
+ catalogue (enabled only when signed in; same query key as cart/checkout, so
|
||||
+ an open cart dedupes it) and rebuilds the offers on region / first-order
|
||||
+ changes and on logout
|
||||
|
||||
--- apps/user-ui/src/lib/region-switch.ts
|
||||
+ clears couponOffers with the catalogue
|
||||
|
||||
--- apps/user-ui/components/ProductCard.tsx
|
||||
with an offer: the price row drops to the struck price's size (text-base ->
|
||||
text-xs, hero text-sm -> text-[10px]) at opacity 0.85, and a new row shows
|
||||
₹discountedPrice in the brand colour with a muted "With Coupon" label.
|
||||
Flash cards price the flash price; out-of-stock cards show no coupon row.
|
||||
|
||||
--- apps/user-ui/components/ProductDetail.tsx
|
||||
+ the same coupon line under the price block (price block itself unchanged:
|
||||
it carries the unit suffix, the % OFF badge and the flash price row)
|
||||
|
||||
--- apps/web-ui/src/lib/stores/central-product-store.ts
|
||||
implements the new members with an always-empty map: web-ui has no coupon
|
||||
support in its cart/checkout, so it shows no coupon price at all.
|
||||
|
||||
--- apps/user-ui/tests
|
||||
+ tests/lib/product-coupons.test.ts (COUPON-01..15): targeting, cart-wide
|
||||
exclusion, region, first-order-only, invalidated, minOrder ignored, best of
|
||||
several, rounding, flash base, price guards
|
||||
+ tests/lib/stores.test.ts (STORE-13..15): offers before/after the catalogue,
|
||||
catalogue refresh keeps the fields, clearing the offers strips them
|
||||
+ tests/components/product-card-coupon.test.tsx (PCARD-01..08): coupon row,
|
||||
"With Coupon", price size == struck size, opacity 0.85, per-sku isolation,
|
||||
flash base, out-of-stock
|
||||
+ tests/pages/product-detail.test.tsx (PD-52..55): coupon line, no line, flash
|
||||
base, out-of-stock
|
||||
+ tests/fixtures: C_SKU2_FLAT / C_SKU2_MIN / C_SKU8_FLASH / C_SKU2_FIRST kept out
|
||||
of `COUPONS` so the cart/checkout payloads are untouched
|
||||
+ tests/helpers/reset.ts resets couponOffers
|
||||
JEST-TEST-CASES.md: rows for all of the above + a seeding rule
|
||||
|
||||
[2026-11-16 01:04:37] debug: log the tRPC bearer token presence per request (token value not printed)
|
||||
apps/admin-ui/src/trpc-client.ts
|
||||
--- a/apps/admin-ui/src/trpc-client.ts
|
||||
+++ b/apps/admin-ui/src/trpc-client.ts
|
||||
@@ headers
|
||||
headers: async () => {
|
||||
const token = await getJWT();
|
||||
+ console.log(
|
||||
+ `[admin-ui][trpc] getJWT: ${token ? `present (${token.length} chars)` : 'MISSING'}`
|
||||
+ );
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
},
|
||||
@@ fetch
|
||||
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' : 'MISSING'}`
|
||||
+ );
|
||||
const response = await fetch(url, options);
|
||||
if (response.status === 401) {
|
||||
+ console.log(
|
||||
+ `[admin-ui][trpc] 401 ${String(url)} | auth was: ${authHeader ? 'PRESENT' : 'MISSING'}`
|
||||
+ );
|
||||
const data = await response.clone().json().catch(() => ({}));
|
||||
|
||||
apps/admin-web/src/lib/trpc-client.ts
|
||||
--- a/apps/admin-web/src/lib/trpc-client.ts
|
||||
+++ b/apps/admin-web/src/lib/trpc-client.ts
|
||||
@@ headers
|
||||
headers: async () => {
|
||||
const token = await getJWT()
|
||||
+ console.log(
|
||||
+ `[admin-web][trpc] getJWT: ${token ? `present (${token.length} chars)` : 'MISSING'}`
|
||||
+ )
|
||||
return token ? { Authorization: `Bearer ${token}` } : {}
|
||||
},
|
||||
@@ fetch
|
||||
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' : 'MISSING'}`
|
||||
+ )
|
||||
const response = await fetch(url, options)
|
||||
if (response.status === 401) {
|
||||
+ console.log(
|
||||
+ `[admin-web][trpc] 401 ${String(url)} | auth was: ${authHeader ? 'PRESENT' : 'MISSING'}`
|
||||
+ )
|
||||
const data = await response.clone().json().catch(() => ({}))
|
||||
|
||||
[2026-11-16 01:08:09] debug: after a 401, re-probe staffUser.me with the same headers; include header length in the request log
|
||||
apps/admin-ui/src/trpc-client.ts
|
||||
--- a/apps/admin-ui/src/trpc-client.ts
|
||||
+++ b/apps/admin-ui/src/trpc-client.ts
|
||||
@@ request log
|
||||
console.log(
|
||||
- `[admin-ui][trpc] request ${String(url)} | auth: ${authHeader ? 'PRESENT' : 'MISSING'}`
|
||||
+ `[admin-ui][trpc] request ${String(url)} | auth: ${
|
||||
+ authHeader ? `PRESENT (${String(authHeader).length} chars)` : 'MISSING'
|
||||
+ }`
|
||||
);
|
||||
@@ 401 branch
|
||||
console.log(
|
||||
`[admin-ui][trpc] 401 ${String(url)} | auth was: ${authHeader ? 'PRESENT' : 'MISSING'}`
|
||||
);
|
||||
+ 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(() => ({}));
|
||||
|
||||
apps/admin-web/src/lib/trpc-client.ts
|
||||
--- a/apps/admin-web/src/lib/trpc-client.ts
|
||||
+++ b/apps/admin-web/src/lib/trpc-client.ts
|
||||
@@ request log
|
||||
console.log(
|
||||
- `[admin-web][trpc] request ${String(url)} | auth: ${authHeader ? 'PRESENT' : 'MISSING'}`
|
||||
+ `[admin-web][trpc] request ${String(url)} | auth: ${
|
||||
+ authHeader ? `PRESENT (${String(authHeader).length} chars)` : 'MISSING'
|
||||
+ }`
|
||||
)
|
||||
@@ 401 branch
|
||||
console.log(
|
||||
`[admin-web][trpc] 401 ${String(url)} | auth was: ${authHeader ? 'PRESENT' : 'MISSING'}`
|
||||
)
|
||||
+ 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(() => ({}))
|
||||
|
||||
[2026-11-16 01:11:30] debug: decode the stored JWT claims (staffId/userId/exp only, not the signature) in the tRPC header log
|
||||
apps/admin-ui/src/trpc-client.ts
|
||||
--- a/apps/admin-ui/src/trpc-client.ts
|
||||
+++ b/apps/admin-ui/src/trpc-client.ts
|
||||
@@ add helper
|
||||
+// 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;
|
||||
+ }
|
||||
+}
|
||||
@@ headers
|
||||
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'
|
||||
+ }`
|
||||
+ );
|
||||
|
||||
apps/admin-web/src/lib/trpc-client.ts
|
||||
--- a/apps/admin-web/src/lib/trpc-client.ts
|
||||
+++ b/apps/admin-web/src/lib/trpc-client.ts
|
||||
@@ add helper
|
||||
+// 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
|
||||
+ }
|
||||
+}
|
||||
@@ headers
|
||||
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'
|
||||
+ }`
|
||||
+ )
|
||||
|
||||
[2026-11-16 01:14:47] fix(admin): debounce the coupon user search (350ms) so keystrokes cannot fire overlapping queries
|
||||
apps/admin-ui/src/components/CouponForm.tsx
|
||||
apps/admin-web/src/components/CouponForm.tsx
|
||||
apps/admin-ui/tests/components/coupon-form.test.tsx
|
||||
|
||||
--- a/apps/admin-ui/src/components/CouponForm.tsx
|
||||
+++ b/apps/admin-ui/src/components/CouponForm.tsx
|
||||
@@ constant
|
||||
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;
|
||||
@@ state
|
||||
const [userSearchQuery, setUserSearchQuery] = useState('');
|
||||
+ const [debouncedUserSearch, setDebouncedUserSearch] = useState('');
|
||||
const [userOffset, setUserOffset] = useState(0);
|
||||
@@ effect before the query
|
||||
+ useEffect(() => {
|
||||
+ const timer = setTimeout(
|
||||
+ () => setDebouncedUserSearch(userSearchQuery),
|
||||
+ USER_SEARCH_DEBOUNCE_MS
|
||||
+ );
|
||||
+ return () => clearTimeout(timer);
|
||||
+ }, [userSearchQuery]);
|
||||
+
|
||||
@@ query input
|
||||
- { search: userSearchQuery, limit: USERS_PAGE_SIZE, offset: userOffset },
|
||||
+ { search: debouncedUserSearch, limit: USERS_PAGE_SIZE, offset: userOffset },
|
||||
@@ opening the dialog resets both values
|
||||
setHasMoreUsers(true);
|
||||
setUserSearchQuery('');
|
||||
+ setDebouncedUserSearch('');
|
||||
}
|
||||
|
||||
--- a/apps/admin-web/src/components/CouponForm.tsx
|
||||
+++ b/apps/admin-web/src/components/CouponForm.tsx
|
||||
(same debounce constant, state, effect, query input and open-reset as the RN form)
|
||||
|
||||
--- a/apps/admin-ui/tests/components/coupon-form.test.tsx
|
||||
+++ b/apps/admin-ui/tests/components/coupon-form.test.tsx
|
||||
+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)
|
||||
+}
|
||||
@@ ACOUPF-15
|
||||
fireEvent.changeText(view.getByPlaceholderText('Search users by name or mobile...'), 'Test')
|
||||
- await flush(2)
|
||||
setProcedure('admin.coupon.getUsersMiniInfo', { ... })
|
||||
- await flush(2)
|
||||
+ await waitForUserSearchDebounce()
|
||||
@@ new ACOUPF-18
|
||||
+ it('ACOUPF-18: rapid typing is debounced into a single user-search request', ...)
|
||||
+ - open the dialog (1 request)
|
||||
+ - type 9 / 96 / 967 / 9676 quickly
|
||||
+ - before the debounce: still 1 request
|
||||
+ - after the debounce: exactly 2 requests, last input search '9676'
|
||||
|
||||
[2026-11-16 01:15:38] test: keep the temporary 401 probe out of the test environment (it adds a fetch; ATRPC-01 asserts exactly one)
|
||||
apps/admin-ui/src/trpc-client.ts
|
||||
apps/admin-web/src/lib/trpc-client.ts
|
||||
--- a/apps/admin-ui/src/trpc-client.ts
|
||||
+++ b/apps/admin-ui/src/trpc-client.ts
|
||||
@@ 401 branch
|
||||
- try {
|
||||
- const probe = await fetch(...)
|
||||
- console.log(...)
|
||||
- } catch (probeError: any) {
|
||||
- console.log(...)
|
||||
- }
|
||||
+ if (process.env.NODE_ENV !== 'test') {
|
||||
+ try {
|
||||
+ const probe = await fetch(...)
|
||||
+ console.log(...)
|
||||
+ } catch (probeError: any) {
|
||||
+ console.log(...)
|
||||
+ }
|
||||
+ }
|
||||
(same guard in the admin-web client)
|
||||
|
||||
[2026-11-16 01:21:49 IST] floating cart bar: show the coupon price per line and point at
|
||||
the checkout coupon step.
|
||||
|
||||
The catalogue store already holds the product-specific coupons, so the expanded
|
||||
sheet prices each line with the same helper the cards use (line total as the base,
|
||||
flash items on flashPrice). The footer, under the subtotal, tells the customer
|
||||
coupons exist at checkout — the cart screens have no coupon picker of their own.
|
||||
|
||||
--- apps/user-ui/components/floating-cart-bar.tsx
|
||||
+ couponOffers read from useCentralProductStore
|
||||
+ each expanded line: under its total, ₹couponLineTotal + "With Coupon"
|
||||
+ footer: "Apply Coupons at checkout" under the Subtotal row
|
||||
|
||||
[2026-11-16 01:24:27 IST] catalogue coupons: the listed price keeps its weight, the
|
||||
coupon price sits at the struck price's size.
|
||||
|
||||
The demotion (halved size + 85% opacity on the listed price) made the coupon number
|
||||
the loudest thing on the card. Reverting it: the listed price keeps its original
|
||||
class and full opacity, the struck price is untouched, and the coupon price moves
|
||||
down to the struck price's size in the brand colour, with the same muted
|
||||
"With Coupon" label. The product detail coupon line drops from text-xl to
|
||||
text-base for the same reason.
|
||||
|
||||
--- apps/user-ui/components/ProductCard.tsx
|
||||
- price row: back to the original class, no opacity wrapper, testID dropped
|
||||
- coupon row: ₹couponPrice at text-xs (default) / text-[10px] (hero), brand colour
|
||||
+ “With Coupon” in text-gray-400
|
||||
--- apps/user-ui/components/ProductDetail.tsx
|
||||
- coupon line: text-xl -> text-base, brand colour + text-gray-400 label
|
||||
--- apps/user-ui/tests/components/product-card-coupon.test.tsx
|
||||
PCARD-03/04 now assert sizes + colours instead of the demotion
|
||||
--- apps/user-ui/tests/pages/product-detail.test.tsx
|
||||
PD-52 also pins the coupon size against the 3xl listed price
|
||||
|
||||
[2026-11-16 15:53:07 IST] floating cart bar layout: coupon price gets its own row, the
|
||||
checkout hint sits beside the subtotal.
|
||||
|
||||
The coupon line was stacked under the line total, squeezing the price column. It
|
||||
now spans the line below the delivery-slot row. The "Apply Coupons at checkout"
|
||||
hint moves from its own block into the subtotal row, next to the amount (mixed
|
||||
case and smaller so it fits beside the 2xl figure).
|
||||
|
||||
--- apps/user-ui/components/floating-cart-bar.tsx
|
||||
- line total: back to a plain ₹total, no stacked column
|
||||
+ coupon row: full-width under the slot dropdown row, ₹couponLine + "With Coupon"
|
||||
(testID cart-item-coupon-price-{id})
|
||||
- footer: standalone hint block under the subtotal row
|
||||
+ hint inline with ₹subtotal (testID apply-coupons-hint, numberOfLines 1)
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import {
|
|||
orders,
|
||||
orderStatus,
|
||||
} from '../db/schema'
|
||||
import { and, desc, eq, inArray, isNull, lt, SQL } from 'drizzle-orm'
|
||||
import { and, desc, eq, inArray, isNull, lt, sql, SQL } from 'drizzle-orm'
|
||||
import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order'
|
||||
import {
|
||||
attachOrderItems,
|
||||
|
|
@ -32,7 +32,7 @@ import type {
|
|||
GetAllOrdersInput,
|
||||
} from '@packages/shared'
|
||||
import type { InferSelectModel } from 'drizzle-orm'
|
||||
import { coerceDate } from '../lib/date'
|
||||
import { coerceDate, nullableDate } from '../lib/date'
|
||||
import { marketStatsForRegion } from '../lib/market-stats'
|
||||
import { composeSkuName, composeUnitNotation } from '../lib/sku-features'
|
||||
|
||||
|
|
@ -109,7 +109,15 @@ export async function updateOrderPackaged(regionId: number, orderId: string, isP
|
|||
|
||||
await db
|
||||
.update(orderItems)
|
||||
.set({ is_packaged: isPackaged })
|
||||
.set(
|
||||
isPackaged
|
||||
? {
|
||||
is_packaged: true,
|
||||
// First packaging moment wins; re-marking must not move the clock.
|
||||
packagedAt: sql`COALESCE(${orderItems.packagedAt}, ${new Date().toISOString()})`,
|
||||
}
|
||||
: { is_packaged: false, packagedAt: null }
|
||||
)
|
||||
.where(eq(orderItems.orderId, orderIdNumber))
|
||||
|
||||
if (!isPackaged) {
|
||||
|
|
@ -117,6 +125,11 @@ export async function updateOrderPackaged(regionId: number, orderId: string, isP
|
|||
.update(orderStatus)
|
||||
.set({ isPackaged, isDelivered: false })
|
||||
.where(eq(orderStatus.orderId, orderIdNumber))
|
||||
// Un-packaging resets delivery, so the recorded delivery time goes with it.
|
||||
await db
|
||||
.update(orders)
|
||||
.set({ deliveredAt: null })
|
||||
.where(eq(orders.id, orderIdNumber))
|
||||
} else {
|
||||
await db
|
||||
.update(orderStatus)
|
||||
|
|
@ -136,7 +149,7 @@ export async function updateOrderDelivered(regionId: number, orderId: string, is
|
|||
|
||||
const orderCheck = await db.query.orders.findFirst({
|
||||
where: and(eq(orders.id, orderIdNumber), eq(orders.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
columns: { id: true, deliveredAt: true },
|
||||
})
|
||||
if (!orderCheck) {
|
||||
return null
|
||||
|
|
@ -147,6 +160,16 @@ export async function updateOrderDelivered(regionId: number, orderId: string, is
|
|||
.set({ isDelivered })
|
||||
.where(eq(orderStatus.orderId, orderIdNumber))
|
||||
|
||||
// Stamp the first delivery moment; a repeat "delivered" call keeps it, and
|
||||
// un-delivering clears it so the next delivery gets a fresh time.
|
||||
const deliveredAt = isDelivered
|
||||
? nullableDate(orderCheck.deliveredAt) ?? new Date()
|
||||
: null
|
||||
await db
|
||||
.update(orders)
|
||||
.set({ deliveredAt })
|
||||
.where(eq(orders.id, orderIdNumber))
|
||||
|
||||
const order = await db.query.orders.findFirst({
|
||||
where: and(eq(orders.id, orderIdNumber), eq(orders.regionId, regionId)),
|
||||
})
|
||||
|
|
@ -238,6 +261,7 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
|
|||
adminNotes: orderData.adminNotes,
|
||||
userNotes: orderData.userNotes,
|
||||
createdAt: orderData.createdAt,
|
||||
deliveredAt: nullableDate(orderData.deliveredAt),
|
||||
status,
|
||||
isPackaged: orderStatusRecord?.isPackaged || false,
|
||||
isDelivered: orderStatusRecord?.isDelivered || false,
|
||||
|
|
@ -252,6 +276,7 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
|
|||
amount: parseFloat(item.price.toString()) * parseFloat(item.quantity || '0'),
|
||||
isPackaged: item.is_packaged,
|
||||
isPackageVerified: item.is_package_verified,
|
||||
packagedAt: nullableDate(item.packagedAt),
|
||||
features: (item.sku.features || []).map((f: any) => ({
|
||||
featureName: f.featureName,
|
||||
featureValue: f.featureValue,
|
||||
|
|
@ -286,10 +311,14 @@ export async function updateOrderItemPackaging(
|
|||
const updateData: Partial<{
|
||||
is_packaged: boolean
|
||||
is_package_verified: boolean
|
||||
packaged_at: Date | null
|
||||
}> = {}
|
||||
|
||||
if (isPackaged !== undefined) {
|
||||
updateData.is_packaged = isPackaged
|
||||
updateData.packaged_at = isPackaged
|
||||
? nullableDate(orderItem.packagedAt) ?? new Date()
|
||||
: null
|
||||
}
|
||||
if (isPackageVerified !== undefined) {
|
||||
updateData.is_package_verified = isPackageVerified
|
||||
|
|
|
|||
|
|
@ -1,3 +1,14 @@
|
|||
/**
|
||||
* `timestampText` reads SQL NULL back as `new Date(0)`, so a plain `?? null`
|
||||
* would hand clients 1970-01-01 instead of "not set". Anything at or before the
|
||||
* epoch is treated as unset.
|
||||
*/
|
||||
export function nullableDate(value: Date | null | undefined): Date | null {
|
||||
if (!value) return null
|
||||
const time = value instanceof Date ? value.getTime() : NaN
|
||||
return Number.isNaN(time) || time <= 0 ? null : value
|
||||
}
|
||||
|
||||
export function coerceDate(value: unknown): Date | null {
|
||||
if (value instanceof Date) {
|
||||
return Number.isNaN(value.getTime()) ? null : value
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { and, eq, gt, inArray, isNull, sql } from 'drizzle-orm'
|
||||
import { db } from '../db/db_index'
|
||||
import { orderItems, orders, productSkus, type OrderItemSnapshot } from '../db/schema'
|
||||
import { nullableDate } from './date'
|
||||
|
||||
const IST_OFFSET_MS = 5.5 * 60 * 60 * 1000
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
|
|
@ -132,7 +133,7 @@ export function buildSnapshot(
|
|||
discountedPrice: row.discountedPrice,
|
||||
isPackaged: row.is_packaged,
|
||||
isPackageVerified: row.is_package_verified,
|
||||
packagedAt: row.packagedAt ? row.packagedAt.toISOString() : null,
|
||||
packagedAt: nullableDate(row.packagedAt)?.toISOString() ?? null,
|
||||
productName: sku.product.name,
|
||||
skuName: sku.name,
|
||||
image: Array.isArray(sku.images) && sku.images.length > 0 ? sku.images[0] : null,
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ export const BASE_API_URL = 'https://worker.freshyo.in'
|
|||
// export const BASE_API_URL = 'https://devapi.freshyo.in'
|
||||
// export const BASE_API_URL = 'https://devbackend.freshyo.in'
|
||||
// export const BASE_API_URL = 'https://192.168.100.126.nip.io:8787'
|
||||
// export const BASE_API_URL = 'http://192.168.1.5:8787'
|
||||
// export const BASE_API_URL = 'http://192.168.100.126:8787'
|
||||
|
||||
// Re-export all types from the types folder
|
||||
export * from './types'
|
||||
|
|
|
|||
|
|
@ -90,6 +90,7 @@ export interface AdminOrderDetailsItem extends AdminOrderItemCore {
|
|||
price: string;
|
||||
productSize: number;
|
||||
unit?: string;
|
||||
packagedAt: Date | null;
|
||||
}
|
||||
|
||||
export interface AdminOrderDetailsCouponData {
|
||||
|
|
@ -112,6 +113,7 @@ export interface AdminOrderDetails {
|
|||
adminNotes: string | null;
|
||||
userNotes: string | null;
|
||||
createdAt: Date;
|
||||
deliveredAt: Date | null;
|
||||
status: 'pending' | 'delivered' | 'cancelled';
|
||||
isPackaged: boolean;
|
||||
isDelivered: boolean;
|
||||
|
|
|
|||
|
|
@ -153,10 +153,42 @@ export interface QuickDeliveryState {
|
|||
}
|
||||
|
||||
// Central product cache — element type differs per app (MergedProduct vs local Product)
|
||||
export interface CentralProductState<Product = unknown> {
|
||||
//
|
||||
// This is the single frontend source of product data: the catalogue JSON is read
|
||||
// once (by the store's own initializer) and every screen selects from here, so a
|
||||
// field added to a product reaches all of them without another fetch.
|
||||
/**
|
||||
* A product-specific coupon as the catalogue needs it: the discount rules, not a
|
||||
* price. The same sku is shown at `price` on the regular catalogue and at
|
||||
* `flashPrice` on the 1 Hr Delivery tab, and both must apply the same coupon.
|
||||
*/
|
||||
export interface ProductCouponOffer {
|
||||
couponId: number
|
||||
couponCode: string
|
||||
discountPercent?: string | number | null
|
||||
flatDiscount?: string | number | null
|
||||
maxValue?: string | number | null
|
||||
}
|
||||
|
||||
export interface CentralProductState<Product = unknown, Tag = unknown> {
|
||||
products: Product[]
|
||||
productsById: Record<number, Product>
|
||||
/** The catalogue's tag strip metadata (products.json `tags`). */
|
||||
tags: Tag[]
|
||||
/**
|
||||
* Catalogue load state, mirrored from the products query. Starts `true` so a
|
||||
* cold start never flashes the empty catalogue before the first fetch lands;
|
||||
* a version bump or a failed background refresh keeps the last catalogue and
|
||||
* leaves the flags alone, matching the query's `keepPreviousData`.
|
||||
*/
|
||||
isLoading: boolean
|
||||
error: unknown | null
|
||||
/** Product-specific coupons per skuId, best-first. Empty until the call lands. */
|
||||
couponOffers: Record<number, ProductCouponOffer[]>
|
||||
refetchProducts: (() => void | Promise<void>) | null
|
||||
setProducts: (products: Product[]) => void
|
||||
setTags: (tags: Tag[]) => void
|
||||
setCatalogMeta: (meta: { isLoading?: boolean; error?: unknown | null }) => void
|
||||
setCouponOffers: (offers: Record<number, ProductCouponOffer[]>) => void
|
||||
setRefetchProducts: (refetch: (() => void | Promise<void>) | null) => void
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue