From a83430eb75e472737d133f032baacf4fc07dc2d5 Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Tue, 20 Oct 2026 19:15:58 +0530 Subject: [PATCH] enh --- .../components/order-options-menu.test.tsx | 14 ++ apps/backend/src/sqliteImporter.ts | 1 + apps/backend/tests/api/admin-order.test.ts | 6 + apps/backend/tests/unit/order-coords.test.ts | 49 +++++ apps/user-ui/JEST-TEST-CASES.md | 4 + apps/user-ui/components/NextOrderGlimpse.tsx | 3 + apps/user-ui/src/hooks/useRegion.ts | 203 +++++++++++++++++- apps/user-ui/src/lib/region-cache.ts | 99 +++++++++ apps/user-ui/tests/lib/order-glimpse.test.ts | 82 +++++++ apps/user-ui/tests/lib/use-region.test.tsx | 99 +++++++++ apps/user-ui/tests/pages/home.test.tsx | 68 ++++++ apps/web-ui/src/components/RegionGate.tsx | 66 +++++- .../src/components/me/NextOrderGlimpse.tsx | 3 + apps/web-ui/src/lib/region-cache.ts | 101 +++++++++ change-log.txt | 80 +++++++ packages/db_helper_sqlite/index.ts | 1 + .../db_helper_sqlite/src/admin-apis/order.ts | 42 +++- packages/shared/index.ts | 2 + packages/shared/order-glimpse.ts | 57 +++++ 19 files changed, 967 insertions(+), 13 deletions(-) create mode 100644 apps/backend/tests/unit/order-coords.test.ts create mode 100644 apps/user-ui/src/lib/region-cache.ts create mode 100644 apps/user-ui/tests/lib/order-glimpse.test.ts create mode 100644 apps/web-ui/src/lib/region-cache.ts create mode 100644 packages/shared/order-glimpse.ts diff --git a/apps/admin-ui/tests/components/order-options-menu.test.tsx b/apps/admin-ui/tests/components/order-options-menu.test.tsx index 112ace8..0de7250 100644 --- a/apps/admin-ui/tests/components/order-options-menu.test.tsx +++ b/apps/admin-ui/tests/components/order-options-menu.test.tsx @@ -189,4 +189,18 @@ describe('OrderOptionsMenu (AOPT-01..07, AOO-01..03)', () => { view.getByTestId('order-menu-attach-location').props.accessibilityState?.disabled, ).toBe(true) }) + + it('shows Open in Maps when real coordinates are present', () => { + const { view } = renderMenu() + + expect(view.getByText('Open in Maps')).toBeTruthy() + }) + + it('hides Open in Maps when the backend omits coordinates (seeded address)', () => { + const { view } = renderMenu({ + order: { ...ORDER, latitude: null, longitude: null }, + }) + + expect(view.queryByText('Open in Maps')).toBeNull() + }) }) diff --git a/apps/backend/src/sqliteImporter.ts b/apps/backend/src/sqliteImporter.ts index 41d962c..a9dd58e 100644 --- a/apps/backend/src/sqliteImporter.ts +++ b/apps/backend/src/sqliteImporter.ts @@ -52,6 +52,7 @@ export { getSlotOrders, updateAddressCoords, getAllOrders, + orderCoords, rebalanceSlots, cancelOrder, deleteOrderById, diff --git a/apps/backend/tests/api/admin-order.test.ts b/apps/backend/tests/api/admin-order.test.ts index a96046d..695e70d 100644 --- a/apps/backend/tests/api/admin-order.test.ts +++ b/apps/backend/tests/api/admin-order.test.ts @@ -534,6 +534,12 @@ describe('admin.order.updateAddressCoords (AORD-26..28)', () => { const row = slotOrders.data.find((o: any) => o.id === orderId) expect(row.latitude).toBe(16.75) expect(row.longitude).toBe(78.02) + + // Attaching real coordinates clears the migration-seeded flag so a later + // order read exposes the admin coordinates instead of omitting them. + const addresses: any = await apiClient(fx.user.token).user.address.getUserAddresses.query() + const addressRow = addresses.data.find((a: any) => a.id === fx.address.id) + expect(addressRow.vagueBackfilledCoords).toBe(false) }) it('AORD-27: an unknown address is NOT_FOUND 404', async () => { diff --git a/apps/backend/tests/unit/order-coords.test.ts b/apps/backend/tests/unit/order-coords.test.ts new file mode 100644 index 0000000..1c2f9e9 --- /dev/null +++ b/apps/backend/tests/unit/order-coords.test.ts @@ -0,0 +1,49 @@ +/** + * Unit tests for `orderCoords`, the gate that keeps migration-seeded address + * coordinates out of the admin order APIs. + * + * `addresses.vague_backfilled_coords = true` means the latitude/longitude are + * the region centre written by the 0006 backfill, not a real delivery location. + * The admin UIs hide "Open in Maps" when coordinates are null, so the backend + * simply omits them. + */ +import { orderCoords } from '@/src/dbService' + +const base = { + latitude: 16.7, + longitude: 78.0, + adminLatitude: null, + adminLongitude: null, + vagueBackfilledCoords: false, +} + +describe('orderCoords', () => { + it('omits the migration-seeded centre when there are no admin coordinates', () => { + expect(orderCoords({ ...base, vagueBackfilledCoords: true })).toEqual({ + latitude: null, + longitude: null, + }) + }) + + it('prefers admin coordinates even when a legacy row still has the seeded flag', () => { + expect( + orderCoords({ + ...base, + vagueBackfilledCoords: true, + adminLatitude: 16.75, + adminLongitude: 78.02, + }) + ).toEqual({ latitude: 16.75, longitude: 78.02 }) + }) + + it('returns real customer coordinates when the address is not seeded', () => { + expect(orderCoords(base)).toEqual({ latitude: 16.7, longitude: 78.0 }) + }) + + it('returns nulls when the address has no coordinates at all', () => { + expect(orderCoords({ ...base, latitude: null, longitude: null })).toEqual({ + latitude: null, + longitude: null, + }) + }) +}) diff --git a/apps/user-ui/JEST-TEST-CASES.md b/apps/user-ui/JEST-TEST-CASES.md index bbfc715..eb8b38d 100644 --- a/apps/user-ui/JEST-TEST-CASES.md +++ b/apps/user-ui/JEST-TEST-CASES.md @@ -1470,6 +1470,10 @@ Covered by HOME-81..98, plus: | REGION-20 | edge | one non-default address, location elsewhere | sole address still wins | | REGION-21 | integration | sole non-default address, location off | Home opens its region; only its cache is fetched | | REGION-22 | integration | sole non-default address, location elsewhere | Home still opens the sole address's region | +| REGION-23 | edge | login after the gate settled | sole address still auto-opens | +| REGION-24 | edge | address list response held | startup waits for it | +| REGION-25 | edge | cached regions + address, live pending | starts from cache; live requests still run | +| REGION-26 | edge | live data differs from cache | region/bound/address reconcile to live | | LOCSTORE-01 | happy | start once | one permission/fix; second start no-op | | LOCSTORE-02 | error | denied | status denied, coords null | | LOCSTORE-03 | edge | services off | status services-off | diff --git a/apps/user-ui/components/NextOrderGlimpse.tsx b/apps/user-ui/components/NextOrderGlimpse.tsx index aee718c..099341b 100644 --- a/apps/user-ui/components/NextOrderGlimpse.tsx +++ b/apps/user-ui/components/NextOrderGlimpse.tsx @@ -1,5 +1,6 @@ import React, { useState, useCallback, useRef } from 'react'; import type { OrderCardActionProps } from '@packages/shared' +import { isInNextOrderGlimpseWindow } from '@packages/shared' import { View, TouchableOpacity, ActivityIndicator, Linking, ScrollView, Dimensions, NativeSyntheticEvent, NativeScrollEvent } from 'react-native'; import { useRouter } from 'expo-router'; import { tw, MyText } from 'common-ui'; @@ -137,6 +138,8 @@ export default function NextOrderGlimpse() { const upcomingOrders = allOrders.filter(order => { if (order.orderStatus.toLowerCase() === 'cancelled') return false; if (order.deliveryStatus.toLowerCase() === 'success') return false; + // Only keep deliveries that are upcoming or at most 24h old. + if (!isInNextOrderGlimpseWindow(order)) return false; return true; }); diff --git a/apps/user-ui/src/hooks/useRegion.ts b/apps/user-ui/src/hooks/useRegion.ts index 2193814..765ccb2 100644 --- a/apps/user-ui/src/hooks/useRegion.ts +++ b/apps/user-ui/src/hooks/useRegion.ts @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { useQueryClient } from '@tanstack/react-query' import type { RegionSummary, RegionBoundSummary } from '@packages/shared' import { useRegionStore } from '@/src/store/regionStore' @@ -6,6 +6,13 @@ import { useAddressStore } from '@/src/store/addressStore' import { useLocationStore } from '@/src/store/locationStore' import { trpc } from '@/src/trpc-client' import { confirmRegionSwitch } from '@/src/lib/region-switch' +import { + readCachedRegions, + readCachedUserAddresses, + writeCachedRegions, + writeCachedUserAddresses, + type CachedUserAddressesResponse, +} from '@/src/lib/region-cache' import { useAuthOptional } from '@/src/contexts/AuthContext' // Give up on the backend resolve and fall back to the saved region / chooser. @@ -70,9 +77,11 @@ export interface UseRegionResult { export function useRegion(): UseRegionResult { const queryClient = useQueryClient() + const utils = trpc.useUtils() const auth = useAuthOptional() const isAuthenticated = auth?.isAuthenticated ?? false const isAuthLoading = auth?.isLoading ?? false + const userId = auth?.user?.id ?? null const region = useRegionStore((state) => state.selectedRegion) const regionId = useRegionStore((state) => state.selectedRegionId) @@ -92,12 +101,24 @@ export function useRegion(): UseRegionResult { // True once the launch location check has a definitive outcome. const [startupResolved, setStartupResolved] = useState(false) + // Last persisted startup responses. These are only the seed: the live tRPC + // queries below always run and replace them (and the storage snapshot). + const [cacheSnapshot, setCacheSnapshot] = useState<{ + ready: boolean + regions: RegionSummary[] | null + addresses: CachedUserAddressesResponse | null + }>({ ready: false, regions: null, addresses: null }) + const cacheBaselineRef = useRef<{ + regions: RegionSummary[] | null + addresses: CachedUserAddressesResponse | null + } | null>(null) + const decisionSignatureRef = useRef(null) + // The user's default address — the anchor for the startup region decision. const defaultAddressQuery = trpc.user.address.getDefaultAddress.useQuery(undefined, { enabled: hydrated && isAuthenticated, staleTime: 60000, }) - const defaultAddress = defaultAddressQuery.data?.data ?? null // A sole address is a valid anchor even when it is not flagged as default. // Query the list only for signed-in users; the result is shared with the @@ -106,7 +127,51 @@ export function useRegion(): UseRegionResult { enabled: hydrated && isAuthenticated, staleTime: 60000, }) - const addresses = addressesQuery.data?.data ?? null + + // Load the last snapshots before the launch decision runs. Seeding React + // Query makes the cached values available to every consumer of the same + // query; updatedAt: 0 keeps the entry stale so the live request still fires. + useEffect(() => { + let cancelled = false + setCacheSnapshot({ ready: false, regions: null, addresses: null }) + + void (async () => { + const cachedRegions = await readCachedRegions() + const cachedAddresses = + isAuthenticated && userId != null + ? await readCachedUserAddresses(userId) + : null + if (cancelled) return + + cacheBaselineRef.current = { regions: cachedRegions, addresses: cachedAddresses } + setCacheSnapshot({ ready: true, regions: cachedRegions, addresses: cachedAddresses }) + + if (cachedRegions && utils.common.listRegions.getData(undefined) === undefined) { + utils.common.listRegions.setData(undefined, cachedRegions, { updatedAt: 0 }) + } + if ( + cachedAddresses && + userId != null && + utils.user.address.getUserAddresses.getData(undefined) === undefined + ) { + utils.user.address.getUserAddresses.setData(undefined, cachedAddresses as any, { + updatedAt: 0, + }) + } + })() + + return () => { + cancelled = true + } + }, [isAuthenticated, userId, utils]) + + const addresses = addressesQuery.data?.data ?? cacheSnapshot.addresses?.data ?? null + const cachedDefaultAddress = + cacheSnapshot.addresses?.data.find((address) => address.isDefault) ?? null + const defaultAddress = + defaultAddressQuery.data !== undefined + ? defaultAddressQuery.data.data ?? null + : cachedDefaultAddress const soleAddress = !defaultAddress && addresses?.length === 1 ? addresses[0] : null @@ -116,7 +181,40 @@ export function useRegion(): UseRegionResult { enabled: hydrated, staleTime: 60000, }) - const regions = regionsQuery.data ?? null + const regions = regionsQuery.data ?? cacheSnapshot.regions ?? null + + // Signature of the data the launch decision is based on. Used to notice when + // the background response differs from the cached snapshot and re-reconcile. + const regionDataSignature = useMemo( + () => + JSON.stringify({ + regions: (regions ?? []).map((region) => [ + region.id, + region.name, + region.description, + region.effectiveBoundId, + ]), + addresses: (addresses ?? []).map((address) => [ + address.id, + address.regionId, + address.boundId, + address.isDefault, + ]), + }), + [regions, addresses] + ) + + // Persist live responses. The cache writer de-duplicates identical payloads, + // so the many useRegion observers do not rewrite the same snapshot. + useEffect(() => { + if (!regionsQuery.data) return + void writeCachedRegions(regionsQuery.data) + }, [regionsQuery.data]) + + useEffect(() => { + if (userId == null || !addressesQuery.data) return + void writeCachedUserAddresses(userId, addressesQuery.data) + }, [userId, addressesQuery.data]) // Active bound = the least-priority bound among the user's addresses in the // region, else the region's effective bound. Derived server-side (the client @@ -187,17 +285,35 @@ export function useRegion(): UseRegionResult { // reconsider). if (isAuthLoading) return + // Wait for the persisted snapshots to be read before deciding. + if (!cacheSnapshot.ready) return + // Signed-in users: wait for the default address and the address list (+ // regions) so a sole address can anchor the decision before we settle. // `isFetched` matters here: a query that just flipped from disabled (auth // was still loading) can report `isLoading: false` for one render before its // first request starts, which would make us settle with no addresses. + // A cached snapshot is already usable while the live request is in flight. if (isAuthenticated) { - if (!defaultAddressQuery.isFetched && !defaultAddressQuery.isError) return - if (!defaultAddress && !addressesQuery.isFetched && !addressesQuery.isError) return + const cachedAddressesAvailable = cacheSnapshot.addresses != null + if ( + !defaultAddressQuery.isFetched && + !defaultAddressQuery.isError && + !cachedAddressesAvailable + ) { + return + } + if ( + !addressesQuery.isFetched && + !addressesQuery.isError && + !cachedAddressesAvailable + ) { + return + } if ((defaultAddress?.regionId ?? soleAddress?.regionId) != null && !regions) return } + decisionSignatureRef.current = regionDataSignature setStartupResolved(true) // Only one consumer performs the switch; the rest just settle their spinner. @@ -277,6 +393,8 @@ export function useRegion(): UseRegionResult { queryClient, isAuthenticated, isAuthLoading, + cacheSnapshot.ready, + cacheSnapshot.addresses, defaultAddressQuery.isFetched, defaultAddressQuery.isError, addressesQuery.isFetched, @@ -284,6 +402,79 @@ export function useRegion(): UseRegionResult { defaultAddress, soleAddress, regions, + regionDataSignature, + ]) + + // Reconcile the cached view with the live responses. The launch decision is + // one-shot, so if it ran on the persisted snapshot we re-arm it once when the + // background fetch shows different addresses/regions. This never fires for a + // normal (cache-less) launch: the decision already waited for live data. + useEffect(() => { + if (!startupResolved) return + const baseline = cacheBaselineRef.current + if (!baseline) return + + const regionsLive = regionsQuery.dataUpdatedAt > 0 || regionsQuery.isError + const addressesLive = !isAuthenticated || addressesQuery.dataUpdatedAt > 0 || addressesQuery.isError + if (!regionsLive || !addressesLive) return + + cacheBaselineRef.current = null + + const baselineRegionsSignature = JSON.stringify( + (baseline.regions ?? []).map((region) => [ + region.id, + region.name, + region.description, + region.effectiveBoundId, + ]) + ) + const baselineAddressesSignature = JSON.stringify( + (baseline.addresses?.data ?? []).map((address) => [ + address.id, + address.regionId, + address.boundId, + address.isDefault, + ]) + ) + const liveRegionsSignature = JSON.stringify( + (regions ?? []).map((region) => [ + region.id, + region.name, + region.description, + region.effectiveBoundId, + ]) + ) + const liveAddressesSignature = JSON.stringify( + (addresses ?? []).map((address) => [ + address.id, + address.regionId, + address.boundId, + address.isDefault, + ]) + ) + + const regionsChanged = + baseline.regions != null && liveRegionsSignature !== baselineRegionsSignature + const addressesChanged = + baseline.addresses != null && liveAddressesSignature !== baselineAddressesSignature + if (!regionsChanged && !addressesChanged) return + + // Allow the re-run to apply the live anchor even though a region is already + // selected from cache. Only `startupLaunchRegionId === regionId` makes the + // decision treat the current region as launch state rather than a manual pick. + startupLaunchRegionId = regionId + startupCheckDone = false + setStartupResolved(false) + }, [ + startupResolved, + regionsQuery.dataUpdatedAt, + regionsQuery.isError, + addressesQuery.dataUpdatedAt, + addressesQuery.isError, + isAuthenticated, + regionId, + regions, + addresses, ]) // Sole-address safety net. The launch decision above runs once per app launch diff --git a/apps/user-ui/src/lib/region-cache.ts b/apps/user-ui/src/lib/region-cache.ts new file mode 100644 index 0000000..1198591 --- /dev/null +++ b/apps/user-ui/src/lib/region-cache.ts @@ -0,0 +1,99 @@ +import { StorageServiceCasual } from 'common-ui' +import type { RegionSummary } from '@packages/shared' + +/** + * Only the fields the startup decision reads. The live query's serialized + * address has `createdAt` as a string, so this is deliberately not the shared + * `UserAddress` DTO (which types it as Date). + */ +export interface CachedUserAddress { + id: number + regionId: number | null + boundId: number | null + isDefault: boolean + [key: string]: unknown +} + +export interface CachedUserAddressesResponse { + success: boolean + data: CachedUserAddress[] +} + +/** + * Small, user-scoped snapshots of the two responses that decide where the app + * starts: + * - the global region list (`common.listRegions`) + * - the signed-in user's addresses (`user.address.getUserAddresses`) + * + * They are only a startup seed. The live tRPC queries always run in the + * background and overwrite both the React Query cache and these snapshots. + */ +export const REGION_LIST_CACHE_KEY = 'region_cache:list_regions:v1' +export const userAddressesCacheKey = (userId: number) => + `region_cache:user_addresses:v1:${userId}` + +let lastWrittenRegions: string | null = null +const lastWrittenAddresses = new Map() + +function parseJson(raw: string | null): unknown { + if (!raw) return null + try { + return JSON.parse(raw) + } catch { + return null + } +} + +export async function readCachedRegions(): Promise { + const parsed = parseJson(await StorageServiceCasual.getItem(REGION_LIST_CACHE_KEY)) + if ( + !Array.isArray(parsed) || + !parsed.every( + (region) => + region != null && + typeof region === 'object' && + typeof (region as RegionSummary).id === 'number' + ) + ) { + return null + } + return parsed as RegionSummary[] +} + +export async function writeCachedRegions(regions: RegionSummary[]): Promise { + const serialized = JSON.stringify(regions) + // useRegion is consumed by several components; only the first observer needs + // to write the same response. + if (serialized === lastWrittenRegions) return + const stored = await StorageServiceCasual.setItem(REGION_LIST_CACHE_KEY, serialized) + if (stored) lastWrittenRegions = serialized +} + +export async function readCachedUserAddresses( + userId: number +): Promise { + const parsed = parseJson(await StorageServiceCasual.getItem(userAddressesCacheKey(userId))) + if (parsed == null || typeof parsed !== 'object') return null + const response = parsed as Partial + const valid = + response.success === true && + Array.isArray(response.data) && + response.data.every( + (address) => + address != null && + typeof address === 'object' && + typeof address.id === 'number' && + typeof address.isDefault === 'boolean' + ) + return valid ? (response as CachedUserAddressesResponse) : null +} + +export async function writeCachedUserAddresses( + userId: number, + response: CachedUserAddressesResponse +): Promise { + const serialized = JSON.stringify(response) + if (serialized === lastWrittenAddresses.get(userId)) return + const stored = await StorageServiceCasual.setItem(userAddressesCacheKey(userId), serialized) + if (stored) lastWrittenAddresses.set(userId, serialized) +} diff --git a/apps/user-ui/tests/lib/order-glimpse.test.ts b/apps/user-ui/tests/lib/order-glimpse.test.ts new file mode 100644 index 0000000..a166458 --- /dev/null +++ b/apps/user-ui/tests/lib/order-glimpse.test.ts @@ -0,0 +1,82 @@ +/** + * Unit tests for the next-order glimpse visibility window. + * + * The glimpse keeps future deliveries and deliveries up to 24 hours old; + * everything older belongs to My Orders, not the Home/Me glimpse. + */ +import { + FLASH_DELIVERY_MINUTES, + NEXT_ORDER_GLIMPSE_LOOKBACK_HOURS, + isInNextOrderGlimpseWindow, +} from '@packages/shared' + +const NOW = new Date('2026-10-20T12:00:00.000Z') +const HOUR = 60 * 60 * 1000 +const iso = (offsetMs: number) => new Date(NOW.getTime() + offsetMs).toISOString() + +function order( + over: Partial<{ + isFlashDelivery: boolean + deliveryDate: string | null + createdAt: string + }> = {} +) { + return { + isFlashDelivery: false, + deliveryDate: iso(2 * HOUR), + createdAt: iso(-HOUR), + ...over, + } +} + +describe('isInNextOrderGlimpseWindow', () => { + it('keeps a future delivery', () => { + expect(isInNextOrderGlimpseWindow(order(), NOW)).toBe(true) + }) + + it('keeps a delivery within the 24-hour lookback', () => { + expect( + isInNextOrderGlimpseWindow(order({ deliveryDate: iso(-23 * HOUR) }), NOW) + ).toBe(true) + }) + + it('keeps a delivery exactly at the lookback boundary', () => { + expect( + isInNextOrderGlimpseWindow( + order({ deliveryDate: iso(-NEXT_ORDER_GLIMPSE_LOOKBACK_HOURS * HOUR) }), + NOW + ) + ).toBe(true) + }) + + it('drops a delivery older than the lookback', () => { + expect( + isInNextOrderGlimpseWindow( + order({ deliveryDate: iso(-(NEXT_ORDER_GLIMPSE_LOOKBACK_HOURS * HOUR + 1)) }), + NOW + ) + ).toBe(false) + }) + + it('drops a scheduled order with no delivery date', () => { + expect(isInNextOrderGlimpseWindow(order({ deliveryDate: null }), NOW)).toBe(false) + }) + + it('uses createdAt + 30 minutes for a flash order with no delivery date', () => { + const recent = order({ + isFlashDelivery: true, + deliveryDate: null, + createdAt: iso(-HOUR), + }) + const old = order({ + isFlashDelivery: true, + deliveryDate: null, + createdAt: iso(-(NEXT_ORDER_GLIMPSE_LOOKBACK_HOURS + 1) * HOUR), + }) + + expect(isInNextOrderGlimpseWindow(recent, NOW)).toBe(true) + expect(isInNextOrderGlimpseWindow(old, NOW)).toBe(false) + // The fallback really is the flash promise, not an arbitrary window. + expect(FLASH_DELIVERY_MINUTES).toBe(30) + }) +}) diff --git a/apps/user-ui/tests/lib/use-region.test.tsx b/apps/user-ui/tests/lib/use-region.test.tsx index ad50e87..0d99357 100644 --- a/apps/user-ui/tests/lib/use-region.test.tsx +++ b/apps/user-ui/tests/lib/use-region.test.tsx @@ -51,6 +51,7 @@ async function withFreshModules(fn: (ctx: any) => Promise) { fetchJson: require('../mocks/fetch-json'), regionStore: require('@/src/store/regionStore').useRegionStore, addressStore: require('@/src/store/addressStore').useAddressStore, + regionCache: require('@/src/lib/region-cache'), locationStore: require('@/src/store/locationStore').useLocationStore, useRegion: require('@/src/hooks/useRegion').useRegion, } @@ -539,6 +540,104 @@ describe('useRegion', () => { } }) }) + + it('REGION-25: cached regions and address open while live requests are pending', async () => { + await withFreshModules(async (ctx) => { + const { REGION_1, REGION_2, A1 } = ctx.fixtures + const sole = { ...A1, isDefault: false } + ctx.auth.__setAuthState({ + isAuthenticated: true, + isLoading: false, + user: { id: 77 }, + }) + ctx.locationMock.__configure({ permission: 'denied' }) + ctx.trpc.setProcedure('common.listRegions', { mode: 'pending' }) + ctx.trpc.setProcedure('user.address.getDefaultAddress', { mode: 'pending' }) + ctx.trpc.setProcedure('user.address.getUserAddresses', { mode: 'pending' }) + + ctx.secure.__set( + ctx.regionCache.REGION_LIST_CACHE_KEY, + JSON.stringify([REGION_1, REGION_2]) + ) + ctx.secure.__set( + ctx.regionCache.userAddressesCacheKey(77), + JSON.stringify({ success: true, data: [sole] }) + ) + + const { result, view } = ctx.renderRegion() + await ctx.testUtils.flush(6) + + expect(result.current.regionId).toBe(1) + expect(result.current.boundId).toBe(7) + expect(ctx.addressStore.getState().selectedAddressId).toBe(sole.id) + // Cached data must not stop the background refresh. + expect(ctx.trpc.procedureQueryCalls('common.listRegions').length).toBeGreaterThan(0) + expect(ctx.trpc.procedureQueryCalls('user.address.getUserAddresses').length).toBeGreaterThan(0) + view.unmount() + }) + }) + + it('REGION-26: live data that differs from the cache reconciles region and address', async () => { + await withFreshModules(async (ctx) => { + const { REGION_1, REGION_2, A1, A2 } = ctx.fixtures + const cachedSole = { ...A1, isDefault: false } + const liveSole = { ...A2, isDefault: false } + ctx.auth.__setAuthState({ + isAuthenticated: true, + isLoading: false, + user: { id: 88 }, + }) + ctx.locationMock.__configure({ permission: 'denied' }) + ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] }) + ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } }) + ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [liveSole] } }) + + ctx.secure.__set( + ctx.regionCache.REGION_LIST_CACHE_KEY, + JSON.stringify([REGION_1, REGION_2]) + ) + ctx.secure.__set( + ctx.regionCache.userAddressesCacheKey(88), + JSON.stringify({ success: true, data: [cachedSole] }) + ) + + // Hold the live address response so the cached snapshot settles first. + const networkMock = (global as any).fetch + let releaseAddresses!: () => void + const addressesGate = new Promise((resolve) => { + releaseAddresses = resolve + }) + ;(global as any).fetch = jest.fn(async (input: any, init: any) => { + const response = await networkMock(input, init) + if (String(input).includes('user.address.getUserAddresses')) await addressesGate + return response + }) + + try { + const { result, view } = ctx.renderRegion() + await ctx.testUtils.flush(6) + + expect(result.current.regionId).toBe(1) + expect(ctx.addressStore.getState().selectedAddressId).toBe(cachedSole.id) + + await ctx.rtl.act(async () => { + releaseAddresses() + }) + await ctx.testUtils.flush(8) + + expect(result.current.regionId).toBe(2) + expect(result.current.boundId).toBe(8) + expect(ctx.addressStore.getState().selectedAddressId).toBe(liveSole.id) + const persistedAddresses = JSON.parse( + ctx.secure.__store.get(ctx.regionCache.userAddressesCacheKey(88)) as string + ) + expect(persistedAddresses.data[0].id).toBe(liveSole.id) + view.unmount() + } finally { + ;(global as any).fetch = networkMock + } + }) + }) }) diff --git a/apps/user-ui/tests/pages/home.test.tsx b/apps/user-ui/tests/pages/home.test.tsx index d03a164..dc56f03 100644 --- a/apps/user-ui/tests/pages/home.test.tsx +++ b/apps/user-ui/tests/pages/home.test.tsx @@ -1526,4 +1526,72 @@ describe('Home (HOME)', () => { expect(dotColor('next-order-dot-1')).toBe(active) }) + + it('HOME-113: an order delivered more than 24 hours ago is excluded', async () => { + signedIn() + setOrders([ + { + ...O1, + id: 1001, + deliveryDate: new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString(), + }, + ]) + const { queryByTestId } = await renderHome() + + expect(queryByTestId('next-order-glimpse')).toBeNull() + }) + + it('HOME-114: an order delivered within the last 24 hours is shown', async () => { + signedIn() + setOrders([ + { + ...O1, + id: 1001, + deliveryDate: new Date(Date.now() - 23 * 60 * 60 * 1000).toISOString(), + }, + ]) + const { getByTestId } = await renderHome() + + expect(getByTestId('next-order-card-1001')).toBeTruthy() + }) + + it('HOME-115: a scheduled order with no delivery date is excluded', async () => { + signedIn() + setOrders([{ ...O1, id: 1001, deliveryDate: undefined }]) + const { queryByTestId } = await renderHome() + + expect(queryByTestId('next-order-glimpse')).toBeNull() + }) + + it('HOME-116: a flash order with no delivery date uses the 30-minute promise', async () => { + signedIn() + setOrders([ + { + ...O1, + id: 1001, + isFlashDelivery: true, + deliveryDate: undefined, + createdAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(), + }, + ]) + const { getByTestId } = await renderHome() + + expect(getByTestId('next-order-card-1001')).toBeTruthy() + }) + + it('HOME-117: an old flash order with no delivery date is excluded', async () => { + signedIn() + setOrders([ + { + ...O1, + id: 1001, + isFlashDelivery: true, + deliveryDate: undefined, + createdAt: new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString(), + }, + ]) + const { queryByTestId } = await renderHome() + + expect(queryByTestId('next-order-glimpse')).toBeNull() + }) }) diff --git a/apps/web-ui/src/components/RegionGate.tsx b/apps/web-ui/src/components/RegionGate.tsx index cf84a6c..f0904b5 100644 --- a/apps/web-ui/src/components/RegionGate.tsx +++ b/apps/web-ui/src/components/RegionGate.tsx @@ -1,10 +1,17 @@ -import React, { useEffect, useState } from 'react' +import React, { useEffect, useRef, useState } from 'react' import { useLocation } from '@tanstack/react-router' import { Loader2 } from 'lucide-react' import { trpc } from '../lib/trpc-client' import { useAuth } from '../lib/auth-context' import { useRegionStore } from '../lib/stores/region-store' import { useAddressStore } from '../lib/stores/address-store' +import { + readCachedRegions, + readCachedUserAddresses, + writeCachedRegions, + writeCachedUserAddresses, + type CachedUserAddressesResponse, +} from '../lib/region-cache' import { RegionSelector } from './RegionSelector' /** @@ -23,7 +30,9 @@ export function RegionGate({ children }: { children: React.ReactNode }) { const setRegion = useRegionStore((state) => state.setRegion) const clearRegion = useRegionStore((state) => state.clearRegion) const setSelectedAddressId = useAddressStore((state) => state.setSelectedAddressId) - const { isAuthenticated, isLoading: isAuthLoading } = useAuth() + const { isAuthenticated, isLoading: isAuthLoading, user } = useAuth() + const userId = user?.id ?? null + const utils = trpc.useUtils() const location = useLocation() @@ -41,6 +50,31 @@ export function RegionGate({ children }: { children: React.ReactNode }) { const soleAddress = isAuthenticated && addressesData?.data?.length === 1 ? addressesData.data[0] : null + const [cacheReady, setCacheReady] = useState(false) + const autoSoleRegionRef = useRef(null) + + // Seed React Query from the snapshots, then let the normal queries refresh + // in the background (updatedAt: 0 means the seeded entry is immediately stale). + useEffect(() => { + const cachedRegions = readCachedRegions() + const cachedAddresses = + isAuthenticated && userId != null ? readCachedUserAddresses(userId) : null + + if (cachedRegions && utils.common.listRegions.getData(undefined) === undefined) { + utils.common.listRegions.setData(undefined, cachedRegions, { updatedAt: 0 }) + } + if ( + cachedAddresses && + userId != null && + utils.user.address.getUserAddresses.getData(undefined) === undefined + ) { + utils.user.address.getUserAddresses.setData(undefined, cachedAddresses as any, { + updatedAt: 0, + }) + } + setCacheReady(true) + }, [isAuthenticated, userId, utils]) + // Wait for the persisted region to load before deciding whether to prompt. useEffect(() => { if (useRegionStore.persist.hasHydrated()) { @@ -80,6 +114,7 @@ export function RegionGate({ children }: { children: React.ReactNode }) { if (!match) return setRegion(match) setSelectedAddressId(soleAddress.id) + autoSoleRegionRef.current = match.id }, [ hasHydrated, selectedRegionId, @@ -90,6 +125,31 @@ export function RegionGate({ children }: { children: React.ReactNode }) { setSelectedAddressId, ]) + // Reconcile the cached sole address with the live one. + useEffect(() => { + if (autoSoleRegionRef.current == null) return + if (!soleAddress || soleAddress.regionId == null || !regions) return + if (soleAddress.regionId === selectedRegionId) { + autoSoleRegionRef.current = null + return + } + const match = regions.find((region) => region.id === soleAddress.regionId) + if (!match) return + setRegion(match) + setSelectedAddressId(soleAddress.id) + autoSoleRegionRef.current = match.id + }, [soleAddress, regions, selectedRegionId, setRegion, setSelectedAddressId]) + + // Persist live responses for the next launch. + useEffect(() => { + if (regions) writeCachedRegions(regions) + }, [regions]) + + useEffect(() => { + if (userId == null || !addressesData?.data) return + writeCachedUserAddresses(userId, addressesData as CachedUserAddressesResponse) + }, [userId, addressesData]) + // Standalone full-screen routes opt out of the region gate overlay. if (location.pathname === '/location-selector') { return <>{children} @@ -103,7 +163,7 @@ export function RegionGate({ children }: { children: React.ReactNode }) { // applies; otherwise the chooser would flash before it is dismissed. if ( selectedRegionId == null && - (isAuthLoading || (isAuthenticated && addressesLoading)) + (!cacheReady || isAuthLoading || (isAuthenticated && addressesLoading)) ) { return ( <> diff --git a/apps/web-ui/src/components/me/NextOrderGlimpse.tsx b/apps/web-ui/src/components/me/NextOrderGlimpse.tsx index 88234fb..b174ede 100644 --- a/apps/web-ui/src/components/me/NextOrderGlimpse.tsx +++ b/apps/web-ui/src/components/me/NextOrderGlimpse.tsx @@ -7,6 +7,7 @@ import { orderStatusManipulator } from '../../lib/string-manipulators' import dayjs from 'dayjs' import { Loader2, ChevronRight } from 'lucide-react' import type { UserOrderSummary } from '@packages/shared' +import { isInNextOrderGlimpseWindow } from '@packages/shared' /** * Port of user-ui's NextOrderGlimpse: a horizontal snap-scroll of amber @@ -127,6 +128,8 @@ export function NextOrderGlimpse() { .filter((order) => { if (order.orderStatus.toLowerCase() === 'cancelled') return false if (order.deliveryStatus.toLowerCase() === 'success') return false + // Only keep deliveries that are upcoming or at most 24h old. + if (!isInNextOrderGlimpseWindow(order)) return false return true }) .sort((a, b) => { diff --git a/apps/web-ui/src/lib/region-cache.ts b/apps/web-ui/src/lib/region-cache.ts new file mode 100644 index 0000000..d8e8f71 --- /dev/null +++ b/apps/web-ui/src/lib/region-cache.ts @@ -0,0 +1,101 @@ +import type { RegionSummary } from '@packages/shared' + +/** + * Web counterpart of the user-ui startup cache. Only the fields RegionGate + * reads are typed; the stored payload is the full serialized tRPC response. + */ +export interface CachedUserAddress { + id: number + regionId: number | null + boundId: number | null + isDefault: boolean + [key: string]: unknown +} + +export interface CachedUserAddressesResponse { + success: boolean + data: CachedUserAddress[] +} + +export const REGION_LIST_CACHE_KEY = 'region_cache:list_regions:v1' +export const userAddressesCacheKey = (userId: number) => + `region_cache:user_addresses:v1:${userId}` + +let lastWrittenRegions: string | null = null +const lastWrittenAddresses = new Map() + +const readRaw = (key: string): string | null => { + try { + return typeof localStorage === 'undefined' ? null : localStorage.getItem(key) + } catch { + return null + } +} + +const writeRaw = (key: string, value: string): boolean => { + try { + if (typeof localStorage !== 'undefined') localStorage.setItem(key, value) + return typeof localStorage !== 'undefined' + } catch { + return false + } +} + +function parseJson(raw: string | null): unknown { + if (!raw) return null + try { + return JSON.parse(raw) + } catch { + return null + } +} + +export function readCachedRegions(): RegionSummary[] | null { + const parsed = parseJson(readRaw(REGION_LIST_CACHE_KEY)) + if ( + !Array.isArray(parsed) || + !parsed.every( + (region) => + region != null && + typeof region === 'object' && + typeof (region as RegionSummary).id === 'number' + ) + ) { + return null + } + return parsed as RegionSummary[] +} + +export function writeCachedRegions(regions: RegionSummary[]): void { + const serialized = JSON.stringify(regions) + if (serialized === lastWrittenRegions) return + if (writeRaw(REGION_LIST_CACHE_KEY, serialized)) lastWrittenRegions = serialized +} + +export function readCachedUserAddresses(userId: number): CachedUserAddressesResponse | null { + const parsed = parseJson(readRaw(userAddressesCacheKey(userId))) + if (parsed == null || typeof parsed !== 'object') return null + const response = parsed as Partial + const valid = + response.success === true && + Array.isArray(response.data) && + response.data.every( + (address) => + address != null && + typeof address === 'object' && + typeof address.id === 'number' && + typeof address.isDefault === 'boolean' + ) + return valid ? (response as CachedUserAddressesResponse) : null +} + +export function writeCachedUserAddresses( + userId: number, + response: CachedUserAddressesResponse +): void { + const serialized = JSON.stringify(response) + if (serialized === lastWrittenAddresses.get(userId)) return + if (writeRaw(userAddressesCacheKey(userId), serialized)) { + lastWrittenAddresses.set(userId, serialized) + } +} diff --git a/change-log.txt b/change-log.txt index 6fe6a43..ca1f336 100644 --- a/change-log.txt +++ b/change-log.txt @@ -8280,6 +8280,41 @@ Run: bun run test -- tests/components/address-form.test.tsx -> 37/37 passed (no assertions needed changing; address-city / address-city-option-* IDs preserved). Typecheck: user-ui clean; web-ui `npm run typecheck` clean. +================================================================================ +[2026-10-20 17:49:38 IST] CACHE-2026-10-20-24 region list + user address cache +================================================================================ +New: apps/user-ui/src/lib/region-cache.ts +- StorageServiceCasual snapshots for `common.listRegions` and + `user.address.getUserAddresses` (addresses keyed by user id). +- Validates cached JSON before use; writes are de-duplicated per payload so the + many useRegion observers don't rewrite the same response. +apps/user-ui/src/hooks/useRegion.ts +- Hydrate the two snapshots once at startup, seed React Query with them + (updatedAt: 0 so the live queries still run in the background), and use them + as effective startup data while the live request is in flight. +- Persist live listRegions / getUserAddresses responses back to storage. +- Reconcile once when fresh live data differs from the cached baseline: re-arm + the one-shot startup decision so the region/address follows the live values. +- Keep the cached default address derived from the address list until the live + getDefaultAddress response lands. +apps/user-ui/tests/lib/use-region.test.tsx +- REGION-25: cached region list + sole address open the app while both live + queries are pending, and both live requests are still issued. +- REGION-26: cached region 1 data opens first, then live address data for + region 2 reconciles the region/bound/address and only then settles. +apps/user-ui/JEST-TEST-CASES.md +- Document REGION-25/26. +Run: user-ui typecheck clean; `npm test -- tests/lib/use-region.test.tsx +--runInBand` -> 26/26 passed (REGION-25/26 added). `tests/pages/home.test.tsx` ++ `tests/lib/prominent-api-hooks.test.tsx` -> 131/131 passed. Location/components ++ use-region -> 80/80 passed. +Web mirror (2026-10-20 18:02:48 IST): +- New apps/web-ui/src/lib/region-cache.ts (localStorage, same cache keys). +- RegionGate hydrates listRegions/getUserAddresses, seeds React Query with + updatedAt 0 for background refresh, persists live responses, and re-adopts the + sole address's region if the live address differs from the cached one. +- web-ui typecheck clean. + ================================================================================ [2026-10-20 17:35:35 IST] FIX-2026-10-20-23 sole address still not selected ================================================================================ @@ -8375,3 +8410,48 @@ cover the three Home scenarios). user-ui typecheck clean. - update the header comment to match. Verified by replaying the file on a copy of the local D1 DB with PRAGMA foreign_keys=ON. Not applied to the live DB. + - Timestamp: 2026-10-20 19:10:20 + Hide "Open in Maps" for seeded addresses by omitting their coordinates from + the admin order APIs (no UI change needed: both admin UIs already hide the + action when latitude/longitude are null). + Files: + * packages/db_helper_sqlite/src/admin-apis/order.ts + + add exported orderCoords(address): returns null/null when the address + is migration-seeded (vague_backfilled_coords = true) and has no + admin-attached coordinates; otherwise admin coords, then customer + coords. + + getSlotOrders / getAllOrders use orderCoords instead of inlining + adminLatitude ?? latitude. + + updateAddressCoords now sets vague_backfilled_coords = false, so a + later refetch exposes the real admin coordinates. + * packages/db_helper_sqlite/index.ts + + export orderCoords. + * apps/backend/tests/unit/order-coords.test.ts (new) + + seeded -> nulls; admin override; real customer coords; no coords. + * apps/backend/tests/api/admin-order.test.ts + + AORD-26 also asserts the seeded flag is cleared by updateAddressCoords. + * apps/admin-ui/tests/components/order-options-menu.test.tsx + + documents that null coordinates hide the Open in Maps row. + No change to admin-ui/admin-web production code; both consume null coords + through the existing hasCoordinates check. + - Timestamp: 2026-10-20 19:14:30 + Next-order glimpse: only show orders whose delivery is in the future or at + most 24 hours in the past. Older orders stay in My Orders but disappear from + the home/me glimpse. + Files: + * packages/shared/order-glimpse.ts (new) + + isInNextOrderGlimpseWindow(order, now?) — deliveryDate, else + createdAt + 30 min for flash orders, else hidden; keeps any future + delivery and deliveries >= now - 24h. + * packages/shared/index.ts + + export the helper + constants. + * apps/user-ui/components/NextOrderGlimpse.tsx + + apply the window in the existing upcomingOrders filter. + * apps/web-ui/src/components/me/NextOrderGlimpse.tsx + + same filter (web counterpart, per AGENTS mirror rule). + * apps/user-ui/tests/lib/order-glimpse.test.ts (new) + + future / 23h / exactly 24h / >24h / missing date / flash fallback. + * apps/user-ui/tests/pages/home.test.tsx + + HOME-113..117 for the new window behaviour. + No backend/API changes: getOrders is shared with My Orders, so the glimpse + filters its own view. diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts index f31fb3b..5384cbe 100644 --- a/packages/db_helper_sqlite/index.ts +++ b/packages/db_helper_sqlite/index.ts @@ -63,6 +63,7 @@ export { getSlotOrders, updateAddressCoords, getAllOrders, + orderCoords, rebalanceSlots, cancelOrder, deleteOrderById, diff --git a/packages/db_helper_sqlite/src/admin-apis/order.ts b/packages/db_helper_sqlite/src/admin-apis/order.ts index 256a90c..411b749 100644 --- a/packages/db_helper_sqlite/src/admin-apis/order.ts +++ b/packages/db_helper_sqlite/src/admin-apis/order.ts @@ -32,6 +32,35 @@ import { composeSkuName, composeUnitNotation } from '../lib/sku-features' type OrderStatusRow = InferSelectModel +/** + * Coordinates exposed to the admin order UIs. + * + * The 0006 backfill filled missing address coordinates with the region centre + * and set `vagueBackfilledCoords`. Those are not a delivery location, so they + * must not reach clients; both admin UIs hide "Open in Maps" when latitude / + * longitude are null. Admin-attached coordinates are real and win even if a + * legacy row still has the flag set. + */ +export function orderCoords(address: { + latitude: number | null + longitude: number | null + adminLatitude: number | null + adminLongitude: number | null + vagueBackfilledCoords: boolean | null +}): { latitude: number | null; longitude: number | null } { + const hasAdminCoords = + address.adminLatitude != null && address.adminLongitude != null + + if (!hasAdminCoords && address.vagueBackfilledCoords === true) { + return { latitude: null, longitude: null } + } + + return { + latitude: address.adminLatitude ?? address.latitude ?? null, + longitude: address.adminLongitude ?? address.longitude ?? null, + } +} + const mapOrderStatusRecord = (record: OrderStatusRow): AdminOrderStatusRecord => ({ id: record.id, orderTime: record.orderTime, @@ -346,6 +375,8 @@ export async function getSlotOrders(regionId: number, slotId: string): Promise first.id - second.id) order.address = order.address || {} + const coords = orderCoords(order.address) return { id: order.id, orderId: order.id.toString(), @@ -495,8 +529,8 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput): order.address.addressLine2 ? `, ${order.address.addressLine2}` : '' }, ${order.address.city}, ${order.address.state}, Phone: ${order.address.phone}`, addressId: order.addressId, - latitude: order.address.adminLatitude ?? order.address.latitude, - longitude: order.address.adminLongitude ?? order.address.longitude, + latitude: coords.latitude, + longitude: coords.longitude, totalAmount: parseFloat(order.totalAmount), deliveryCharge: parseFloat(order.deliveryCharge || '0'), items, diff --git a/packages/shared/index.ts b/packages/shared/index.ts index e4e6255..baf22ba 100644 --- a/packages/shared/index.ts +++ b/packages/shared/index.ts @@ -21,3 +21,5 @@ export const BASE_API_URL = 'https://devbackend.freshyo.in' export * from './types' // Framework-agnostic coupon/cart money helpers (used by the backend pricing path). export * from './cart-pricing' +// Home/Me "next order" glimpse visibility window. +export * from './order-glimpse' diff --git a/packages/shared/order-glimpse.ts b/packages/shared/order-glimpse.ts new file mode 100644 index 0000000..053dfda --- /dev/null +++ b/packages/shared/order-glimpse.ts @@ -0,0 +1,57 @@ +/** + * Visibility window for the "Upcoming Order" glimpse. + * + * The glimpse is a short call-to-action on Home/Me, not order history. Show an + * order while its delivery is still upcoming, or for 24 hours after the + * delivery time. Older orders remain available in My Orders. + */ + +export const NEXT_ORDER_GLIMPSE_LOOKBACK_HOURS = 24 +export const FLASH_DELIVERY_MINUTES = 30 + +const HOUR_MS = 60 * 60 * 1000 +const MINUTE_MS = 60 * 1000 + +export interface NextOrderGlimpseOrderLike { + isFlashDelivery: boolean + deliveryDate?: string | null + createdAt: string +} + +/** + * The moment the order is promised for. Prefers the slot delivery date; a + * flash order without a slot uses the 30-minute promise shown on the card. + */ +function deliveryMoment(order: NextOrderGlimpseOrderLike): Date | null { + if (order.deliveryDate) { + const date = new Date(order.deliveryDate) + if (!Number.isNaN(date.getTime())) return date + } + + if (order.isFlashDelivery) { + const created = new Date(order.createdAt) + if (!Number.isNaN(created.getTime())) { + return new Date(created.getTime() + FLASH_DELIVERY_MINUTES * MINUTE_MS) + } + } + + return null +} + +/** + * True when the order should appear in the next-order glimpse: + * any future delivery, or one that happened within the lookback window. + * Returns false when the delivery moment cannot be determined. + */ +export function isInNextOrderGlimpseWindow( + order: NextOrderGlimpseOrderLike, + now: Date = new Date() +): boolean { + const deliveryAt = deliveryMoment(order) + if (!deliveryAt) return false + + return ( + deliveryAt.getTime() >= + now.getTime() - NEXT_ORDER_GLIMPSE_LOOKBACK_HOURS * HOUR_MS + ) +}