register address
This commit is contained in:
2
app.json
2
app.json
@@ -2,7 +2,7 @@
|
|||||||
"expo": {
|
"expo": {
|
||||||
"name": "Info target",
|
"name": "Info target",
|
||||||
"slug": "infotarget",
|
"slug": "infotarget",
|
||||||
"version": "1.0.3",
|
"version": "1.0.5",
|
||||||
"orientation": "portrait",
|
"orientation": "portrait",
|
||||||
"icon": "./assets/images/logo.png",
|
"icon": "./assets/images/logo.png",
|
||||||
"scheme": "infotarget",
|
"scheme": "infotarget",
|
||||||
|
|||||||
@@ -25,6 +25,15 @@ interface Category {
|
|||||||
is_leaf: boolean;
|
is_leaf: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type DRFError = {
|
||||||
|
[key: string]: Array<
|
||||||
|
| string
|
||||||
|
| {
|
||||||
|
[key: string]: string[];
|
||||||
|
}
|
||||||
|
>;
|
||||||
|
};
|
||||||
|
|
||||||
export default function CategorySelectScreen() {
|
export default function CategorySelectScreen() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -74,28 +83,55 @@ export default function CategorySelectScreen() {
|
|||||||
referral: string;
|
referral: string;
|
||||||
first_name: string;
|
first_name: string;
|
||||||
last_name: string;
|
last_name: string;
|
||||||
district: number;
|
district: string;
|
||||||
company_name: string;
|
company_name: string;
|
||||||
address: number;
|
address: string;
|
||||||
}) => auth_api.register(body),
|
}) => auth_api.register(body),
|
||||||
onSuccess: async () => {
|
onSuccess: async () => {
|
||||||
router.replace('/(auth)/register-confirm');
|
router.replace('/(auth)/register-confirm');
|
||||||
await AsyncStorage.setItem('phone', phone);
|
await AsyncStorage.setItem('phone', phone);
|
||||||
},
|
},
|
||||||
onError: (err: AxiosError) => {
|
onError: (error: AxiosError<DRFError>) => {
|
||||||
const errMessage = (err.response?.data as any)?.data?.stir?.[0];
|
const data = error.response?.data as any;
|
||||||
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;
|
|
||||||
|
|
||||||
const message =
|
let message = t('Xatolik yuz berdi');
|
||||||
errMessage ||
|
|
||||||
errMessageReffral ||
|
|
||||||
errMessageDetail ||
|
|
||||||
errMessageDetailData ||
|
|
||||||
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,
|
director_full_name,
|
||||||
first_name,
|
first_name,
|
||||||
last_name,
|
last_name,
|
||||||
district: Number(district),
|
district: district,
|
||||||
address: Number(address),
|
address: address,
|
||||||
company_name
|
company_name
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||||
import { router } from 'expo-router';
|
|
||||||
import { createContext, useContext, useEffect, useState } from 'react';
|
import { createContext, useContext, useEffect, useState } from 'react';
|
||||||
|
|
||||||
type AuthContextType = {
|
type AuthContextType = {
|
||||||
@@ -32,8 +31,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||||||
const logout = async () => {
|
const logout = async () => {
|
||||||
await AsyncStorage.removeItem('access_token');
|
await AsyncStorage.removeItem('access_token');
|
||||||
await AsyncStorage.removeItem('refresh_token');
|
await AsyncStorage.removeItem('refresh_token');
|
||||||
setIsAuthenticated(false);
|
setIsAuthenticated(false)
|
||||||
router.replace('/(auth)');
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -31,7 +31,10 @@ export const CustomHeader = ({
|
|||||||
<Image source={LogoText} style={{ width: 160, height: 30, objectFit: 'contain' }} />
|
<Image source={LogoText} style={{ width: 160, height: 30, objectFit: 'contain' }} />
|
||||||
</View>
|
</View>
|
||||||
{logoutbtn && (
|
{logoutbtn && (
|
||||||
<TouchableOpacity onPress={logout}>
|
<TouchableOpacity onPress={async () => {
|
||||||
|
await logout();
|
||||||
|
router.replace('/(auth)');
|
||||||
|
}}>
|
||||||
<LogOut color={'red'} />
|
<LogOut color={'red'} />
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -16,8 +16,7 @@ const latinToCyrillicMap = [
|
|||||||
["'", ""] // apostrofni olib tashlaymiz
|
["'", ""] // apostrofni olib tashlaymiz
|
||||||
];
|
];
|
||||||
|
|
||||||
export function formatText(str: string | null) {
|
export function formatText(str: string) {
|
||||||
if (!str) return null;
|
|
||||||
let result = str;
|
let result = str;
|
||||||
for (let [latin, cyrillic] of latinToCyrillicMap) {
|
for (let [latin, cyrillic] of latinToCyrillicMap) {
|
||||||
const regex = new RegExp(latin, "g");
|
const regex = new RegExp(latin, "g");
|
||||||
@@ -32,6 +31,7 @@ const cyrillicToLatinMap = [
|
|||||||
["Ш", "Sh"], ["ш", "sh"],
|
["Ш", "Sh"], ["ш", "sh"],
|
||||||
["Ч", "Ch"], ["ч", "ch"],
|
["Ч", "Ch"], ["ч", "ch"],
|
||||||
["ё", "yo"], ["Ё", "YO"],
|
["ё", "yo"], ["Ё", "YO"],
|
||||||
|
["Я", "Ya"], ["я", "ya"],
|
||||||
["А", "A"], ["Б", "B"], ["Д", "D"], ["Е", "E"], ["Ф", "F"],
|
["А", "A"], ["Б", "B"], ["Д", "D"], ["Е", "E"], ["Ф", "F"],
|
||||||
["Г", "G"], ["Ҳ", "H"], ["И", "I"], ["Ж", "J"], ["К", "K"],
|
["Г", "G"], ["Ҳ", "H"], ["И", "I"], ["Ж", "J"], ["К", "K"],
|
||||||
["Л", "L"], ["М", "M"], ["Н", "N"], ["О", "O"], ["П", "P"],
|
["Л", "L"], ["М", "M"], ["Н", "N"], ["О", "O"], ["П", "P"],
|
||||||
@@ -44,8 +44,7 @@ const cyrillicToLatinMap = [
|
|||||||
["в", "v"], ["х", "x"], ["й", "y"], ["з", "z"],
|
["в", "v"], ["х", "x"], ["й", "y"], ["з", "z"],
|
||||||
];
|
];
|
||||||
|
|
||||||
export function formatTextToLatin(str: string | null) {
|
export function formatTextToLatin(str: string) {
|
||||||
if (!str) return null;
|
|
||||||
let result = str;
|
let result = str;
|
||||||
for (let [cyrillic, latin] of cyrillicToLatinMap) {
|
for (let [cyrillic, latin] of cyrillicToLatinMap) {
|
||||||
const regex = new RegExp(cyrillic, "g");
|
const regex = new RegExp(cyrillic, "g");
|
||||||
|
|||||||
@@ -65,7 +65,6 @@ const ConfirmScreen = () => {
|
|||||||
savedToken(res.data.data.token.access);
|
savedToken(res.data.data.token.access);
|
||||||
await AsyncStorage.setItem('refresh_token', res.data.data.token.refresh);
|
await AsyncStorage.setItem('refresh_token', res.data.data.token.refresh);
|
||||||
await login(res.data.data.token.access);
|
await login(res.data.data.token.access);
|
||||||
|
|
||||||
// **Push tokenni qayta serverga yuborish**
|
// **Push tokenni qayta serverga yuborish**
|
||||||
const pushToken = await registerForPushNotificationsAsync();
|
const pushToken = await registerForPushNotificationsAsync();
|
||||||
if (pushToken) {
|
if (pushToken) {
|
||||||
@@ -78,6 +77,7 @@ const ConfirmScreen = () => {
|
|||||||
// Notification querylarni refetch
|
// Notification querylarni refetch
|
||||||
queryClient.refetchQueries({ queryKey: ['notification-list'] });
|
queryClient.refetchQueries({ queryKey: ['notification-list'] });
|
||||||
queryClient.refetchQueries({ queryKey: ['notifications-list'] });
|
queryClient.refetchQueries({ queryKey: ['notifications-list'] });
|
||||||
|
queryClient.refetchQueries({ queryKey: ['get_me'] });
|
||||||
|
|
||||||
// Dashboardga yo‘naltirish
|
// Dashboardga yo‘naltirish
|
||||||
router.replace('/(dashboard)');
|
router.replace('/(dashboard)');
|
||||||
|
|||||||
@@ -146,8 +146,8 @@ export const auth_api = {
|
|||||||
director_full_name: string;
|
director_full_name: string;
|
||||||
first_name: string;
|
first_name: string;
|
||||||
last_name: string;
|
last_name: string;
|
||||||
district: number;
|
district: string;
|
||||||
address: number;
|
address: string;
|
||||||
company_name: string;
|
company_name: string;
|
||||||
}) {
|
}) {
|
||||||
const res = await httpClient.post(API_URLS.Register, body);
|
const res = await httpClient.post(API_URLS.Register, body);
|
||||||
|
|||||||
@@ -77,6 +77,7 @@ const RegisterConfirmScreen = () => {
|
|||||||
// Notification querylarni refetch
|
// Notification querylarni refetch
|
||||||
queryClient.refetchQueries({ queryKey: ['notification-list'] });
|
queryClient.refetchQueries({ queryKey: ['notification-list'] });
|
||||||
queryClient.refetchQueries({ queryKey: ['notifications-list'] });
|
queryClient.refetchQueries({ queryKey: ['notifications-list'] });
|
||||||
|
queryClient.refetchQueries({ queryKey: ['get_me'] });
|
||||||
|
|
||||||
// Dashboardga yo‘naltirish
|
// Dashboardga yo‘naltirish
|
||||||
router.replace('/(dashboard)');
|
router.replace('/(dashboard)');
|
||||||
|
|||||||
@@ -38,9 +38,9 @@ export default function CategorySelectScreen() {
|
|||||||
director_full_name: string;
|
director_full_name: string;
|
||||||
first_name: string;
|
first_name: string;
|
||||||
last_name: string;
|
last_name: string;
|
||||||
district: number;
|
district: string;
|
||||||
company_name: string;
|
company_name: string;
|
||||||
address: number;
|
address: string;
|
||||||
}) => auth_api.register(body),
|
}) => auth_api.register(body),
|
||||||
onSuccess: () => router.replace('/'),
|
onSuccess: () => router.replace('/'),
|
||||||
});
|
});
|
||||||
@@ -75,9 +75,9 @@ export default function CategorySelectScreen() {
|
|||||||
director_full_name: String(director_full_name),
|
director_full_name: String(director_full_name),
|
||||||
first_name: String(first_name),
|
first_name: String(first_name),
|
||||||
last_name: String(last_name),
|
last_name: String(last_name),
|
||||||
district: Number(address),
|
district: address,
|
||||||
company_name: String(company_name),
|
company_name: String(company_name),
|
||||||
address: Number(address),
|
address: address,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import AuthHeader from '@/components/ui/AuthHeader';
|
import AuthHeader from '@/components/ui/AuthHeader';
|
||||||
import { decryptToken } from '@/constants/crypto';
|
import { decryptToken } from '@/constants/crypto';
|
||||||
import { formatPhone, normalizeDigits } from '@/constants/formatPhone';
|
import { formatPhone, normalizeDigits } from '@/constants/formatPhone';
|
||||||
import { formatText, formatTextToLatin } from '@/constants/formatText';
|
|
||||||
import { products_api } from '@/screens/home/lib/api';
|
import { products_api } from '@/screens/home/lib/api';
|
||||||
import BottomSheet, { BottomSheetBackdrop, BottomSheetFlatList, BottomSheetTextInput } from '@gorhom/bottom-sheet';
|
import BottomSheet, { BottomSheetBackdrop, BottomSheetFlatList, BottomSheetTextInput } from '@gorhom/bottom-sheet';
|
||||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
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 { auth_api, GetInfo } from '../login/lib/api';
|
||||||
import PhonePrefix from '../login/ui/PhonePrefix';
|
import PhonePrefix from '../login/ui/PhonePrefix';
|
||||||
import { UseLoginForm } from '../login/ui/UseLoginForm';
|
import { UseLoginForm } from '../login/ui/UseLoginForm';
|
||||||
|
import { useResolveLocation } from './lib/useResolveLocation';
|
||||||
interface CoordsData {
|
|
||||||
lat: number;
|
|
||||||
lon: number;
|
|
||||||
polygon: [number, number][][];
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function RegisterFormScreen() {
|
export default function RegisterFormScreen() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -52,57 +46,71 @@ export default function RegisterFormScreen() {
|
|||||||
const [info, setInfo] = useState<GetInfo | null>(null);
|
const [info, setInfo] = useState<GetInfo | null>(null);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [referal, setReferal] = useState('');
|
const [referal, setReferal] = useState('');
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [district, setDistrict] = useState<string | null>(null)
|
const [token, setTokens] = useState<{ name: string, value: string } | null>(null);
|
||||||
const [region, setRegion] = useState<string | null>(null)
|
|
||||||
const [token, setTokens] = useState<{ name: string, value: string } | null>(null)
|
|
||||||
|
|
||||||
const [directorTinInput, setDirectorTinInput] = useState('');
|
const [directorTinInput, setDirectorTinInput] = useState('');
|
||||||
|
|
||||||
|
// ─── Token ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const { data } = useQuery({
|
const { data } = useQuery({
|
||||||
queryKey: ["tokens"],
|
queryKey: ["tokens"],
|
||||||
queryFn: async () => auth_api.get_tokens(),
|
queryFn: async () => auth_api.get_tokens(),
|
||||||
select(data) {
|
select(data) {
|
||||||
return data.data.data.results
|
return data.data.data.results;
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (data?.length) {
|
if (data?.length) {
|
||||||
const token = data[0]
|
const token = data[0];
|
||||||
const tokenValue = decryptToken(token.value)
|
const tokenValue = decryptToken(token.value);
|
||||||
if (tokenValue) {
|
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({
|
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) => {
|
onSuccess: (res) => {
|
||||||
setInfo(res.data);
|
setInfo(res.data);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setError(null)
|
setError(null);
|
||||||
setDistrict(res.data.address)
|
if (res.data?.address) {
|
||||||
|
resolveLocation(res.data.address);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
setInfo(null);
|
setInfo(null);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setError("Foydalanuvchi topilmadi")
|
setError("Foydalanuvchi topilmadi");
|
||||||
|
resetLocation();
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: districts } = useQuery({
|
// ─── Country list ─────────────────────────────────────────────────────────────
|
||||||
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,
|
|
||||||
})
|
|
||||||
|
|
||||||
const { data: countryResponse, isLoading: countryLoading } = useQuery({
|
const { data: countryResponse, isLoading: countryLoading } = useQuery({
|
||||||
queryKey: ['country-detail'],
|
queryKey: ['country-detail'],
|
||||||
@@ -110,109 +118,38 @@ export default function RegisterFormScreen() {
|
|||||||
select: (res) => res.data?.data || [],
|
select: (res) => res.data?.data || [],
|
||||||
});
|
});
|
||||||
|
|
||||||
const getRegionDistrictFromAddress = async (address: string) => {
|
// ─── Validation helpers ───────────────────────────────────────────────────────
|
||||||
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]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (info === null || (stir.length === 9 && info.name && info.fullName)) {
|
if (info === null || (stir.length === 9 && info.name && info.fullName)) {
|
||||||
setError(null)
|
setError(null);
|
||||||
} else if (info?.name === null || info?.fullName === 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) {
|
} 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 hasDirectorTin = info?.directorPinfl && String(info.directorPinfl).length > 0;
|
||||||
|
|
||||||
const isDirectorTinValid = !hasDirectorTin || directorTinInput === String(info.directorPinfl);
|
const isDirectorTinValid = !hasDirectorTin || directorTinInput === String(info.directorPinfl);
|
||||||
const hasValidName = Boolean(info?.name || info?.fullName);
|
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(() => {
|
const filteredCountries = useMemo(() => {
|
||||||
if (!countrySearch.trim()) return countryResponse || [];
|
if (!countrySearch.trim()) return countryResponse || [];
|
||||||
const q = countrySearch.toLowerCase().trim();
|
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]);
|
}, [countryResponse, countrySearch]);
|
||||||
|
|
||||||
const openCountrySheet = useCallback(() => {
|
const openCountrySheet = useCallback(() => {
|
||||||
@@ -225,8 +162,9 @@ export default function RegisterFormScreen() {
|
|||||||
const selectedCountryName = useMemo(() => {
|
const selectedCountryName = useMemo(() => {
|
||||||
if (!selectedCountry) return t('Tanlang');
|
if (!selectedCountry) return t('Tanlang');
|
||||||
return (
|
return (
|
||||||
countryResponse?.find((c: any) => c.flag?.toUpperCase() === selectedCountry)?.name ||
|
countryResponse?.find(
|
||||||
t('Tanlang')
|
(c: any) => c.flag?.toUpperCase() === selectedCountry
|
||||||
|
)?.name || t('Tanlang')
|
||||||
);
|
);
|
||||||
}, [selectedCountry, countryResponse, t]);
|
}, [selectedCountry, countryResponse, t]);
|
||||||
|
|
||||||
@@ -248,13 +186,7 @@ export default function RegisterFormScreen() {
|
|||||||
setTimeout(() => setCountrySearch(''), 300);
|
setTimeout(() => setCountrySearch(''), 300);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const valid =
|
// ─── Render ───────────────────────────────────────────────────────────────────
|
||||||
phone.length === 9 &&
|
|
||||||
(stir.length === 9 || stir.length === 14) &&
|
|
||||||
info &&
|
|
||||||
hasValidName &&
|
|
||||||
isDirectorTinValid &&
|
|
||||||
error === null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -295,19 +227,17 @@ export default function RegisterFormScreen() {
|
|||||||
<UserPlus size={32} color="#fff" />
|
<UserPlus size={32} color="#fff" />
|
||||||
</LinearGradient>
|
</LinearGradient>
|
||||||
</View>
|
</View>
|
||||||
<Text style={styles.title}>{t('Ro\'yxatdan o\'tish')}</Text>
|
<Text style={styles.title}>{t("Ro'yxatdan o'tish")}</Text>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
<View style={styles.card}>
|
<View style={styles.card}>
|
||||||
<View style={styles.formGap}>
|
<View style={styles.formGap}>
|
||||||
<View>
|
|
||||||
|
{/* Country */}
|
||||||
<View>
|
<View>
|
||||||
<Text style={styles.label}>{t('Davlat')}</Text>
|
<Text style={styles.label}>{t('Davlat')}</Text>
|
||||||
<TouchableOpacity
|
<TouchableOpacity
|
||||||
style={[
|
style={[styles.input, styles.inputDisabled]}
|
||||||
styles.input,
|
|
||||||
styles.inputDisabled,
|
|
||||||
]}
|
|
||||||
onPress={openCountrySheet}
|
onPress={openCountrySheet}
|
||||||
activeOpacity={0.7}
|
activeOpacity={0.7}
|
||||||
testID="country-select"
|
testID="country-select"
|
||||||
@@ -323,10 +253,7 @@ export default function RegisterFormScreen() {
|
|||||||
resizeMode="cover"
|
resizeMode="cover"
|
||||||
/>
|
/>
|
||||||
<Text
|
<Text
|
||||||
style={[
|
style={[styles.textInput, { color: '#94a3b8' }]}
|
||||||
styles.textInput,
|
|
||||||
{ color: '#94a3b8' },
|
|
||||||
]}
|
|
||||||
numberOfLines={1}
|
numberOfLines={1}
|
||||||
>
|
>
|
||||||
{selectedCountryName}
|
{selectedCountryName}
|
||||||
@@ -336,8 +263,8 @@ export default function RegisterFormScreen() {
|
|||||||
<ChevronDown size={18} color={'#cbd5e1'} />
|
<ChevronDown size={18} color={'#cbd5e1'} />
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
|
||||||
|
|
||||||
|
{/* STIR */}
|
||||||
<View>
|
<View>
|
||||||
<Text style={styles.label}>{t('STIR')}</Text>
|
<Text style={styles.label}>{t('STIR')}</Text>
|
||||||
<View style={styles.input}>
|
<View style={styles.input}>
|
||||||
@@ -351,14 +278,10 @@ export default function RegisterFormScreen() {
|
|||||||
onChangeText={(text) => {
|
onChangeText={(text) => {
|
||||||
const v = normalizeDigits(text).slice(0, 14);
|
const v = normalizeDigits(text).slice(0, 14);
|
||||||
setStir(v);
|
setStir(v);
|
||||||
|
|
||||||
if (v.length === 9 || v.length === 14) {
|
if (v.length === 9 || v.length === 14) {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
resetLocation();
|
||||||
mutate(v);
|
mutate(v);
|
||||||
setRegionId(null)
|
|
||||||
setDistrictId(null)
|
|
||||||
setRegion(null)
|
|
||||||
setDistrict(null)
|
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -366,6 +289,7 @@ export default function RegisterFormScreen() {
|
|||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
|
{/* Referal */}
|
||||||
<View>
|
<View>
|
||||||
<Text style={styles.label}>{t('Referal')}</Text>
|
<Text style={styles.label}>{t('Referal')}</Text>
|
||||||
<View style={styles.input}>
|
<View style={styles.input}>
|
||||||
@@ -382,6 +306,7 @@ export default function RegisterFormScreen() {
|
|||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
|
{/* Phone */}
|
||||||
<View>
|
<View>
|
||||||
<Text style={styles.label}>{t('Telefon raqami')}</Text>
|
<Text style={styles.label}>{t('Telefon raqami')}</Text>
|
||||||
<View style={styles.input}>
|
<View style={styles.input}>
|
||||||
@@ -397,10 +322,16 @@ export default function RegisterFormScreen() {
|
|||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
|
{/* Director TIN */}
|
||||||
{hasDirectorTin && (
|
{hasDirectorTin && (
|
||||||
<View>
|
<View>
|
||||||
<Text style={styles.label}>{t('Direktor STIR')}</Text>
|
<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" />
|
<Hash size={18} color="#94a3b8" />
|
||||||
<TextInput
|
<TextInput
|
||||||
value={directorTinInput}
|
value={directorTinInput}
|
||||||
@@ -412,19 +343,22 @@ export default function RegisterFormScreen() {
|
|||||||
onChangeText={(t) => setDirectorTinInput(normalizeDigits(t))}
|
onChangeText={(t) => setDirectorTinInput(normalizeDigits(t))}
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
{directorTinInput.length === 14 && !isDirectorTinValid && (
|
{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>
|
</View>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{error !== null ?
|
{/* Info / Error */}
|
||||||
|
{error !== null ? (
|
||||||
<Text style={styles.notFound}>{t(error)}</Text>
|
<Text style={styles.notFound}>{t(error)}</Text>
|
||||||
: info && hasValidName &&
|
) : (
|
||||||
|
info && hasValidName && (
|
||||||
<Text style={styles.info}>{info.fullName || info.name}</Text>
|
<Text style={styles.info}>{info.fullName || info.name}</Text>
|
||||||
}
|
)
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Submit */}
|
||||||
<TouchableOpacity
|
<TouchableOpacity
|
||||||
disabled={!valid}
|
disabled={!valid}
|
||||||
style={[styles.btn, !valid && styles.disabled]}
|
style={[styles.btn, !valid && styles.disabled]}
|
||||||
@@ -437,26 +371,33 @@ export default function RegisterFormScreen() {
|
|||||||
first_name: stir.length === 9 ? info?.director : info?.fullName,
|
first_name: stir.length === 9 ? info?.director : info?.fullName,
|
||||||
last_name: stir.length === 9 ? info?.director : info?.fullName,
|
last_name: stir.length === 9 ? info?.director : info?.fullName,
|
||||||
company_name: info?.name,
|
company_name: info?.name,
|
||||||
district: districtId !== null ? districtId : regionId,
|
district: location.district?.id,
|
||||||
address: districtId !== null ? districtId : regionId,
|
address: location.district?.id,
|
||||||
director_full_name: stir.length === 9 ? info?.director : info?.fullName,
|
director_full_name: stir.length === 9 ? info?.director : info?.fullName,
|
||||||
stir,
|
stir,
|
||||||
referal,
|
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>
|
<Text style={styles.btnText}>{t('Davom etish')}</Text>
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
|
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
</SafeAreaView>
|
</SafeAreaView>
|
||||||
</View >
|
</View>
|
||||||
</KeyboardAwareScrollView >
|
</KeyboardAwareScrollView>
|
||||||
|
|
||||||
|
{/* Country BottomSheet */}
|
||||||
<BottomSheet
|
<BottomSheet
|
||||||
ref={countrySheetRef}
|
ref={countrySheetRef}
|
||||||
index={-1}
|
index={-1}
|
||||||
@@ -533,7 +474,7 @@ export default function RegisterFormScreen() {
|
|||||||
);
|
);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</BottomSheet >
|
</BottomSheet>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -580,13 +521,6 @@ const styles = StyleSheet.create({
|
|||||||
marginBottom: 8,
|
marginBottom: 8,
|
||||||
letterSpacing: 0.5,
|
letterSpacing: 0.5,
|
||||||
},
|
},
|
||||||
subtitle: {
|
|
||||||
fontSize: 14,
|
|
||||||
color: '#94a3b8',
|
|
||||||
textAlign: 'center',
|
|
||||||
lineHeight: 20,
|
|
||||||
paddingHorizontal: 10,
|
|
||||||
},
|
|
||||||
card: {
|
card: {
|
||||||
backgroundColor: '#ffffff',
|
backgroundColor: '#ffffff',
|
||||||
borderRadius: 28,
|
borderRadius: 28,
|
||||||
@@ -617,6 +551,15 @@ const styles = StyleSheet.create({
|
|||||||
borderColor: '#e2e8f0',
|
borderColor: '#e2e8f0',
|
||||||
gap: 8,
|
gap: 8,
|
||||||
},
|
},
|
||||||
|
inputDisabled: {
|
||||||
|
backgroundColor: '#f1f5f9',
|
||||||
|
borderColor: '#e2e8f0',
|
||||||
|
},
|
||||||
|
textInput: {
|
||||||
|
flex: 1,
|
||||||
|
fontSize: 15,
|
||||||
|
color: '#1e293b',
|
||||||
|
},
|
||||||
bottomSheetBg: {
|
bottomSheetBg: {
|
||||||
backgroundColor: '#ffffff',
|
backgroundColor: '#ffffff',
|
||||||
borderTopLeftRadius: 24,
|
borderTopLeftRadius: 24,
|
||||||
@@ -708,55 +651,6 @@ const styles = StyleSheet.create({
|
|||||||
color: '#94a3b8',
|
color: '#94a3b8',
|
||||||
fontWeight: '500',
|
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: {
|
btn: {
|
||||||
height: 54,
|
height: 54,
|
||||||
backgroundColor: '#2563eb',
|
backgroundColor: '#2563eb',
|
||||||
@@ -795,11 +689,6 @@ const styles = StyleSheet.create({
|
|||||||
borderRadius: 175,
|
borderRadius: 175,
|
||||||
backgroundColor: 'rgba(16, 185, 129, 0.08)',
|
backgroundColor: 'rgba(16, 185, 129, 0.08)',
|
||||||
},
|
},
|
||||||
inputDisabled: {
|
|
||||||
backgroundColor: '#f1f5f9',
|
|
||||||
borderColor: '#e2e8f0',
|
|
||||||
},
|
|
||||||
|
|
||||||
info: {
|
info: {
|
||||||
padding: 12,
|
padding: 12,
|
||||||
borderRadius: 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}
|
contentContainerStyle={styles.listContent}
|
||||||
showsVerticalScrollIndicator={false}
|
showsVerticalScrollIndicator={false}
|
||||||
ListHeaderComponent={() => {
|
ListHeaderComponent={() => {
|
||||||
if (notifications.length === 0) {
|
if (notifications.length > 0 && notifications.some((n) => !n.is_read)) {
|
||||||
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)) {
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.headerActions}>
|
<View style={styles.headerActions}>
|
||||||
<TouchableOpacity
|
<TouchableOpacity
|
||||||
@@ -150,6 +126,7 @@ export function NotificationTab() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.allReadContainer}>
|
<View style={styles.allReadContainer}>
|
||||||
|
{notifications.length > 0 && (
|
||||||
<Text
|
<Text
|
||||||
style={[
|
style={[
|
||||||
styles.allReadText,
|
styles.allReadText,
|
||||||
@@ -158,6 +135,7 @@ export function NotificationTab() {
|
|||||||
>
|
>
|
||||||
{t("Barcha bildirishnomalar o‘qilgan")}
|
{t("Barcha bildirishnomalar o‘qilgan")}
|
||||||
</Text>
|
</Text>
|
||||||
|
)}
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}}
|
}}
|
||||||
|
|||||||
Reference in New Issue
Block a user