freshyo/apps/user-ui/components/RegionGate.tsx
2026-10-07 00:27:11 +05:30

308 lines
12 KiB
TypeScript

import React, { useState, useEffect, useRef } from 'react';
import * as Location from 'expo-location';
import * as Linking from 'expo-linking';
import { View, ActivityIndicator, AppState, Platform } from 'react-native';
import { MyText, MyTouchableOpacity, tw } from 'common-ui';
import type { ReactParentComponent } from '@packages/shared';
import { trpc } from '../src/trpc-client';
import { useRegion } from '../src/contexts/RegionContext';
import { useRegionSwitchContext } from '../src/hooks/useRegionSwitch';
type GateReason = 'denied' | 'servicesOff' | 'unserved' | 'error';
// Minimum sustained movement before a foreground fix re-resolves the region.
// Guards against GPS jitter flapping the region/cart reconciliation.
const RE_RESOLVE_MIN_MOVE_M = 100;
const distanceM = (
a: { lat: number; lng: number },
b: { lat: number; lng: number }
): number => {
const rad = Math.PI / 180;
const dLat = (b.lat - a.lat) * rad;
const dLng = (b.lng - a.lng) * rad;
const s =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(a.lat * rad) * Math.cos(b.lat * rad) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
return 2 * 6371000 * Math.asin(Math.sqrt(s));
};
const RegionGate: React.FC<ReactParentComponent> = ({ children }) => {
const { regionId, regionName, isLoading: regionLoading, setRegion } = useRegion();
const { switchRegion } = useRegionSwitchContext();
const utils = trpc.useUtils();
const [coords, setCoords] = useState<{ lat: number; lng: number } | null>(null);
const [denied, setDenied] = useState(false);
const [servicesOff, setServicesOff] = useState(false);
const [detectError, setDetectError] = useState(false);
const [detecting, setDetecting] = useState(true);
const [showPicker, setShowPicker] = useState(false);
const [picked, setPicked] = useState(false);
const [attempt, setAttempt] = useState(0);
const passedRef = useRef(false);
const appState = useRef(AppState.currentState);
// Set once the first detection completes: later re-runs refresh silently
// behind the settled screen instead of flashing the full loading view.
const settledRef = useRef(false);
const lastRunRef = useRef(0);
// True while the user is in OS Settings (via the primary action): the
// return re-check must bypass the flapping cooldown below.
const expectReturnRef = useRef(false);
// Baseline for foreground re-resolution (P6): anchored to the first watch
// fix; later fixes only act after sustained movement. Mirrors of values
// the watch callback needs without resubscribing.
const lastFixRef = useRef<{ lat: number; lng: number } | null>(null);
const regionIdRef = useRef<number | null>(null);
regionIdRef.current = regionId;
const runDetection = async () => {
if (passedRef.current) return;
lastRunRef.current = Date.now();
setDetecting(true);
if (!settledRef.current) {
setDenied(false);
setServicesOff(false);
setDetectError(false);
setCoords(null);
}
try {
const { status } = await Location.requestForegroundPermissionsAsync();
if (passedRef.current) return;
if (status !== 'granted') {
setDenied(true);
return;
}
const servicesEnabled = await Location.hasServicesEnabledAsync();
if (passedRef.current) return;
if (!servicesEnabled) {
setServicesOff(true);
return;
}
const location = await Location.getCurrentPositionAsync({});
if (passedRef.current) return;
setCoords({ lat: location.coords.latitude, lng: location.coords.longitude });
} catch (error) {
if (!passedRef.current) setDetectError(true);
} finally {
if (!passedRef.current) {
setDetecting(false);
settledRef.current = true;
}
}
};
useEffect(() => {
void runDetection();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [attempt]);
// Re-check when returning from OS/app Settings. Cooldown guards against
// AppState flapping: a background re-run must never flash loading anyway
// (see settledRef), but there is no reason to spam the OS location stack.
useEffect(() => {
const sub = AppState.addEventListener('change', (next) => {
if (appState.current.match(/inactive|background/) && next === 'active') {
if (expectReturnRef.current || Date.now() - lastRunRef.current > 15000) {
setAttempt((a) => a + 1);
}
expectReturnRef.current = false;
}
appState.current = next;
});
return () => sub.remove();
}, []);
// Foreground re-resolution: a spoofed or real move while foregrounded must
// re-resolve the region (previously only relaunch/background did). A
// different served region goes through switchRegion so carts reconcile; an
// unserved fix drops back to the manual picker.
useEffect(() => {
let subscription: Location.LocationSubscription | null = null;
let cancelled = false;
void (async () => {
const perms = await Location.getForegroundPermissionsAsync();
if (cancelled || perms.status !== 'granted') return;
subscription = await Location.watchPositionAsync(
{
accuracy: Location.Accuracy.Balanced,
timeInterval: 8000,
distanceInterval: 50,
},
(position) => {
const fix = { lat: position.coords.latitude, lng: position.coords.longitude };
const baseline = lastFixRef.current;
if (!baseline) {
lastFixRef.current = fix;
return;
}
if (distanceM(baseline, fix) < RE_RESOLVE_MIN_MOVE_M) return;
lastFixRef.current = fix;
void utils.common.resolveRegionForLocation.fetch(fix).then((resolved) => {
if (resolved?.regionId != null) {
if (resolved.regionId !== regionIdRef.current) {
void switchRegion(resolved.regionId, resolved.regionName ?? '');
}
} else if (regionIdRef.current != null) {
// Moved out of every served polygon: reset the gate so the
// user picks a region instead of serving a ghost one.
passedRef.current = false;
setPicked(false);
setCoords(fix);
}
}).catch((error) => {
console.error('Foreground region re-resolution failed:', error);
});
}
);
})();
return () => {
cancelled = true;
subscription?.remove();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const resolveQuery = trpc.common.resolveRegionForLocation.useQuery(
{ lat: coords?.lat ?? 0, lng: coords?.lng ?? 0 },
{ enabled: !!coords, retry: false, refetchOnWindowFocus: false, staleTime: Infinity }
);
const resolved = resolveQuery.data;
const resolveFailed = resolveQuery.isError;
useEffect(() => {
if (resolved?.regionId != null) {
passedRef.current = true;
void setRegion(resolved.regionId, resolved.regionName ?? '', resolved.boundId, resolved.boundName);
}
}, [resolved, setRegion]);
const { data: regionsData, isLoading: regionsLoading } = trpc.common.getRegions.useQuery(
undefined,
{ staleTime: Infinity }
);
const handlePick = (id: number, name: string) => {
passedRef.current = true;
setPicked(true);
void setRegion(id, name);
};
const handlePrimaryAction = async () => {
if (servicesOff && Platform.OS === 'android') {
try {
await Location.enableNetworkProviderAsync();
} catch {
// User dismissed the system dialog; fall through to re-check.
}
setAttempt((a) => a + 1);
return;
}
expectReturnRef.current = true;
await Linking.openSettings();
};
// GPS resolved to a served region, or the user picked/continued manually.
if (resolved?.regionId != null || picked) {
return <>{children}</>;
}
if ((detecting && !settledRef.current) || regionLoading || (!!coords && !resolved && !resolveFailed)) {
return (
<View style={tw`flex-1 items-center justify-center bg-white`} testID="region-gate-loading">
<ActivityIndicator size="large" />
<MyText style={tw`text-gray-500 mt-3`}>Detecting your region…</MyText>
</View>
);
}
const detectionBlocked = denied || servicesOff;
const reason: GateReason = denied
? 'denied'
: servicesOff
? 'servicesOff'
: resolveFailed || detectError
? 'error'
: 'unserved';
// Hard failure (permission or location switch): message + action, picker on demand.
if ((detectionBlocked || showPicker) && reason !== 'unserved') {
if (!showPicker) {
const subheading = denied
? 'We need location permission to auto-detect your region. Grant access in Settings, or choose your region manually.'
: 'Your location is turned off. Turn it on to auto-detect your region, or choose your region manually.';
return (
<View style={tw`flex-1 items-center justify-center bg-white px-8`} testID="region-gate-blocked">
<MyText style={tw`text-2xl font-extrabold text-gray-900 text-center`}>
Unable to obtain location
</MyText>
<MyText style={tw`text-gray-500 mt-3 text-center`}>{subheading}</MyText>
<MyTouchableOpacity
testID="region-gate-action"
style={tw`mt-8 w-full bg-brand500 rounded-xl py-4`}
onPress={handlePrimaryAction}
>
<MyText style={tw`text-white text-center font-bold`}>
{servicesOff && Platform.OS === 'android' ? 'Turn on location' : 'Open Settings'}
</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="region-gate-manual"
style={tw`mt-3 w-full border border-gray-200 rounded-xl py-4`}
onPress={() => setShowPicker(true)}
>
<MyText style={tw`text-gray-900 text-center font-bold`}>Choose region manually</MyText>
</MyTouchableOpacity>
{regionId != null && (
<MyTouchableOpacity
testID="region-gate-continue-stored"
style={tw`mt-3`}
onPress={() => handlePick(regionId, regionName ?? '')}
>
<MyText style={tw`text-gray-500 text-center text-sm`}>
Continue with {regionName ?? 'saved region'}
</MyText>
</MyTouchableOpacity>
)}
</View>
);
}
}
// Region picker: unserved GPS, resolution failure, or manual choice.
const pickerTitle = reason === 'unserved' ? 'Outside service area' : 'Choose your region';
const pickerMessage =
reason === 'unserved'
? 'Your current location is outside the areas we serve. You can still continue by picking a region below.'
: reason === 'error'
? 'We could not detect your region. Pick one below to continue.'
: 'Pick your region below to continue.';
const regions = regionsData?.regions ?? [];
return (
<View style={tw`flex-1 bg-white px-6 pt-20`} testID="region-gate-picker">
<MyText style={tw`text-2xl font-extrabold text-gray-900`}>{pickerTitle}</MyText>
<MyText style={tw`text-gray-500 mt-2 mb-6`}>{pickerMessage}</MyText>
{regionsLoading ? (
<ActivityIndicator size="large" />
) : (
regions.map((region) => (
<MyTouchableOpacity
key={region.id}
testID={`region-pick-${region.id}`}
style={tw`border border-gray-200 rounded-xl px-4 py-4 mb-3`}
onPress={() => handlePick(region.id, region.name)}
>
<MyText style={tw`text-lg font-bold text-gray-900`}>{region.name}</MyText>
{!!region.description && (
<MyText style={tw`text-gray-500 text-sm mt-1`}>{region.description}</MyText>
)}
</MyTouchableOpacity>
))
)}
</View>
);
};
export default RegionGate;