mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-06-20 13:51:45 +00:00
20791a29a7
* Migrate TREK 3 to NestJS + React 19 with a shared Zod contract layer
Brownfield strangler migration of the backend onto NestJS modules
(auth, trips, days, places, assignments, packing, todo, budget,
reservations, collab, files, photos, journey, share, settings, backup,
oidc, oauth, admin, atlas, vacay, weather, airports, maps, categories,
tags, notifications, system-notices) served through a per-prefix
dispatcher, keeping the existing SQLite/better-sqlite3 DB and JWT
httpOnly cookie auth, with behavioural parity for every route.
Client: React 19 upgrade, "page = wiring container + data hook"
pattern across all pages, per-domain Zustand stores bound to
@trek/shared contracts, and decomposition of the large components
(DayPlanSidebar, PackingListPanel, CollabNotes, FileManager,
MemoriesPanel, PlacesSidebar, CollabChat, SystemNoticeModal,
BudgetPanel, PlaceFormModal, ...) into focused render units backed by
in-file hooks.
Apply the shared global request pipeline (helmet/CSP, CORS, HSTS,
forced HTTPS, the global MFA policy and request logging) to the NestJS
instance as well, so a migrated route is protected identically to the
legacy fallback rather than bypassing it.
* Finish the NestJS migration — drop the legacy Express app
NestJS now serves the whole surface: every /api domain plus the platform
routes (uploads, /mcp, the OAuth/MCP SDK + /.well-known metadata and the
production SPA fallback). Removed server/src/app.ts, all of
server/src/routes/* and the strangler dispatcher; index.ts and the
integration suite share a single buildApp() bootstrap so prod and tests
can't drift.
- Platform/transport routes extracted to nest/platform/platform.routes.ts
and mounted before app.init() — Nest's router answers an unmatched
request with a 404, so a route registered after init is never reached.
The SPA fallback is a NotFoundException filter and the catch-all uses a
RegExp (Express 5's path-to-regexp rejects a bare '*').
- New modules: memories (/api/integrations/memories — the Journey
gallery's Immich/Synology proxy), addons (GET /api/addons) and the
cross-trip GET /api/reservations/upcoming.
- TrekExceptionFilter reproduces the old multer / err.statusCode handling
so upload rejections keep their 400/413 { error } body and non-ASCII
filenames survive (defParamCharset).
- addTripToJourney and the MCP get_journey_share_link tool gained the
trip-access check they were missing.
- Re-pointed the 34 integration tests + the websocket test onto the Nest
app; removed the now-meaningless Express-vs-Nest parity tests and a few
orphaned client components.
* Restore the reset-password rate limit and fix copyTrip reservation links
Two correctness/security gaps the NestJS migration introduced:
- POST /api/auth/reset-password lost its per-IP rate limiter. Restore it
(5 attempts / 15 min on a dedicated bucket, same as the old resetLimiter)
so reset tokens can't be brute-forced unthrottled. Covered by AUTH-019.
- copyTripById did not copy reservations.end_day_id (a day reference — now
remapped through dayMap like day_id) or needs_review, so a duplicated trip
lost multi-day transport end-day links and reset the review flag.
* Clean up dead code, dedupe helpers, fix the reset-password contract
- Remove server exports orphaned by the Express removal: the immich
album-link helpers, seven route-only service exports, getFileByIdFull;
de-export internal-only helpers (utcSuffix).
- De-duplicate verifyTripAccess (9 identical copies -> services/tripAccess.ts)
and avatarUrl (3 -> services/avatarUrl.ts); name the bcrypt cost
(BCRYPT_COST) and the email regex (EMAIL_REGEX). Public API unchanged.
- resetPasswordRequestSchema declared `password`, but the client sends and
the service reads `new_password` — rename it so the contract matches and
the client types resolve.
- Make ATLAS-013 deterministic: stub the admin-1 GeoJSON download instead of
fetching ~4600 features from GitHub during the test (it hung the suite).
* Make the client typecheck runnable (vitest/vite ambient types)
The client had no `typecheck` script and tsc couldn't even start (the
baseUrl deprecation errored out, same as server/shared already silence).
Add `ignoreDeprecations: "6.0"` to match the other workspaces, a `typecheck`
npm script, and a src/vite-env.d.ts referencing vite/client + vitest/globals
so tsc knows the test globals (describe/it/expect/vi). This turns ~3600
phantom "Cannot find name" errors into a real, measurable count (~590 actual
type errors remain, to be worked down). Type-only; no runtime change.
* Derive client domain types from the shared schema contracts
Add entity/response Zod schemas to @trek/shared (place, trip, assignment, day, budget, packing, reservation), each matched against the producing server service, and re-export them from client types.ts instead of the hand-written duplicates that had drifted (name/title, amount/total_price, owner_id/user_id, cover_url/cover_image, ...). Updates the call sites and test fixtures the corrected types surfaced; type-only, no runtime behaviour change.
* chore(db): log swallowed errors in addon-disable migration + guard against destructive migrations
The migration that disables the legacy "memories" addon swallowed any
error in an empty catch, as did ~30 other catch blocks in the migration
runner (column adds, the journey rebuild, index probes). Replace each
silent catch with the existing console.warn('[migrations] ...') log so
failures are visible. Control flow is unchanged: every step stays
non-fatal, nothing new is thrown.
Add a static guardrail test that scans the migration source and fails
when a new destructive statement (DROP TABLE / DROP COLUMN / TRUNCATE /
DELETE FROM / ALTER ... DROP) appears outside a reviewed allowlist, and
when an empty/silent catch block is reintroduced. The existing
destructive statements are all legitimate table rebuilds or
bounded cleanups and are recorded in the allowlist with a reason.
* Re-check SSRF on every redirect hop when resolving short links
Replace the one-shot checkSsrf + fetch(redirect:'follow') in the maps and place short-link resolvers with safeFetchFollow, which follows redirects manually and re-runs checkSsrf against the DNS-pinned IP of each hop (max 5). A redirect to an internal/loopback address is now blocked even when the initial URL is public, while legitimate cross-host redirects (goo.gl -> maps.google.com) still resolve.
* Reject WebSocket tokens minted before a password change
Stamp the user's password_version onto the ephemeral ws token and verify it on connect, closing the socket (4001) when it no longer matches, so a token issued before a password reset can't be replayed. Tokens minted without a version are treated as version 0, matching the JWT pv-claim semantics.
* fix(i18n): guard locale key parity and finish the OAuth consent page strings
Every non-en locale now exposes the exact same flat key set as en. Keys that
had drifted out of sync are backfilled with the English source value (tagged
en-fallback) so t() resolves a real string instead of relying on the silent
runtime fallback; no existing translation was touched and no key was removed.
Add a parity test that imports each aggregated locale bundle and asserts its
key set matches en, with a diagnostic listing of any missing/extra keys. This
complements the file-level check in shared/scripts by guarding the merged
export the app actually serves.
Finish internationalising OAuthAuthorizePage: the ~15 remaining hardcoded
English chrome strings now go through oauth.authorize.* keys (English source
in en, en-fallback placeholders elsewhere). Markup and behaviour are unchanged.
* Add semantic theme color tokens to Tailwind
Map the CSS theme variables from src/index.css (:root light / .dark dark) to named Tailwind utilities — bg-surface, text-content, border-edge, bg-accent and their variants. This gives components a Tailwind-native target for the theme colors so we can replace inline `style={{ ... 'var(--...)' }}` with utility classes without changing the rendered values.
* Surface silent store failures to the user and validate API responses in dev
Reservation toggle, todo/packing toggle and budget reorder were swallowing API errors after rolling back, so the user saw the change silently snap back with no explanation. Route those failures through the existing toast channel (new store/notify.ts bridges to window.__addToast, the same channel SystemNoticeBanner uses); the reservation toggle re-throws so ReservationsPanel's own translated toast finally fires. Also wire the existing parseInDev/checkInDev response validation into the maps and notification-test endpoints to catch contract drift in dev.
* Migrate static theme inline styles to Tailwind utilities and extract page sub-components
Replace the static, color-only inline `style={{ ... 'var(--bg-primary)' ... }}` props with the new semantic Tailwind utilities (bg-surface, text-content, border-edge, ...) wherever the result is byte-identical; dynamic/conditional theme styles and hardcoded status colors are left inline. Extract the Atlas country-search autocomplete, the Admin update banner, and two Journey dialogs into their own presentational components to shrink the oversized page files, keeping behaviour and markup identical.
* Remove the unrouted photos page and its dead photo components
PhotosPage was never wired into the router and its usePhotos hook read a tripStore photos slice that was never implemented; the Photos gallery, lightbox and upload components were only reachable through it. Per-trip photos now live in the Journey gallery (Immich/Synology). Removed the dead page, hook and components — the live Journey PhotoLightbox is a separate component and stays.
* Resolve the remaining client type errors and the trip.title navbar bug
Drive the client typecheck to zero without any/ts-ignore: convert the tripId route param to a number once at the page boundary so it matches the numeric props and store actions it feeds, fix trip.name -> trip.title (the wire field is title, so the old read rendered blank in the files/offline views), and tighten the scattered handler-arity, DOM-cast and untyped-payload sites. No runtime behaviour change.
* Convert the remaining dynamic and hardcoded inline styles to Tailwind utilities
Second styling pass over the components and pages: move conditional theme colors into className ternaries (bg-accent / bg-surface-hover etc.), turn reused CSSProperties constants into className constants, and express static hardcoded hex/rgba colors as Tailwind arbitrary values so the exact rendered colour is preserved. Truly dynamic styling (computed geometry, gradients, multi-part shadows, data-driven colours, the undefined --sidebar/--nav layout vars) stays inline as it cannot be expressed as a static class. Updated three component tests that asserted the old inline active-state styles to assert the equivalent utility class instead.
Verified: client typecheck 0, full client suite green, and a live light/dark render check in the dev server confirms the semantic theme tokens resolve correctly (the earlier 'transparent popups' were a stale dev server that pre-dated the tailwind.config token addition, not a code issue).
* Add eslint flat-config for client and server and gate typecheck, lint and pages in CI
client and server had lint scripts but no eslint config (only shared was linted in CI). Add flat configs mirroring shared's stack (js + typescript-eslint recommended + eslint-config-prettier) plus the client's react-hooks/react-refresh plugins. Pre-existing patterns in this never-linted code (explicit any, require() in the CommonJS server, empty catches, exhaustive-deps) are set to 'warn' rather than 'error' so the gate passes at 0 errors without a repo-wide reformat — these can be ratcheted to errors over time. Wire blocking typecheck + lint + lint:pages steps into the client and server CI jobs (now that both typechecks are clean) and promote the server typecheck from informational to blocking.
* Decompose the remaining God Components into hooks, helpers and sub-components
FE6: split the oversized page and panel components into thin layout shells plus colocated use<Component> hooks, .constants.ts, .helpers.ts (with tests) and presentational sub-components, following the established 'logic in a hook, render in slices' pattern. Behaviour, markup, classes and effect order are unchanged. Largest reductions: PackingListPanel 1598->42, FileManager 1055->36, AdminPage 1525->167, BudgetPanel 1266->146, JourneyDetailPage 2822->547, PlacesSidebar 945->66, CollabChat 861->106, CollabNotes 1417->532. DayPlanSidebar's drag-and-drop render body was left intact (ref-identity sensitive) and only its toolbar/modals/constants were extracted.
* Fix duplicate React keys in the file-assign place list
When a place is assigned to the same day more than once it appeared twice in a day's list, so the place-button key={p.id} collided and React warned about duplicate keys. Key by place id + render index so siblings stay unique. Pre-existing in the old FileManager; behaviour unchanged.
* Format the shared package and drop an unused import to satisfy the lint gate
The i18n and schema changes added code that wasn't prettier-formatted, and place.schema.ts imported categorySchema without using it. Run prettier over shared and remove the import so 'npm run lint' + 'format:check' pass.
* Install all workspaces in the server CI job so SWC's native binary is present
The server vitest config transforms via unplugin-swc, which needs @swc/core's platform-specific native binary. A workspace-scoped 'npm ci --workspace server' skips that optional dependency, so vitest failed to load the config on the Linux runner. Use a full 'npm ci'.
* Re-resolve dependencies with npm install in the server CI job for SWC
Full 'npm ci' still skipped @swc/core's Linux native binary because the committed lockfile was generated on Windows and lacks the Linux optional-dep install metadata. 'npm install' re-resolves and fetches the platform-matching binary, which the server's unplugin-swc transform needs to load vitest.config.ts.
* Install @swc/core's Linux binary explicitly in the server CI job
Neither npm ci nor npm install fetched @swc/core-linux-x64-gnu on the Linux runner because the lockfile was generated on Windows and lacks the Linux optional-dep metadata. Add a step that installs the matching @swc/core-linux-x64-gnu version (no-save, no-lockfile) so unplugin-swc can load the server's vitest config.
* Use legacy-peer-deps when installing the SWC Linux binary in CI
The explicit @swc/core-linux-x64-gnu install re-resolved the tree and hit the pre-existing lucide-react/react-19 peer conflict that the lockfile was generated around. Add --legacy-peer-deps so the step matches the project's resolution and installs the binary.
* Keep the lockfile when installing the SWC binary so other deps stay pinned
Dropping --no-package-lock made npm re-resolve the whole tree and upgrade eslint, whose newer recommended config flagged no-useless-assignment as an error in the server lint step. Keep the lockfile so only @swc/core-linux-x64-gnu is added and every other dependency (incl. eslint) stays at its locked version.
791 lines
27 KiB
TypeScript
791 lines
27 KiB
TypeScript
import { useState, useEffect, useRef, useMemo, useCallback } from 'react'
|
|
import Modal from '../shared/Modal'
|
|
import CustomSelect from '../shared/CustomSelect'
|
|
import { mapsApi } from '../../api/client'
|
|
import { useAuthStore } from '../../store/authStore'
|
|
import { useCanDo } from '../../store/permissionsStore'
|
|
import { useTripStore } from '../../store/tripStore'
|
|
import { useToast } from '../shared/Toast'
|
|
import { Search, Paperclip, X, AlertTriangle, Loader2 } from 'lucide-react'
|
|
import { useTranslation } from '../../i18n'
|
|
import CustomTimePicker from '../shared/CustomTimePicker'
|
|
import { DEFAULT_FORM, isGoogleMapsUrl, type PlaceFormData } from './PlaceFormModal.helpers'
|
|
import type { Place, Category, Assignment } from '../../types'
|
|
|
|
// The submit payload mirrors the form, but lat/lng are parsed to numbers and
|
|
// category_id is normalised, plus any files chosen before the place existed.
|
|
export interface PlaceSubmitData extends Omit<PlaceFormData, 'lat' | 'lng' | 'category_id'> {
|
|
lat: number | null
|
|
lng: number | null
|
|
category_id: string | null
|
|
_pendingFiles?: File[]
|
|
}
|
|
|
|
interface PlaceFormModalProps {
|
|
isOpen: boolean
|
|
onClose: () => void
|
|
onSave: (data: PlaceSubmitData, files?: File[]) => Promise<void> | void
|
|
place: Place | null
|
|
prefillCoords?: { lat: number; lng: number; name?: string; address?: string } | null
|
|
tripId: number
|
|
categories: Category[]
|
|
onCategoryCreated: (category: { name: string; color?: string; icon?: string }) => Promise<Category> | undefined
|
|
assignmentId: number | null
|
|
dayAssignments?: Assignment[]
|
|
}
|
|
|
|
|
|
/** Place create/edit form state: maps search + Google-URL resolve + autocomplete,
|
|
* category creation, file attachments and submit. Keeps PlaceFormModal a thin
|
|
* render over the form fields. */
|
|
function usePlaceFormModal(props: PlaceFormModalProps) {
|
|
const {
|
|
isOpen, onClose, onSave, place, prefillCoords, tripId, categories,
|
|
onCategoryCreated, assignmentId, dayAssignments = [],
|
|
} = props
|
|
const [form, setForm] = useState(DEFAULT_FORM)
|
|
const [mapsSearch, setMapsSearch] = useState('')
|
|
const [mapsResults, setMapsResults] = useState([])
|
|
const [isSearchingMaps, setIsSearchingMaps] = useState(false)
|
|
const [newCategoryName, setNewCategoryName] = useState('')
|
|
const [showNewCategory, setShowNewCategory] = useState(false)
|
|
const [isSaving, setIsSaving] = useState(false)
|
|
const [pendingFiles, setPendingFiles] = useState([])
|
|
const fileRef = useRef(null)
|
|
const [acSuggestions, setAcSuggestions] = useState<{ placeId: string; mainText: string; secondaryText: string }[]>([])
|
|
const [acHighlight, setAcHighlight] = useState(-1)
|
|
const acDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
|
const acAbortRef = useRef<AbortController | null>(null)
|
|
const toast = useToast()
|
|
const { t, language } = useTranslation()
|
|
const { hasMapsKey } = useAuthStore()
|
|
const can = useCanDo()
|
|
const tripObj = useTripStore((s) => s.trip)
|
|
const canUploadFiles = can('file_upload', tripObj)
|
|
|
|
useEffect(() => {
|
|
if (place) {
|
|
setForm({
|
|
name: place.name || '',
|
|
description: place.description || '',
|
|
address: place.address || '',
|
|
lat: place.lat != null ? String(place.lat) : '',
|
|
lng: place.lng != null ? String(place.lng) : '',
|
|
category_id: place.category_id != null ? String(place.category_id) : '',
|
|
place_time: place.place_time || '',
|
|
end_time: place.end_time || '',
|
|
notes: place.notes || '',
|
|
transport_mode: place.transport_mode || 'walking',
|
|
website: place.website || '',
|
|
})
|
|
} else if (prefillCoords) {
|
|
setForm({
|
|
...DEFAULT_FORM,
|
|
lat: String(prefillCoords.lat),
|
|
lng: String(prefillCoords.lng),
|
|
name: prefillCoords.name || '',
|
|
address: prefillCoords.address || '',
|
|
})
|
|
} else {
|
|
setForm(DEFAULT_FORM)
|
|
}
|
|
setPendingFiles([])
|
|
}, [place, prefillCoords, isOpen])
|
|
|
|
// Derive location bias bounding box from the trip's existing places
|
|
const places = useTripStore((s) => s.places)
|
|
const locationBias = useMemo(() => {
|
|
const withCoords = (places || []).filter((p) => p.lat != null && p.lng != null)
|
|
if (withCoords.length === 0) return undefined
|
|
|
|
let minLat = Infinity, maxLat = -Infinity, minLng = Infinity, maxLng = -Infinity
|
|
for (const p of withCoords) {
|
|
const lat = Number(p.lat), lng = Number(p.lng)
|
|
if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue
|
|
if (lat < minLat) minLat = lat
|
|
if (lat > maxLat) maxLat = lat
|
|
if (lng < minLng) minLng = lng
|
|
if (lng > maxLng) maxLng = lng
|
|
}
|
|
if (!Number.isFinite(minLat)) return undefined
|
|
|
|
// Skip bias if the bounding box is too large (~500 km diagonal)
|
|
const dlat = maxLat - minLat
|
|
const dlng = maxLng - minLng
|
|
const avgLatRad = ((minLat + maxLat) / 2) * (Math.PI / 180)
|
|
const diagKm = Math.sqrt((dlat * 111) ** 2 + (dlng * 111 * Math.cos(avgLatRad)) ** 2)
|
|
if (diagKm > 500) return undefined
|
|
|
|
return { low: { lat: minLat, lng: minLng }, high: { lat: maxLat, lng: maxLng } }
|
|
}, [places])
|
|
|
|
// Autocomplete fetch — aborts any in-flight request before starting a new one
|
|
const fetchSuggestions = useCallback(async (query: string) => {
|
|
if (query.length < 2 || isGoogleMapsUrl(query)) {
|
|
setAcSuggestions([])
|
|
setAcHighlight(-1)
|
|
return
|
|
}
|
|
acAbortRef.current?.abort()
|
|
const controller = new AbortController()
|
|
acAbortRef.current = controller
|
|
try {
|
|
const result = await mapsApi.autocomplete(query, language, locationBias, controller.signal)
|
|
setAcSuggestions(result.suggestions || [])
|
|
setAcHighlight(-1)
|
|
} catch (err: unknown) {
|
|
if (err instanceof Error && err.name === 'AbortError') return
|
|
if (err instanceof Error && err.name === 'CanceledError') return // axios abort
|
|
console.error('Autocomplete failed:', err)
|
|
setAcSuggestions([])
|
|
}
|
|
}, [language, locationBias])
|
|
|
|
// Debounce effect — only watches mapsSearch
|
|
useEffect(() => {
|
|
if (acDebounceRef.current) clearTimeout(acDebounceRef.current)
|
|
|
|
const trimmed = mapsSearch.trim()
|
|
if (trimmed.length < 2 || isGoogleMapsUrl(trimmed)) {
|
|
setAcSuggestions([])
|
|
setAcHighlight(-1)
|
|
return
|
|
}
|
|
|
|
acDebounceRef.current = setTimeout(() => fetchSuggestions(trimmed), 300)
|
|
|
|
return () => {
|
|
if (acDebounceRef.current) clearTimeout(acDebounceRef.current)
|
|
}
|
|
}, [mapsSearch, fetchSuggestions])
|
|
|
|
const handleChange = (field: string, value: string) => {
|
|
setForm(prev => ({ ...prev, [field]: value }))
|
|
}
|
|
|
|
const handleMapsSearch = async () => {
|
|
if (!mapsSearch.trim()) return
|
|
setIsSearchingMaps(true)
|
|
try {
|
|
// Detect Google Maps URLs and resolve them directly
|
|
const trimmed = mapsSearch.trim()
|
|
if (isGoogleMapsUrl(trimmed)) {
|
|
const resolved = await mapsApi.resolveUrl(trimmed)
|
|
if (resolved.lat && resolved.lng) {
|
|
setForm(prev => ({
|
|
...prev,
|
|
name: resolved.name || prev.name,
|
|
address: resolved.address || prev.address,
|
|
lat: String(resolved.lat),
|
|
lng: String(resolved.lng),
|
|
}))
|
|
setMapsResults([])
|
|
setMapsSearch('')
|
|
toast.success(t('places.urlResolved'))
|
|
return
|
|
}
|
|
}
|
|
const result = await mapsApi.search(mapsSearch, language)
|
|
setMapsResults(result.places || [])
|
|
} catch (err: unknown) {
|
|
toast.error(t('places.mapsSearchError'))
|
|
} finally {
|
|
setIsSearchingMaps(false)
|
|
}
|
|
}
|
|
|
|
const handleSelectMapsResult = (result) => {
|
|
setForm(prev => ({
|
|
...prev,
|
|
name: result.name || prev.name,
|
|
address: result.address || prev.address,
|
|
lat: result.lat || prev.lat,
|
|
lng: result.lng || prev.lng,
|
|
google_place_id: result.google_place_id || prev.google_place_id,
|
|
osm_id: result.osm_id || prev.osm_id,
|
|
website: result.website || prev.website,
|
|
phone: result.phone || prev.phone,
|
|
}))
|
|
setMapsResults([])
|
|
setMapsSearch('')
|
|
}
|
|
|
|
const handleSelectSuggestion = async (suggestion: { placeId: string; mainText: string; secondaryText: string }) => {
|
|
setAcSuggestions([])
|
|
setAcHighlight(-1)
|
|
const previousSearch = mapsSearch
|
|
setMapsSearch('')
|
|
setForm(prev => ({ ...prev, name: suggestion.mainText }))
|
|
setIsSearchingMaps(true)
|
|
try {
|
|
const result = await mapsApi.details(suggestion.placeId, language)
|
|
if (result.place) {
|
|
handleSelectMapsResult(result.place)
|
|
} else {
|
|
setMapsSearch(previousSearch)
|
|
toast.error(t('places.mapsSearchError'))
|
|
}
|
|
} catch (err) {
|
|
console.error('Failed to fetch place details:', err)
|
|
setMapsSearch(previousSearch)
|
|
toast.error(t('places.mapsSearchError'))
|
|
} finally {
|
|
setIsSearchingMaps(false)
|
|
}
|
|
}
|
|
|
|
const handleSearchKeyDown = (e: React.KeyboardEvent) => {
|
|
if (acSuggestions.length > 0) {
|
|
if (e.key === 'ArrowDown') {
|
|
e.preventDefault()
|
|
setAcHighlight(prev => (prev + 1) % acSuggestions.length)
|
|
} else if (e.key === 'ArrowUp') {
|
|
e.preventDefault()
|
|
setAcHighlight(prev => (prev <= 0 ? acSuggestions.length - 1 : prev - 1))
|
|
} else if (e.key === 'Enter') {
|
|
e.preventDefault()
|
|
if (acHighlight >= 0) {
|
|
handleSelectSuggestion(acSuggestions[acHighlight])
|
|
} else {
|
|
setAcSuggestions([])
|
|
handleMapsSearch()
|
|
}
|
|
} else if (e.key === 'Escape') {
|
|
setAcSuggestions([])
|
|
setAcHighlight(-1)
|
|
}
|
|
} else if (e.key === 'Enter') {
|
|
e.preventDefault()
|
|
handleMapsSearch()
|
|
}
|
|
}
|
|
|
|
const handleCreateCategory = async () => {
|
|
if (!newCategoryName.trim()) return
|
|
try {
|
|
const cat = await onCategoryCreated?.({ name: newCategoryName, color: '#6366f1', icon: 'MapPin' })
|
|
if (cat) setForm(prev => ({ ...prev, category_id: String(cat.id) }))
|
|
setNewCategoryName('')
|
|
setShowNewCategory(false)
|
|
} catch (err: unknown) {
|
|
toast.error(t('places.categoryCreateError'))
|
|
}
|
|
}
|
|
|
|
const handleFileAdd = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
const files = Array.from(e.target.files || [])
|
|
setPendingFiles(prev => [...prev, ...files])
|
|
e.target.value = ''
|
|
}
|
|
|
|
const handleRemoveFile = (idx: number) => {
|
|
setPendingFiles(prev => prev.filter((_, i) => i !== idx))
|
|
}
|
|
|
|
// Paste support for files/images
|
|
const handlePaste = (e: React.ClipboardEvent) => {
|
|
if (!canUploadFiles) return
|
|
const items = e.clipboardData?.items
|
|
if (!items) return
|
|
for (const item of Array.from(items)) {
|
|
if (item.type.startsWith('image/') || item.type === 'application/pdf') {
|
|
e.preventDefault()
|
|
const file = item.getAsFile()
|
|
if (file) setPendingFiles(prev => [...prev, file])
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
const hasTimeError = place && form.place_time && form.end_time && form.place_time.length >= 5 && form.end_time.length >= 5 && form.end_time <= form.place_time
|
|
|
|
const handleSubmit = async (e) => {
|
|
e.preventDefault()
|
|
if (!form.name.trim()) {
|
|
toast.error(t('places.nameRequired'))
|
|
return
|
|
}
|
|
setIsSaving(true)
|
|
try {
|
|
await onSave({
|
|
...form,
|
|
lat: form.lat ? parseFloat(form.lat) : null,
|
|
lng: form.lng ? parseFloat(form.lng) : null,
|
|
category_id: form.category_id || null,
|
|
_pendingFiles: pendingFiles.length > 0 ? pendingFiles : undefined,
|
|
})
|
|
onClose()
|
|
} catch (err: unknown) {
|
|
toast.error(err instanceof Error ? err.message : t('places.saveError'))
|
|
} finally {
|
|
setIsSaving(false)
|
|
}
|
|
}
|
|
|
|
return {
|
|
isOpen,
|
|
onClose,
|
|
onSave,
|
|
place,
|
|
prefillCoords,
|
|
tripId,
|
|
categories,
|
|
onCategoryCreated,
|
|
assignmentId,
|
|
dayAssignments,
|
|
form,
|
|
setForm,
|
|
mapsSearch,
|
|
setMapsSearch,
|
|
mapsResults,
|
|
setMapsResults,
|
|
isSearchingMaps,
|
|
setIsSearchingMaps,
|
|
newCategoryName,
|
|
setNewCategoryName,
|
|
showNewCategory,
|
|
setShowNewCategory,
|
|
isSaving,
|
|
setIsSaving,
|
|
pendingFiles,
|
|
setPendingFiles,
|
|
fileRef,
|
|
acSuggestions,
|
|
setAcSuggestions,
|
|
acHighlight,
|
|
setAcHighlight,
|
|
acDebounceRef,
|
|
acAbortRef,
|
|
toast,
|
|
t,
|
|
language,
|
|
hasMapsKey,
|
|
can,
|
|
tripObj,
|
|
canUploadFiles,
|
|
places,
|
|
locationBias,
|
|
fetchSuggestions,
|
|
handleChange,
|
|
handleMapsSearch,
|
|
handleSelectMapsResult,
|
|
handleSelectSuggestion,
|
|
handleSearchKeyDown,
|
|
handleCreateCategory,
|
|
handleFileAdd,
|
|
handleRemoveFile,
|
|
handlePaste,
|
|
hasTimeError,
|
|
handleSubmit,
|
|
}
|
|
}
|
|
|
|
export default function PlaceFormModal(props: PlaceFormModalProps) {
|
|
const S = usePlaceFormModal(props)
|
|
const {
|
|
isOpen,
|
|
onClose,
|
|
onSave,
|
|
place,
|
|
prefillCoords,
|
|
tripId,
|
|
categories,
|
|
onCategoryCreated,
|
|
assignmentId,
|
|
dayAssignments,
|
|
form,
|
|
setForm,
|
|
mapsSearch,
|
|
setMapsSearch,
|
|
mapsResults,
|
|
setMapsResults,
|
|
isSearchingMaps,
|
|
setIsSearchingMaps,
|
|
newCategoryName,
|
|
setNewCategoryName,
|
|
showNewCategory,
|
|
setShowNewCategory,
|
|
isSaving,
|
|
setIsSaving,
|
|
pendingFiles,
|
|
setPendingFiles,
|
|
fileRef,
|
|
acSuggestions,
|
|
setAcSuggestions,
|
|
acHighlight,
|
|
setAcHighlight,
|
|
acDebounceRef,
|
|
acAbortRef,
|
|
toast,
|
|
t,
|
|
language,
|
|
hasMapsKey,
|
|
can,
|
|
tripObj,
|
|
canUploadFiles,
|
|
places,
|
|
locationBias,
|
|
fetchSuggestions,
|
|
handleChange,
|
|
handleMapsSearch,
|
|
handleSelectMapsResult,
|
|
handleSelectSuggestion,
|
|
handleSearchKeyDown,
|
|
handleCreateCategory,
|
|
handleFileAdd,
|
|
handleRemoveFile,
|
|
handlePaste,
|
|
hasTimeError,
|
|
handleSubmit,
|
|
} = S
|
|
return (
|
|
<Modal
|
|
isOpen={isOpen}
|
|
onClose={onClose}
|
|
title={place ? t('places.editPlace') : t('places.addPlace')}
|
|
size="lg"
|
|
footer={
|
|
<div className="flex justify-end gap-3">
|
|
<button
|
|
type="button"
|
|
onClick={onClose}
|
|
className="px-4 py-2 text-sm text-gray-600 hover:text-gray-900 border border-gray-200 rounded-lg hover:bg-gray-50"
|
|
>
|
|
{t('common.cancel')}
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleSubmit}
|
|
disabled={isSaving || hasTimeError}
|
|
className="px-6 py-2 bg-slate-900 text-white text-sm rounded-lg hover:bg-slate-700 disabled:opacity-60 font-medium"
|
|
>
|
|
{isSaving ? t('common.saving') : place ? t('common.update') : t('common.add')}
|
|
</button>
|
|
</div>
|
|
}
|
|
>
|
|
<form onSubmit={handleSubmit} className="space-y-4" onPaste={handlePaste}>
|
|
{/* Place Search */}
|
|
<div className="bg-slate-50 rounded-xl p-3 border border-slate-200">
|
|
{!hasMapsKey && (
|
|
<p className="mb-2 text-xs text-content-faint">
|
|
{t('places.osmActive')}
|
|
</p>
|
|
)}
|
|
<div className="relative">
|
|
<div className="flex gap-2">
|
|
<input
|
|
type="text"
|
|
value={mapsSearch}
|
|
onChange={e => setMapsSearch(e.target.value)}
|
|
onKeyDown={handleSearchKeyDown}
|
|
onBlur={() => setTimeout(() => setAcSuggestions([]), 150)}
|
|
onFocus={() => {
|
|
if (mapsSearch.trim().length >= 2 && acSuggestions.length === 0 && mapsResults.length === 0) {
|
|
fetchSuggestions(mapsSearch.trim())
|
|
}
|
|
}}
|
|
placeholder={t('places.mapsSearchPlaceholder')}
|
|
className="flex-1 border border-slate-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-slate-400 bg-white"
|
|
/>
|
|
<button
|
|
type="button"
|
|
onClick={() => { setAcSuggestions([]); handleMapsSearch() }}
|
|
disabled={isSearchingMaps}
|
|
className="bg-slate-900 text-white px-3 py-1.5 rounded-lg text-sm hover:bg-slate-700 disabled:opacity-60"
|
|
>
|
|
{isSearchingMaps ? '...' : <Search className="w-4 h-4" />}
|
|
</button>
|
|
</div>
|
|
|
|
{/* Autocomplete dropdown */}
|
|
{acSuggestions.length > 0 && (
|
|
<div className="absolute left-0 right-0 z-20 mt-1 bg-white rounded-lg border border-slate-200 shadow-lg overflow-hidden">
|
|
{acSuggestions.map((s, idx) => (
|
|
<button
|
|
key={s.placeId}
|
|
type="button"
|
|
onMouseDown={() => handleSelectSuggestion(s)}
|
|
onMouseEnter={() => setAcHighlight(idx)}
|
|
className={`w-full text-left px-3 py-2 border-b border-slate-100 last:border-0 ${
|
|
idx === acHighlight ? 'bg-slate-100' : 'hover:bg-slate-50'
|
|
}`}
|
|
>
|
|
<div className="font-medium text-sm">{s.mainText}</div>
|
|
{s.secondaryText && (
|
|
<div className="text-xs text-slate-500 truncate">{s.secondaryText}</div>
|
|
)}
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Search results (populated after full search) */}
|
|
{mapsResults.length > 0 && (
|
|
<div className="bg-white rounded-lg border border-slate-200 overflow-hidden max-h-40 overflow-y-auto mt-2">
|
|
{mapsResults.map((result, idx) => (
|
|
<button
|
|
key={idx}
|
|
type="button"
|
|
onClick={() => handleSelectMapsResult(result)}
|
|
className="w-full text-left px-3 py-2 hover:bg-slate-50 border-b border-slate-100 last:border-0"
|
|
>
|
|
<div className="font-medium text-sm">{result.name}</div>
|
|
<div className="text-xs text-slate-500 truncate">{result.address}</div>
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Name */}
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">{t('places.formName')} *</label>
|
|
<div className="relative">
|
|
<input
|
|
type="text"
|
|
value={form.name}
|
|
onChange={e => handleChange('name', e.target.value)}
|
|
required
|
|
placeholder={t('places.formNamePlaceholder')}
|
|
className="form-input"
|
|
/>
|
|
{isSearchingMaps && (
|
|
<div className="absolute right-2.5 top-0 bottom-0 flex items-center" role="status" aria-label={t('places.loadingDetails')}>
|
|
<Loader2 className="w-4 h-4 animate-spin text-slate-400" aria-hidden="true" />
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Description */}
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">{t('places.formDescription')}</label>
|
|
<textarea
|
|
value={form.description}
|
|
onChange={e => handleChange('description', e.target.value)}
|
|
rows={2}
|
|
placeholder={t('places.formDescriptionPlaceholder')}
|
|
className="form-input" style={{ resize: 'vertical' }}
|
|
/>
|
|
</div>
|
|
|
|
{/* Notes */}
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">{t('places.formNotes')}</label>
|
|
<textarea
|
|
value={form.notes}
|
|
onChange={e => handleChange('notes', e.target.value)}
|
|
rows={3}
|
|
maxLength={2000}
|
|
placeholder={t('places.formNotesPlaceholder')}
|
|
className="form-input" style={{ resize: 'vertical' }}
|
|
/>
|
|
</div>
|
|
|
|
{/* Address + Coordinates */}
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">{t('places.formAddress')}</label>
|
|
<input
|
|
type="text"
|
|
value={form.address}
|
|
onChange={e => handleChange('address', e.target.value)}
|
|
placeholder={t('places.formAddressPlaceholder')}
|
|
className="form-input"
|
|
/>
|
|
<div className="grid grid-cols-2 gap-2 mt-2">
|
|
<input
|
|
type="number"
|
|
step="any"
|
|
value={form.lat}
|
|
onChange={e => handleChange('lat', e.target.value)}
|
|
onPaste={e => {
|
|
const text = e.clipboardData.getData('text').trim()
|
|
const match = text.match(/^(-?\d+\.?\d*)\s*[,;\s]\s*(-?\d+\.?\d*)$/)
|
|
if (match) {
|
|
e.preventDefault()
|
|
handleChange('lat', match[1])
|
|
handleChange('lng', match[2])
|
|
}
|
|
}}
|
|
placeholder={t('places.formLat')}
|
|
className="form-input"
|
|
/>
|
|
<input
|
|
type="number"
|
|
step="any"
|
|
value={form.lng}
|
|
onChange={e => handleChange('lng', e.target.value)}
|
|
placeholder={t('places.formLng')}
|
|
className="form-input"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Category */}
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">{t('places.formCategory')}</label>
|
|
{!showNewCategory ? (
|
|
<div className="flex gap-2">
|
|
<CustomSelect
|
|
value={form.category_id}
|
|
onChange={value => handleChange('category_id', String(value))}
|
|
placeholder={t('places.noCategory')}
|
|
options={[
|
|
{ value: '', label: t('places.noCategory') },
|
|
...(categories || []).map(c => ({
|
|
value: c.id,
|
|
label: c.name,
|
|
})),
|
|
]}
|
|
style={{ flex: 1 }}
|
|
size="sm"
|
|
/>
|
|
</div>
|
|
) : (
|
|
<div className="flex gap-2">
|
|
<input
|
|
type="text"
|
|
value={newCategoryName}
|
|
onChange={e => setNewCategoryName(e.target.value)}
|
|
placeholder={t('places.categoryNamePlaceholder')}
|
|
className="form-input" style={{ flex: 1 }}
|
|
/>
|
|
<button type="button" onClick={handleCreateCategory} className="bg-slate-900 text-white px-3 rounded-lg hover:bg-slate-700 text-sm">
|
|
OK
|
|
</button>
|
|
<button type="button" onClick={() => setShowNewCategory(false)} className="text-gray-500 px-2 text-sm">
|
|
{t('common.cancel')}
|
|
</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Time — only shown when editing, not when creating */}
|
|
{place && (
|
|
<TimeSection
|
|
form={form}
|
|
handleChange={handleChange}
|
|
assignmentId={assignmentId}
|
|
dayAssignments={dayAssignments}
|
|
hasTimeError={hasTimeError}
|
|
t={t}
|
|
/>
|
|
)}
|
|
|
|
{/* Website */}
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">{t('places.formWebsite')}</label>
|
|
<input
|
|
type="url"
|
|
value={form.website}
|
|
onChange={e => handleChange('website', e.target.value)}
|
|
placeholder="https://..."
|
|
className="form-input"
|
|
/>
|
|
</div>
|
|
|
|
{/* File Attachments */}
|
|
{canUploadFiles && (
|
|
<div className="border border-gray-200 rounded-xl p-3 space-y-2">
|
|
<div className="flex items-center justify-between">
|
|
<label className="block text-sm font-medium text-gray-700">{t('files.title')}</label>
|
|
<button type="button" onClick={() => fileRef.current?.click()}
|
|
className="flex items-center gap-1 text-xs text-slate-500 hover:text-slate-700 transition-colors">
|
|
<Paperclip size={12} /> {t('files.attach')}
|
|
</button>
|
|
</div>
|
|
<input ref={fileRef} type="file" multiple style={{ display: 'none' }} onChange={handleFileAdd} />
|
|
{pendingFiles.length > 0 && (
|
|
<div className="space-y-1">
|
|
{pendingFiles.map((file, idx) => (
|
|
<div key={idx} className="flex items-center gap-2 px-2 py-1.5 rounded-lg bg-slate-50 text-xs">
|
|
<Paperclip size={10} className="text-slate-400 shrink-0" />
|
|
<span className="truncate flex-1 text-slate-600">{file.name}</span>
|
|
<button type="button" onClick={() => handleRemoveFile(idx)} className="text-slate-400 hover:text-red-500 shrink-0">
|
|
<X size={12} />
|
|
</button>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
{pendingFiles.length === 0 && (
|
|
<p className="text-xs text-slate-400">{t('files.pasteHint')}</p>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
</form>
|
|
</Modal>
|
|
)
|
|
}
|
|
|
|
interface TimeSectionProps {
|
|
form: PlaceFormData
|
|
handleChange: (field: string, value: string) => void
|
|
assignmentId: number | null
|
|
dayAssignments: Assignment[]
|
|
hasTimeError: boolean
|
|
t: (key: string, params?: Record<string, string | number>) => string
|
|
}
|
|
|
|
function TimeSection({ form, handleChange, assignmentId, dayAssignments, hasTimeError, t }: TimeSectionProps) {
|
|
|
|
const collisions = useMemo(() => {
|
|
if (!assignmentId || !form.place_time || form.place_time.length < 5) return []
|
|
// Find the day_id for the current assignment
|
|
const current = dayAssignments.find(a => a.id === assignmentId)
|
|
if (!current) return []
|
|
const myStart = form.place_time
|
|
const myEnd = form.end_time && form.end_time.length >= 5 ? form.end_time : null
|
|
return dayAssignments.filter(a => {
|
|
if (a.id === assignmentId) return false
|
|
if (a.day_id !== current.day_id) return false
|
|
const aStart = a.place?.place_time
|
|
const aEnd = a.place?.end_time
|
|
if (!aStart) return false
|
|
// Check overlap: two intervals overlap if start < otherEnd AND otherStart < end
|
|
const s1 = myStart, e1 = myEnd || myStart
|
|
const s2 = aStart, e2 = aEnd || aStart
|
|
return s1 < (e2 || '23:59') && s2 < (e1 || '23:59') && s1 !== e2 && s2 !== e1
|
|
})
|
|
}, [assignmentId, dayAssignments, form.place_time, form.end_time])
|
|
|
|
return (
|
|
<div>
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">{t('places.startTime')}</label>
|
|
<CustomTimePicker
|
|
value={form.place_time}
|
|
onChange={v => handleChange('place_time', v)}
|
|
/>
|
|
</div>
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">{t('places.endTime')}</label>
|
|
<CustomTimePicker
|
|
value={form.end_time}
|
|
onChange={v => handleChange('end_time', v)}
|
|
/>
|
|
</div>
|
|
</div>
|
|
{hasTimeError && (
|
|
<div className="flex items-center gap-1.5 mt-2 px-2.5 py-1.5 rounded-lg text-xs" style={{ background: 'var(--bg-warning, #fef3c7)', color: 'var(--text-warning, #92400e)' }}>
|
|
<AlertTriangle size={13} className="shrink-0" />
|
|
{t('places.endTimeBeforeStart')}
|
|
</div>
|
|
)}
|
|
{collisions.length > 0 && (
|
|
<div className="flex items-start gap-1.5 mt-2 px-2.5 py-1.5 rounded-lg text-xs" style={{ background: 'var(--bg-warning, #fef3c7)', color: 'var(--text-warning, #92400e)' }}>
|
|
<AlertTriangle size={13} className="shrink-0 mt-0.5" />
|
|
<span>
|
|
{t('places.timeCollision')}{' '}
|
|
{collisions.map(a => a.place?.name).filter(Boolean).join(', ')}
|
|
</span>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|