register address
This commit is contained in:
2
app.json
2
app.json
@@ -2,7 +2,7 @@
|
||||
"expo": {
|
||||
"name": "Info target",
|
||||
"slug": "infotarget",
|
||||
"version": "1.0.3",
|
||||
"version": "1.0.5",
|
||||
"orientation": "portrait",
|
||||
"icon": "./assets/images/logo.png",
|
||||
"scheme": "infotarget",
|
||||
|
||||
@@ -25,6 +25,15 @@ interface Category {
|
||||
is_leaf: boolean;
|
||||
}
|
||||
|
||||
type DRFError = {
|
||||
[key: string]: Array<
|
||||
| string
|
||||
| {
|
||||
[key: string]: string[];
|
||||
}
|
||||
>;
|
||||
};
|
||||
|
||||
export default function CategorySelectScreen() {
|
||||
const router = useRouter();
|
||||
const { t } = useTranslation();
|
||||
@@ -74,28 +83,55 @@ export default function CategorySelectScreen() {
|
||||
referral: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
district: number;
|
||||
district: string;
|
||||
company_name: string;
|
||||
address: number;
|
||||
address: string;
|
||||
}) => auth_api.register(body),
|
||||
onSuccess: async () => {
|
||||
router.replace('/(auth)/register-confirm');
|
||||
await AsyncStorage.setItem('phone', phone);
|
||||
},
|
||||
onError: (err: AxiosError) => {
|
||||
const errMessage = (err.response?.data as any)?.data?.stir?.[0];
|
||||
const errMessageDetail = (err.response?.data as any)?.data?.detail;
|
||||
const errMessageReffral = (err.response?.data as any).data.referral[0];
|
||||
const errMessageDetailData = (err.response?.data as any)?.data;
|
||||
onError: (error: AxiosError<DRFError>) => {
|
||||
const data = error.response?.data as any;
|
||||
|
||||
const message =
|
||||
errMessage ||
|
||||
errMessageReffral ||
|
||||
errMessageDetail ||
|
||||
errMessageDetailData ||
|
||||
t('Xatolik yuz berdi');
|
||||
let message = t('Xatolik yuz berdi');
|
||||
|
||||
Toast.error(String(message));
|
||||
if (data) {
|
||||
const source = data.data || data; // 🔥 ba'zida data ichida keladi
|
||||
|
||||
if (typeof source === 'object') {
|
||||
const firstKey = Object.keys(source)[0];
|
||||
const firstValue = source[firstKey];
|
||||
|
||||
// ✅ 1️⃣ Agar oddiy string array bo‘lsa
|
||||
if (Array.isArray(firstValue) && typeof firstValue[0] === 'string') {
|
||||
message = firstValue[0];
|
||||
}
|
||||
|
||||
// ✅ 2️⃣ Agar nested object bo‘lsa
|
||||
else if (Array.isArray(firstValue) && typeof firstValue[0] === 'object') {
|
||||
const firstErrorObj = firstValue[0];
|
||||
const innerKey = Object.keys(firstErrorObj)[0];
|
||||
const innerValue = firstErrorObj[innerKey];
|
||||
|
||||
if (Array.isArray(innerValue)) {
|
||||
message = innerValue[0];
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ 3️⃣ Agar string bo‘lsa
|
||||
else if (typeof firstValue === 'string') {
|
||||
message = firstValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ❗ Network error fallback
|
||||
if (!error.response) {
|
||||
message = error.message;
|
||||
}
|
||||
|
||||
Toast.error(message);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -163,8 +199,8 @@ export default function CategorySelectScreen() {
|
||||
director_full_name,
|
||||
first_name,
|
||||
last_name,
|
||||
district: Number(district),
|
||||
address: Number(address),
|
||||
district: district,
|
||||
address: address,
|
||||
company_name
|
||||
});
|
||||
}}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { router } from 'expo-router';
|
||||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
|
||||
type AuthContextType = {
|
||||
@@ -32,8 +31,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const logout = async () => {
|
||||
await AsyncStorage.removeItem('access_token');
|
||||
await AsyncStorage.removeItem('refresh_token');
|
||||
setIsAuthenticated(false);
|
||||
router.replace('/(auth)');
|
||||
setIsAuthenticated(false)
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -31,7 +31,10 @@ export const CustomHeader = ({
|
||||
<Image source={LogoText} style={{ width: 160, height: 30, objectFit: 'contain' }} />
|
||||
</View>
|
||||
{logoutbtn && (
|
||||
<TouchableOpacity onPress={logout}>
|
||||
<TouchableOpacity onPress={async () => {
|
||||
await logout();
|
||||
router.replace('/(auth)');
|
||||
}}>
|
||||
<LogOut color={'red'} />
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
|
||||
@@ -16,8 +16,7 @@ const latinToCyrillicMap = [
|
||||
["'", ""] // apostrofni olib tashlaymiz
|
||||
];
|
||||
|
||||
export function formatText(str: string | null) {
|
||||
if (!str) return null;
|
||||
export function formatText(str: string) {
|
||||
let result = str;
|
||||
for (let [latin, cyrillic] of latinToCyrillicMap) {
|
||||
const regex = new RegExp(latin, "g");
|
||||
@@ -32,6 +31,7 @@ const cyrillicToLatinMap = [
|
||||
["Ш", "Sh"], ["ш", "sh"],
|
||||
["Ч", "Ch"], ["ч", "ch"],
|
||||
["ё", "yo"], ["Ё", "YO"],
|
||||
["Я", "Ya"], ["я", "ya"],
|
||||
["А", "A"], ["Б", "B"], ["Д", "D"], ["Е", "E"], ["Ф", "F"],
|
||||
["Г", "G"], ["Ҳ", "H"], ["И", "I"], ["Ж", "J"], ["К", "K"],
|
||||
["Л", "L"], ["М", "M"], ["Н", "N"], ["О", "O"], ["П", "P"],
|
||||
@@ -44,8 +44,7 @@ const cyrillicToLatinMap = [
|
||||
["в", "v"], ["х", "x"], ["й", "y"], ["з", "z"],
|
||||
];
|
||||
|
||||
export function formatTextToLatin(str: string | null) {
|
||||
if (!str) return null;
|
||||
export function formatTextToLatin(str: string) {
|
||||
let result = str;
|
||||
for (let [cyrillic, latin] of cyrillicToLatinMap) {
|
||||
const regex = new RegExp(cyrillic, "g");
|
||||
|
||||
@@ -65,7 +65,6 @@ const ConfirmScreen = () => {
|
||||
savedToken(res.data.data.token.access);
|
||||
await AsyncStorage.setItem('refresh_token', res.data.data.token.refresh);
|
||||
await login(res.data.data.token.access);
|
||||
|
||||
// **Push tokenni qayta serverga yuborish**
|
||||
const pushToken = await registerForPushNotificationsAsync();
|
||||
if (pushToken) {
|
||||
@@ -78,6 +77,7 @@ const ConfirmScreen = () => {
|
||||
// Notification querylarni refetch
|
||||
queryClient.refetchQueries({ queryKey: ['notification-list'] });
|
||||
queryClient.refetchQueries({ queryKey: ['notifications-list'] });
|
||||
queryClient.refetchQueries({ queryKey: ['get_me'] });
|
||||
|
||||
// Dashboardga yo‘naltirish
|
||||
router.replace('/(dashboard)');
|
||||
|
||||
@@ -146,8 +146,8 @@ export const auth_api = {
|
||||
director_full_name: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
district: number;
|
||||
address: number;
|
||||
district: string;
|
||||
address: string;
|
||||
company_name: string;
|
||||
}) {
|
||||
const res = await httpClient.post(API_URLS.Register, body);
|
||||
|
||||
@@ -77,6 +77,7 @@ const RegisterConfirmScreen = () => {
|
||||
// Notification querylarni refetch
|
||||
queryClient.refetchQueries({ queryKey: ['notification-list'] });
|
||||
queryClient.refetchQueries({ queryKey: ['notifications-list'] });
|
||||
queryClient.refetchQueries({ queryKey: ['get_me'] });
|
||||
|
||||
// Dashboardga yo‘naltirish
|
||||
router.replace('/(dashboard)');
|
||||
|
||||
@@ -38,9 +38,9 @@ export default function CategorySelectScreen() {
|
||||
director_full_name: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
district: number;
|
||||
district: string;
|
||||
company_name: string;
|
||||
address: number;
|
||||
address: string;
|
||||
}) => auth_api.register(body),
|
||||
onSuccess: () => router.replace('/'),
|
||||
});
|
||||
@@ -75,9 +75,9 @@ export default function CategorySelectScreen() {
|
||||
director_full_name: String(director_full_name),
|
||||
first_name: String(first_name),
|
||||
last_name: String(last_name),
|
||||
district: Number(address),
|
||||
district: address,
|
||||
company_name: String(company_name),
|
||||
address: Number(address),
|
||||
address: address,
|
||||
});
|
||||
}
|
||||
}}
|
||||
|
||||
@@ -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 noto‘g‘ri')}</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,
|
||||
|
||||
340
screens/auth/register/lib/useResolveLocation.ts
Normal file
340
screens/auth/register/lib/useResolveLocation.ts
Normal file
@@ -0,0 +1,340 @@
|
||||
// hooks/useResolveLocation.ts
|
||||
import axios from "axios";
|
||||
import { useCallback, useState } from "react";
|
||||
|
||||
// ─── Types ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface District {
|
||||
districtId: number;
|
||||
name: string;
|
||||
regionId: number;
|
||||
}
|
||||
|
||||
export interface Region {
|
||||
regionId: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ResolvedLocation {
|
||||
region: { id: number; name: string } | null;
|
||||
district: { id: number; name: string } | null;
|
||||
}
|
||||
|
||||
interface NominatimAddress {
|
||||
state?: string;
|
||||
county?: string;
|
||||
district?: string;
|
||||
suburb?: string;
|
||||
city_district?: string;
|
||||
}
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
// utils/geoLocation.ts
|
||||
|
||||
// ─── Extract meaningful location keyword from raw street address ──────────────
|
||||
function extractLocationKeyword(address: string): string[] {
|
||||
const keywords: string[] = [];
|
||||
const lower = address.toLowerCase();
|
||||
|
||||
// Pattern 1: "X район" or "X tumani" or "X district"
|
||||
const districtMatch = lower.match(
|
||||
/([а-яёa-z\-]+(?:\s[а-яёa-z\-]+)?)\s*(район|tumani|tuman|district)/i,
|
||||
);
|
||||
if (districtMatch?.[1]) keywords.push(districtMatch[1].trim());
|
||||
|
||||
// Pattern 2: "X МФЙ" (mahalla) — the word before МФЙ is usually district name
|
||||
const mfyMatch = lower.match(/([а-яёa-z\-]+(?:\s[а-яёa-z\-]+)?)\s*мфй/i);
|
||||
if (mfyMatch?.[1]) keywords.push(mfyMatch[1].trim());
|
||||
|
||||
// Pattern 3: First word of address (last resort)
|
||||
const firstWord = address.trim().split(/[\s,]+/)[0];
|
||||
if (firstWord) keywords.push(firstWord);
|
||||
|
||||
// Always include full address for Nominatim
|
||||
keywords.push(address);
|
||||
|
||||
return [...new Set(keywords)]; // deduplicate
|
||||
}
|
||||
|
||||
// Normalize Cyrillic/Uzbek → Latin for fuzzy matching
|
||||
function toLatinLower(str: string): string {
|
||||
return (
|
||||
str
|
||||
.toLowerCase()
|
||||
.replace(/ш/g, "sh")
|
||||
.replace(/ч/g, "ch")
|
||||
.replace(/ж/g, "zh")
|
||||
.replace(/ъ/g, "")
|
||||
.replace(/ь/g, "")
|
||||
.replace(/а/g, "a")
|
||||
.replace(/б/g, "b")
|
||||
.replace(/в/g, "v")
|
||||
.replace(/г/g, "g")
|
||||
.replace(/д/g, "d")
|
||||
.replace(/е/g, "e")
|
||||
.replace(/ё/g, "yo")
|
||||
.replace(/з/g, "z")
|
||||
.replace(/и/g, "i")
|
||||
.replace(/й/g, "y")
|
||||
.replace(/к/g, "k")
|
||||
.replace(/л/g, "l")
|
||||
.replace(/м/g, "m")
|
||||
.replace(/н/g, "n")
|
||||
.replace(/о/g, "o")
|
||||
.replace(/п/g, "p")
|
||||
.replace(/р/g, "r")
|
||||
.replace(/с/g, "s")
|
||||
.replace(/т/g, "t")
|
||||
.replace(/у/g, "u")
|
||||
.replace(/ф/g, "f")
|
||||
.replace(/х/g, "x")
|
||||
.replace(/ц/g, "ts")
|
||||
.replace(/щ/g, "sh")
|
||||
.replace(/э/g, "e")
|
||||
.replace(/ю/g, "yu")
|
||||
.replace(/я/g, "ya")
|
||||
// Uzbek specific
|
||||
.replace(/ў/g, "o")
|
||||
.replace(/қ/g, "q")
|
||||
.replace(/ғ/g, "g")
|
||||
.replace(/ҳ/g, "h")
|
||||
.replace(/[''`]/g, "")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
);
|
||||
}
|
||||
|
||||
// Score-based fuzzy match: returns 0–1 similarity
|
||||
function matchScore(source: string, target: string): number {
|
||||
const s = toLatinLower(source);
|
||||
const t = toLatinLower(target);
|
||||
if (s === t) return 1;
|
||||
if (s.includes(t) || t.includes(s)) return 0.9;
|
||||
|
||||
// Compare first meaningful word
|
||||
const sWord = s.split(" ")[0];
|
||||
const tWord = t.split(" ")[0];
|
||||
if (sWord === tWord) return 0.8;
|
||||
if (sWord.length >= 4 && tWord.includes(sWord.slice(0, 5))) return 0.7;
|
||||
if (tWord.length >= 4 && sWord.includes(tWord.slice(0, 5))) return 0.7;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
function findBestDistrictMatch(
|
||||
query: string,
|
||||
list: District[],
|
||||
threshold = 0.7,
|
||||
): District | null {
|
||||
let best: District | null = null;
|
||||
let bestScore = 0;
|
||||
|
||||
for (const item of list) {
|
||||
const score = matchScore(query, item.name);
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
best = item;
|
||||
}
|
||||
}
|
||||
return bestScore >= threshold ? best : null;
|
||||
}
|
||||
|
||||
function findBestRegionMatch(
|
||||
query: string,
|
||||
list: Region[],
|
||||
threshold = 0.7,
|
||||
): Region | null {
|
||||
let best: Region | null = null;
|
||||
let bestScore = 0;
|
||||
|
||||
|
||||
for (const item of list) {
|
||||
const score = matchScore(query, item.name);
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
best = item;
|
||||
}
|
||||
}
|
||||
return bestScore >= threshold ? best : null;
|
||||
}
|
||||
|
||||
// ─── Nominatim geocoder ───────────────────────────────────────────────────────
|
||||
|
||||
async function geocodeAddress(
|
||||
address: string,
|
||||
): Promise<NominatimAddress | null> {
|
||||
const queries = extractLocationKeyword(address);
|
||||
|
||||
for (const query of queries) {
|
||||
try {
|
||||
const encoded = encodeURIComponent(`${query}, 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 (your@email.com)",
|
||||
},
|
||||
},
|
||||
);
|
||||
const data = await res.json();
|
||||
if (data.length > 0) {
|
||||
return data[0].address as NominatimAddress;
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── Fetch districts & regions ────────────────────────────────────────────────
|
||||
|
||||
async function fetchDistricts(
|
||||
token: string,
|
||||
tokenName: string,
|
||||
): Promise<District[]> {
|
||||
const res = await axios.get("https://testapi3.didox.uz/v1/districts/all/", {
|
||||
headers: { "Accept-Language": "uz", [tokenName]: token },
|
||||
});
|
||||
// handle both array and {data: [...]} shapes
|
||||
return Array.isArray(res.data) ? res.data : (res.data?.data ?? []);
|
||||
}
|
||||
|
||||
async function fetchRegions(
|
||||
token: string,
|
||||
tokenName: string,
|
||||
): Promise<Region[]> {
|
||||
const res = await axios.get("https://testapi3.didox.uz/v1/regions/all/", {
|
||||
headers: { "Accept-Language": "uz", [tokenName]: token },
|
||||
});
|
||||
return Array.isArray(res.data) ? res.data : (res.data?.data ?? []);
|
||||
}
|
||||
|
||||
// ─── Core resolver (usable standalone, outside React) ────────────────────────
|
||||
|
||||
export async function resolveLocationFromAddress(
|
||||
rawAddress: string,
|
||||
token: string,
|
||||
tokenName: string,
|
||||
): Promise<ResolvedLocation> {
|
||||
if (!rawAddress?.trim() || !token || !tokenName) {
|
||||
return { region: null, district: null };
|
||||
}
|
||||
|
||||
const [geo, districts, regions] = await Promise.all([
|
||||
geocodeAddress(rawAddress),
|
||||
fetchDistricts(token, tokenName),
|
||||
fetchRegions(token, tokenName),
|
||||
]);
|
||||
|
||||
// Build candidates from Nominatim + direct address keywords
|
||||
const addressKeywords = extractLocationKeyword(rawAddress);
|
||||
|
||||
const candidates = [
|
||||
geo?.county,
|
||||
geo?.city_district,
|
||||
geo?.district,
|
||||
geo?.suburb,
|
||||
geo?.state,
|
||||
...addressKeywords, // ← include extracted keywords directly
|
||||
].filter(Boolean) as string[];
|
||||
|
||||
// ── Try DISTRICT match first ──
|
||||
for (const candidate of candidates) {
|
||||
const matched = findBestDistrictMatch(candidate, districts);
|
||||
if (matched) {
|
||||
const parentRegion =
|
||||
regions.find((r: Region) => r.regionId === matched.regionId) ?? null;
|
||||
return {
|
||||
district: { id: matched.districtId, name: matched.name },
|
||||
region: parentRegion
|
||||
? { id: parentRegion.regionId, name: parentRegion.name }
|
||||
: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ── Fall back to REGION match ──
|
||||
for (const candidate of candidates) {
|
||||
const matched = findBestRegionMatch(candidate, regions);
|
||||
if (matched) {
|
||||
return {
|
||||
region: { id: matched.regionId, name: matched.name },
|
||||
district: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { region: null, district: null };
|
||||
}
|
||||
|
||||
// ─── Hook ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface UseResolveLocationOptions {
|
||||
token: string | null;
|
||||
tokenName: string | null;
|
||||
}
|
||||
|
||||
|
||||
interface UseResolveLocationReturn {
|
||||
location: ResolvedLocation;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
resolve: (address: string) => Promise<void>;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
export function useResolveLocation({
|
||||
token,
|
||||
tokenName,
|
||||
}: UseResolveLocationOptions): UseResolveLocationReturn {
|
||||
const [location, setLocation] = useState<ResolvedLocation>({
|
||||
region: null,
|
||||
district: null,
|
||||
});
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const resolve = useCallback(
|
||||
async (address: string) => {
|
||||
if (!token || !tokenName) {
|
||||
setError("Token not ready");
|
||||
return;
|
||||
}
|
||||
if (!address?.trim()) {
|
||||
setError("Address is empty");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await resolveLocationFromAddress(
|
||||
address,
|
||||
token,
|
||||
tokenName,
|
||||
);
|
||||
setLocation(result);
|
||||
|
||||
if (!result.region && !result.district) {
|
||||
setError("Location not found");
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e?.message ?? "Failed to resolve location");
|
||||
setLocation({ region: null, district: null });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[token, tokenName],
|
||||
);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setLocation({ region: null, district: null });
|
||||
setError(null);
|
||||
setIsLoading(false);
|
||||
}, []);
|
||||
|
||||
return { location, isLoading, error, resolve, reset };
|
||||
}
|
||||
@@ -98,31 +98,7 @@ export function NotificationTab() {
|
||||
contentContainerStyle={styles.listContent}
|
||||
showsVerticalScrollIndicator={false}
|
||||
ListHeaderComponent={() => {
|
||||
if (notifications.length === 0) {
|
||||
return (
|
||||
<View style={styles.emptyHeader}>
|
||||
<Text
|
||||
style={[
|
||||
styles.emptyTitle,
|
||||
{ color: isDark ? '#f1f5f9' : '#0f172a' },
|
||||
]}
|
||||
>
|
||||
{t("Hozircha bildirishnomalar yo'q")}
|
||||
</Text>
|
||||
|
||||
<Text
|
||||
style={[
|
||||
styles.emptyDesc,
|
||||
{ color: isDark ? '#94a3b8' : '#64748b' },
|
||||
]}
|
||||
>
|
||||
{t("Yangi xabarlar shu yerda paydo bo‘ladi")}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (notifications.some((n) => !n.is_read)) {
|
||||
if (notifications.length > 0 && notifications.some((n) => !n.is_read)) {
|
||||
return (
|
||||
<View style={styles.headerActions}>
|
||||
<TouchableOpacity
|
||||
@@ -150,14 +126,16 @@ export function NotificationTab() {
|
||||
|
||||
return (
|
||||
<View style={styles.allReadContainer}>
|
||||
<Text
|
||||
style={[
|
||||
styles.allReadText,
|
||||
{ color: isDark ? '#94a3b8' : '#64748b' },
|
||||
]}
|
||||
>
|
||||
{t("Barcha bildirishnomalar o‘qilgan")}
|
||||
</Text>
|
||||
{notifications.length > 0 && (
|
||||
<Text
|
||||
style={[
|
||||
styles.allReadText,
|
||||
{ color: isDark ? '#94a3b8' : '#64748b' },
|
||||
]}
|
||||
>
|
||||
{t("Barcha bildirishnomalar o‘qilgan")}
|
||||
</Text>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}}
|
||||
|
||||
Reference in New Issue
Block a user