diff --git a/backend/app/geo_utils.py b/backend/app/geo_utils.py
index 14ac68c5..4424dcf2 100644
--- a/backend/app/geo_utils.py
+++ b/backend/app/geo_utils.py
@@ -1,5 +1,6 @@
import logging
import math
+import os
import requests
from sqlalchemy import func
@@ -45,7 +46,7 @@ def get_external_region_bounds(
params = {"q": query, "format": "json", "limit": 1, "addressdetails": 1}
headers = {
- "User-Agent": "Divemap-Backend/1.0 (info@divemap.com)" # Nominatim requires a User-Agent
+ "User-Agent": "Divemap-Backend/1.0 (info@divemap.blue)" # Nominatim requires a User-Agent
}
response = requests.get(url, params=params, headers=headers, timeout=10.0)
@@ -119,38 +120,348 @@ def get_empirical_region_bounds(
return None
-def get_location_info_from_coords(lat: float, lon: float) -> dict[str, str | None]:
+def clean_regional_unit(text: str | None) -> str | None:
+ """Strips verbose suffixes like 'Regional Unit' from administrative region names."""
+ if text:
+ if text.endswith(" Regional Unit"):
+ return text[: -len(" Regional Unit")].strip()
+ elif text.endswith("Regional Unit"):
+ return text[: -len("Regional Unit")].strip()
+ return text.strip()
+ return text
+
+
+def perform_reverse_geocode(latitude: float, longitude: float) -> dict[str, str | None]:
"""
- Reverse geocodes coordinates to find country and region using Nominatim.
+ 3-tier reverse geocoder resolving country, region, and city from coordinates:
+ Tier 1: Geoapify (if GEOAPIFY_KEY is set in environment)
+ Tier 2: Photon (Komoot)
+ Tier 3: OpenStreetMap Nominatim
"""
- result = {"country": None, "region": None}
+ result = {
+ "country": None,
+ "region": None,
+ "county": None,
+ "state": None,
+ "city": None,
+ "suburb": None,
+ }
+
+ timeout_errors = []
+ connection_errors = []
+ attempts = 0
+
+ # 1. Tier 1: Geoapify
+ geoapify_key = os.getenv("GEOAPIFY_KEY")
+ if geoapify_key:
+ attempts += 1
+ try:
+ url = "https://api.geoapify.com/v1/geocode/reverse"
+ params = {
+ "lat": latitude,
+ "lon": longitude,
+ "apiKey": geoapify_key,
+ "lang": "en",
+ }
+ resp = requests.get(url, params=params, timeout=2.0)
+ if resp.status_code == 200:
+ data = resp.json()
+ features = data.get("features", [])
+ if features:
+ props = features[0].get("properties", {})
+ country = props.get("country")
+ state = clean_regional_unit(props.get("state"))
+ county = clean_regional_unit(props.get("county"))
+ city = (
+ props.get("city")
+ or props.get("municipality")
+ or props.get("town")
+ )
+
+ region = state or county or props.get("region")
+
+ result.update(
+ {
+ "country": country,
+ "region": region,
+ "county": county,
+ "state": state,
+ "city": city,
+ "suburb": props.get("suburb"),
+ }
+ )
+ if result["country"]:
+ logger.debug("Geoapify reverse geocoding succeeded")
+ return result
+ except requests.exceptions.Timeout as e:
+ timeout_errors.append(e)
+ logger.warning("Geoapify reverse geocoding timed out")
+ except requests.exceptions.ConnectionError as e:
+ connection_errors.append(e)
+ logger.warning("Geoapify reverse geocoding connection error")
+ except Exception as e:
+ logger.warning(f"Geoapify reverse geocoding failed: {e}")
+
+ # 2. Tier 2: Photon (Komoot)
+ attempts += 1
+ try:
+ url = "https://photon.komoot.io/reverse"
+ params = {"lat": latitude, "lon": longitude, "lang": "en"}
+ headers = {"User-Agent": "Divemap-Backend/1.0 (info@divemap.blue)"}
+ resp = requests.get(url, params=params, headers=headers, timeout=2.0)
+ if resp.status_code == 200:
+ data = resp.json()
+ features = data.get("features", [])
+ if features:
+ props = features[0].get("properties", {})
+ country = props.get("country")
+ state = clean_regional_unit(props.get("state"))
+ county = clean_regional_unit(props.get("county"))
+ city = (
+ props.get("city") or props.get("district") or props.get("locality")
+ )
+
+ region = state or county or props.get("region")
+
+ result.update(
+ {
+ "country": country,
+ "region": region,
+ "county": county,
+ "state": state,
+ "city": city,
+ }
+ )
+ if result["country"]:
+ logger.debug("Photon reverse geocoding succeeded")
+ return result
+ except requests.exceptions.Timeout as e:
+ timeout_errors.append(e)
+ logger.warning("Photon reverse geocoding timed out")
+ except requests.exceptions.ConnectionError as e:
+ connection_errors.append(e)
+ logger.warning("Photon reverse geocoding connection error")
+ except Exception as e:
+ logger.warning(f"Photon reverse geocoding failed: {e}")
+
+ # 3. Tier 3: Nominatim (OpenStreetMap)
+ attempts += 1
try:
url = "https://nominatim.openstreetmap.org/reverse"
params = {
- "lat": lat,
- "lon": lon,
+ "lat": latitude,
+ "lon": longitude,
"format": "json",
- "zoom": 5, # City/Region level
+ "addressdetails": 1,
+ "zoom": 8,
+ "accept-language": "en",
}
- headers = {"User-Agent": "Divemap-Backend/1.0 (info@divemap.com)"}
- response = requests.get(url, params=params, headers=headers, timeout=5.0)
- response.raise_for_status()
- data = response.json()
- address = data.get("address", {})
+ headers = {"User-Agent": "Divemap-Backend/1.0 (info@divemap.blue)"}
+ resp = requests.get(url, params=params, headers=headers, timeout=6.0)
+ if resp.status_code == 200:
+ data = resp.json()
+ address = data.get("address", {})
+
+ country = address.get("country")
+ county = clean_regional_unit(address.get("county"))
+ state_district = clean_regional_unit(address.get("state_district"))
+ state = clean_regional_unit(address.get("state"))
+
+ if county and state_district:
+ region = f"{county}, {state_district}"
+ else:
+ region = (
+ state
+ or clean_regional_unit(address.get("province"))
+ or clean_regional_unit(address.get("region"))
+ or county
+ )
- result["country"] = address.get("country")
- # Try to find the most relevant regional administrative level
- result["region"] = (
- address.get("state") or address.get("region") or address.get("county")
- )
+ city = (
+ address.get("city")
+ or address.get("town")
+ or address.get("village")
+ or address.get("municipality")
+ )
- if result["country"]:
- logger.info(f"Resolved location info from coords ({lat}, {lon}): {result}")
+ result.update(
+ {
+ "country": country,
+ "region": region,
+ "county": county,
+ "state": state,
+ "city": city,
+ "suburb": address.get("suburb"),
+ }
+ )
+ if result["country"]:
+ logger.debug("Nominatim reverse geocoding succeeded")
+ return result
+ except requests.exceptions.Timeout as e:
+ timeout_errors.append(e)
+ logger.warning("Nominatim reverse geocoding timed out")
+ except requests.exceptions.ConnectionError as e:
+ connection_errors.append(e)
+ logger.warning("Nominatim reverse geocoding connection error")
except Exception as e:
- logger.error(f"Error reverse geocoding coords ({lat}, {lon}): {e}")
+ logger.error(f"Nominatim reverse geocoding failed: {e}")
+
+ if attempts > 0 and len(timeout_errors) == attempts:
+ raise timeout_errors[0]
+ if attempts > 0 and len(connection_errors) == attempts:
+ raise connection_errors[0]
+
return result
+def search_places(
+ query: str,
+ lat: float | None = None,
+ lon: float | None = None,
+ limit: int = 5,
+) -> list[dict]:
+ """
+ 3-tier forward place search:
+ Tier 1: Geoapify Autocomplete (if GEOAPIFY_KEY is set in environment)
+ Tier 2: Photon (Komoot)
+ Tier 3: OpenStreetMap Nominatim
+ """
+ clean_q = (query or "").strip()
+ if not clean_q:
+ return []
+
+ # 1. Tier 1: Geoapify Autocomplete
+ geoapify_key = os.getenv("GEOAPIFY_KEY")
+ if geoapify_key:
+ try:
+ url = "https://api.geoapify.com/v1/geocode/autocomplete"
+ params = {
+ "text": clean_q,
+ "apiKey": geoapify_key,
+ "limit": limit,
+ }
+ if lat is not None and lon is not None:
+ params["bias"] = f"proximity:{lon},{lat}"
+
+ resp = requests.get(url, params=params, timeout=2.0)
+ if resp.status_code == 200:
+ data = resp.json()
+ features = data.get("features", [])
+ if features:
+ results = []
+ for f in features:
+ p = f.get("properties", {})
+ coords = f.get("geometry", {}).get("coordinates", [0, 0])
+ results.append(
+ {
+ "display_name": p.get("formatted")
+ or p.get("name")
+ or clean_q,
+ "name": p.get("name") or p.get("city") or clean_q,
+ "latitude": coords[1],
+ "longitude": coords[0],
+ "country": p.get("country"),
+ "region": clean_regional_unit(
+ p.get("state") or p.get("county")
+ ),
+ "type": p.get("result_type"),
+ }
+ )
+ logger.debug(f"Geoapify place search found {len(results)} items")
+ return results
+ except Exception as e:
+ logger.warning(f"Geoapify search failed: {e}")
+
+ # 2. Tier 2: Photon (Komoot)
+ try:
+ url = "https://photon.komoot.io/api/"
+ params = {"q": clean_q, "limit": limit, "lang": "en"}
+ if lat is not None and lon is not None:
+ params["lat"] = lat
+ params["lon"] = lon
+
+ headers = {"User-Agent": "Divemap-Backend/1.0 (info@divemap.blue)"}
+ resp = requests.get(url, params=params, headers=headers, timeout=2.0)
+ if resp.status_code == 200:
+ data = resp.json()
+ features = data.get("features", [])
+ if features:
+ results = []
+ for f in features:
+ p = f.get("properties", {})
+ coords = f.get("geometry", {}).get("coordinates", [0, 0])
+ parts = [
+ p.get("name"),
+ p.get("city"),
+ p.get("state"),
+ p.get("country"),
+ ]
+ display_name = ", ".join(filter(None, parts))
+ results.append(
+ {
+ "display_name": display_name,
+ "name": p.get("name") or clean_q,
+ "latitude": coords[1],
+ "longitude": coords[0],
+ "country": p.get("country"),
+ "region": clean_regional_unit(
+ p.get("state") or p.get("county")
+ ),
+ "type": p.get("type") or p.get("osm_value"),
+ }
+ )
+ logger.debug(f"Photon place search found {len(results)} items")
+ return results
+ except Exception as e:
+ logger.warning(f"Photon search failed: {e}")
+
+ # 3. Tier 3: Nominatim (OpenStreetMap)
+ try:
+ url = "https://nominatim.openstreetmap.org/search"
+ params = {
+ "q": clean_q,
+ "format": "json",
+ "limit": limit,
+ "addressdetails": 1,
+ "accept-language": "en",
+ }
+ headers = {"User-Agent": "Divemap-Backend/1.0 (info@divemap.blue)"}
+ resp = requests.get(url, params=params, headers=headers, timeout=6.0)
+ if resp.status_code == 200:
+ data = resp.json()
+ if isinstance(data, list) and data:
+ results = []
+ for d in data:
+ addr = d.get("address", {})
+ results.append(
+ {
+ "display_name": d.get("display_name"),
+ "name": d.get("display_name", "").split(",")[0],
+ "latitude": float(d["lat"]),
+ "longitude": float(d["lon"]),
+ "country": addr.get("country"),
+ "region": clean_regional_unit(
+ addr.get("state") or addr.get("county")
+ ),
+ "type": d.get("addresstype") or d.get("type"),
+ }
+ )
+ logger.debug(f"Nominatim place search found {len(results)} items")
+ return results
+ except Exception as e:
+ logger.error(f"Nominatim search failed: {e}")
+
+ return []
+
+
+def get_location_info_from_coords(lat: float, lon: float) -> dict[str, str | None]:
+ """
+ Reverse geocodes coordinates to find country and region using the 3-tier geocoder.
+ """
+ geo = perform_reverse_geocode(lat, lon)
+ return {"country": geo.get("country"), "region": geo.get("region")}
+
+
def get_country_from_ip(ip: str) -> str | None:
"""
Looks up the country name for an IP address using ip-api.com.
diff --git a/backend/app/models.py b/backend/app/models.py
index e3371b72..3f2783c8 100644
--- a/backend/app/models.py
+++ b/backend/app/models.py
@@ -1130,6 +1130,9 @@ class Dive(Base):
dive_site_id = Column(
Integer, ForeignKey("dive_sites.id", ondelete="SET NULL"), nullable=True
)
+ unlinked_site_name = Column(
+ String(255), nullable=True, index=True
+ ) # Free-text site name when not linked to a dive site
diving_center_id = Column(
Integer, ForeignKey("diving_centers.id", ondelete="SET NULL"), nullable=True
) # Link to diving center
diff --git a/backend/app/routers/dive_sites.py b/backend/app/routers/dive_sites.py
index 1a4295e9..15a82fa6 100644
--- a/backend/app/routers/dive_sites.py
+++ b/backend/app/routers/dive_sites.py
@@ -6,7 +6,6 @@
from pathlib import Path
from typing import Optional
-import orjson
import requests
from fastapi import (
APIRouter,
@@ -846,60 +845,21 @@ def search_dive_sites_with_fuzzy(
def _perform_reverse_geocode(latitude: float, longitude: float) -> dict | None:
- """Internal helper to perform reverse geocoding without requiring a Request object."""
+ """Internal helper to perform reverse geocoding via 3-tier geocoder."""
try:
- import requests
-
- # Use OpenStreetMap Nominatim API for reverse geocoding
- url = "https://nominatim.openstreetmap.org/reverse"
- params = {
- "lat": latitude,
- "lon": longitude,
- "format": "json",
- "addressdetails": 1,
- "zoom": 8,
- "accept-language": "en",
- }
-
- headers = {"User-Agent": "Divemap/1.0 (https://github.com/kargig/divemap)"}
-
- response = requests.get(url, params=params, headers=headers, timeout=10)
- if response.status_code != 200:
- return None
-
- data = response.json()
- address = data.get("address", {})
-
- # Extract country and region information
- country = address.get("country")
-
- def clean_regional_unit(text):
- if text:
- if text.endswith(" Regional Unit"):
- return text[: -len(" Regional Unit")].strip()
- elif text.endswith("Regional Unit"):
- return text[: -len("Regional Unit")].strip()
- return text
- return text
-
- county = clean_regional_unit(address.get("county"))
- state_district = clean_regional_unit(address.get("state_district"))
-
- if county and state_district:
- region = f"{county}, {state_district}"
- else:
- region = (
- clean_regional_unit(address.get("state"))
- or clean_regional_unit(address.get("province"))
- or clean_regional_unit(address.get("region"))
- or county
- )
-
- return {
- "country": country,
- "region": region,
- "full_address": data.get("display_name", ""),
- }
+ from app.geo_utils import perform_reverse_geocode
+
+ res = perform_reverse_geocode(latitude, longitude)
+ if res and res.get("country"):
+ return {
+ "country": res.get("country"),
+ "region": res.get("region"),
+ "full_address": res.get("city")
+ or res.get("region")
+ or res.get("country")
+ or "",
+ }
+ return None
except Exception as e:
logger.error(f"Internal geocoding error: {e}")
return None
@@ -966,134 +926,59 @@ async def reverse_geocode(
latitude: float = Query(..., ge=-90, le=90),
longitude: float = Query(..., ge=-180, le=180),
debug: bool = Query(
- False, description="Enable debug logging for Nominatim API calls"
+ False, description="Enable debug logging for geocoding API calls"
),
db: Session = Depends(get_db),
):
"""
- Get country and region suggestions based on coordinates using OpenStreetMap Nominatim API
+ Get country and region suggestions based on coordinates using 3-tier geocoder (Geoapify -> Photon -> Nominatim)
"""
- try:
- # Use OpenStreetMap Nominatim API for reverse geocoding
- url = "https://nominatim.openstreetmap.org/reverse"
- params = {
- "lat": latitude,
- "lon": longitude,
- "format": "json",
- "addressdetails": 1,
- "zoom": 8, # Get more detailed results
- "accept-language": "en", # Request English language results
- }
-
- # Add User-Agent header as required by Nominatim
- headers = {"User-Agent": "Divemap/1.0 (https://github.com/kargig/divemap)"}
-
- response = requests.get(url, params=params, headers=headers, timeout=15)
-
- # Log the response for debugging
- if debug:
- logger.debug(f"🔍 Nominatim API Request: URL={url}, Parameters={params}")
-
- response.raise_for_status()
-
- data = response.json()
-
- if debug:
- logger.debug(
- f"📡 Nominatim API Response: Status={response.status_code}, Content={orjson.dumps(data).decode('utf-8')}"
- )
-
- address = data.get("address", {})
-
- # Extract country and region information
- country = address.get("country")
-
- # Helper function to clean "Regional Unit" from text
- # Only remove "Regional Unit" if it appears at the end, keep it if it appears at the beginning
- def clean_regional_unit(text):
- if text:
- # Remove " Regional Unit" only if it appears at the end
- if text.endswith(" Regional Unit"):
- return text[: -len(" Regional Unit")].strip()
- # Remove "Regional Unit" only if it appears at the end (no leading space)
- elif text.endswith("Regional Unit"):
- return text[: -len("Regional Unit")].strip()
- return text
- return text
-
- # Get and clean county and state_district fields
- county = clean_regional_unit(address.get("county"))
- state_district = clean_regional_unit(address.get("state_district"))
-
- if county and state_district:
- region = f"{county}, {state_district}"
- else:
- # Fallback to previous priority order, also cleaning "Regional Unit"
- region = (
- clean_regional_unit(address.get("state"))
- or clean_regional_unit(address.get("province"))
- or clean_regional_unit(address.get("region"))
- or county # county alone if no state_district
- )
-
- # Log the extracted data
- if debug:
- print("📍 Extracted Location Data:")
- print(f" Country: '{country}'")
- print(f" Region: '{region}'")
- print(f" Full Address: '{data.get('display_name', '')}'")
- print(
- f" Raw Address Object: {orjson.dumps(address, option=orjson.OPT_INDENT_2).decode('utf-8')}"
- )
-
- # Show which region fields were found and used
- print(" Region Field Analysis:")
- print(f" county: '{address.get('county')}' → cleaned: '{county}'")
- print(
- f" state_district: '{address.get('state_district')}' → cleaned: '{state_district}'"
- )
- print(
- f" state: '{address.get('state')}' → cleaned: '{clean_regional_unit(address.get('state'))}'"
- )
- print(
- f" province: '{address.get('province')}' → cleaned: '{clean_regional_unit(address.get('province'))}'"
- )
- print(
- f" region: '{address.get('region')}' → cleaned: '{clean_regional_unit(address.get('region'))}'"
- )
- if county and state_district:
- print(f" → Using concatenated: '{county}, {state_district}'")
- else:
- print(f" → Using fallback: '{region}'")
-
- return {
- "country": country,
- "region": region,
- "full_address": data.get("display_name", ""),
- }
+ from app.geo_utils import perform_reverse_geocode
+ try:
+ data = perform_reverse_geocode(latitude, longitude)
except requests.exceptions.Timeout:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Geocoding service timeout. Please try again later.",
)
except requests.exceptions.ConnectionError:
- # Fallback to basic location detection based on coordinates
- if debug:
- print("❌ OpenStreetMap API unavailable, using fallback location detection")
- fallback_result = get_fallback_location(latitude, longitude, debug)
- return fallback_result
- except requests.RequestException as e:
- # Fallback to basic location detection based on coordinates
if debug:
- print(f"❌ OpenStreetMap API error: {e}, using fallback location detection")
- fallback_result = get_fallback_location(latitude, longitude, debug)
- return fallback_result
+ print("❌ Geocoding API unavailable, using fallback location detection")
+ return get_fallback_location(latitude, longitude, debug)
except Exception as e:
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=f"Unexpected error during geocoding: {str(e)}",
- )
+ logger.error(f"Reverse geocoding error: {e}")
+ return get_fallback_location(latitude, longitude, debug)
+
+ return {
+ "country": data.get("country"),
+ "region": data.get("region"),
+ "city": data.get("city"),
+ "county": data.get("county"),
+ "state": data.get("state"),
+ "full_address": data.get("city")
+ or data.get("region")
+ or data.get("country")
+ or f"Coordinates: {latitude}, {longitude}",
+ }
+
+
+@router.get("/search-places")
+@skip_rate_limit_for_admin("120/minute")
+async def search_places_endpoint(
+ request: Request,
+ q: str = Query(..., min_length=1),
+ latitude: float | None = Query(None, ge=-90, le=90),
+ longitude: float | None = Query(None, ge=-180, le=180),
+ limit: int = Query(5, ge=1, le=10),
+ db: Session = Depends(get_db),
+):
+ """
+ Forward geocode place search using 3-tier geocoder (Geoapify -> Photon -> Nominatim)
+ """
+ from app.geo_utils import search_places
+
+ return search_places(query=q, lat=latitude, lon=longitude, limit=limit)
def get_fallback_location(latitude: float, longitude: float, debug: bool = False):
diff --git a/backend/app/routers/dives/imports/confirm.py b/backend/app/routers/dives/imports/confirm.py
index b008d061..5c6a8892 100644
--- a/backend/app/routers/dives/imports/confirm.py
+++ b/backend/app/routers/dives/imports/confirm.py
@@ -58,6 +58,11 @@ async def confirm_import_dives(
# Create/Update data
dive_create = DiveCreate(
dive_site_id=dive_data.get("dive_site_id"),
+ unlinked_site_name=(
+ dive_data.get("unlinked_site_name")
+ if not dive_data.get("dive_site_id")
+ else None
+ ),
diving_center_id=dive_data.get("diving_center_id"),
name=dive_data.get("name"),
is_private=dive_data.get("is_private", False),
@@ -138,6 +143,10 @@ async def confirm_import_dives(
else:
if original_dive_name:
dive.name = f"Dive - {dive.dive_date} - {original_dive_name}"
+ elif dive.unlinked_site_name:
+ dive.name = (
+ f"Dive - {dive.dive_date} - {dive.unlinked_site_name}"
+ )
else:
dive.name = f"Dive - {dive.dive_date}"
@@ -239,7 +248,8 @@ async def confirm_import_dives(
"name": dive.name,
"dive_date": dive.dive_date.isoformat() if dive.dive_date else None,
"dive_site_id": dive.dive_site_id,
- "dive_site_name": dive_site_name,
+ "dive_site_name": dive_site_name or dive.unlinked_site_name,
+ "unlinked_site_name": dive.unlinked_site_name,
}
)
diff --git a/backend/app/routers/dives/imports/subsurface.py b/backend/app/routers/dives/imports/subsurface.py
index e2c21d47..42ca3497 100644
--- a/backend/app/routers/dives/imports/subsurface.py
+++ b/backend/app/routers/dives/imports/subsurface.py
@@ -427,14 +427,15 @@ def convert_to_divemap_format(
if extradata.get("key") == "Deco model":
dive_info_parts.append(f"Deco Model: {extradata['value']}")
- for weight in weights:
- weight_info = []
- if weight.get("weight"):
- weight_info.append(weight["weight"])
- if weight.get("description"):
- weight_info.append(weight["description"])
- if weight_info:
- dive_info_parts.append(f"Weight: {' - '.join(weight_info)}")
+ if weights:
+ for weight in weights:
+ weight_info = []
+ if weight.get("weight"):
+ weight_info.append(weight["weight"])
+ if weight.get("description"):
+ weight_info.append(weight["description"])
+ if weight_info:
+ dive_info_parts.append(f"Weight: {' - '.join(weight_info)}")
max_depth = 0.0
average_depth = 0.0
@@ -461,9 +462,28 @@ def convert_to_divemap_format(
if match.get("match_type") == "similarity":
proposed_sites = match.get("proposed_sites")
else:
+ gps_val = dive_sites[divesiteid].get("gps")
+ lat = None
+ lng = None
+ if gps_val and isinstance(gps_val, str):
+ parts = [
+ p.strip() for p in gps_val.replace(",", " ").split() if p.strip()
+ ]
+ if len(parts) >= 2:
+ try:
+ p_lat = float(parts[0])
+ p_lng = float(parts[1])
+ if -90 <= p_lat <= 90 and -180 <= p_lng <= 180:
+ lat = p_lat
+ lng = p_lng
+ except ValueError:
+ pass
+
unmatched_dive_site = {
"name": site_name,
- "gps": dive_sites[divesiteid].get("gps"),
+ "gps": gps_val,
+ "latitude": lat,
+ "longitude": lng,
}
gas_bottles_used = create_structured_gas_data(cylinders, events=events)
diff --git a/backend/app/routers/diving_centers.py b/backend/app/routers/diving_centers.py
index 6103835d..db3311c0 100644
--- a/backend/app/routers/diving_centers.py
+++ b/backend/app/routers/diving_centers.py
@@ -3,7 +3,6 @@
from pathlib import Path
from typing import Any
-import orjson
import requests
from fastapi import (
APIRouter,
@@ -608,192 +607,39 @@ async def reverse_geocode(
latitude: float = Query(..., ge=-90, le=90),
longitude: float = Query(..., ge=-180, le=180),
debug: bool = Query(
- False, description="Enable debug logging for Nominatim API calls"
+ False, description="Enable debug logging for geocoding API calls"
),
db: Session = Depends(get_db),
):
"""
- Get country, region, and city suggestions based on coordinates using OpenStreetMap Nominatim API
+ Get country, region, and city suggestions based on coordinates using 3-tier geocoder (Geoapify -> Photon -> Nominatim).
"""
- try:
- # Use OpenStreetMap Nominatim API for reverse geocoding
- url = "https://nominatim.openstreetmap.org/reverse"
- params = {
- "lat": latitude,
- "lon": longitude,
- "format": "json",
- "addressdetails": 1,
- "zoom": 10, # Get more detailed results
- "accept-language": "en", # Request English language results
- }
-
- # Add User-Agent header as required by Nominatim
- headers = {"User-Agent": "Divemap/1.0 (https://github.com/kargig/divemap)"}
-
- response = requests.get(url, params=params, headers=headers, timeout=15)
-
- # Log the response for debugging
- if debug:
- logger.debug(f"🔍 Nominatim API Request: URL={url}, Parameters={params}")
-
- response.raise_for_status()
-
- data = response.json()
-
- if debug:
- logger.debug(
- f"📡 Nominatim API Response: Status={response.status_code}, Content={orjson.dumps(data).decode('utf-8')}"
- )
-
- address = data.get("address", {})
-
- # Extract country, region, and city information
- country = address.get("country")
-
- # Helper function to clean "Regional Unit" from text
- # Only remove "Regional Unit" if it appears at the end, keep it if it appears at the beginning
- def clean_regional_unit(text):
- if text:
- # Remove " Regional Unit" only if it appears at the end
- if text.endswith(" Regional Unit"):
- return text[: -len(" Regional Unit")].strip()
- # Remove "Regional Unit" only if it appears at the end (no leading space)
- elif text.endswith("Regional Unit"):
- return text[: -len("Regional Unit")].strip()
- return text
- return text
-
- # Helper function to clean "Municipal Unit" and "Municipality" from text
- def clean_municipal_suffixes(text):
- if text:
- # Remove " Municipal Unit" if it appears at the end
- if text.endswith(" Municipal Unit"):
- return text[: -len(" Municipal Unit")].strip()
- # Remove "Municipal Unit" if it appears at the end (no leading space)
- elif text.endswith("Municipal Unit"):
- return text[: -len("Municipal Unit")].strip()
- # Remove "Municipality" if it appears at the end
- elif text.endswith(" Municipality"):
- return text[: -len(" Municipality")].strip()
- # Remove "Municipality" if it appears at the end (no leading space)
- elif text.endswith("Municipality"):
- return text[: -len("Municipality")].strip()
- # Remove "Municipality of " if it appears at the beginning
- elif text.startswith("Municipality of "):
- return text[len("Municipality of ") :].strip()
- # Remove "Municipal Unit of " if it appears at the beginning
- elif text.startswith("Municipal Unit of "):
- return text[len("Municipal Unit of ") :].strip()
- return text
- return text
-
- # Get and clean county and state_district fields
- county = clean_regional_unit(address.get("county"))
- state_district = clean_regional_unit(address.get("state_district"))
-
- if county and state_district:
- region = f"{county}, {state_district}"
- else:
- # Fallback to previous priority order, also cleaning "Regional Unit"
- region = (
- clean_regional_unit(address.get("state"))
- or clean_regional_unit(address.get("province"))
- or clean_regional_unit(address.get("region"))
- or county # county alone if no state_district
- )
-
- # Clean up "Regional Unit of" prefix from the final region
- if region and region.startswith("Regional Unit of "):
- region = region[len("Regional Unit of ") :]
-
- # Extract city information with fallback hierarchy
- city_raw = (
- address.get("city")
- or address.get("town")
- or address.get("village")
- or address.get("hamlet")
- or address.get("suburb")
- or address.get("neighbourhood")
- or address.get("municipality") # Add municipality as fallback
- or ""
- )
-
- # Clean up municipal suffixes from the city field
- city = clean_municipal_suffixes(city_raw)
-
- # Log the extracted data
- if debug:
- print("📍 Extracted Location Data:")
- print(f" Country: '{country}'")
- print(f" Region: '{region}'")
- print(f" City: '{city}'")
- print(f" Full Address: '{data.get('display_name', '')}'")
- print(
- f" Raw Address Object: {orjson.dumps(address, option=orjson.OPT_INDENT_2).decode('utf-8')}"
- )
-
- # Show which region fields were found and used
- print(" Region Field Analysis:")
- print(f" county: '{address.get('county')}' → cleaned: '{county}'")
- print(
- f" state_district: '{address.get('state_district')}' → cleaned: '{state_district}'"
- )
- print(
- f" state: '{address.get('state')}' → cleaned: '{clean_regional_unit(address.get('state'))}'"
- )
- print(
- f" province: '{address.get('province')}' → cleaned: '{clean_regional_unit(address.get('province'))}'"
- )
- print(
- f" region: '{address.get('region')}' → cleaned: '{clean_regional_unit(address.get('region'))}'"
- )
- if county and state_district:
- print(f" → Using concatenated: '{county}, {state_district}'")
- else:
- print(f" → Using fallback: '{region}'")
-
- # Show which city fields were found and used
- print(" City Field Analysis:")
- print(f" city: '{address.get('city')}'")
- print(f" town: '{address.get('town')}'")
- print(f" village: '{address.get('village')}'")
- print(f" hamlet: '{address.get('hamlet')}'")
- print(f" suburb: '{address.get('suburb')}'")
- print(f" neighbourhood: '{address.get('neighbourhood')}'")
- print(f" municipality: '{address.get('municipality')}'")
- print(f" Raw city value: '{city_raw}'")
- print(f" Cleaned city value: '{city}'")
- print(f" → Using: '{city}'")
-
- return {
- "country": country,
- "region": region,
- "city": city,
- "full_address": data.get("display_name", ""),
- }
+ from app.geo_utils import perform_reverse_geocode
+ try:
+ data = perform_reverse_geocode(latitude, longitude)
except requests.exceptions.Timeout:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Geocoding service timeout. Please try again later.",
)
except requests.exceptions.ConnectionError:
- # Fallback to basic location detection based on coordinates
if debug:
- print("❌ OpenStreetMap API unavailable, using fallback location detection")
- fallback_result = get_fallback_location(latitude, longitude, debug)
- return fallback_result
- except requests.RequestException as e:
- # Fallback to basic location detection based on coordinates
- if debug:
- print(f"❌ OpenStreetMap API error: {e}, using fallback location detection")
- fallback_result = get_fallback_location(latitude, longitude, debug)
- return fallback_result
+ print("❌ Geocoding API unavailable, using fallback location detection")
+ return get_fallback_location(latitude, longitude, debug)
except Exception as e:
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=f"Unexpected error during geocoding: {str(e)}",
- )
+ logger.error(f"Reverse geocoding error: {e}")
+ return get_fallback_location(latitude, longitude, debug)
+
+ return {
+ "country": data.get("country"),
+ "region": data.get("region"),
+ "city": data.get("city"),
+ "full_address": data.get("city")
+ or data.get("region")
+ or data.get("country")
+ or f"Coordinates: {latitude}, {longitude}",
+ }
def get_fallback_location(latitude: float, longitude: float, debug: bool = False):
diff --git a/backend/app/schemas/__init__.py b/backend/app/schemas/__init__.py
index f8364a1e..b4a35b83 100644
--- a/backend/app/schemas/__init__.py
+++ b/backend/app/schemas/__init__.py
@@ -1259,6 +1259,7 @@ class DivingCenterResponseWithOrganizations(DivingCenterResponse):
# Dive Schemas
class DiveBase(BaseModel):
dive_site_id: int | None = None
+ unlinked_site_name: str | None = Field(None, max_length=255)
diving_center_id: int | None = None # Link to diving center
selected_route_id: int | None = None # Selected dive route
name: str | None = Field(None, max_length=255) # Custom name/alias
@@ -1300,6 +1301,7 @@ class DiveCreate(DiveBase):
class DiveUpdate(BaseModel):
dive_site_id: int | None = None
+ unlinked_site_name: str | None = Field(None, max_length=255)
diving_center_id: int | None = None # Link to diving center
selected_route_id: int | None = None # Selected dive route
name: str | None = Field(None, max_length=255)
@@ -1339,6 +1341,7 @@ class DiveResponse(DiveBase):
id: int
user_id: int
dive_site_id: int | None = None
+ unlinked_site_name: str | None = None
diving_center_id: int | None = None # Link to diving center
selected_route_id: int | None = None # Selected dive route
name: str | None = None
diff --git a/backend/migrations/versions/0110_add_unlinked_site_name_to_dives.py b/backend/migrations/versions/0110_add_unlinked_site_name_to_dives.py
new file mode 100644
index 00000000..75d19bd3
--- /dev/null
+++ b/backend/migrations/versions/0110_add_unlinked_site_name_to_dives.py
@@ -0,0 +1,31 @@
+"""add unlinked_site_name to dives
+
+Revision ID: 0110
+Revises: 0109
+Create Date: 2026-10-27 10:00:00.000000
+
+"""
+import sqlalchemy as sa
+from alembic import op
+
+revision = "0110"
+down_revision = "0109"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.add_column(
+ "dives",
+ sa.Column("unlinked_site_name", sa.String(length=255), nullable=True),
+ )
+ op.create_index(
+ "ix_dives_unlinked_site_name",
+ "dives",
+ ["unlinked_site_name"],
+ )
+
+
+def downgrade():
+ op.drop_index("ix_dives_unlinked_site_name", table_name="dives")
+ op.drop_column("dives", "unlinked_site_name")
diff --git a/backend/tests/test_geo_service.py b/backend/tests/test_geo_service.py
new file mode 100644
index 00000000..0b4eb539
--- /dev/null
+++ b/backend/tests/test_geo_service.py
@@ -0,0 +1,109 @@
+from unittest.mock import MagicMock, patch
+
+from app.geo_utils import perform_reverse_geocode, search_places
+
+
+def test_perform_reverse_geocode_geoapify_success():
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {
+ "features": [
+ {
+ "properties": {
+ "country": "Greece",
+ "state": "Attica Regional Unit",
+ "city": "Glyfada",
+ }
+ }
+ ]
+ }
+
+ with patch("os.getenv", return_value="fake_geoapify_key"):
+ with patch("requests.get", return_value=mock_resp):
+ res = perform_reverse_geocode(37.88, 23.75)
+ assert res is not None
+ assert res["country"] == "Greece"
+ assert res["region"] == "Attica"
+ assert res["city"] == "Glyfada"
+
+
+def test_perform_reverse_geocode_photon_fallback():
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {
+ "features": [
+ {
+ "properties": {
+ "country": "Egypt",
+ "state": "South Sinai",
+ "city": "Sharm El Sheikh",
+ }
+ }
+ ]
+ }
+
+ with patch("os.getenv", return_value=None): # No Geoapify key
+ with patch("requests.get", return_value=mock_resp):
+ res = perform_reverse_geocode(27.73, 34.25)
+ assert res is not None
+ assert res["country"] == "Egypt"
+ assert res["region"] == "South Sinai"
+ assert res["city"] == "Sharm El Sheikh"
+
+
+def test_search_places_geoapify_success():
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {
+ "features": [
+ {
+ "properties": {
+ "name": "Sydney",
+ "formatted": "Sydney, NSW, Australia",
+ "country": "Australia",
+ "result_type": "city",
+ },
+ "geometry": {
+ "coordinates": [151.208, -33.869],
+ },
+ }
+ ]
+ }
+
+ with patch("os.getenv", return_value="fake_key"):
+ with patch("requests.get", return_value=mock_resp):
+ results = search_places("Sydney")
+ assert len(results) == 1
+ assert results[0]["name"] == "Sydney"
+ assert results[0]["country"] == "Australia"
+ assert results[0]["latitude"] == -33.869
+ assert results[0]["longitude"] == 151.208
+
+
+def test_search_places_photon_fallback():
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {
+ "features": [
+ {
+ "properties": {
+ "name": "Ras Mohammed Wall",
+ "city": "Sharm El Sheikh",
+ "state": "South Sinai",
+ "country": "Egypt",
+ },
+ "geometry": {
+ "coordinates": [34.259, 27.732],
+ },
+ }
+ ]
+ }
+
+ with patch("os.getenv", return_value=None):
+ with patch("requests.get", return_value=mock_resp):
+ results = search_places("Ras Mohammed")
+ assert len(results) == 1
+ assert results[0]["name"] == "Ras Mohammed Wall"
+ assert results[0]["country"] == "Egypt"
+ assert results[0]["latitude"] == 27.732
+ assert results[0]["longitude"] == 34.259
diff --git a/backend/tests/test_unlinked_dive_import.py b/backend/tests/test_unlinked_dive_import.py
new file mode 100644
index 00000000..ed4f0fe8
--- /dev/null
+++ b/backend/tests/test_unlinked_dive_import.py
@@ -0,0 +1,104 @@
+import pytest
+
+from app.models import Dive
+from app.routers.dives.imports.subsurface import convert_to_divemap_format
+
+
+def test_subsurface_gps_parsing_to_lat_lng():
+ # Test space-separated GPS
+ dive_sites = {
+ "site1": {
+ "name": "Custom Spot",
+ "gps": "37.8812 23.7548",
+ }
+ }
+ res = convert_to_divemap_format(
+ dive_number=1,
+ rating=None,
+ visibility=None,
+ sac=None,
+ otu=None,
+ cns=None,
+ tags=None,
+ divesiteid="site1",
+ dive_date="2026-10-12",
+ dive_time="10:00:00",
+ duration="45 min",
+ buddy=None,
+ suit=None,
+ cylinders=[],
+ weights=None,
+ computer_data={},
+ dive_sites=dive_sites,
+ db=None,
+ events=[],
+ site_match_cache={},
+ )
+ assert res["dive_site_id"] is None
+ unmatched = res["unmatched_dive_site"]
+ assert unmatched is not None
+ assert unmatched["name"] == "Custom Spot"
+ assert unmatched["gps"] == "37.8812 23.7548"
+ assert unmatched["latitude"] == pytest.approx(37.8812)
+ assert unmatched["longitude"] == pytest.approx(23.7548)
+
+ # Test comma-separated GPS
+ dive_sites_comma = {
+ "site2": {
+ "name": "Comma Spot",
+ "gps": "37.8812, 23.7548",
+ }
+ }
+ res_comma = convert_to_divemap_format(
+ dive_number=2,
+ rating=None,
+ visibility=None,
+ sac=None,
+ otu=None,
+ cns=None,
+ tags=None,
+ divesiteid="site2",
+ dive_date="2026-10-12",
+ dive_time="10:00:00",
+ duration="45 min",
+ buddy=None,
+ suit=None,
+ cylinders=[],
+ weights=None,
+ computer_data={},
+ dive_sites=dive_sites_comma,
+ db=None,
+ events=[],
+ site_match_cache={},
+ )
+ unmatched_comma = res_comma["unmatched_dive_site"]
+ assert unmatched_comma["latitude"] == pytest.approx(37.8812)
+ assert unmatched_comma["longitude"] == pytest.approx(23.7548)
+
+
+def test_confirm_import_persists_unlinked_site_name(client, auth_headers, db_session):
+ dives = [
+ {
+ "dive_site_id": None,
+ "unlinked_site_name": "Shark Reef & Yolanda",
+ "is_private": False,
+ "dive_date": "2026-10-12",
+ "duration": 45,
+ "max_depth": 25.0,
+ }
+ ]
+
+ resp = client.post("/api/v1/dives/import/confirm", json=dives, headers=auth_headers)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert len(data["imported_dives"]) == 1
+ imported = data["imported_dives"][0]
+ assert imported["dive_site_id"] is None
+ assert imported["unlinked_site_name"] == "Shark Reef & Yolanda"
+ assert "Shark Reef & Yolanda" in imported["name"]
+
+ # Verify directly from DB
+ dive = db_session.query(Dive).filter(Dive.id == imported["id"]).first()
+ assert dive is not None
+ assert dive.dive_site_id is None
+ assert dive.unlinked_site_name == "Shark Reef & Yolanda"
diff --git a/backend/tests/test_unlinked_site_schema.py b/backend/tests/test_unlinked_site_schema.py
new file mode 100644
index 00000000..bda09f0c
--- /dev/null
+++ b/backend/tests/test_unlinked_site_schema.py
@@ -0,0 +1,33 @@
+from app.models import Dive
+from app.schemas import DiveCreate, DiveResponse, DiveUpdate
+
+
+def test_dive_schema_supports_unlinked_site_name():
+ data = {
+ "dive_date": "2026-10-12",
+ "unlinked_site_name": "Shark Reef & Yolanda",
+ "dive_site_id": None,
+ }
+ create_schema = DiveCreate(**data)
+ assert create_schema.unlinked_site_name == "Shark Reef & Yolanda"
+ assert create_schema.dive_site_id is None
+
+
+def test_dive_update_schema_supports_unlinked_site_name():
+ update_schema = DiveUpdate(unlinked_site_name="Blue Hole")
+ assert update_schema.unlinked_site_name == "Blue Hole"
+
+
+def test_dive_response_schema_supports_unlinked_site_name():
+ resp = DiveResponse(
+ id=1,
+ user_id=1,
+ dive_date="2026-10-12",
+ unlinked_site_name="Ras Mohammed",
+ )
+ assert resp.unlinked_site_name == "Ras Mohammed"
+
+
+def test_dive_model_has_unlinked_site_name_column():
+ assert hasattr(Dive, "unlinked_site_name")
+ assert Dive.unlinked_site_name.property.columns[0].nullable is True
diff --git a/frontend/src/components/__tests__/DiveSiteExplorerCard.test.jsx b/frontend/src/components/DiveSiteExplorerCard.test.jsx
similarity index 93%
rename from frontend/src/components/__tests__/DiveSiteExplorerCard.test.jsx
rename to frontend/src/components/DiveSiteExplorerCard.test.jsx
index d831dcba..3bf2043a 100644
--- a/frontend/src/components/__tests__/DiveSiteExplorerCard.test.jsx
+++ b/frontend/src/components/DiveSiteExplorerCard.test.jsx
@@ -3,7 +3,7 @@ import { QueryClient, QueryClientProvider } from 'react-query';
import { MemoryRouter } from 'react-router-dom';
import { describe, it, expect } from 'vitest';
-import DiveSiteExplorerCard from '../DiveSiteExplorerCard';
+import DiveSiteExplorerCard from './DiveSiteExplorerCard';
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
diff --git a/frontend/src/components/__tests__/DiveSiteMediaPreview.test.jsx b/frontend/src/components/DiveSiteMediaPreview.test.jsx
similarity index 97%
rename from frontend/src/components/__tests__/DiveSiteMediaPreview.test.jsx
rename to frontend/src/components/DiveSiteMediaPreview.test.jsx
index e84ffdde..a4561387 100644
--- a/frontend/src/components/__tests__/DiveSiteMediaPreview.test.jsx
+++ b/frontend/src/components/DiveSiteMediaPreview.test.jsx
@@ -1,7 +1,7 @@
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
-import DiveSiteMediaPreview from '../DiveSiteMediaPreview';
+import DiveSiteMediaPreview from './DiveSiteMediaPreview';
describe('DiveSiteMediaPreview', () => {
const mockPhoto = {
diff --git a/frontend/src/components/__tests__/DiveSiteSpecsCard.test.jsx b/frontend/src/components/DiveSiteSpecsCard.test.jsx
similarity index 96%
rename from frontend/src/components/__tests__/DiveSiteSpecsCard.test.jsx
rename to frontend/src/components/DiveSiteSpecsCard.test.jsx
index d12ca29b..c11d2495 100644
--- a/frontend/src/components/__tests__/DiveSiteSpecsCard.test.jsx
+++ b/frontend/src/components/DiveSiteSpecsCard.test.jsx
@@ -1,7 +1,7 @@
import { render, screen, fireEvent, act } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import DiveSiteSpecsCard from '../DiveSiteSpecsCard';
+import DiveSiteSpecsCard from './DiveSiteSpecsCard';
describe('DiveSiteSpecsCard', () => {
const mockDiveSite = {
diff --git a/frontend/src/components/ImportDivesModal.jsx b/frontend/src/components/ImportDivesModal.jsx
index a9f2118a..0e74cd7e 100644
--- a/frontend/src/components/ImportDivesModal.jsx
+++ b/frontend/src/components/ImportDivesModal.jsx
@@ -31,6 +31,7 @@ import { TANK_SIZES } from '../utils/diveConstants';
import DivingCenterSearchableDropdown from './DivingCenterSearchableDropdown';
import FuzzySearchInput from './FuzzySearchInput';
import GasTanksDisplay from './GasTanksDisplay';
+import QuickCreateDiveSiteModal from './QuickCreateDiveSiteModal';
import Button from './ui/Button';
import Modal from './ui/Modal';
@@ -41,6 +42,7 @@ const ImportDivesModal = ({ isOpen, onClose, onSuccess }) => {
const [parsedDives, setParsedDives] = useState([]);
const [availableDiveSites, setAvailableDiveSites] = useState([]);
const [availableDivingCenters, setAvailableDivingCenters] = useState([]);
+ const [quickCreateData, setQuickCreateData] = useState(null);
const [currentStep, setCurrentStep] = useState('upload'); // 'upload', 'mapping', 'review', 'importing'
const [isProcessing, setIsProcessing] = useState(false);
const [diveSiteSearchStrings, setDiveSiteSearchStrings] = useState({});
@@ -357,6 +359,69 @@ const ImportDivesModal = ({ isOpen, onClose, onSuccess }) => {
handleDiveSiteSearchChange(index, site.name);
};
+ const handleOpenQuickCreate = (index, dive) => {
+ const unmatchedName = dive.unmatched_dive_site?.name || '';
+ const matchingCount = parsedDives.filter(
+ d => !d.skip && d.unmatched_dive_site?.name === unmatchedName
+ ).length;
+
+ setQuickCreateData({
+ index,
+ initialData: {
+ name: unmatchedName,
+ latitude: dive.unmatched_dive_site?.latitude,
+ longitude: dive.unmatched_dive_site?.longitude,
+ country: dive.country || '',
+ },
+ matchingCount: matchingCount || 1,
+ unmatchedName,
+ });
+ };
+
+ const handleQuickCreateSuccess = (site, applyToAll) => {
+ // 1. Inject newly created/selected site into availableDiveSites state
+ setAvailableDiveSites(prev => [site, ...prev.filter(s => s.id !== site.id)]);
+
+ const targetIndices = new Set();
+ if (quickCreateData) {
+ parsedDives.forEach((d, i) => {
+ if (
+ i === quickCreateData.index ||
+ (applyToAll &&
+ quickCreateData.unmatchedName &&
+ d.unmatched_dive_site?.name === quickCreateData.unmatchedName)
+ ) {
+ targetIndices.add(i);
+ }
+ });
+ }
+
+ // 2. Update parsedDives
+ setParsedDives(prev =>
+ prev.map((d, i) => {
+ if (targetIndices.has(i)) {
+ return {
+ ...d,
+ dive_site_id: site.id,
+ unmatched_dive_site: null,
+ };
+ }
+ return d;
+ })
+ );
+
+ // 3. Update search strings
+ setDiveSiteSearchStrings(prev => {
+ const next = { ...prev };
+ targetIndices.forEach(idx => {
+ next[idx] = site.name;
+ });
+ return next;
+ });
+
+ setQuickCreateData(null);
+ };
+
const handleDiveCenterChange = (index, centerId, centerName) => {
setParsedDives(prev =>
prev.map((dive, i) =>
@@ -592,33 +657,10 @@ const ImportDivesModal = ({ isOpen, onClose, onSuccess }) => {
return;
}
- const unresolvedDives = parsedDives.filter(
- dive => !dive.skip && dive.unmatched_dive_site && !dive.dive_site_id
- );
- if (unresolvedDives.length > 0) {
- toast.error(
- `${unresolvedDives.length} dive(s) have unmatched dive sites. Please select dive sites or create new ones before importing.`
- );
- return;
- }
-
- const unresolvedProposedDives = parsedDives.filter(
- dive => !dive.skip && dive.proposed_dive_sites && !dive.dive_site_id
- );
- if (unresolvedProposedDives.length > 0) {
- toast.error(
- `${unresolvedProposedDives.length} dive(s) have proposed dive sites but no selection. Please select one of the proposed sites or choose a different one.`
- );
- return;
- }
-
- const filteredDives = parsedDives.filter(
- dive =>
- !dive.skip && !dive.unmatched_dive_site && !(dive.proposed_dive_sites && !dive.dive_site_id)
- );
+ const filteredDives = parsedDives.filter(dive => !dive.skip);
if (filteredDives.length === 0) {
- toast.error('No dives to import after filtering out unmatched dive sites and skipped dives');
+ toast.error('No dives selected for import');
return;
}
@@ -633,6 +675,14 @@ const ImportDivesModal = ({ isOpen, onClose, onSuccess }) => {
...cleanDive
} = dive;
+ if (!dive.dive_site_id) {
+ if (dive.unmatched_dive_site?.name) {
+ cleanDive.unlinked_site_name = dive.unmatched_dive_site.name;
+ } else if (dive.proposed_dive_sites?.[0]?.original_name) {
+ cleanDive.unlinked_site_name = dive.proposed_dive_sites[0].original_name;
+ }
+ }
+
// Keep profile_data for the backend to save/update
if (dive.profile_data) {
cleanDive.profile_data = dive.profile_data;
@@ -1021,10 +1071,10 @@ const ImportDivesModal = ({ isOpen, onClose, onSuccess }) => {
{dive.unmatched_dive_site ? (
-
+
{dive.unmatched_dive_site.name} not found in
- database
+ database (will import as unlinked dive if left unselected)
@@ -1041,21 +1091,12 @@ const ImportDivesModal = ({ isOpen, onClose, onSuccess }) => {
/>
@@ -1203,18 +1244,7 @@ const ImportDivesModal = ({ isOpen, onClose, onSuccess }) => {
{isProcessing ? (
'Importing...'
) : (
- <>
- Import{' '}
- {
- parsedDives.filter(
- dive =>
- !dive.unmatched_dive_site &&
- !(dive.proposed_dive_sites && !dive.dive_site_id) &&
- !dive.skip
- ).length
- }{' '}
- Dives
- >
+ <>Import {parsedDives.filter(dive => !dive.skip).length} Dives>
)}
@@ -1229,6 +1259,16 @@ const ImportDivesModal = ({ isOpen, onClose, onSuccess }) => {
)}
+
+ {quickCreateData && (
+ setQuickCreateData(null)}
+ initialData={quickCreateData.initialData}
+ matchingCount={quickCreateData.matchingCount}
+ onSuccess={handleQuickCreateSuccess}
+ />
+ )}
);
};
diff --git a/frontend/src/components/ImportDivesModal.test.jsx b/frontend/src/components/ImportDivesModal.test.jsx
new file mode 100644
index 00000000..ed5b8c34
--- /dev/null
+++ b/frontend/src/components/ImportDivesModal.test.jsx
@@ -0,0 +1,241 @@
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import React from 'react';
+import { QueryClient, QueryClientProvider } from 'react-query';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+import * as divesService from '../services/dives';
+
+import ImportDivesModal from './ImportDivesModal';
+
+vi.mock('../services/dives', () => ({
+ importSubsurfaceXML: vi.fn(),
+ confirmImportDives: vi.fn(),
+ getCSVHeaders: vi.fn(),
+ processCSVImport: vi.fn(),
+ importGarminFIT: vi.fn(),
+ importSuuntoJSON: vi.fn(),
+ importShearwaterDB: vi.fn(),
+}));
+
+vi.mock('./QuickCreateDiveSiteModal', () => ({
+ default: ({ isOpen, onClose, initialData, matchingCount, onSuccess }) => {
+ if (!isOpen) return null;
+ return (
+
+ Quick Create: {initialData?.name}
+ Matching: {matchingCount}
+
+
+
+ );
+ },
+}));
+
+describe('ImportDivesModal - Diving Center Selection', () => {
+ let queryClient;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ });
+
+ const renderComponent = (props = {}) =>
+ render(
+
+
+
+ );
+
+ it('populates available diving centers on XML import and retains center selection', async () => {
+ divesService.importSubsurfaceXML.mockResolvedValueOnce({
+ message: 'Successfully parsed 1 dives',
+ dives: [
+ {
+ dive_date: '2026-06-28',
+ dive_time: '12:18:14',
+ duration: 73,
+ max_depth: 41.6,
+ dive_site_id: 22,
+ diving_center_id: null,
+ is_private: false,
+ },
+ ],
+ available_dive_sites: [{ id: 22, name: 'Arsida wall' }],
+ available_diving_centers: [
+ { id: 61, name: 'Amorgos Diving Center', country: 'Greece' },
+ { id: 62, name: 'Athens Divers Club', country: 'Greece' },
+ ],
+ });
+
+ renderComponent();
+
+ const file = new globalThis.File([''], 'arsida.xml', { type: 'text/xml' });
+ const fileInput = document.querySelector('input[type="file"]');
+ expect(fileInput).toBeInTheDocument();
+
+ fireEvent.change(fileInput, { target: { files: [file] } });
+
+ const processBtn = screen.getByRole('button', { name: /Process Files/i });
+ expect(processBtn).not.toBeDisabled();
+ fireEvent.click(processBtn);
+
+ await waitFor(() => {
+ expect(screen.getByText('Review Dives to Import')).toBeInTheDocument();
+ });
+
+ const centerTrigger = screen.getByRole('combobox', {
+ name: /Search for a diving center\.\.\./i,
+ });
+ expect(centerTrigger).toBeInTheDocument();
+
+ fireEvent.click(centerTrigger);
+
+ const option = await screen.findByText('Amorgos Diving Center (Greece)');
+ expect(option).toBeInTheDocument();
+
+ fireEvent.click(option);
+
+ await waitFor(() => {
+ expect(centerTrigger).toHaveTextContent('Amorgos Diving Center (Greece)');
+ });
+ });
+
+ it('allows importing dives with unmatched dive sites as unlinked dives without blocking', async () => {
+ divesService.importSubsurfaceXML.mockResolvedValueOnce({
+ message: 'Successfully parsed 1 dives',
+ dives: [
+ {
+ dive_date: '2026-06-28',
+ dive_time: '12:18:14',
+ duration: 45,
+ max_depth: 25.0,
+ dive_site_id: null,
+ unmatched_dive_site: {
+ name: 'Unknown Secret Reef',
+ latitude: 37.88,
+ longitude: 23.75,
+ },
+ is_private: false,
+ },
+ ],
+ available_dive_sites: [{ id: 1, name: 'Arsida' }],
+ available_diving_centers: [],
+ });
+
+ divesService.confirmImportDives.mockResolvedValueOnce({
+ message: 'Successfully imported 1 dives',
+ imported_dives: [{ id: 101, name: 'Dive - 2026-06-28 - Unknown Secret Reef' }],
+ });
+
+ renderComponent();
+
+ const file = new globalThis.File([''], 'dive.xml', { type: 'text/xml' });
+ const fileInput = document.querySelector('input[type="file"]');
+ fireEvent.change(fileInput, { target: { files: [file] } });
+
+ const processBtn = screen.getByRole('button', { name: /Process Files/i });
+ fireEvent.click(processBtn);
+
+ await waitFor(() => {
+ expect(screen.getByText('Review Dives to Import')).toBeInTheDocument();
+ });
+
+ // Unmatched site warning is rendered
+ expect(screen.getByText('Unknown Secret Reef')).toBeInTheDocument();
+
+ // Confirm import button is clicked
+ const confirmBtn = screen.getByRole('button', { name: /Import 1 Dives/i });
+ fireEvent.click(confirmBtn);
+
+ // Should NOT be blocked; should call confirmImportDives with unlinked_site_name
+ await waitFor(() => {
+ expect(divesService.confirmImportDives).toHaveBeenCalledWith(
+ expect.arrayContaining([
+ expect.objectContaining({
+ dive_site_id: null,
+ unlinked_site_name: 'Unknown Secret Reef',
+ }),
+ ])
+ );
+ });
+ });
+
+ it('opens QuickCreateDiveSiteModal and batch-applies new site to matching dives', async () => {
+ divesService.importSubsurfaceXML.mockResolvedValueOnce({
+ message: 'Successfully parsed 2 dives',
+ dives: [
+ {
+ dive_date: '2026-06-28',
+ dive_site_id: null,
+ unmatched_dive_site: {
+ name: 'Shark Reef',
+ latitude: 27.7281,
+ longitude: 34.2519,
+ },
+ is_private: false,
+ },
+ {
+ dive_date: '2026-06-29',
+ dive_site_id: null,
+ unmatched_dive_site: {
+ name: 'Shark Reef',
+ latitude: 27.7281,
+ longitude: 34.2519,
+ },
+ is_private: false,
+ },
+ ],
+ available_dive_sites: [],
+ available_diving_centers: [],
+ });
+
+ renderComponent();
+
+ const file = new globalThis.File([''], 'dives.xml', { type: 'text/xml' });
+ const fileInput = document.querySelector('input[type="file"]');
+ fireEvent.change(fileInput, { target: { files: [file] } });
+
+ fireEvent.click(screen.getByRole('button', { name: /Process Files/i }));
+
+ await waitFor(() => {
+ expect(screen.getByText('Review Dives to Import')).toBeInTheDocument();
+ });
+
+ // Find and click the "Quick Create" button for Shark Reef
+ const quickCreateButtons = screen.getAllByRole('button', { name: /quick create/i });
+ fireEvent.click(quickCreateButtons[0]);
+
+ // Quick create modal should open
+ expect(await screen.findByTestId('quick-create-modal')).toBeInTheDocument();
+ expect(screen.getByText('Matching: 2')).toBeInTheDocument();
+
+ // Trigger mock create success
+ const mockSuccessBtn = screen.getByText('Mock Create Success');
+ fireEvent.click(mockSuccessBtn);
+
+ // Modal closes
+ await waitFor(() => {
+ expect(screen.queryByTestId('quick-create-modal')).not.toBeInTheDocument();
+ });
+
+ // Unmatched warnings should now be resolved for both dives
+ expect(screen.queryByText(/not found in database/i)).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/LinkDiveSiteModal.jsx b/frontend/src/components/LinkDiveSiteModal.jsx
new file mode 100644
index 00000000..13f4d139
--- /dev/null
+++ b/frontend/src/components/LinkDiveSiteModal.jsx
@@ -0,0 +1,205 @@
+import { AlertCircle, Link2, Plus, Loader2 } from 'lucide-react';
+import PropTypes from 'prop-types';
+import React, { useState } from 'react';
+import toast from 'react-hot-toast';
+import { useQuery, useMutation, useQueryClient } from 'react-query';
+
+import api from '../api';
+
+import FuzzySearchInput from './FuzzySearchInput';
+import QuickCreateDiveSiteModal from './QuickCreateDiveSiteModal';
+import Modal from './ui/Modal';
+
+const LinkDiveSiteModal = ({ isOpen, onClose, dive, onSuccess }) => {
+ const queryClient = useQueryClient();
+ const [selectedSite, setSelectedSite] = useState(null);
+ const [searchString, setSearchString] = useState(dive?.unlinked_site_name || '');
+ const [isQuickCreateOpen, setIsQuickCreateOpen] = useState(false);
+
+ // Fetch dive sites list for fuzzy search
+ const { data: diveSites = [], isLoading: isLoadingSites } = useQuery(
+ ['dive-sites-list-all'],
+ async () => {
+ const res = await api.get('/api/v1/dive-sites/', {
+ params: { limit: 1000 },
+ });
+ return Array.isArray(res.data) ? res.data : res.data?.items || [];
+ },
+ {
+ enabled: isOpen,
+ staleTime: 60000,
+ }
+ );
+
+ const linkMutation = useMutation(
+ async ({ siteId }) => {
+ await api.put(`/api/v1/dives/${dive.id}`, {
+ dive_site_id: siteId,
+ });
+ },
+ {
+ onSuccess: (data, { site }) => {
+ queryClient.invalidateQueries(['dives']);
+ queryClient.invalidateQueries(['user-dives']);
+ queryClient.invalidateQueries(['dive', dive.id]);
+ queryClient.invalidateQueries(['dive', String(dive.id)]);
+ toast.success('Dive site linked successfully!');
+ if (onSuccess) {
+ onSuccess(site || selectedSite);
+ }
+ if (onClose) {
+ onClose();
+ }
+ },
+ onError: () => {
+ toast.error('Failed to link dive site.');
+ },
+ }
+ );
+
+ if (!isOpen || !dive) return null;
+
+ const handleConfirmLink = () => {
+ if (!selectedSite) {
+ toast.error('Please select a dive site first.');
+ return;
+ }
+ linkMutation.mutate({ siteId: selectedSite.id, site: selectedSite });
+ };
+
+ const handleQuickCreateSuccess = createdSite => {
+ queryClient.invalidateQueries(['dive-sites-list-all']);
+ setSelectedSite(createdSite);
+ setSearchString(createdSite.name);
+ linkMutation.mutate({ siteId: createdSite.id, site: createdSite });
+ };
+
+ return (
+ <>
+
+
+ {/* Current Unlinked Site Info */}
+
+
+
+ Current site label from log:{' '}
+
+ {dive.unlinked_site_name || 'Unlinked Site'}
+
+
+
+
+
+
+ {isLoadingSites ? (
+
+ Loading dive sites...
+
+ ) : (
+
{
+ setSelectedSite(site);
+ setSearchString(site.name);
+ }}
+ placeholder='Type at least 3 letters to search...'
+ minQueryLength={3}
+ configType='diveSites'
+ />
+ )}
+
+
+ {selectedSite && (
+
+
+
+ Selected: {selectedSite.name}
+
+ {selectedSite.country && (
+
+ {selectedSite.country}
+
+ )}
+
+
Ready
+
+ )}
+
+
+
+
+
+
+
+
+
+
+
+
+ {/* Embedded Quick Create Modal fallback */}
+ {isQuickCreateOpen && (
+ setIsQuickCreateOpen(false)}
+ initialData={{
+ name: dive.unlinked_site_name || '',
+ }}
+ matchingCount={1}
+ onSuccess={handleQuickCreateSuccess}
+ />
+ )}
+ >
+ );
+};
+
+LinkDiveSiteModal.propTypes = {
+ isOpen: PropTypes.bool.isRequired,
+ onClose: PropTypes.func.isRequired,
+ dive: PropTypes.shape({
+ id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
+ unlinked_site_name: PropTypes.string,
+ }),
+ onSuccess: PropTypes.func,
+};
+
+export default LinkDiveSiteModal;
diff --git a/frontend/src/components/LocationPickerMap.jsx b/frontend/src/components/LocationPickerMap.jsx
new file mode 100644
index 00000000..b927c273
--- /dev/null
+++ b/frontend/src/components/LocationPickerMap.jsx
@@ -0,0 +1,698 @@
+import L from 'leaflet';
+import 'leaflet/dist/leaflet.css';
+import { Layers, Maximize2, Search, Loader2, MapPin, X, AlertCircle } from 'lucide-react';
+import PropTypes from 'prop-types';
+import React, { useState, useEffect, useRef, useCallback } from 'react';
+import toast from 'react-hot-toast';
+import {
+ MapContainer,
+ TileLayer,
+ Marker,
+ Popup,
+ Tooltip,
+ useMap,
+ useMapEvents,
+} from 'react-leaflet';
+
+import api from '../api';
+
+import MapLayersPanel from './MapLayersPanel';
+import Modal from './ui/Modal';
+
+// Fix Leaflet default marker assets in bundler
+delete L.Icon.Default.prototype._getIconUrl;
+L.Icon.Default.mergeOptions({
+ iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png',
+ iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png',
+ shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
+});
+
+// Distinct Blue pin for the user's draggable target dive site
+const USER_PIN_ICON = L.divIcon({
+ className: 'custom-user-pin-marker',
+ html: `
+
+ `,
+ iconSize: [32, 32],
+ iconAnchor: [16, 28],
+ popupAnchor: [0, -28],
+});
+
+// Distinct Amber pin for existing nearby dive sites
+const NEARBY_SITE_ICON = L.divIcon({
+ className: 'custom-nearby-pin-marker',
+ html: `
+
+ `,
+ iconSize: [28, 28],
+ iconAnchor: [14, 24],
+ popupAnchor: [0, -24],
+});
+
+const SATELLITE_LAYER = {
+ id: 'satellite',
+ name: 'Satellite',
+ description: 'Satellite imagery view',
+ url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
+ attribution: '© Esri',
+};
+
+// Map controller for programmatic center/zoom updates and size invalidation
+const MapController = ({ targetView, isMaximized }) => {
+ const map = useMap();
+ useEffect(() => {
+ if (!map || !targetView?.center) return;
+ const currentZoom = map.getZoom ? map.getZoom() : 14;
+ map.setView(targetView.center, targetView.zoom ?? currentZoom, { animate: false });
+ }, [map, targetView]);
+
+ useEffect(() => {
+ if (!map) return;
+ const timer = setTimeout(() => {
+ map.invalidateSize?.();
+ }, 100);
+ return () => clearTimeout(timer);
+ }, [map, isMaximized]);
+
+ return null;
+};
+
+// Event listener for map clicks and zoom level changes
+const MapEventsHandler = ({ onMapClick, zoomRef }) => {
+ useMapEvents({
+ click(e) {
+ if (onMapClick) {
+ onMapClick(e.latlng);
+ }
+ },
+ zoomend(e) {
+ if (zoomRef) {
+ zoomRef.current = e.target.getZoom();
+ }
+ },
+ });
+ return null;
+};
+
+const LocationPickerMap = ({
+ latitude,
+ longitude,
+ onChange,
+ height = 'h-64 sm:h-80',
+ country = '',
+ region = '',
+ initialSearchQuery = '',
+ autoSearchOnMount = false,
+ onSelectNearbySite,
+ onLocationResolved,
+ showSearch = true,
+ showNearbyAlert = true,
+ className = '',
+}) => {
+ const [selectedLayer, setSelectedLayer] = useState(SATELLITE_LAYER);
+ const [showLayers, setShowLayers] = useState(false);
+ const [isMaximized, setIsMaximized] = useState(false);
+
+ // Search state
+ const [searchQuery, setSearchQuery] = useState(initialSearchQuery || '');
+ const [isSearching, setIsSearching] = useState(false);
+ const [searchResults, setSearchResults] = useState([]);
+ const [showSearchDropdown, setShowSearchDropdown] = useState(false);
+ const hasAutoSearchedRef = useRef(false);
+
+ // Proximity check state
+ const [nearbySites, setNearbySites] = useState([]);
+ const [isCheckingProximity, setIsCheckingProximity] = useState(false);
+ const proximityTimeoutRef = useRef(null);
+ const reverseGeocodeTimeoutRef = useRef(null);
+ const isInternalUpdateRef = useRef(false);
+
+ // Parse coords
+ const parsedLat = typeof latitude === 'string' ? parseFloat(latitude) : latitude;
+ const parsedLng = typeof longitude === 'string' ? parseFloat(longitude) : longitude;
+ const hasValidCoords =
+ typeof parsedLat === 'number' &&
+ !isNaN(parsedLat) &&
+ typeof parsedLng === 'number' &&
+ !isNaN(parsedLng);
+
+ // Default center if no coordinates
+ const defaultCenter = hasValidCoords ? [parsedLat, parsedLng] : [37.9838, 23.7275]; // Athens default
+ const defaultZoom = hasValidCoords ? 13 : country ? 6 : 4;
+
+ const [targetView, setTargetView] = useState({
+ center: defaultCenter,
+ zoom: defaultZoom,
+ id: 0,
+ });
+ const zoomRef = useRef(defaultZoom);
+
+ // Update search input if initialSearchQuery changes and search input is empty
+ useEffect(() => {
+ if (initialSearchQuery && !searchQuery) {
+ setSearchQuery(initialSearchQuery);
+ }
+ }, [initialSearchQuery, searchQuery]);
+
+ // Sync center when coordinates change from external input (e.g. typing or initial load)
+ useEffect(() => {
+ if (isInternalUpdateRef.current) {
+ isInternalUpdateRef.current = false;
+ return;
+ }
+
+ if (hasValidCoords) {
+ setTargetView({
+ center: [parsedLat, parsedLng],
+ zoom: zoomRef.current < 12 ? 14 : undefined,
+ id: Date.now(),
+ });
+ }
+ }, [parsedLat, parsedLng, hasValidCoords]);
+
+ // Proximity check (1km) with 400ms debounce
+ useEffect(() => {
+ if (!hasValidCoords || !showNearbyAlert) {
+ setNearbySites([]);
+ return;
+ }
+
+ if (proximityTimeoutRef.current) {
+ clearTimeout(proximityTimeoutRef.current);
+ }
+
+ proximityTimeoutRef.current = setTimeout(async () => {
+ setIsCheckingProximity(true);
+ try {
+ const res = await api.get('/api/v1/dive-sites/check-proximity', {
+ params: {
+ lat: parsedLat,
+ lng: parsedLng,
+ radius_m: 1000,
+ },
+ });
+ setNearbySites(res.data || []);
+ } catch (err) {
+ console.error('Failed to check proximity for dive sites:', err);
+ setNearbySites([]);
+ } finally {
+ setIsCheckingProximity(false);
+ }
+ }, 400);
+
+ return () => {
+ if (proximityTimeoutRef.current) {
+ clearTimeout(proximityTimeoutRef.current);
+ }
+ };
+ }, [parsedLat, parsedLng, hasValidCoords, showNearbyAlert]);
+
+ // Auto reverse-geocode coordinates (500ms debounce) to auto-fill Country and Region
+ useEffect(() => {
+ if (!hasValidCoords || !onLocationResolved) return;
+
+ if (reverseGeocodeTimeoutRef.current) {
+ clearTimeout(reverseGeocodeTimeoutRef.current);
+ }
+
+ reverseGeocodeTimeoutRef.current = setTimeout(async () => {
+ try {
+ const res = await api.get('/api/v1/dive-sites/reverse-geocode', {
+ params: { latitude: parsedLat, longitude: parsedLng },
+ });
+ if (res.data && (res.data.country || res.data.region)) {
+ onLocationResolved({
+ country: res.data.country || '',
+ region: res.data.region || '',
+ city: res.data.city || '',
+ });
+ }
+ } catch (err) {
+ console.warn('Auto reverse-geocoding failed:', err);
+ }
+ }, 500);
+
+ return () => {
+ if (reverseGeocodeTimeoutRef.current) {
+ clearTimeout(reverseGeocodeTimeoutRef.current);
+ }
+ };
+ }, [parsedLat, parsedLng, hasValidCoords, onLocationResolved]);
+
+ // Handle map click
+ const handleMapClick = useCallback(
+ latlng => {
+ setShowSearchDropdown(false);
+ if (onChange) {
+ isInternalUpdateRef.current = true;
+ const lat = parseFloat(latlng.lat.toFixed(6));
+ const lng = parseFloat(latlng.lng.toFixed(6));
+ onChange({ lat, lng });
+ const currentZoom = zoomRef.current;
+ setTargetView({
+ center: [lat, lng],
+ zoom: currentZoom < 12 ? 14 : undefined,
+ id: Date.now(),
+ });
+ }
+ },
+ [onChange]
+ );
+
+ // Handle marker drag
+ const handleMarkerDragEnd = useCallback(
+ e => {
+ const marker = e.target;
+ if (marker && onChange) {
+ isInternalUpdateRef.current = true;
+ const position = marker.getLatLng();
+ const lat = parseFloat(position.lat.toFixed(6));
+ const lng = parseFloat(position.lng.toFixed(6));
+ onChange({ lat, lng });
+ setTargetView({
+ center: [lat, lng],
+ id: Date.now(),
+ });
+ }
+ },
+ [onChange]
+ );
+
+ // Handle selecting a geocoded search result
+ const handleSelectSearchResult = useCallback(
+ item => {
+ const lat = parseFloat(item.lat);
+ const lon = parseFloat(item.lon);
+ if (!isNaN(lat) && !isNaN(lon)) {
+ const isCountryOrRegion = item.addresstype === 'country' || item.type === 'administrative';
+ const targetZoom = isCountryOrRegion ? 6 : 14;
+ setTargetView({
+ center: [lat, lon],
+ zoom: targetZoom,
+ id: Date.now(),
+ });
+ setShowSearchDropdown(false);
+ setSearchQuery(item.display_name.split(',')[0]);
+ if (onChange) {
+ onChange({
+ lat: parseFloat(lat.toFixed(6)),
+ lng: parseFloat(lon.toFixed(6)),
+ });
+ }
+ if (onLocationResolved && (item.country || item.region)) {
+ onLocationResolved({
+ country: item.country || '',
+ region: item.region || '',
+ });
+ }
+ }
+ },
+ [onChange, onLocationResolved]
+ );
+
+ // Geocoding place search via backend (which handles 3-tier fallback: Geoapify -> Photon -> Nominatim)
+ const executeSearch = useCallback(
+ async (rawQuery, isAuto = false) => {
+ const query = (rawQuery || '').trim();
+ if (!query) return;
+
+ setIsSearching(true);
+ try {
+ const res = await api.get('/api/v1/dive-sites/search-places', {
+ params: {
+ q: query,
+ latitude: hasValidCoords ? parsedLat : undefined,
+ longitude: hasValidCoords ? parsedLng : undefined,
+ limit: 5,
+ },
+ });
+
+ const items = Array.isArray(res.data)
+ ? res.data.map(d => ({
+ display_name: d.display_name,
+ name: d.name,
+ lat: d.latitude,
+ lon: d.longitude,
+ country: d.country,
+ region: d.region,
+ type: d.type,
+ }))
+ : [];
+
+ if (items.length === 0) {
+ setSearchResults([]);
+ setShowSearchDropdown(false);
+ if (!isAuto) {
+ toast.error(`No locations found for "${query}".`);
+ }
+ } else if (items.length === 1) {
+ setSearchResults(items);
+ handleSelectSearchResult(items[0]);
+ if (isAuto) {
+ toast.success(
+ `Found location for "${items[0].name}" from map search. Adjust pin if needed.`
+ );
+ } else {
+ toast.success(`Found and centered on: ${items[0].name}`);
+ }
+ } else {
+ setSearchResults(items);
+ if (!isAuto) {
+ setShowSearchDropdown(true);
+ }
+ }
+ } catch (err) {
+ console.error('Place search failed:', err);
+ setSearchResults([]);
+ if (!isAuto) {
+ toast.error('Place search failed. Please try again or click the map directly.');
+ }
+ } finally {
+ setIsSearching(false);
+ }
+ },
+ [hasValidCoords, parsedLat, parsedLng, handleSelectSearchResult]
+ );
+
+ const handleSearch = e => {
+ if (e) e.preventDefault();
+ executeSearch(searchQuery, false);
+ };
+
+ // Auto search on mount if requested and no coordinates are preset
+ useEffect(() => {
+ if (autoSearchOnMount && initialSearchQuery && !hasAutoSearchedRef.current && !hasValidCoords) {
+ hasAutoSearchedRef.current = true;
+ executeSearch(initialSearchQuery, true);
+ }
+ }, [autoSearchOnMount, initialSearchQuery, hasValidCoords, executeSearch]);
+
+ const renderMapContent = (isModal = false) => (
+
+ {/* Top Floating Controls */}
+
+
+
+ {!isModal && (
+
+ )}
+
+
+ {/* Coordinate Pill Overlay */}
+ {hasValidCoords && (
+
+
+
+ {parsedLat.toFixed(6)}, {parsedLng.toFixed(6)}
+
+
+ )}
+
+ {/* Instruction Badge */}
+
+ Click map or drag pin to choose dive location
+
+
+ {/* MapLayersPanel */}
+
setShowLayers(false)}
+ selectedLayer={selectedLayer}
+ onLayerChange={layer => {
+ setSelectedLayer(layer);
+ setShowLayers(false);
+ }}
+ />
+
+ {/* Leaflet MapContainer */}
+
+
+
+
+ {hasValidCoords && (
+
+
+
+ New Site Pin (Drag to move)
+
+
+
+ )}
+ {nearbySites.map(site => {
+ if (!site.latitude || !site.longitude) return null;
+ return (
+
+
+
+ {site.name}
+
+ {site.distance_m != null && (
+
+ ({Math.round(site.distance_m)}m away)
+
+ )}
+
+
+
+
{site.name}
+ {site.distance_m != null && (
+
+ {Math.round(site.distance_m)}m from your pin
+
+ )}
+ {site.description && (
+
+ {site.description}
+
+ )}
+ {onSelectNearbySite && (
+
+ )}
+
+
+
+ );
+ })}
+
+
+ );
+
+ return (
+
+ {/* Place Search Bar */}
+ {showSearch && (
+
+
{
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ handleSearch(e);
+ }
+ }}
+ className='flex gap-1.5'
+ >
+
+ setSearchQuery(e.target.value)}
+ onFocus={() => searchResults.length > 0 && setShowSearchDropdown(true)}
+ placeholder='Search island, bay, town, or reef...'
+ className='w-full pl-8 pr-3 py-1.5 text-sm border border-gray-300 dark:border-slate-600 rounded-md bg-white dark:bg-slate-800 text-gray-900 dark:text-slate-100 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500'
+ />
+
+
+
+
+
+ {/* Autocomplete Dropdown */}
+ {showSearchDropdown && searchResults.length > 0 && (
+
+
+ Places found
+
+
+ {searchResults.map((item, idx) => (
+
+ ))}
+
+ )}
+
+ )}
+
+ {/* Main Map */}
+ {renderMapContent(false)}
+
+ {/* Proximity Warning / Suggestion Banner */}
+ {showNearbyAlert && nearbySites.length > 0 && (
+
+
+
+
+
+ Dive site already exists nearby (within 1km)
+
+
+ Did you dive at an existing site with a slightly different name?
+
+
+
+ {nearbySites.slice(0, 3).map(site => (
+
+
+
+ {site.name}
+
+
+ {site.country && `${site.country} • `}
+ {Math.round(site.distance_m)}m away
+
+
+ {onSelectNearbySite ? (
+
+ ) : (
+
+ View Site →
+
+ )}
+
+ ))}
+
+
+
+
+ )}
+
+ {/* Maximized Modal */}
+ {isMaximized && (
+
setIsMaximized(false)}
+ title='Select Dive Site Location'
+ className='w-full max-w-4xl p-0 overflow-hidden'
+ >
+
+ Click map to place or adjust pin
+
+
+ {renderMapContent(true)}
+
+ )}
+
+ );
+};
+
+LocationPickerMap.propTypes = {
+ latitude: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
+ longitude: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
+ onChange: PropTypes.func.isRequired,
+ height: PropTypes.string,
+ country: PropTypes.string,
+ region: PropTypes.string,
+ initialSearchQuery: PropTypes.string,
+ autoSearchOnMount: PropTypes.bool,
+ onSelectNearbySite: PropTypes.func,
+ showSearch: PropTypes.bool,
+ showNearbyAlert: PropTypes.bool,
+ className: PropTypes.string,
+};
+
+export default LocationPickerMap;
diff --git a/frontend/src/components/LocationPickerMap.test.jsx b/frontend/src/components/LocationPickerMap.test.jsx
new file mode 100644
index 00000000..e9fc714e
--- /dev/null
+++ b/frontend/src/components/LocationPickerMap.test.jsx
@@ -0,0 +1,228 @@
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import React from 'react';
+import { QueryClient, QueryClientProvider } from 'react-query';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+import api from '../api';
+
+import LocationPickerMap from './LocationPickerMap';
+
+// Mock react-leaflet components for JSDOM
+let mapClickHandler = null;
+vi.mock('react-leaflet', () => ({
+ MapContainer: ({ children, center, zoom, className }) => (
+ mapClickHandler && mapClickHandler({ latlng: { lat: 37.88, lng: 23.75 } })}
+ >
+ {children}
+
+ ),
+ TileLayer: ({ url, attribution }) => (
+
+ ),
+ Marker: ({ position, draggable, children }) => (
+
+ {children}
+
+ ),
+ Tooltip: ({ children }) => {children}
,
+ Popup: ({ children }) => {children}
,
+ useMap: () => ({
+ setView: vi.fn(),
+ flyTo: vi.fn(),
+ getZoom: vi.fn().mockReturnValue(13),
+ invalidateSize: vi.fn(),
+ }),
+ useMapEvents: handlers => {
+ mapClickHandler = handlers?.click;
+ return null;
+ },
+}));
+
+vi.mock('leaflet', () => ({
+ default: {
+ Icon: {
+ Default: {
+ prototype: {},
+ mergeOptions: vi.fn(),
+ },
+ },
+ divIcon: vi.fn(() => ({})),
+ },
+ Icon: {
+ Default: {
+ prototype: {},
+ mergeOptions: vi.fn(),
+ },
+ },
+}));
+
+vi.mock('../api', () => ({
+ default: {
+ get: vi.fn(),
+ },
+}));
+
+describe('LocationPickerMap', () => {
+ let queryClient;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mapClickHandler = null;
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ });
+
+ const renderComponent = props =>
+ render(
+
+
+
+ );
+
+ it('defaults to the Satellite map layer (ESRI World Imagery)', () => {
+ renderComponent();
+ const tileLayer = screen.getByTestId('tile-layer');
+ expect(tileLayer).toHaveAttribute(
+ 'data-url',
+ expect.stringContaining('World_Imagery/MapServer')
+ );
+ });
+
+ it('renders map layers button and toggles MapLayersPanel', () => {
+ renderComponent();
+ const layersBtn = screen.getByRole('button', { name: /layers/i });
+ expect(layersBtn).toBeInTheDocument();
+
+ fireEvent.click(layersBtn);
+ expect(screen.getByText('Map Layers')).toBeInTheDocument();
+ expect(screen.getByText('Street Map')).toBeInTheDocument();
+ });
+
+ it('calls onChange when clicking on the map', () => {
+ const handleChange = vi.fn();
+ renderComponent({ onChange: handleChange });
+
+ const mapContainer = screen.getByTestId('map-container');
+ fireEvent.click(mapContainer);
+
+ expect(handleChange).toHaveBeenCalledWith(
+ expect.objectContaining({
+ lat: expect.any(Number),
+ lng: expect.any(Number),
+ })
+ );
+ });
+
+ it('queries check-proximity with 1km radius when coordinates are provided', async () => {
+ api.get.mockResolvedValueOnce({
+ data: [
+ {
+ id: 10,
+ name: 'Shark Reef & Yolanda Reef',
+ distance_m: 85,
+ country: 'Egypt',
+ },
+ ],
+ });
+
+ const handleSelectNearby = vi.fn();
+ renderComponent({ onSelectNearbySite: handleSelectNearby });
+
+ await waitFor(() => {
+ expect(api.get).toHaveBeenCalledWith('/api/v1/dive-sites/check-proximity', {
+ params: expect.objectContaining({
+ lat: 37.8812,
+ lng: 23.7548,
+ radius_m: 1000,
+ }),
+ });
+ });
+
+ // Check suggestion banner
+ expect(await screen.findByText('Shark Reef & Yolanda Reef')).toBeInTheDocument();
+ expect(screen.getByText(/85m away/i)).toBeInTheDocument();
+
+ // Click "Use This Site"
+ const useBtn = screen.getByRole('button', { name: /use this site/i });
+ fireEvent.click(useBtn);
+ expect(handleSelectNearby).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 10, name: 'Shark Reef & Yolanda Reef' })
+ );
+ });
+
+ it('queries backend search-places endpoint as primary geocoder', async () => {
+ api.get.mockImplementation(url => {
+ if (url.includes('/api/v1/dive-sites/search-places')) {
+ return Promise.resolve({
+ data: [
+ {
+ name: 'Sydney',
+ display_name: 'Sydney, NSW, Australia',
+ latitude: -33.869,
+ longitude: 151.208,
+ country: 'Australia',
+ region: 'New South Wales',
+ type: 'city',
+ },
+ ],
+ });
+ }
+ return Promise.resolve({ data: [] });
+ });
+
+ renderComponent({ latitude: 37.88, longitude: 23.75 });
+ const searchInput = screen.getByPlaceholderText(/search island, bay, town/i);
+ fireEvent.change(searchInput, { target: { value: 'Sydney' } });
+ fireEvent.click(screen.getByRole('button', { name: /find/i }));
+
+ await waitFor(() => {
+ expect(api.get).toHaveBeenCalledWith(
+ '/api/v1/dive-sites/search-places',
+ expect.objectContaining({
+ params: expect.objectContaining({ q: 'Sydney' }),
+ })
+ );
+ });
+ });
+
+ it('triggers onLocationResolved on coordinates update via reverse-geocode', async () => {
+ const handleLocationResolved = vi.fn();
+ api.get.mockImplementation(url => {
+ if (url.includes('/api/v1/dive-sites/reverse-geocode')) {
+ return Promise.resolve({
+ data: {
+ country: 'Greece',
+ region: 'Attica',
+ city: 'Glyfada',
+ },
+ });
+ }
+ return Promise.resolve({ data: [] });
+ });
+
+ renderComponent({
+ latitude: 37.88,
+ longitude: 23.75,
+ onLocationResolved: handleLocationResolved,
+ });
+
+ await waitFor(() => {
+ expect(handleLocationResolved).toHaveBeenCalledWith(
+ expect.objectContaining({
+ country: 'Greece',
+ region: 'Attica',
+ })
+ );
+ });
+ });
+});
diff --git a/frontend/src/components/QuickCreateDiveSiteModal.jsx b/frontend/src/components/QuickCreateDiveSiteModal.jsx
new file mode 100644
index 00000000..1b201c20
--- /dev/null
+++ b/frontend/src/components/QuickCreateDiveSiteModal.jsx
@@ -0,0 +1,350 @@
+import { Loader2, AlertTriangle } from 'lucide-react';
+import PropTypes from 'prop-types';
+import React, { useState, useEffect } from 'react';
+import toast from 'react-hot-toast';
+
+import api from '../api';
+import { getUniqueCountries } from '../services/diveSites';
+
+import LocationPickerMap from './LocationPickerMap';
+import Modal from './ui/Modal';
+
+const QuickCreateDiveSiteModal = ({
+ isOpen,
+ onClose,
+ initialData = {},
+ matchingCount = 1,
+ onSuccess,
+}) => {
+ const [name, setName] = useState('');
+ const [country, setCountry] = useState('');
+ const [region, setRegion] = useState('');
+ const [latitude, setLatitude] = useState('');
+ const [longitude, setLongitude] = useState('');
+ const [applyToAll, setApplyToAll] = useState(true);
+
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [conflictSite, setConflictSite] = useState(null);
+ const [errorMsg, setErrorMsg] = useState('');
+ const [countriesList, setCountriesList] = useState([]);
+
+ useEffect(() => {
+ let mounted = true;
+ getUniqueCountries()
+ .then(countries => {
+ if (mounted && Array.isArray(countries)) {
+ setCountriesList(
+ countries.map(c => (typeof c === 'string' ? c : c.name || c.country)).filter(Boolean)
+ );
+ }
+ })
+ .catch(() => {});
+ return () => {
+ mounted = false;
+ };
+ }, []);
+
+ // Sync initialData when opened or changed
+ useEffect(() => {
+ if (isOpen) {
+ setName(initialData.name || '');
+ setCountry(initialData.country || '');
+ setRegion(initialData.region || '');
+ setLatitude(initialData.latitude != null ? String(initialData.latitude) : '');
+ setLongitude(initialData.longitude != null ? String(initialData.longitude) : '');
+ setApplyToAll(true);
+ setConflictSite(null);
+ setErrorMsg('');
+ }
+ }, [isOpen, initialData]);
+
+ const handleSelectExisting = site => {
+ toast.success(`Linked to existing site: ${site.name}`);
+ if (onSuccess) {
+ onSuccess(site, applyToAll);
+ }
+ if (onClose) {
+ onClose();
+ }
+ };
+
+ const handleSubmit = async (e, forceModeration = false) => {
+ if (e) e.preventDefault();
+ setErrorMsg('');
+
+ const trimmedName = name.trim();
+ const trimmedCountry = country.trim();
+ const latNum = parseFloat(latitude);
+ const lngNum = parseFloat(longitude);
+
+ if (!trimmedName) {
+ setErrorMsg('Dive site name is required.');
+ return;
+ }
+ if (!trimmedCountry) {
+ setErrorMsg('Country is required.');
+ return;
+ }
+ if (isNaN(latNum) || latNum < -90 || latNum > 90) {
+ setErrorMsg('Please select a valid latitude between -90 and 90.');
+ return;
+ }
+ if (isNaN(lngNum) || lngNum < -180 || lngNum > 180) {
+ setErrorMsg('Please select a valid longitude between -180 and 180.');
+ return;
+ }
+
+ setIsSubmitting(true);
+ try {
+ const payload = {
+ name: trimmedName,
+ country: trimmedCountry,
+ region: region.trim() || undefined,
+ latitude: latNum,
+ longitude: lngNum,
+ moderation_needed: forceModeration,
+ };
+
+ const res = await api.post('/api/v1/dive-sites/', payload);
+ toast.success('Dive site created successfully!');
+ if (onSuccess) {
+ onSuccess(res.data, applyToAll);
+ }
+ if (onClose) {
+ onClose();
+ }
+ } catch (err) {
+ if (err.response?.status === 409 && err.response?.data?.detail?.nearby_sites?.[0]) {
+ setConflictSite(err.response.data.detail.nearby_sites[0]);
+ } else {
+ const msg =
+ err.response?.data?.detail?.message ||
+ (typeof err.response?.data?.detail === 'string'
+ ? err.response.data.detail
+ : 'Failed to create dive site.');
+ setErrorMsg(msg);
+ }
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ if (!isOpen) return null;
+
+ return (
+
+
+
+ );
+};
+
+QuickCreateDiveSiteModal.propTypes = {
+ isOpen: PropTypes.bool.isRequired,
+ onClose: PropTypes.func.isRequired,
+ initialData: PropTypes.shape({
+ name: PropTypes.string,
+ country: PropTypes.string,
+ region: PropTypes.string,
+ latitude: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
+ longitude: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
+ }),
+ matchingCount: PropTypes.number,
+ onSuccess: PropTypes.func,
+};
+
+export default QuickCreateDiveSiteModal;
diff --git a/frontend/src/components/QuickCreateDiveSiteModal.test.jsx b/frontend/src/components/QuickCreateDiveSiteModal.test.jsx
new file mode 100644
index 00000000..5148d4f0
--- /dev/null
+++ b/frontend/src/components/QuickCreateDiveSiteModal.test.jsx
@@ -0,0 +1,130 @@
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import React from 'react';
+import { QueryClient, QueryClientProvider } from 'react-query';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+import api from '../api';
+
+import QuickCreateDiveSiteModal from './QuickCreateDiveSiteModal';
+
+vi.mock('./LocationPickerMap', () => ({
+ default: ({ latitude, longitude, onChange, onSelectNearbySite }) => (
+
+
+
+
+ ),
+}));
+
+vi.mock('../api', () => ({
+ default: {
+ post: vi.fn(),
+ get: vi.fn(),
+ },
+}));
+
+describe('QuickCreateDiveSiteModal', () => {
+ let queryClient;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ });
+
+ const renderModal = (props = {}) =>
+ render(
+
+
+
+ );
+
+ it('pre-fills site name, coordinates, and country from initialData', () => {
+ renderModal();
+ expect(screen.getByDisplayValue('Shark Reef')).toBeInTheDocument();
+ expect(screen.getByDisplayValue('27.7281')).toBeInTheDocument();
+ expect(screen.getByDisplayValue('34.2519')).toBeInTheDocument();
+ expect(screen.getByDisplayValue('Egypt')).toBeInTheDocument();
+ });
+
+ it('displays batch apply checkbox with the correct matching count', () => {
+ renderModal({ matchingCount: 4 });
+ const checkbox = screen.getByRole('checkbox');
+ expect(checkbox).toBeChecked();
+ expect(
+ screen.getByText(
+ (content, element) =>
+ element?.tagName?.toLowerCase() === 'span' &&
+ element.textContent.includes('Apply this site to all 4 dives')
+ )
+ ).toBeInTheDocument();
+ });
+
+ it('submits new dive site to API and calls onSuccess', async () => {
+ const handleSuccess = vi.fn();
+ api.post.mockResolvedValueOnce({
+ data: {
+ id: 105,
+ name: 'Shark Reef',
+ country: 'Egypt',
+ latitude: 27.7281,
+ longitude: 34.2519,
+ },
+ });
+
+ renderModal({ onSuccess: handleSuccess });
+
+ const submitBtn = screen.getByRole('button', { name: /create & link site/i });
+ fireEvent.click(submitBtn);
+
+ await waitFor(() => {
+ expect(api.post).toHaveBeenCalledWith(
+ '/api/v1/dive-sites/',
+ expect.objectContaining({
+ name: 'Shark Reef',
+ country: 'Egypt',
+ latitude: 27.7281,
+ longitude: 34.2519,
+ })
+ );
+ });
+
+ expect(handleSuccess).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 105, name: 'Shark Reef' }),
+ true // applyToAll is true
+ );
+ });
+
+ it('invokes onSuccess directly when a nearby site is selected from map', () => {
+ const handleSuccess = vi.fn();
+ renderModal({ onSuccess: handleSuccess });
+
+ const pickNearbyBtn = screen.getByText('Pick Nearby Site');
+ fireEvent.click(pickNearbyBtn);
+
+ expect(handleSuccess).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 99, name: 'Shark Reef & Yolanda Reef' }),
+ true
+ );
+ });
+});
diff --git a/frontend/src/components/__tests__/ImportDivesModal.test.jsx b/frontend/src/components/__tests__/ImportDivesModal.test.jsx
deleted file mode 100644
index 21437fbe..00000000
--- a/frontend/src/components/__tests__/ImportDivesModal.test.jsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import { render, screen, fireEvent, waitFor } from '@testing-library/react';
-import React from 'react';
-import { QueryClient, QueryClientProvider } from 'react-query';
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-
-import * as divesService from '../../services/dives';
-import ImportDivesModal from '../ImportDivesModal';
-
-vi.mock('../../services/dives', () => ({
- importSubsurfaceXML: vi.fn(),
- confirmImportDives: vi.fn(),
- getCSVHeaders: vi.fn(),
- processCSVImport: vi.fn(),
- importGarminFIT: vi.fn(),
- importSuuntoJSON: vi.fn(),
- importShearwaterDB: vi.fn(),
-}));
-
-describe('ImportDivesModal - Diving Center Selection', () => {
- let queryClient;
-
- beforeEach(() => {
- vi.clearAllMocks();
- queryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
- });
-
- const renderComponent = () =>
- render(
-
-
-
- );
-
- it('populates available diving centers on XML import and retains center selection', async () => {
- divesService.importSubsurfaceXML.mockResolvedValueOnce({
- message: 'Successfully parsed 1 dives',
- dives: [
- {
- dive_date: '2026-06-28',
- dive_time: '12:18:14',
- duration: 73,
- max_depth: 41.6,
- dive_site_id: 22,
- diving_center_id: null,
- is_private: false,
- },
- ],
- available_dive_sites: [{ id: 22, name: 'Arsida wall' }],
- available_diving_centers: [
- { id: 61, name: 'Amorgos Diving Center', country: 'Greece' },
- { id: 62, name: 'Athens Divers Club', country: 'Greece' },
- ],
- });
-
- renderComponent();
-
- // Select a file
- const file = new globalThis.File([''], 'arsida.xml', { type: 'text/xml' });
- const fileInput = document.querySelector('input[type="file"]');
- expect(fileInput).toBeInTheDocument();
-
- fireEvent.change(fileInput, { target: { files: [file] } });
-
- // Process file
- const processBtn = screen.getByRole('button', { name: /Process Files/i });
- expect(processBtn).not.toBeDisabled();
- fireEvent.click(processBtn);
-
- // Review step should appear
- await waitFor(() => {
- expect(screen.getByText('Review Dives to Import')).toBeInTheDocument();
- });
-
- // The diving center combobox trigger should be present
- const centerTrigger = screen.getByRole('combobox', {
- name: /Search for a diving center\.\.\./i,
- });
- expect(centerTrigger).toBeInTheDocument();
-
- // Open the dropdown
- fireEvent.click(centerTrigger);
-
- // Amorgos Diving Center option should be visible
- const option = await screen.findByText('Amorgos Diving Center (Greece)');
- expect(option).toBeInTheDocument();
-
- // Select Amorgos Diving Center
- fireEvent.click(option);
-
- // The selected center should remain visible in the combobox trigger button and NOT disappear
- await waitFor(() => {
- expect(centerTrigger).toHaveTextContent('Amorgos Diving Center (Greece)');
- });
- });
-});
diff --git a/frontend/src/components/forms/FormField.jsx b/frontend/src/components/forms/FormField.jsx
index a5ccbf05..fa7cadd5 100644
--- a/frontend/src/components/forms/FormField.jsx
+++ b/frontend/src/components/forms/FormField.jsx
@@ -42,3 +42,5 @@ FormField.propTypes = {
className: PropTypes.string,
required: PropTypes.bool,
};
+
+export default FormField;
diff --git a/frontend/src/pages/CreateDiveSite.jsx b/frontend/src/pages/CreateDiveSite.jsx
index 9622e5d6..f5f5504c 100644
--- a/frontend/src/pages/CreateDiveSite.jsx
+++ b/frontend/src/pages/CreateDiveSite.jsx
@@ -8,8 +8,9 @@ import { useNavigate, useSearchParams } from 'react-router-dom';
import { z } from 'zod';
import api from '../api';
-import { FormField } from '../components/forms/FormField';
+import FormField from '../components/forms/FormField';
import TagSelection from '../components/forms/TagSelection';
+import LocationPickerMap from '../components/LocationPickerMap';
import SEO from '../components/SEO';
import Button from '../components/ui/Button';
import MarkdownEditor from '../components/ui/MarkdownEditor';
@@ -70,10 +71,12 @@ const CreateDiveSite = () => {
const formData = watch();
- // Pre-fill latitude and longitude from query parameters (e.g. from Garmin FIT import)
+ // Pre-fill name, latitude and longitude from query parameters (e.g. from dive log import)
useEffect(() => {
+ const nameParam = searchParams.get('name');
const lat = searchParams.get('lat');
const lng = searchParams.get('lng');
+ if (nameParam) setValue('name', nameParam, { shouldValidate: true });
if (lat) setValue('latitude', lat, { shouldValidate: true });
if (lng) setValue('longitude', lng, { shouldValidate: true });
}, [searchParams, setValue]);
@@ -99,25 +102,6 @@ const CreateDiveSite = () => {
const [nearbySites, setNearbySites] = useState([]);
const [pendingSubmitData, setPendingSubmitData] = useState(null);
- // Background proximity check
- const { data: backgroundNearbySites } = useQuery(
- ['check-proximity', formData.latitude, formData.longitude],
- async () => {
- if (!formData.latitude || !formData.longitude) return [];
- const lat = parseFloat(formData.latitude);
- const lng = parseFloat(formData.longitude);
- if (isNaN(lat) || isNaN(lng)) return [];
- const res = await api.get('/api/v1/dive-sites/check-proximity', {
- params: { lat, lng, radius_m: 50 },
- });
- return res.data;
- },
- {
- enabled: !!formData.latitude && !!formData.longitude,
- staleTime: 30000,
- }
- );
-
// Automatic Location and Shore Detection
useEffect(() => {
if (!formData.latitude || !formData.longitude) return;
@@ -650,44 +634,32 @@ const CreateDiveSite = () => {
)}
-
- {/* Background Proximity Hint */}
- {backgroundNearbySites && backgroundNearbySites.length > 0 && !showDuplicateModal && (
-
-
-
-
-
- Did you know? There
- are already dive sites right here:
-
- {backgroundNearbySites.map(site => (
- -
- {site.name} ({site.distance_m}m away)
-
- ))}
-
-
- Consider adding a new Dive Route to an existing site instead.
-
-
-
-
+
+
+ {
+ setValue('latitude', lat.toFixed(6));
+ setValue('longitude', lng.toFixed(6));
+ trigger(['latitude', 'longitude']);
+ }}
+ onLocationResolved={({ country: resCountry, region: resRegion }) => {
+ if (resCountry) setValue('country', resCountry, { shouldValidate: true });
+ if (resRegion) setValue('region', resRegion, { shouldValidate: true });
+ }}
+ onSelectNearbySite={site => navigate(`/dive-sites/${site.id}`)}
+ />
- )}
+
{/* Location Suggestion Button */}
diff --git a/frontend/src/pages/CreateDiveSiteMapPicker.test.jsx b/frontend/src/pages/CreateDiveSiteMapPicker.test.jsx
new file mode 100644
index 00000000..3b0f0ba6
--- /dev/null
+++ b/frontend/src/pages/CreateDiveSiteMapPicker.test.jsx
@@ -0,0 +1,98 @@
+import { render, screen, fireEvent } from '@testing-library/react';
+import React from 'react';
+import { HelmetProvider } from 'react-helmet-async';
+import { QueryClient, QueryClientProvider } from 'react-query';
+import { BrowserRouter } from 'react-router-dom';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+import CreateDiveSite from './CreateDiveSite';
+
+vi.mock('../components/SEO', () => ({
+ default: () => null,
+}));
+
+vi.mock('../components/ui/MarkdownEditor', () => ({
+ default: ({ value, onChange, placeholder }) => (
+
+
+
+
+ {
+ setValue('latitude', lat.toFixed(6));
+ setValue('longitude', lng.toFixed(6));
+ trigger(['latitude', 'longitude']);
+ }}
+ onLocationResolved={({ country: resCountry, region: resRegion }) => {
+ if (resCountry) setValue('country', resCountry, { shouldValidate: true });
+ if (resRegion) setValue('region', resRegion, { shouldValidate: true });
+ }}
+ onSelectNearbySite={site => window.open(`/dive-sites/${site.id}`, '_blank')}
+ />
+
{/* Country and Region Information */}