417 lines
15 KiB
TypeScript
417 lines
15 KiB
TypeScript
import React, { useCallback, useEffect, useState } from 'react'
|
|
import { trpc } from '../lib/trpc-client'
|
|
import { useRegionStore } from '../lib/stores/region-store'
|
|
import { p, pInput as PInput, MyButton, div } from 'web-components'
|
|
import { MapPin } from 'lucide-react'
|
|
import * as Yup from 'yup'
|
|
import type { AddressFormProps } from '@packages/shared'
|
|
|
|
type Coords = { latitude: number; longitude: number }
|
|
type ResolvedRegion = { regionId: number; boundId: number | null }
|
|
// Where the delivery coordinates came from, so the heading can say so.
|
|
type LocationSource = 'device' | 'map'
|
|
|
|
const validationSchema = Yup.object({
|
|
name: Yup.string().required('Name is required'),
|
|
phone: Yup.string().required('Phone is required').matches(/^\d{10}$/, 'Phone must be 10 digits'),
|
|
addressLine1: Yup.string().required('Address Line 1 is required'),
|
|
addressLine2: Yup.string(),
|
|
state: Yup.string().required('State is required'),
|
|
isDefault: Yup.boolean(),
|
|
})
|
|
|
|
export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolvedRegion }: AddressFormProps) {
|
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
|
const [submitError, setSubmitError] = useState<string | null>(null)
|
|
const [mapOpen, setMapOpen] = useState(false)
|
|
const [mapCenter, setMapCenter] = useState<{ lat: number; lng: number } | null>(null)
|
|
const [locating, setLocating] = useState(false)
|
|
const [locationError, setLocationError] = useState<string | null>(null)
|
|
const [locationSource, setLocationSource] = useState<LocationSource | null>(
|
|
initialValues?.latitude != null && initialValues?.longitude != null ? 'device' : null
|
|
)
|
|
const [currentLocation, setCurrentLocation] = useState<Coords | null>(
|
|
initialValues?.latitude != null && initialValues?.longitude != null
|
|
? { latitude: initialValues.latitude, longitude: initialValues.longitude }
|
|
: null
|
|
)
|
|
const browsingRegionId = useRegionStore((state) => state.selectedRegionId)
|
|
const browsingRegion = useRegionStore((state) => state.selectedRegion)
|
|
// The town (region) for this address. Pre-selected from the app's current
|
|
// browsing region when one exists; otherwise picked from the City dropdown.
|
|
const [resolvedRegion, setResolvedRegion] = useState<ResolvedRegion | null>(() =>
|
|
browsingRegionId != null
|
|
? { regionId: browsingRegionId, boundId: browsingRegion?.effectiveBoundId ?? null }
|
|
: null
|
|
)
|
|
|
|
const utils = trpc.useUtils()
|
|
|
|
// Towns (regions) the user can deliver in — the City field is a picker over them.
|
|
const { data: regionsData } = trpc.common.listRegions.useQuery()
|
|
const regions = regionsData ?? []
|
|
const cityName = regions.find((region) => region.id === resolvedRegion?.regionId)?.name ?? ''
|
|
|
|
const handleCityChange = useCallback(
|
|
async (regionId: number) => {
|
|
if (!currentLocation) {
|
|
setResolvedRegion({ regionId, boundId: null })
|
|
setLocationError('Use your location or pick a point inside this town.')
|
|
return
|
|
}
|
|
setResolvedRegion({ regionId, boundId: null })
|
|
setLocationError(null)
|
|
try {
|
|
const resolved = await utils.common.resolveBound.fetch({
|
|
regionId,
|
|
lat: currentLocation.latitude,
|
|
lng: currentLocation.longitude,
|
|
})
|
|
const info: ResolvedRegion = { regionId, boundId: resolved.boundId }
|
|
setResolvedRegion(info)
|
|
onResolvedRegion?.(info)
|
|
} catch {
|
|
setLocationError('Your location is outside this town. Pick a point on the map inside it.')
|
|
}
|
|
},
|
|
[utils, currentLocation, onResolvedRegion]
|
|
)
|
|
|
|
const [values, setValues] = useState(() => ({
|
|
name: initialValues?.name || '',
|
|
phone: initialValues?.phone || '',
|
|
addressLine1: initialValues?.addressLine1 || '',
|
|
addressLine2: initialValues?.addressLine2 || '',
|
|
city: initialValues?.city || '',
|
|
state: initialValues?.state || 'Telangana',
|
|
isDefault: initialValues?.isDefault || false,
|
|
googleMapsUrl: initialValues?.googleMapsUrl || '',
|
|
}))
|
|
|
|
const [errors, setErrors] = useState<Record<string, string>>({})
|
|
|
|
const resolveLocation = useCallback(
|
|
async (coords: Coords, source: LocationSource = 'device') => {
|
|
setCurrentLocation(coords)
|
|
setLocationSource(source)
|
|
setLocationError(null)
|
|
try {
|
|
const resolved = await utils.common.resolveRegionByLocation.fetch({
|
|
lat: coords.latitude,
|
|
lng: coords.longitude,
|
|
})
|
|
if (!resolved) {
|
|
setResolvedRegion(null)
|
|
setLocationError('This location is outside our delivery area. Try selecting on the map.')
|
|
return
|
|
}
|
|
const info: ResolvedRegion = {
|
|
regionId: resolved.region.id,
|
|
boundId: resolved.bound?.id ?? null,
|
|
}
|
|
setResolvedRegion(info)
|
|
onResolvedRegion?.(info)
|
|
} catch {
|
|
setResolvedRegion(null)
|
|
setLocationError('Could not verify this location. Please try again.')
|
|
}
|
|
},
|
|
[utils, onResolvedRegion]
|
|
)
|
|
|
|
useEffect(() => {
|
|
if (initialValues?.latitude != null && initialValues?.longitude != null) {
|
|
void resolveLocation({ latitude: initialValues.latitude, longitude: initialValues.longitude })
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [])
|
|
|
|
// Pre-select the browsing town once known — unless the user already picked a
|
|
// town or attached a location.
|
|
useEffect(() => {
|
|
if (resolvedRegion != null || currentLocation != null) return
|
|
if (browsingRegionId == null) return
|
|
setResolvedRegion({
|
|
regionId: browsingRegionId,
|
|
boundId: browsingRegion?.effectiveBoundId ?? null,
|
|
})
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [browsingRegionId, browsingRegion])
|
|
|
|
// Coordinates picked on the embedded map are delivered via postMessage.
|
|
useEffect(() => {
|
|
if (!mapOpen) return
|
|
const handler = (event: MessageEvent) => {
|
|
if (event.origin !== window.location.origin) return
|
|
const data = event.data
|
|
if (
|
|
data?.type === 'location-selected' &&
|
|
typeof data.latitude === 'number' &&
|
|
typeof data.longitude === 'number'
|
|
) {
|
|
setMapOpen(false)
|
|
void resolveLocation({ latitude: data.latitude, longitude: data.longitude }, 'map')
|
|
}
|
|
}
|
|
window.addEventListener('message', handler)
|
|
return () => window.removeEventListener('message', handler)
|
|
}, [mapOpen, resolveLocation])
|
|
|
|
const createMutation = trpc.user.address.createAddress.useMutation({
|
|
onSuccess: (data) => {
|
|
setIsSubmitting(false)
|
|
onSuccess(data?.data?.id)
|
|
},
|
|
onError: (error: any) => {
|
|
setIsSubmitting(false)
|
|
setSubmitError(error.message || 'Failed to save address')
|
|
},
|
|
})
|
|
|
|
const updateMutation = trpc.user.address.updateAddress.useMutation({
|
|
onSuccess: () => {
|
|
setIsSubmitting(false)
|
|
onSuccess()
|
|
},
|
|
onError: (error: any) => {
|
|
setIsSubmitting(false)
|
|
setSubmitError(error.message || 'Failed to update address')
|
|
},
|
|
})
|
|
|
|
const handleChange = (field: string, value: string | boolean) => {
|
|
setValues((prev) => ({ ...prev, [field]: value }))
|
|
if (errors[field]) {
|
|
setErrors((prev) => ({ ...prev, [field]: '' }))
|
|
}
|
|
}
|
|
|
|
const handleDetectLocation = () => {
|
|
if (!navigator.geolocation) {
|
|
setLocationError('Location is not supported in this browser. Please select on the map.')
|
|
return
|
|
}
|
|
setLocating(true)
|
|
navigator.geolocation.getCurrentPosition(
|
|
(position) => {
|
|
setLocating(false)
|
|
void resolveLocation({
|
|
latitude: position.coords.latitude,
|
|
longitude: position.coords.longitude,
|
|
})
|
|
},
|
|
() => {
|
|
setLocating(false)
|
|
setLocationError('Could not get your location. Please select on the map.')
|
|
},
|
|
{ enableHighAccuracy: true, timeout: 10000 }
|
|
)
|
|
}
|
|
|
|
const handleSubmit = async () => {
|
|
try {
|
|
await validationSchema.validate(values, { abortEarly: false })
|
|
if (!currentLocation) {
|
|
setSubmitError('Please use your current location or select one on the map.')
|
|
return
|
|
}
|
|
if (!resolvedRegion || locationError) {
|
|
setSubmitError(locationError || 'Please choose a town and a location inside it.')
|
|
return
|
|
}
|
|
setIsSubmitting(true)
|
|
setSubmitError(null)
|
|
|
|
const payload = {
|
|
...values,
|
|
city: cityName || values.city || '',
|
|
regionId: resolvedRegion.regionId,
|
|
latitude: currentLocation.latitude,
|
|
longitude: currentLocation.longitude,
|
|
googleMapsUrl: values.googleMapsUrl || undefined,
|
|
}
|
|
|
|
if (isEdit && initialValues?.id) {
|
|
updateMutation.mutate({ id: initialValues.id, ...payload })
|
|
} else {
|
|
createMutation.mutate(payload)
|
|
}
|
|
} catch (err: any) {
|
|
const validationErrors: Record<string, string> = {}
|
|
err.inner?.forEach((error: any) => {
|
|
validationErrors[error.path] = error.message
|
|
})
|
|
setErrors(validationErrors)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="p-6">
|
|
<div className="mb-6 flex items-center justify-between">
|
|
<p className="font-bold text-xl">{isEdit ? 'Edit Address' : 'Add Address'}</p>
|
|
</div>
|
|
|
|
{submitError && (
|
|
<div className="mb-4 rounded-lg border border-red-200 bg-red-50 p-3">
|
|
<p className="text-sm text-red-600">{submitError}</p>
|
|
</div>
|
|
)}
|
|
|
|
<div className="space-y-4">
|
|
<div>
|
|
<PInput
|
|
placeholder="Name"
|
|
value={values.name}
|
|
onChange={(e) => handleChange('name', e.target.value)}
|
|
className={errors.name ? 'border-red-500' : ''}
|
|
/>
|
|
{errors.name && <p className="mt-1 text-sm text-red-500">{errors.name}</p>}
|
|
</div>
|
|
|
|
<div>
|
|
<PInput
|
|
placeholder="Phone"
|
|
type="tel"
|
|
value={values.phone}
|
|
onChange={(e) => handleChange('phone', e.target.value)}
|
|
className={errors.phone ? 'border-red-500' : ''}
|
|
/>
|
|
{errors.phone && <p className="mt-1 text-sm text-red-500">{errors.phone}</p>}
|
|
</div>
|
|
|
|
<div>
|
|
<PInput
|
|
placeholder="Address Line 1"
|
|
value={values.addressLine1}
|
|
onChange={(e) => handleChange('addressLine1', e.target.value)}
|
|
className={errors.addressLine1 ? 'border-red-500' : ''}
|
|
/>
|
|
{errors.addressLine1 && <p className="mt-1 text-sm text-red-500">{errors.addressLine1}</p>}
|
|
</div>
|
|
|
|
<div>
|
|
<PInput
|
|
placeholder="Address Line 2 (Optional)"
|
|
value={values.addressLine2}
|
|
onChange={(e) => handleChange('addressLine2', e.target.value)}
|
|
/>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div>
|
|
<label className="mb-1 block text-xs text-gray-500">City *</label>
|
|
<select
|
|
data-testid="address-city"
|
|
value={resolvedRegion?.regionId ?? ''}
|
|
onChange={(e) => {
|
|
void handleCityChange(Number(e.target.value))
|
|
}}
|
|
className="w-full rounded-lg border border-gray-200 bg-gray-50 p-3 text-base outline-none"
|
|
>
|
|
<option value="">Select town</option>
|
|
{regions.map((region) => (
|
|
<option key={region.id} value={region.id} data-testid={`address-city-option-${region.id}`}>
|
|
{region.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
<div>
|
|
<PInput placeholder="State" value={values.state} disabled className="bg-gray-100" />
|
|
</div>
|
|
</div>
|
|
|
|
{/* Location is mandatory: attach the device location or pick on the map. */}
|
|
<div className="rounded-lg border border-gray-200 p-3">
|
|
<p className="mb-2 text-xs text-gray-500">Delivery Location *</p>
|
|
{currentLocation ? (
|
|
<div className="flex flex-col gap-2">
|
|
<p className="flex items-center gap-2 text-sm font-bold text-green-600">
|
|
<MapPin className="h-4 w-4" />{' '}
|
|
{locationSource === 'map'
|
|
? 'Location Attached from Map'
|
|
: 'Current Location Attached'}
|
|
</p>
|
|
<p className="text-xs text-gray-500">
|
|
📍 {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)}
|
|
</p>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setMapCenter(null)
|
|
setMapOpen(true)
|
|
}}
|
|
className="flex items-center gap-2 text-left text-sm font-medium text-blue-500"
|
|
>
|
|
<MapPin className="h-4 w-4" /> Choose Another Location in Map
|
|
</button>
|
|
</div>
|
|
) : (
|
|
<div className="flex flex-col gap-2">
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setMapCenter(null)
|
|
setMapOpen(true)
|
|
}}
|
|
className="flex items-center gap-2 text-left text-sm font-medium text-blue-500"
|
|
>
|
|
<MapPin className="h-4 w-4" /> Attach Location in map
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleDetectLocation}
|
|
disabled={locating}
|
|
className="flex items-center gap-2 text-left text-xs font-medium text-gray-500 disabled:opacity-50"
|
|
>
|
|
<MapPin className="h-4 w-4" />
|
|
{locating ? 'Fetching location…' : 'Use my current location'}
|
|
</button>
|
|
</div>
|
|
)}
|
|
{locationError && <p className="mt-1 text-sm text-red-500">{locationError}</p>}
|
|
</div>
|
|
|
|
<label className="flex cursor-pointer items-center gap-2">
|
|
<input
|
|
type="checkbox"
|
|
checked={values.isDefault}
|
|
onChange={(e) => handleChange('isDefault', e.target.checked)}
|
|
className="h-4 w-4 rounded border-gray-300 text-brand-500 focus:ring-brand-500"
|
|
/>
|
|
<p>Set as default address</p>
|
|
</label>
|
|
|
|
<MyButton
|
|
fullWidth
|
|
textContent={isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')}
|
|
onClick={handleSubmit}
|
|
disabled={isSubmitting || !currentLocation}
|
|
className="bg-brand-500 text-white"
|
|
/>
|
|
</div>
|
|
|
|
{/* Full-screen in-page map picker (same origin, posts coordinates back). */}
|
|
{mapOpen && (
|
|
<div className="fixed inset-0 z-[200] bg-white">
|
|
<iframe
|
|
src={
|
|
mapCenter
|
|
? `/location-selector?lat=${mapCenter.lat}&lng=${mapCenter.lng}`
|
|
: '/location-selector'
|
|
}
|
|
title="Select delivery location"
|
|
className="h-full w-full border-0"
|
|
/>
|
|
<button
|
|
type="button"
|
|
onClick={() => setMapOpen(false)}
|
|
className="absolute left-4 top-4 rounded-full bg-white px-4 py-2 font-bold text-gray-700 shadow"
|
|
>
|
|
Cancel
|
|
</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|