This commit is contained in:
shafi54 2026-10-15 20:53:29 +05:30
parent 713420c8bb
commit bd09d84822
6 changed files with 341 additions and 65 deletions

View file

@ -177,6 +177,88 @@ const clearLocalCart = async (cartType: CartType = "regular"): Promise<void> =>
await StorageServiceCasual.setItem(key, JSON.stringify([]));
};
/* -------------------------------------------------------------------------- *
* Per-region cart snapshots
*
* A region switch clears both carts, so the outgoing region's carts are
* remembered first and restored when that region is switched back to. Only the
* product, its chosen slot and the quantity are kept.
* -------------------------------------------------------------------------- */
interface StashedCartItem {
skuId: number;
slotId: number;
quantity: number;
}
type StashedCarts = Record<CartType, StashedCartItem[]>;
const CART_TYPES: CartType[] = ["regular", "flash"];
const getRegionCartStorageKey = (regionId: number): string => `region_carts_${regionId}`;
const emptyStashedCarts = (): StashedCarts => ({ regular: [], flash: [] });
const readStashedCarts = async (regionId: number): Promise<StashedCarts> => {
const raw = await StorageServiceCasual.getItem(getRegionCartStorageKey(regionId));
if (!raw) return emptyStashedCarts();
try {
const parsed = JSON.parse(raw) as Partial<StashedCarts>;
return { regular: parsed?.regular ?? [], flash: parsed?.flash ?? [] };
} catch {
return emptyStashedCarts();
}
};
/** Remember a region's carts (product + slot + quantity) before a switch clears them. */
const stashRegionCarts = async (regionId: number): Promise<void> => {
const stashed = await readStashedCarts(regionId);
for (const cartType of CART_TYPES) {
const items = await getLocalCart(cartType);
stashed[cartType] = items.map((item) => ({
skuId: item.skuId,
slotId: item.slotId ?? 0,
quantity: item.quantity,
}));
}
await StorageServiceCasual.setItem(
getRegionCartStorageKey(regionId),
JSON.stringify(stashed)
);
};
/**
* Rebuild a region's carts from its snapshot. Item ids are re-issued from the
* local counter. A region that was never visited restores to empty; a snapshot
* written before quantities were kept restores those lines at 1.
*/
const restoreRegionCarts = async (regionId: number): Promise<void> => {
const stashed = await readStashedCarts(regionId);
for (const cartType of CART_TYPES) {
const items: LocalCartItem[] = [];
for (const stashedItem of stashed[cartType]) {
const quantity =
Number.isFinite(stashedItem.quantity) && stashedItem.quantity > 0
? stashedItem.quantity
: 1;
items.push({
id: getNextCartItemId(items),
skuId: stashedItem.skuId,
quantity,
slotId: stashedItem.slotId ?? 0,
addedAt: new Date().toISOString(),
});
}
await saveLocalCart(items, cartType);
}
};
export function useGetCart(options: UseGetCartOptions = {}, cartType: CartType = "regular"): UseGetCartReturn {
const productsById = useCentralProductStore((state) => state.productsById);
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
@ -415,4 +497,4 @@ export function useRemoveFromCart(options: MutationOptions<LocalCartItem[], Remo
}
// Export clear cart function for direct use
export { clearLocalCart };
export { clearLocalCart, stashRegionCarts, restoreRegionCarts };

View file

@ -52,7 +52,6 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose, no
const utils = trpc.useUtils()
const auth = useAuthOptional()
const isAuthenticated = auth?.isAuthenticated ?? false
const isAuthLoading = auth?.isLoading ?? false
const [mode, setMode] = useState<'choose' | 'add' | 'login'>('choose')
const [busy, setBusy] = useState(false)
@ -235,60 +234,66 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose, no
</View>
)}
{isAuthenticated && addressesQuery.isLoading && (
<View style={tw`flex-1 items-center justify-center`}>
<ActivityIndicator size="large" color={theme.colors.brand500} />
</View>
)}
<ScrollView style={tw`flex-1`} contentContainerStyle={tw`px-5 pb-10`}>
{isAuthenticated &&
addresses.map((address) => (
<View
key={address.id}
style={tw`bg-white border border-gray-100 rounded-2xl p-4 mb-3 shadow-sm`}
>
<MyTouchableOpacity disabled={busy} onPress={() => handleSelect(address)}>
<View style={tw`flex-row items-center mb-1`}>
<MyText style={tw`text-base font-bold text-gray-900 mr-2`}>{address.name}</MyText>
{address.isDefault && (
<View style={tw`bg-green-100 px-2 py-0.5 rounded-full`}>
<MyText style={tw`text-green-700 text-[10px] font-semibold`}>Default</MyText>
</View>
)}
</View>
<MyText style={tw`text-gray-600 text-sm`}>
{address.addressLine1}
{address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city}
</MyText>
</MyTouchableOpacity>
{!address.isDefault && (
<MyTouchableOpacity
onPress={() => handleSetDefault(address)}
disabled={busy || updateAddress.isPending}
style={tw`mt-2 self-start`}
>
<MyText style={tw`text-blue-500 text-xs font-medium`}>Set as default</MyText>
</MyTouchableOpacity>
)}
{/* The list owns the remaining height, so it scrolls while the footer below
stays pinned (and is therefore always reachable). */}
<View style={tw`flex-1`}>
<ScrollView style={tw`flex-1`} contentContainerStyle={tw`px-5 pb-10`}>
{isAuthenticated && addressesQuery.isLoading && (
<View style={tw`items-center justify-center py-10`}>
<ActivityIndicator size="large" color={theme.colors.brand500} />
</View>
))}
)}
{isAuthenticated && !addressesQuery.isLoading && addresses.length === 0 && (
<MyText style={tw`text-gray-500 mb-3`}>No saved addresses yet.</MyText>
)}
{isAuthenticated &&
addresses.map((address) => (
<View
key={address.id}
style={tw`bg-white border border-gray-100 rounded-2xl p-4 mb-3 shadow-sm`}
>
<MyTouchableOpacity disabled={busy} onPress={() => handleSelect(address)}>
<View style={tw`flex-row items-center mb-1`}>
<MyText style={tw`text-base font-bold text-gray-900 mr-2`}>{address.name}</MyText>
{address.isDefault && (
<View style={tw`bg-green-100 px-2 py-0.5 rounded-full`}>
<MyText style={tw`text-green-700 text-[10px] font-semibold`}>Default</MyText>
</View>
)}
</View>
<MyText style={tw`text-gray-600 text-sm`}>
{address.addressLine1}
{address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city}
</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
onPress={() => setMode('add')}
style={tw`bg-white border border-dashed border-gray-300 rounded-2xl p-4 flex-row items-center`}
>
<MaterialIcons name="add-location-alt" size={22} color={theme.colors.brand500} />
<MyText style={tw`text-gray-900 font-bold ml-2`}>Add a new address</MyText>
</MyTouchableOpacity>
</ScrollView>
{!address.isDefault && (
<MyTouchableOpacity
onPress={() => handleSetDefault(address)}
disabled={busy || updateAddress.isPending}
style={tw`mt-2 self-start`}
>
<MyText style={tw`text-blue-500 text-xs font-medium`}>Set as default</MyText>
</MyTouchableOpacity>
)}
</View>
))}
{!isAuthenticated && !isAuthLoading && (
{isAuthenticated && !addressesQuery.isLoading && addresses.length === 0 && (
<MyText style={tw`text-gray-500 mb-3`}>No saved addresses yet.</MyText>
)}
<MyTouchableOpacity
onPress={() => setMode('add')}
style={tw`bg-white border border-dashed border-gray-300 rounded-2xl p-4 flex-row items-center`}
>
<MaterialIcons name="add-location-alt" size={22} color={theme.colors.brand500} />
<MyText style={tw`text-gray-900 font-bold ml-2`}>Add a new address</MyText>
</MyTouchableOpacity>
</ScrollView>
</View>
{/* Pinned footer: shown for the whole signed-out time, not only once auth
has settled, so the Login button is always available. */}
{!isAuthenticated && (
<View style={tw`px-5 pt-3 pb-6 border-t border-gray-100 bg-white`}>
<MyText style={tw`text-gray-500 text-sm text-center mb-3`}>
Login to get existing addresses.

View file

@ -1,6 +1,6 @@
import type { QueryClient } from '@tanstack/react-query'
import type { RegionSummary } from '@packages/shared'
import { clearLocalCart } from '@/hooks/cart-query-hooks'
import { clearLocalCart, restoreRegionCarts, stashRegionCarts } from '@/hooks/cart-query-hooks'
import { useRegionStore } from '@/src/store/regionStore'
import { useCartStore } from '@/src/store/cartStore'
import { useFlashCartStore } from '@/src/store/flashCartStore'
@ -15,9 +15,10 @@ import { useFlashNavigationStore } from '@/components/stores/flashNavigationStor
* The one and only way to change the browsing region.
*
* Manual switching (RegionSelector) and the checkout address flow both call
* this so the reset behaviour can never drift. It clears every cart variant,
* drops derived checkout selections, persists the new region and invalidates
* region-scoped react-query caches.
* this so the reset behaviour can never drift. Each region keeps its own cart:
* the carts are snapshotted (product + slot + quantity) for the region being left
* and restored when that region is switched back to. Everything else is cleared
* and the region-scoped react-query caches are invalidated.
*
* NOTE: callers must obtain a user confirmation before invoking this.
*/
@ -26,8 +27,19 @@ export async function confirmRegionSwitch(
queryClient: QueryClient,
boundId?: number | null,
): Promise<void> {
// 1. Clear the persisted local carts (regular + flash).
await Promise.all([clearLocalCart('regular'), clearLocalCart('flash')])
// Switching to the region we are already in must not wipe the carts.
const previousRegionId = useRegionStore.getState().selectedRegionId
const isSameRegion = previousRegionId === region.id
if (!isSameRegion) {
// 1a. Remember the outgoing region's carts so switching back restores them.
if (previousRegionId != null) {
await stashRegionCarts(previousRegionId)
}
// 1b. Clear the persisted local carts (regular + flash).
await Promise.all([clearLocalCart('regular'), clearLocalCart('flash')])
}
// 2. Drop in-memory checkout / quick-delivery selections.
useQuickDeliveryStore.getState().setSelectedSlotId(null)
@ -56,6 +68,11 @@ export async function confirmRegionSwitch(
// 4. Persist the new browsing region (and its bound).
useRegionStore.getState().setRegion(region, boundId ?? region.effectiveBoundId ?? null)
// 4b. Bring back this region's carts if it has been visited before.
if (!isSameRegion) {
await restoreRegionCarts(region.id)
}
// 5. Refetch everything now scoped to the new region.
await queryClient.invalidateQueries()
}

View file

@ -1,5 +1,6 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import type { CartData as SharedCartData } from '@packages/shared'
import { StorageServiceCasual } from 'web-components'
type CartType = 'regular' | 'flash'
@ -144,3 +145,83 @@ export function useRemoveFromCart(cartType: CartType = 'regular') {
export function clearLocalCart(cartType: CartType = 'regular') {
localStorage.removeItem(getCartKey(cartType))
}
/* -------------------------------------------------------------------------- *
* Per-region cart snapshots
*
* A region switch clears both carts, so the outgoing region's carts are
* remembered first and restored when that region is switched back to. Only the
* product, its chosen slot, the quantity and the slot's delivery time are kept -
* a store id is not (nothing reads it).
* -------------------------------------------------------------------------- */
interface StashedCartItem {
skuId: number
slotId: number | null
quantity: number
deliveryDate: string | null
}
type StashedCarts = Record<CartType, StashedCartItem[]>
const CART_TYPES: CartType[] = ['regular', 'flash']
const getRegionCartStorageKey = (regionId: number): string => `region_carts_${regionId}`
const emptyStashedCarts = (): StashedCarts => ({ regular: [], flash: [] })
async function readStashedCarts(regionId: number): Promise<StashedCarts> {
const raw = await StorageServiceCasual.getItem(getRegionCartStorageKey(regionId))
if (!raw) return emptyStashedCarts()
try {
const parsed = JSON.parse(raw) as Partial<StashedCarts>
return { regular: parsed?.regular ?? [], flash: parsed?.flash ?? [] }
} catch {
return emptyStashedCarts()
}
}
/** Remember a region's carts before a switch clears them. */
export async function stashRegionCarts(regionId: number): Promise<void> {
const stashed = await readStashedCarts(regionId)
for (const cartType of CART_TYPES) {
stashed[cartType] = readCart(cartType).map((item) => ({
skuId: item.skuId,
slotId: item.slotId ?? null,
quantity: item.quantity,
deliveryDate: item.deliveryDate ?? null,
}))
}
await StorageServiceCasual.setItem(getRegionCartStorageKey(regionId), JSON.stringify(stashed))
}
/**
* Rebuild a region's carts from its snapshot. Item ids are re-issued (the cart
* keys rows by item.id). A region that was never visited restores to empty; a
* snapshot written before quantities were kept restores those lines at 1.
*/
export async function restoreRegionCarts(regionId: number): Promise<void> {
const stashed = await readStashedCarts(regionId)
for (const cartType of CART_TYPES) {
const idBase = Date.now()
const items: CartItem[] = stashed[cartType].map((stashedItem, index) => ({
id: idBase + index,
skuId: stashedItem.skuId,
quantity:
Number.isFinite(stashedItem.quantity) && stashedItem.quantity > 0
? stashedItem.quantity
: 1,
// Not part of the snapshot - nothing reads it.
storeId: null,
addedAt: Date.now(),
slotId: stashedItem.slotId ?? null,
deliveryDate: stashedItem.deliveryDate ?? null,
}))
writeCart(cartType, items)
}
}

View file

@ -1,6 +1,6 @@
import type { QueryClient } from '@tanstack/react-query'
import type { RegionSummary } from '@packages/shared'
import { clearLocalCart } from '../hooks/cart-query-hooks'
import { clearLocalCart, restoreRegionCarts, stashRegionCarts } from '../hooks/cart-query-hooks'
import { useRegionStore } from './stores/region-store'
import { useCartStore } from './stores/cart-store'
import { useFlashCartStore } from './stores/flash-cart-store'
@ -15,9 +15,10 @@ import { useFlashNavigationStore } from './stores/flash-navigation-store'
* The one and only way to change the browsing region.
*
* Manual switching (RegionSelector) and the checkout address flow both call
* this so the reset behaviour can never drift. It clears every cart variant,
* drops derived checkout selections, persists the new region and invalidates
* region-scoped react-query caches.
* this so the reset behaviour can never drift. Each region keeps its own carts:
* they are snapshotted for the region being left and restored when that region
* is switched back to. Everything else is cleared and the region-scoped
* react-query caches are invalidated.
*
* NOTE: callers must obtain a user confirmation before invoking this.
*/
@ -25,9 +26,20 @@ export async function confirmRegionSwitch(
region: RegionSummary,
queryClient: QueryClient
): Promise<void> {
// 1. Clear the persisted local carts (regular + flash).
clearLocalCart('regular')
clearLocalCart('flash')
// Switching to the region we are already in must not wipe the carts.
const previousRegionId = useRegionStore.getState().selectedRegionId
const isSameRegion = previousRegionId === region.id
if (!isSameRegion) {
// 1a. Remember the outgoing region's carts so switching back restores them.
if (previousRegionId != null) {
await stashRegionCarts(previousRegionId)
}
// 1b. Clear the persisted local carts (regular + flash).
clearLocalCart('regular')
clearLocalCart('flash')
}
// 2. Drop in-memory checkout / quick-delivery selections.
useQuickDeliveryStore.getState().setSelectedSlotId(null)
@ -59,6 +71,11 @@ export async function confirmRegionSwitch(
// 4. Persist the new browsing region.
useRegionStore.getState().setRegion(region)
// 4b. Bring back this region's carts if it has been visited before.
if (!isSameRegion) {
await restoreRegionCarts(region.id)
}
// 5. Refetch everything now scoped to the new region.
await queryClient.invalidateQueries()
}

View file

@ -4551,6 +4551,32 @@ user-ui
Not done (needs a switch / not asked): tests. tests/helpers/consts.ts setConst routes through
updateConstants, which ignores bound-scope keys, so the flash tests and the admin-ui
customize-app-hub test need a bound-settings setter / tab move. No tests run.
2026-10-15 20:37:41 Keep each region's cart across a region switch (user-ui).
A region switch clears the carts (confirmRegionSwitch step 1). Now the outgoing region's
carts are remembered first and restored when that region is switched back to.
apps/user-ui/hooks/cart-query-hooks.tsx
- + StashedCartItem { skuId, slotId } and one storage key per region
(`region_carts_<regionId>`, holding { regular, flash }), read through the same
StorageServiceCasual the cart already uses.
- + stashRegionCarts(regionId): snapshot both carts as product + slot only.
- + restoreRegionCarts(regionId): rebuild both carts from the snapshot. Quantity is not
part of the snapshot, so restored lines start at 1; ids are re-issued from the local
counter; a never-visited region restores to empty.
- exported alongside clearLocalCart.
apps/user-ui/src/lib/region-switch.ts
- captures the region being left, stashes its carts, clears, sets the new region, then
restores that region's carts before the final invalidateQueries (which refetches the
local-cart queries).
- switching to the SAME region no longer wipes the cart: stash/clear/restore are skipped.
Note: storage goes through common-ui/src/services/StorageServiceCasual (the service the cart
already uses: SecureStore on device, localStorage + `web_` prefix on web). The attached
packages/web-components/src/services/storage-service-casual.ts is the web-only twin (plain
localStorage) and is not importable from the native app; same API. web-ui's region-switch is
untouched - say the word and I'll mirror this there with that exact service.
No tests run.
- Coupon stacking: switched multiple coupons from parallel (each on the full
eligible base) to a sequential waterfall applied in the order the user selected
them, each rounded to the nearest rupee. Files:
@ -4660,3 +4686,51 @@ user-ui
locally without it). File:
/private/var/folders/6t/3blzq7_j6p95xzry6t7c14hw0000gn/T/opencode/add_complaints_region.sql
(ALTER TABLE complaints ADD COLUMN region_id + backfill + idx_complaints_region).
2026-10-15 20:40:39 Region cart snapshot also keeps the quantity.
apps/user-ui/hooks/cart-query-hooks.tsx
- StashedCartItem gains `quantity`; stashRegionCarts stores item.quantity;
restoreRegionCarts restores it (falls back to 1 for snapshots written before this
and for any non-positive/non-finite value), so restored lines come back at their
old quantity instead of always 1.
- comments updated (the snapshot is now product + slot + quantity).
apps/user-ui/src/lib/region-switch.ts
- doc comment updated to match.
No other file changed. No tests run.
2026-10-15 20:43:45 Region cart snapshots in web-ui too (apps/web-ui).
Same behaviour as user-ui: a region switch remembers the outgoing region's carts and restores
them when that region is switched back to.
apps/web-ui/src/hooks/cart-query-hooks.ts
- + StashedCartItem { skuId, slotId, quantity, deliveryDate } and one key per region
(`region_carts_<regionId>`, holding { regular, flash }), read/written through
StorageServiceCasual from 'web-components' (the localStorage service web-ui already
imports from that package).
- + stashRegionCarts(regionId) / restoreRegionCarts(regionId), exported next to
clearLocalCart.
- restore re-issues item ids (Date.now() + index) because FloatingCartBar keys rows by
item.id and uses it for the quantity map; storeId is NOT stored (nothing reads it, per
your call) so it restores as null.
- deliveryDate IS stored, unlike storeId: FloatingCartBar renders item.deliveryDate, so
dropping it would show a bogus time. Say the word to drop it.
- quantity falls back to 1 for a snapshot written before this and for invalid values.
apps/web-ui/src/lib/region-switch.ts
- captures the region being left, stashes, clears, sets the new region, restores, then
invalidates. Switching to the SAME region no longer wipes the cart.
No other file changed. No tests run.
2026-10-15 20:51:17 First address-selection page (LocationFallbackFlow): make the address list
scroll and keep the Login button pinned.
apps/user-ui/src/components/location/LocationFallbackFlow.tsx
- the address list + "Add a new address" now live in a `flex-1` wrapper whose ScrollView is
the ONLY flexible child, so the list owns the remaining height and scrolls instead of
pushing the footer off-screen.
- the address-loading spinner moved INSIDE that scroll area (it used to be a sibling with
`flex-1`, which split the page with the ScrollView and left the list half-height).
- the Login footer is now rendered whenever the user is not signed in (dropped the
`&& !isAuthLoading` guard), so the button is present while auth settles too.
No other file changed. No tests run.