register address

This commit is contained in:
Samandar Turgunboyev
2026-03-26 14:23:58 +05:00
parent fee9213c59
commit a671706fb3
12 changed files with 555 additions and 311 deletions

View File

@@ -1,7 +1,6 @@
import AuthHeader from '@/components/ui/AuthHeader';
import { decryptToken } from '@/constants/crypto';
import { formatPhone, normalizeDigits } from '@/constants/formatPhone';
import { formatText, formatTextToLatin } from '@/constants/formatText';
import { products_api } from '@/screens/home/lib/api';
import BottomSheet, { BottomSheetBackdrop, BottomSheetFlatList, BottomSheetTextInput } from '@gorhom/bottom-sheet';
import { useMutation, useQuery } from '@tanstack/react-query';
@@ -32,12 +31,7 @@ import { SafeAreaView } from 'react-native-safe-area-context';
import { auth_api, GetInfo } from '../login/lib/api';
import PhonePrefix from '../login/ui/PhonePrefix';
import { UseLoginForm } from '../login/ui/UseLoginForm';
interface CoordsData {
lat: number;
lon: number;
polygon: [number, number][][];
}
import { useResolveLocation } from './lib/useResolveLocation';
export default function RegisterFormScreen() {
const router = useRouter();
@@ -52,57 +46,71 @@ export default function RegisterFormScreen() {
const [info, setInfo] = useState<GetInfo | null>(null);
const [loading, setLoading] = useState(false);
const [referal, setReferal] = useState('');
const [error, setError] = useState<string | null>(null)
const [district, setDistrict] = useState<string | null>(null)
const [region, setRegion] = useState<string | null>(null)
const [token, setTokens] = useState<{ name: string, value: string } | null>(null)
const [error, setError] = useState<string | null>(null);
const [token, setTokens] = useState<{ name: string, value: string } | null>(null);
const [directorTinInput, setDirectorTinInput] = useState('');
// ─── Token ───────────────────────────────────────────────────────────────────
const { data } = useQuery({
queryKey: ["tokens"],
queryFn: async () => auth_api.get_tokens(),
select(data) {
return data.data.data.results
return data.data.data.results;
},
})
});
useEffect(() => {
if (data?.length) {
const token = data[0]
const tokenValue = decryptToken(token.value)
const token = data[0];
const tokenValue = decryptToken(token.value);
if (tokenValue) {
setTokens({ name: token.key, value: tokenValue })
setTokens({ name: token.key, value: tokenValue });
}
}
}, [data])
}, [data]);
// ─── Location resolver hook ───────────────────────────────────────────────────
const {
location,
resolve: resolveLocation,
reset: resetLocation,
} = useResolveLocation({
token: token?.value ?? null,
tokenName: token?.name ?? null,
});
console.log("location", location.district?.id);
// ─── STIR info mutation ───────────────────────────────────────────────────────
const { mutate } = useMutation({
mutationFn: (stir: string) => auth_api.get_info({ value: stir, token: token?.value || "", tokenName: token?.name || "" }),
mutationFn: (stir: string) =>
auth_api.get_info({
value: stir,
token: token?.value || "",
tokenName: token?.name || "",
}),
onSuccess: (res) => {
setInfo(res.data);
setLoading(false);
setError(null)
setDistrict(res.data.address)
setError(null);
if (res.data?.address) {
resolveLocation(res.data.address);
}
},
onError: () => {
setInfo(null);
setLoading(false);
setError("Foydalanuvchi topilmadi")
setError("Foydalanuvchi topilmadi");
resetLocation();
},
});
const { data: districts } = useQuery({
queryKey: ["discrit"],
queryFn: async () => auth_api.get_district({ token: token?.value || "", tokenName: token?.name || "" }),
enabled: !!token,
})
const { data: regions } = useQuery({
queryKey: ["regions"],
queryFn: async () => auth_api.get_region({ token: token?.value || "", tokenName: token?.name || "" }),
enabled: !!token,
})
// ─── Country list ─────────────────────────────────────────────────────────────
const { data: countryResponse, isLoading: countryLoading } = useQuery({
queryKey: ['country-detail'],
@@ -110,109 +118,38 @@ export default function RegisterFormScreen() {
select: (res) => res.data?.data || [],
});
const getRegionDistrictFromAddress = async (address: string) => {
try {
const encoded = encodeURIComponent(address + ", Uzbekistan");
const res = await fetch(
`https://nominatim.openstreetmap.org/search?q=${encoded}&format=json&addressdetails=1&limit=1`,
{ headers: { 'Accept-Language': 'uz', 'User-Agent': 'MyApp/1.0 (turgunboyevsamandar4@gamil.com)' } }
);
const data = await res.json();
if (data.length > 0) {
const addr = data[0].address;
return {
district: addr.county || addr.district || addr.suburb,
region: addr.state,
};
}
} catch (e) { }
return null;
};
useEffect(() => {
if (district) {
const dis = formatText(district)?.split(" ")[0].toLocaleUpperCase()
let reg = null
if (dis) {
reg = districts?.data.find((item) => item.name.includes(dis))
};
if (reg) {
const region = regions?.data.find((item) => item.regionId == reg.regionId)
setRegion(region?.name || "")
}
}
}, [district])
const [districtId, setDistrictId] = useState<number | null>(null);
const [regionId, setRegionId] = useState<number | null>(null);
useEffect(() => {
if (!district || !countryResponse?.length) return;
const resolve = async () => {
const geo = await getRegionDistrictFromAddress(district.split(" ")[0]);
const searchRegion = geo?.region || region;
const searchDistrict = geo?.district || district
for (const country of countryResponse) {
const regionName = formatTextToLatin(searchRegion)?.split(" ")[0];
let foundRegion = null
if (regionName) {
foundRegion = country.region.find((r: any) =>
formatTextToLatin(r.name)?.includes(regionName)
);
}
if (foundRegion) {
setRegionId(foundRegion.id);
setDistrictId(null);
return;
}
for (const reg of country.region || []) {
const dis = formatTextToLatin(searchDistrict)?.split(" ")[0].toUpperCase();
let foundDistrict = null
if (dis) {
foundDistrict = reg.districts.find((d: any) => {
return formatTextToLatin(d.name)?.toUpperCase().includes(dis.slice(0, 4))
}
);
};
if (foundDistrict) {
setDistrictId(foundDistrict.id);
setRegionId(null);
return;
}
}
}
};
resolve();
}, [district, countryResponse]);
// ─── Validation helpers ───────────────────────────────────────────────────────
useEffect(() => {
if (info === null || (stir.length === 9 && info.name && info.fullName)) {
setError(null)
setError(null);
} else if (info?.name === null || info?.fullName === null) {
setError("Sizning shaxsiy ma'lumotlaringiz topilmadi")
setError("Sizning shaxsiy ma'lumotlaringiz topilmadi");
} else if (!info?.selfEmployment && !info?.isItd) {
setError("Siz o'zini o'zi band qilgan yoki yakka tartibdagi tadbirkorlik bo'lishingiz kerak")
setError("Siz o'zini o'zi band qilgan yoki yakka tartibdagi tadbirkorlik bo'lishingiz kerak");
}
}, [info])
}, [info]);
const hasDirectorTin = info?.directorPinfl && String(info.directorPinfl).length > 0;
const isDirectorTinValid = !hasDirectorTin || directorTinInput === String(info.directorPinfl);
const hasValidName = Boolean(info?.name || info?.fullName);
const valid =
phone.length === 9 &&
(stir.length === 9 || stir.length === 14) &&
info &&
hasValidName &&
isDirectorTinValid &&
error === null;
// ─── Country sheet ────────────────────────────────────────────────────────────
const filteredCountries = useMemo(() => {
if (!countrySearch.trim()) return countryResponse || [];
const q = countrySearch.toLowerCase().trim();
return (countryResponse || []).filter((c: any) => c.name?.toLowerCase().includes(q));
return (countryResponse || []).filter((c: any) =>
c.name?.toLowerCase().includes(q)
);
}, [countryResponse, countrySearch]);
const openCountrySheet = useCallback(() => {
@@ -225,8 +162,9 @@ export default function RegisterFormScreen() {
const selectedCountryName = useMemo(() => {
if (!selectedCountry) return t('Tanlang');
return (
countryResponse?.find((c: any) => c.flag?.toUpperCase() === selectedCountry)?.name ||
t('Tanlang')
countryResponse?.find(
(c: any) => c.flag?.toUpperCase() === selectedCountry
)?.name || t('Tanlang')
);
}, [selectedCountry, countryResponse, t]);
@@ -248,13 +186,7 @@ export default function RegisterFormScreen() {
setTimeout(() => setCountrySearch(''), 300);
}, []);
const valid =
phone.length === 9 &&
(stir.length === 9 || stir.length === 14) &&
info &&
hasValidName &&
isDirectorTinValid &&
error === null;
// ─── Render ───────────────────────────────────────────────────────────────────
return (
<>
@@ -295,49 +227,44 @@ export default function RegisterFormScreen() {
<UserPlus size={32} color="#fff" />
</LinearGradient>
</View>
<Text style={styles.title}>{t('Ro\'yxatdan o\'tish')}</Text>
<Text style={styles.title}>{t("Ro'yxatdan o'tish")}</Text>
</View>
<View style={styles.card}>
<View style={styles.formGap}>
{/* Country */}
<View>
<View>
<Text style={styles.label}>{t('Davlat')}</Text>
<TouchableOpacity
style={[
styles.input,
styles.inputDisabled,
]}
onPress={openCountrySheet}
activeOpacity={0.7}
testID="country-select"
disabled
>
{countryLoading ? (
<ActivityIndicator size="small" color="#3b82f6" style={{ flex: 1 }} />
) : (
<>
<Image
source={{ uri: `https://flagcdn.com/w320/${selectedCountry.toLowerCase()}.png` }}
style={{ width: 30, height: 15 }}
resizeMode="cover"
/>
<Text
style={[
styles.textInput,
{ color: '#94a3b8' },
]}
numberOfLines={1}
>
{selectedCountryName}
</Text>
</>
)}
<ChevronDown size={18} color={'#cbd5e1'} />
</TouchableOpacity>
</View>
<Text style={styles.label}>{t('Davlat')}</Text>
<TouchableOpacity
style={[styles.input, styles.inputDisabled]}
onPress={openCountrySheet}
activeOpacity={0.7}
testID="country-select"
disabled
>
{countryLoading ? (
<ActivityIndicator size="small" color="#3b82f6" style={{ flex: 1 }} />
) : (
<>
<Image
source={{ uri: `https://flagcdn.com/w320/${selectedCountry.toLowerCase()}.png` }}
style={{ width: 30, height: 15 }}
resizeMode="cover"
/>
<Text
style={[styles.textInput, { color: '#94a3b8' }]}
numberOfLines={1}
>
{selectedCountryName}
</Text>
</>
)}
<ChevronDown size={18} color={'#cbd5e1'} />
</TouchableOpacity>
</View>
{/* STIR */}
<View>
<Text style={styles.label}>{t('STIR')}</Text>
<View style={styles.input}>
@@ -351,14 +278,10 @@ export default function RegisterFormScreen() {
onChangeText={(text) => {
const v = normalizeDigits(text).slice(0, 14);
setStir(v);
if (v.length === 9 || v.length === 14) {
setLoading(true);
resetLocation();
mutate(v);
setRegionId(null)
setDistrictId(null)
setRegion(null)
setDistrict(null)
}
}}
/>
@@ -366,6 +289,7 @@ export default function RegisterFormScreen() {
</View>
</View>
{/* Referal */}
<View>
<Text style={styles.label}>{t('Referal')}</Text>
<View style={styles.input}>
@@ -382,6 +306,7 @@ export default function RegisterFormScreen() {
</View>
</View>
{/* Phone */}
<View>
<Text style={styles.label}>{t('Telefon raqami')}</Text>
<View style={styles.input}>
@@ -397,10 +322,16 @@ export default function RegisterFormScreen() {
</View>
</View>
{/* Director TIN */}
{hasDirectorTin && (
<View>
<Text style={styles.label}>{t('Direktor STIR')}</Text>
<View style={[styles.input, { backgroundColor: isDirectorTinValid ? '#f0fdf4' : '#f8fafc' }]}>
<View
style={[
styles.input,
{ backgroundColor: isDirectorTinValid ? '#f0fdf4' : '#f8fafc' },
]}
>
<Hash size={18} color="#94a3b8" />
<TextInput
value={directorTinInput}
@@ -412,19 +343,22 @@ export default function RegisterFormScreen() {
onChangeText={(t) => setDirectorTinInput(normalizeDigits(t))}
/>
</View>
{directorTinInput.length === 14 && !isDirectorTinValid && (
<Text style={styles.error}>{t('Direktor STIR notogri')}</Text>
<Text style={styles.error}>{t("Direktor STIR noto'g'ri")}</Text>
)}
</View>
)}
{error !== null ?
{/* Info / Error */}
{error !== null ? (
<Text style={styles.notFound}>{t(error)}</Text>
: info && hasValidName &&
<Text style={styles.info}>{info.fullName || info.name}</Text>
}
) : (
info && hasValidName && (
<Text style={styles.info}>{info.fullName || info.name}</Text>
)
)}
{/* Submit */}
<TouchableOpacity
disabled={!valid}
style={[styles.btn, !valid && styles.disabled]}
@@ -437,26 +371,33 @@ export default function RegisterFormScreen() {
first_name: stir.length === 9 ? info?.director : info?.fullName,
last_name: stir.length === 9 ? info?.director : info?.fullName,
company_name: info?.name,
district: districtId !== null ? districtId : regionId,
address: districtId !== null ? districtId : regionId,
district: location.district?.id,
address: location.district?.id,
director_full_name: stir.length === 9 ? info?.director : info?.fullName,
stir,
referal,
person_type: stir.length === 9 ? 'legal_entity' : info?.selfEmployment ? 'band' : info?.isItd ? 'ytt' : 'ytt',
person_type:
stir.length === 9
? 'legal_entity'
: info?.selfEmployment
? 'band'
: 'ytt',
},
})
});
}
}}
>
<Text style={styles.btnText}>{t('Davom etish')}</Text>
</TouchableOpacity>
</View>
</View>
</View>
</SafeAreaView>
</View >
</KeyboardAwareScrollView >
</View>
</KeyboardAwareScrollView>
{/* Country BottomSheet */}
<BottomSheet
ref={countrySheetRef}
index={-1}
@@ -533,7 +474,7 @@ export default function RegisterFormScreen() {
);
}}
/>
</BottomSheet >
</BottomSheet>
</>
);
}
@@ -580,13 +521,6 @@ const styles = StyleSheet.create({
marginBottom: 8,
letterSpacing: 0.5,
},
subtitle: {
fontSize: 14,
color: '#94a3b8',
textAlign: 'center',
lineHeight: 20,
paddingHorizontal: 10,
},
card: {
backgroundColor: '#ffffff',
borderRadius: 28,
@@ -617,6 +551,15 @@ const styles = StyleSheet.create({
borderColor: '#e2e8f0',
gap: 8,
},
inputDisabled: {
backgroundColor: '#f1f5f9',
borderColor: '#e2e8f0',
},
textInput: {
flex: 1,
fontSize: 15,
color: '#1e293b',
},
bottomSheetBg: {
backgroundColor: '#ffffff',
borderTopLeftRadius: 24,
@@ -708,55 +651,6 @@ const styles = StyleSheet.create({
color: '#94a3b8',
fontWeight: '500',
},
textInput: {
flex: 1,
fontSize: 15,
color: '#1e293b',
},
passportRow: {
flexDirection: 'row',
gap: 10,
},
passportSeries: {
width: 100,
flex: undefined,
},
passportNumber: {
flex: 1,
},
infoBox: {
backgroundColor: '#f0fdf4',
padding: 14,
marginTop: 10,
borderRadius: 14,
borderWidth: 1,
borderColor: '#bbf7d0',
},
infoLabel: {
fontSize: 11,
fontWeight: '600' as const,
color: '#059669',
marginBottom: 2,
textTransform: 'uppercase',
letterSpacing: 0.5,
},
infoText: {
fontWeight: '700' as const,
color: '#166534',
fontSize: 14,
},
errorBox: {
backgroundColor: '#fef2f2',
padding: 14,
borderRadius: 14,
borderWidth: 1,
borderColor: '#fecaca',
},
errorText: {
fontWeight: '700' as const,
color: '#dc2626',
fontSize: 14,
},
btn: {
height: 54,
backgroundColor: '#2563eb',
@@ -795,11 +689,6 @@ const styles = StyleSheet.create({
borderRadius: 175,
backgroundColor: 'rgba(16, 185, 129, 0.08)',
},
inputDisabled: {
backgroundColor: '#f1f5f9',
borderColor: '#e2e8f0',
},
info: {
padding: 12,
borderRadius: 12,