create address + fix location restaurant

This commit is contained in:
hamid zarghami
2025-11-27 09:47:14 +03:30
parent b3716d8602
commit fa7f95df43
17 changed files with 711 additions and 368 deletions
@@ -32,31 +32,35 @@ function OrderTrackingPage() {
const router = useRouter();
const { state: cancelModal, toggle: toggleCancelModal } = useToggle();
// Example initial position (Tehran)
const initialPosition = React.useMemo<[number, number]>(() => [35.6892, 51.3890], []);
useEffect(() => {
// Initialize markers on the client side
const initializeMarkers = async () => {
// Dynamic import of Leaflet on the client side
const L = (await import('leaflet')).default;
const iconHtml = `
<div style="display: flex; flex-direction: column; align-items: center; text-align: center;">
<img src="/icons/restaurant-marker.svg" alt="موقعیت رستوران" style="width: 24px; height: 30px; display: block;" />
</div>
`;
setMarkers([
{
position: initialPosition,
title: 'Restaurant Location',
icon: new L.Icon({
iconUrl: '/icons/restaurant-marker.png',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
position: mapCenter,
title: 'موقعیت رستوران',
icon: L.divIcon({
html: iconHtml,
className: 'custom-restaurant-marker',
iconSize: [32, 32],
iconAnchor: [16, 32],
popupAnchor: [0, -32],
})
}
]);
};
initializeMarkers();
}, [initialPosition]);
}, [mapCenter]);
const handleZoomChange = (zoom: number) => {
@@ -0,0 +1,19 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { createAddress, getAddresses } from "../service/AddressService";
export const useGetAddresses = () => {
return useQuery({
queryKey: ["addresses"],
queryFn: () => getAddresses(),
});
};
export const useCreateAddress = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: createAddress,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["addresses"] });
},
});
};
@@ -0,0 +1,72 @@
import AnimatedBottomSheet from '@/components/bottomsheet/AnimatedBottomSheet';
import Button from '@/components/button/PrimaryButton';
import { AddressDisplay } from './AddressDisplay';
import { AddressForm } from './AddressForm';
import { NominatimReverseGeocodingResponse } from '../../types/Types';
interface AddressDetailsModalProps {
visible: boolean;
selectedAddress: NominatimReverseGeocodingResponse | null;
formData: {
title: string;
addressDetails: string;
phone: string;
postalCode: string;
isDefault: boolean;
};
isPending: boolean;
onClose: () => void;
onFormDataChange: (data: Partial<AddressDetailsModalProps['formData']>) => void;
onSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
}
export const AddressDetailsModal = ({
visible,
selectedAddress,
formData,
isPending,
onClose,
onFormDataChange,
onSubmit,
}: AddressDetailsModalProps) => {
return (
<AnimatedBottomSheet
bgOpacity={0}
inDuration={0}
blurOpacity={null}
noBlur
visible={visible}
title='آدرس'
onClick={onClose}
overrideClassName='bg-container!'
>
<form onSubmit={onSubmit}>
<div className='px-4'>
<AddressDisplay selectedAddress={selectedAddress} />
<AddressForm
formData={formData}
selectedAddress={selectedAddress}
onFormDataChange={onFormDataChange}
/>
<div className='grid grid-cols-2 gap-4 mt-16'>
<Button
type='submit'
disabled={isPending}
>
{isPending ? 'در حال ثبت...' : 'تایید'}
</Button>
<Button
type='button'
onClick={onClose}
className='bg-disabled! text-foreground!'
disabled={isPending}
>
انصراف
</Button>
</div>
</div>
</form>
</AnimatedBottomSheet>
);
};
@@ -0,0 +1,23 @@
import { Skeleton } from '@/components/ui/skeleton';
import { NominatimReverseGeocodingResponse } from '../../types/Types';
import { formatSelectedAddress } from '../utils/formatAddress';
interface AddressDisplayProps {
selectedAddress: NominatimReverseGeocodingResponse | null;
}
export const AddressDisplay = ({ selectedAddress }: AddressDisplayProps) => {
return (
<div className='px-4 mt-2 bg-container'>
<span className='text-sm'>
{!selectedAddress ? (
<Skeleton className='h-6 w-full' />
) : (
formatSelectedAddress(selectedAddress)
)}
</span>
<hr className='border border-border mt-3 mb-10' />
</div>
);
};
@@ -0,0 +1,74 @@
import InputField from '@/components/input/InputField';
import { NominatimReverseGeocodingResponse } from '../../types/Types';
interface AddressFormProps {
formData: {
title: string;
addressDetails: string;
phone: string;
postalCode: string;
isDefault: boolean;
};
selectedAddress: NominatimReverseGeocodingResponse | null;
onFormDataChange: (data: Partial<AddressFormProps['formData']>) => void;
}
export const AddressForm = ({
formData,
selectedAddress,
onFormDataChange,
}: AddressFormProps) => {
return (
<div className='px-4'>
<InputField
htmlFor={'addressTitle'}
labelText={'عنوان آدرس'}
placeholder='مثال: منزل، محل کار ...'
className='bg-inherit'
value={formData.title}
onChange={(e) => onFormDataChange({ title: e.target.value })}
/>
<InputField
htmlFor={'addressDetails'}
labelText={'جزئیات آدرس'}
placeholder='میدان باغ ملی، مجتمع آسمان، واحد 12، پلاک 1234567890'
className='bg-inherit mt-8'
value={formData.addressDetails}
onChange={(e) => onFormDataChange({ addressDetails: e.target.value })}
/>
<InputField
htmlFor={'phone'}
labelText={'شماره تلفن'}
placeholder='09123456789'
className='bg-inherit mt-8'
value={formData.phone}
onChange={(e) => onFormDataChange({ phone: e.target.value })}
/>
<InputField
htmlFor={'postalCode'}
labelText={'کد پستی'}
placeholder={selectedAddress?.address?.postcode || '1234567890'}
className='bg-inherit mt-8'
value={formData.postalCode || selectedAddress?.address?.postcode || ''}
onChange={(e) => onFormDataChange({ postalCode: e.target.value })}
/>
<div className='inline-flex justify-between items-center w-full mt-8'>
<label
htmlFor={'isDefault'}
className='text-sm2 px-2 py-0.5 mt-0.5 cursor-pointer'
>
تنظیم به عنوان آدرس پیشفرض
</label>
<input
name={'isDefault'}
id={'isDefault'}
className='h-4.5 w-4.5 checked:accent-primary cursor-pointer'
onChange={(e) => onFormDataChange({ isDefault: e.target.checked })}
type='checkbox'
checked={formData.isDefault}
/>
</div>
</div>
);
};
@@ -0,0 +1,40 @@
import AnimatedBottomSheet from '@/components/bottomsheet/AnimatedBottomSheet';
import Button from '@/components/button/PrimaryButton';
interface ConfirmPositionModalProps {
visible: boolean;
onConfirm: () => void;
onCancel: () => void;
}
export const ConfirmPositionModal = ({
visible,
onConfirm,
onCancel,
}: ConfirmPositionModalProps) => {
return (
<AnimatedBottomSheet
bgOpacity={0}
inDuration={0}
blurOpacity={null}
noBlur
visible={visible}
showCloseButton={false}
showTitle={false}
overrideClassName='!pt-6 bg-container!'
>
<div className='grid grid-cols-2 gap-4 px-4'>
<Button onClick={onConfirm}>
انتخاب
</Button>
<Button
onClick={onCancel}
className='bg-disabled! text-foreground!'
>
انصراف
</Button>
</div>
</AnimatedBottomSheet>
);
};
@@ -0,0 +1,87 @@
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useCreateAddress } from '../../hooks/useAddressData';
import { toast } from '@/components/Toast';
import { CreateAddressType, NominatimReverseGeocodingResponse } from '../../types/Types';
interface UseAddressFormProps {
selectedPosition: [number, number] | null;
selectedAddress: NominatimReverseGeocodingResponse | null;
initialPhone?: string;
}
export const useAddressForm = ({
selectedPosition,
selectedAddress,
initialPhone = '',
}: UseAddressFormProps) => {
const router = useRouter();
const { mutate: createAddress, isPending } = useCreateAddress();
const [formData, setFormData] = useState({
title: '',
addressDetails: '',
phone: initialPhone,
postalCode: '',
isDefault: false,
});
const handleFormDataChange = (data: Partial<typeof formData>) => {
setFormData((prev) => ({ ...prev, ...data }));
};
const submitAddress = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!selectedPosition || !selectedAddress) {
toast('لطفا موقعیت را روی نقشه انتخاب کنید', 'error');
return;
}
if (!formData.title.trim()) {
toast('لطفا عنوان آدرس را وارد کنید', 'error');
return;
}
if (!formData.addressDetails.trim()) {
toast('لطفا جزئیات آدرس را وارد کنید', 'error');
return;
}
if (!formData.phone.trim()) {
toast('لطفا شماره تلفن را وارد کنید', 'error');
return;
}
const addressData: CreateAddressType = {
title: formData.title,
address: formData.addressDetails,
city: selectedAddress.address.city || selectedAddress.address.district || '',
province: selectedAddress.address.province || selectedAddress.address.state || '',
postalCode: formData.postalCode || selectedAddress.address.postcode || '',
latitude: selectedPosition[0],
longitude: selectedPosition[1],
phone: formData.phone,
isDefault: formData.isDefault,
};
createAddress(addressData, {
onSuccess: () => {
toast('آدرس با موفقیت ثبت شد', 'success');
router.back();
},
onError: (error) => {
const errorMessage = error instanceof Error ? error.message : 'خطا در ثبت آدرس';
toast(errorMessage, 'error');
},
});
};
return {
formData,
isPending,
handleFormDataChange,
submitAddress,
};
};
@@ -2,93 +2,66 @@
import { useSearchParams } from 'next/navigation';
import React, { useState, useEffect } from 'react';
import type { Icon } from 'leaflet';
import dynamic from 'next/dynamic';
import AnimatedBottomSheet from '@/components/bottomsheet/AnimatedBottomSheet';
import Button from '@/components/button/PrimaryButton';
import InputField from '@/components/input/InputField';
import { Skeleton } from '@/components/ui/skeleton';
import useToggle from '@/hooks/helpers/useToggle';
import { useAuthStore } from '@/zustand/authStore';
import { MarkerData, NominatimReverseGeocodingResponse } from '../types/Types';
import { ConfirmPositionModal } from './components/ConfirmPositionModal';
import { AddressDetailsModal } from './components/AddressDetailsModal';
import { useAddressForm } from './hooks/useAddressForm';
import { fetchAddressFromCoordinates } from './utils/fetchAddress';
const CustomMap = dynamic(
() => import('@/components/map/CustomMap'),
{ ssr: false } // Leaflet requires browser APIs
{ ssr: false }
);
export interface MarkerData {
position: [number, number];
title: string;
icon?: Icon;
}
export interface NominatimReverseGeocodingResponse {
place_id: number
licence: string
osm_type: string
osm_id: number
lat: string
lon: string
class: string
type: string
place_rank: number
importance: number
addresstype: string
name: string
display_name: string
address: NominatimReverseGeocodingResponseAddress
boundingbox: string[]
}
export interface NominatimReverseGeocodingResponseAddress {
road: string
neighbourhood: string
suburb: string
city: string
district: string
county: string
province: string
"ISO3166-2-lvl4": string
postcode: string
country: string
state: string
country_code: string
}
function OrderTrackingPage() {
const params = useSearchParams();
const user = useAuthStore((state) => state.user);
const [selectedPosition, setSelectedPosition] = useState<[number, number] | null>(null);
const [selectedAddress, setSelectedAddress] = useState<NominatimReverseGeocodingResponse | null>(null);
const [markers, setMarkers] = useState<MarkerData[]>([]);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [mapCenter, setMapCenter] = useState<[number, number]>([Number(params?.get('lon')) || 35.6892, Number(params?.get('lon')) || 51.3890]);
const [mapCenter] = useState<[number, number]>([
Number(params?.get('lat')) || 35.6892,
Number(params?.get('lon')) || 51.3890
]);
const { state: confirmModal, toggle: toggleConfirmModal, set: setConfirmModal } = useToggle();
const { state: detailsModal, toggle: _toggleDetailsModal, set: setDetailsModal } = useToggle();
// Example initial position (Tehran)
const initialPosition = React.useMemo<[number, number]>(() => [35.6892, 51.3890], []);
const { formData, isPending, handleFormDataChange, submitAddress } = useAddressForm({
selectedPosition,
selectedAddress,
initialPhone: user?.number || '',
});
useEffect(() => {
// Initialize markers on the client side
const initializeMarkers = async () => {
// Dynamic import of Leaflet on the client side
const L = (await import('leaflet')).default;
const iconHtml = `
<div style="display: flex; flex-direction: column; align-items: center; text-align: center;">
<img src="/icons/restaurant-marker.svg" alt="موقعیت رستوران" style="width: 24px; height: 30px; display: block;" />
</div>
`;
setMarkers([
{
position: initialPosition,
title: 'Restaurant Location',
icon: new L.Icon({
iconUrl: '/icons/restaurant-marker.png',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
position: mapCenter,
title: 'موقعیت رستوران',
icon: L.divIcon({
html: iconHtml,
className: 'custom-restaurant-marker',
iconSize: [32, 32],
iconAnchor: [16, 32],
popupAnchor: [0, -32],
})
}
]);
};
initializeMarkers();
}, [initialPosition]);
}, [mapCenter]);
const handlePositionSelect = (position: [number, number]) => {
setSelectedPosition((prev) => {
@@ -100,8 +73,6 @@ function OrderTrackingPage() {
});
setConfirmModal(position && true);
setDetailsModal(false);
// You can handle the selected position here
console.log('Selected position:', position);
};
const handleZoomChange = (zoom: number) => {
@@ -112,7 +83,6 @@ function OrderTrackingPage() {
console.log('Map clicked at:', e.latlng);
};
const toggleDetailsModal = async () => {
if (!selectedPosition) {
setConfirmModal(false);
@@ -122,59 +92,16 @@ function OrderTrackingPage() {
setConfirmModal(false);
_toggleDetailsModal();
if (!detailsModal) {
const address = await fetchAddressFromCoordinates(selectedPosition[0], selectedPosition[1]);
setSelectedAddress(address);
}
}
const fetchAddressFromCoordinates = async (lat: unknown, lon: unknown) => {
try {
const response = await fetch(
`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json&addressdetails=1&accept-language=fa`
const address = await fetchAddressFromCoordinates(
selectedPosition[0],
selectedPosition[1]
);
const data = await response.json();
return data; // Full formatted address
} catch (error) {
console.error('Error fetching address:', error);
return null;
setSelectedAddress(address);
}
};
const submitAddressAction = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
console.log(formData);
}
const getSelectedAddress = () => {
if (!selectedAddress) {
return "آدرس یافت نشد"
}
try {
return [
selectedAddress.address.state ?? selectedAddress.address.province,
selectedAddress.address.city,
selectedAddress.address.neighbourhood,
!selectedAddress.address.road.startsWith('میدان') &&
!selectedAddress.address.road.startsWith('بلوار') &&
!selectedAddress.address.road.startsWith('خیابان') &&
!selectedAddress.address.road.startsWith('کوچه') ?
selectedAddress.type === 'secondary' ? `بلوار ${selectedAddress.address.road}` :
selectedAddress.type === 'tertiary' ? `خیابان ${selectedAddress.address.road}` :
selectedAddress.type === 'residential' ? `کوچه ${selectedAddress.address.road}` :
selectedAddress.address.road : selectedAddress.address.road
].filter(x => x).join('، ')
} catch {
if (selectedAddress.display_name)
return selectedAddress.display_name;
else
return "آدرس یافت نشد"
}
}
return (
<div className="fixed inset-0 bg-gray-50">
<div className="absolute inset-0">
<CustomMap
initialPosition={mapCenter}
@@ -186,93 +113,23 @@ function OrderTrackingPage() {
/>
</div>
{/* {selectedPosition && (
<div className="selected-location-indicator">
<p className="font-iran">موقعیت انتخاب شده: {selectedPosition[0].toFixed(4)}, {selectedPosition[1].toFixed(4)}</p>
</div>
)} */}
<div className="absolute bottom-0 left-0 right-0 z-[1000]">
<div className='relative w-full h-full' >
<AnimatedBottomSheet
bgOpacity={0}
inDuration={0}
blurOpacity={null}
noBlur
<div className='relative w-full h-full'>
<ConfirmPositionModal
visible={confirmModal}
showCloseButton={false}
showTitle={false}
overrideClassName='!pt-6 bg-container!'
>
<div className='grid grid-cols-2 gap-4 px-4'>
<Button
onClick={toggleDetailsModal}
>
انتخاب
</Button>
<Button
onClick={toggleConfirmModal}
className='bg-disabled! text-foreground!'
>
انصراف
</Button>
</div>
</AnimatedBottomSheet>
onConfirm={toggleDetailsModal}
onCancel={toggleConfirmModal}
/>
<AnimatedBottomSheet
bgOpacity={0}
inDuration={0}
blurOpacity={null}
noBlur
<AddressDetailsModal
visible={detailsModal}
title='آدرس'
onClick={toggleDetailsModal}
overrideClassName='bg-container!'
>
<form onSubmit={submitAddressAction}>
<div className='px-4'>
<div className='px-4 mt-2 bg-container'>
<span className='text-sm'>
{!selectedAddress ?
<Skeleton
className='h-6 w-full'
/>
:
getSelectedAddress()
}
</span>
<hr className='border border-border mt-3 mb-10 ' />
<InputField
htmlFor={'addressTitle'}
labelText={'عنوان آدرس'}
placeholder='مثال: منزل، محل کار ...'
className='bg-inherit'
onChange={() => { }}
/>
<InputField
htmlFor={'addressDetails'}
labelText={'جزئیات آدرس'}
placeholder='میدان باغ ملی، مجتمع آسمان، واحد 12، پلاک 1234567890'
className='bg-inherit mt-8'
onChange={() => { }}
/>
</div>
<div className='grid grid-cols-2 gap-4 mt-16'>
<Button
type='submit'>
تایید
</Button>
<Button
type='button'
onClick={toggleDetailsModal}
className='bg-disabled! text-foreground!'
>
انصراف
</Button>
</div>
</div>
</form>
</AnimatedBottomSheet>
selectedAddress={selectedAddress}
formData={formData}
isPending={isPending}
onClose={toggleDetailsModal}
onFormDataChange={handleFormDataChange}
onSubmit={submitAddress}
/>
</div>
</div>
</div>
@@ -0,0 +1,18 @@
import { NominatimReverseGeocodingResponse } from '../../types/Types';
export const fetchAddressFromCoordinates = async (
lat: number,
lon: number
): Promise<NominatimReverseGeocodingResponse | null> => {
try {
const response = await fetch(
`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json&addressdetails=1&accept-language=fa`
);
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching address:', error);
return null;
}
};
@@ -0,0 +1,30 @@
import { NominatimReverseGeocodingResponse } from '../../types/Types';
export const formatSelectedAddress = (selectedAddress: NominatimReverseGeocodingResponse | null): string => {
if (!selectedAddress) {
return "آدرس یافت نشد";
}
try {
return [
selectedAddress.address.state ?? selectedAddress.address.province,
selectedAddress.address.city,
selectedAddress.address.neighbourhood,
!selectedAddress.address.road.startsWith('میدان') &&
!selectedAddress.address.road.startsWith('بلوار') &&
!selectedAddress.address.road.startsWith('خیابان') &&
!selectedAddress.address.road.startsWith('کوچه') ?
selectedAddress.type === 'secondary' ? `بلوار ${selectedAddress.address.road}` :
selectedAddress.type === 'tertiary' ? `خیابان ${selectedAddress.address.road}` :
selectedAddress.type === 'residential' ? `کوچه ${selectedAddress.address.road}` :
selectedAddress.address.road : selectedAddress.address.road
].filter(x => x).join('، ');
} catch {
if (selectedAddress.display_name) {
return selectedAddress.display_name;
} else {
return "آدرس یافت نشد";
}
}
};
@@ -0,0 +1,12 @@
import { api } from "@/lib/api/axiosInstance";
import { CreateAddressType } from "../types/Types";
export const getAddresses = async () => {
const { data } = await api.get("/public/user/addresses");
return data;
};
export const createAddress = async (params: CreateAddressType) => {
const { data } = await api.post("/public/user/addresses", params);
return data;
};
@@ -0,0 +1,56 @@
import type { Icon, DivIcon } from "leaflet";
export type CreateAddressType = {
title: string;
address: string;
city: string;
province: string;
postalCode: string;
latitude: number;
longitude: number;
phone: string;
isDefault: boolean;
};
export type UpdateAddressType = CreateAddressType & {
id: string;
};
export interface MarkerData {
position: [number, number];
title: string;
icon?: Icon | DivIcon;
}
export interface NominatimReverseGeocodingResponse {
place_id: number;
licence: string;
osm_type: string;
osm_id: number;
lat: string;
lon: string;
class: string;
type: string;
place_rank: number;
importance: number;
addresstype: string;
name: string;
display_name: string;
address: NominatimReverseGeocodingResponseAddress;
boundingbox: string[];
}
export interface NominatimReverseGeocodingResponseAddress {
road: string;
neighbourhood: string;
suburb: string;
city: string;
district: string;
county: string;
province: string;
"ISO3166-2-lvl4": string;
postcode: string;
country: string;
state: string;
country_code: string;
}
+2 -2
View File
@@ -2,11 +2,11 @@ import { api } from "@/lib/api/axiosInstance";
import { LoginOTPRequestType, LoginVerifyOTPType } from "../types/Types";
export const loginOTP = async (params: LoginOTPRequestType) => {
const { data } = await api.post("/auth/otp/request", params);
const { data } = await api.post("/public/auth/otp/request", params);
return data;
};
export const loginVerifyOTP = async (params: LoginVerifyOTPType) => {
const { data } = await api.post("/auth/otp/verify", params);
const { data } = await api.post("/public/auth/otp/verify", params);
return data;
};