Compare commits

..

25 Commits

Author SHA1 Message Date
Maurice 51894c09f3 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.
2026-05-31 20:53:23 +02:00
Maurice 033f757c66 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.
2026-05-31 20:45:59 +02:00
Maurice 06fcfa29ac 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.
2026-05-31 20:37:26 +02:00
Maurice 4523ef6814 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.
2026-05-31 20:30:00 +02:00
Maurice 0ccc5d5d26 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'.
2026-05-31 20:22:54 +02:00
Maurice fb36ae5678 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.
2026-05-31 20:22:54 +02:00
Maurice 64bd0de7e8 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.
2026-05-31 20:10:24 +02:00
Maurice 47671d52e0 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.
2026-05-31 20:07:17 +02:00
Maurice 8ec62c7518 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.
2026-05-31 19:34:54 +02:00
Maurice cf21c718fa 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).
2026-05-31 19:19:35 +02:00
Maurice 404981505c 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.
2026-05-31 18:29:23 +02:00
Maurice 80627f33fd 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.
2026-05-31 18:29:22 +02:00
Maurice 9614a5cf84 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.
2026-05-31 17:15:54 +02:00
Maurice 43173e2b33 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.
2026-05-31 17:15:53 +02:00
Maurice 177be53e64 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.
2026-05-31 16:46:45 +02:00
Maurice e63a7799fb 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.
2026-05-31 16:08:08 +02:00
Maurice eed9e8ce7c 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.
2026-05-31 15:52:19 +02:00
Maurice 460694e335 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.
2026-05-31 15:52:13 +02:00
Maurice 5a0124e7cb 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.
2026-05-31 15:50:02 +02:00
Maurice 3977a5ecba 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.
2026-05-31 15:42:39 +02:00
Maurice 239a68bb48 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.
2026-05-31 14:24:30 +02:00
Maurice 4cb4454d9f 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).
2026-05-31 14:13:04 +02:00
Maurice 4c9631998f 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.
2026-05-31 13:38:02 +02:00
Maurice bfe52579df 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.
2026-05-31 13:29:22 +02:00
Maurice fc7d8b5d12 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.
2026-05-30 02:39:26 +02:00
22 changed files with 119 additions and 327 deletions
@@ -15,8 +15,7 @@ export function DatePicker({ value, onChange, tripDates }: {
})
const daysInMonth = new Date(viewMonth.year, viewMonth.month + 1, 0).getDate()
// Monday-first, matching CustomDateTimePicker / VacayCalendar (getDay() is Sunday=0).
const firstDow = (new Date(viewMonth.year, viewMonth.month, 1).getDay() + 6) % 7
const firstDow = new Date(viewMonth.year, viewMonth.month, 1).getDay()
const monthName = new Date(viewMonth.year, viewMonth.month).toLocaleDateString(undefined, { month: 'long', year: 'numeric' })
const prevMonth = () => {
@@ -69,7 +68,7 @@ export function DatePicker({ value, onChange, tripDates }: {
{/* Weekday headers */}
<div className="grid grid-cols-7 mb-1">
{['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map((d, i) => (
{['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((d, i) => (
<div key={i} className="text-center text-[10px] font-medium text-zinc-400 py-1">{d}</div>
))}
</div>
@@ -10,7 +10,6 @@ import JourneyShareSection from './JourneyShareSection'
import type { JourneyDetail } from '../../store/journeyStore'
import { pickGradient } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
import { AddTripDialog } from './JourneyDetailPageAddTripDialog'
import { normalizeImageFile } from '../../utils/convertHeic'
export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite, onRefresh }: {
journey: JourneyDetail
@@ -50,7 +49,7 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
const file = e.target.files?.[0]
if (!file) return
const formData = new FormData()
formData.append('cover', await normalizeImageFile(file))
formData.append('cover', file)
try {
await journeyApi.uploadCover(journey.id, formData)
toast.success(t('journey.settings.coverUpdated'))
+2 -2
View File
@@ -447,7 +447,7 @@ export function MapViewGL({
geometry: { type: 'LineString' as const, coordinates: seg.map(([lat, lng]) => [lng, lat]) },
}))
src.setData({ type: 'FeatureCollection', features })
}, [route, mapReady])
}, [route])
// Travel times now live in the day sidebar (per-segment connectors), not on the map.
@@ -470,7 +470,7 @@ export function MapViewGL({
} catch { return [] }
})
src.setData({ type: 'FeatureCollection', features })
}, [places, mapReady])
}, [places])
// Reservation overlay — mirrors the Leaflet ReservationOverlay: great-
// circle arcs for flights/cruises, straight lines for trains/cars,
+68 -100
View File
@@ -31,7 +31,7 @@ export default function FileImportModal({ isOpen, onClose, tripId, pushUndo, ini
const loadTrip = useTripStore((s) => s.loadTrip)
const fileInputRef = useRef<HTMLInputElement>(null)
const [files, setFiles] = useState<File[]>([])
const [file, setFile] = useState<File | null>(null)
const [isDragOver, setIsDragOver] = useState(false)
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
@@ -51,7 +51,7 @@ export default function FileImportModal({ isOpen, onClose, tripId, pushUndo, ini
}
const reset = () => {
setFiles([])
setFile(null)
setIsDragOver(false)
setLoading(false)
setError('')
@@ -67,14 +67,14 @@ export default function FileImportModal({ isOpen, onClose, tripId, pushUndo, ini
if (initialFile) {
const err = validateFile(initialFile)
if (err) {
setFiles([])
setFile(null)
setError(err)
} else {
setFiles([initialFile])
setFile(initialFile)
setError('')
}
} else {
setFiles([])
setFile(null)
setError('')
}
// validateFile uses t() which is stable — intentionally omitted from deps
@@ -86,32 +86,22 @@ export default function FileImportModal({ isOpen, onClose, tripId, pushUndo, ini
onClose()
}
const selectFiles = (incoming: File[]) => {
if (incoming.length === 0) return
const valid: File[] = []
let firstError: string | null = null
for (const f of incoming) {
const validationError = validateFile(f)
if (validationError) {
firstError = firstError ?? validationError
continue
}
valid.push(f)
}
if (valid.length === 0) {
setError(firstError ?? '')
setFiles([])
const selectFile = (f: File) => {
const validationError = validateFile(f)
if (validationError) {
setError(validationError)
setFile(null)
return
}
setFiles(valid)
setError(firstError ?? '')
setFile(f)
setError('')
setSummary(null)
}
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const list = e.target.files ? Array.from(e.target.files) : []
const f = e.target.files?.[0]
e.target.value = ''
if (list.length) selectFiles(list)
if (f) selectFile(f)
}
const handleDragOver = (e: React.DragEvent) => {
@@ -126,92 +116,71 @@ export default function FileImportModal({ isOpen, onClose, tripId, pushUndo, ini
const handleDrop = (e: React.DragEvent) => {
e.preventDefault()
setIsDragOver(false)
const list = Array.from(e.dataTransfer.files)
if (list.length) selectFiles(list)
const f = e.dataTransfer.files[0]
if (f) selectFile(f)
}
const handleImport = async () => {
if (files.length === 0 || loading) return
if (!file || loading) return
const ext = file.name.toLowerCase().split('.').pop()
setLoading(true)
setError('')
setSummary(null)
let totalCreated = 0
let totalSkipped = 0
const createdIds: number[] = []
const errors: string[] = []
let mergedSummary: PlacesImportSummary | null = null
let importedGpx = false
let importedKml = false
for (const f of files) {
const ext = f.name.toLowerCase().split('.').pop()
try {
if (ext === 'gpx') {
importedGpx = true
const result = await placesApi.importGpx(tripId, f, gpxOpts)
totalCreated += result.count ?? 0
totalSkipped += result.skipped ?? 0
if (result.places?.length > 0) createdIds.push(...result.places.map((p: { id: number }) => p.id))
} else {
importedKml = true
const result = await placesApi.importMapFile(tripId, f, kmlOpts)
totalCreated += result.count ?? 0
if (result.places?.length > 0) createdIds.push(...result.places.map((p: { id: number }) => p.id))
const s = result.summary as PlacesImportSummary | undefined
if (s) {
mergedSummary = mergedSummary
? {
totalPlacemarks: mergedSummary.totalPlacemarks + s.totalPlacemarks,
createdCount: mergedSummary.createdCount + s.createdCount,
skippedCount: mergedSummary.skippedCount + s.skippedCount,
warnings: [...mergedSummary.warnings, ...(s.warnings ?? [])],
errors: [...mergedSummary.errors, ...(s.errors ?? [])],
}
: s
totalSkipped += s.skippedCount ?? 0
}
}
} catch (err: any) {
const message = err?.response?.data?.error || t('places.importFileError')
errors.push(files.length > 1 ? `${f.name}: ${message}` : message)
}
}
await loadTrip(tripId)
if (createdIds.length > 0) {
pushUndo?.(importedGpx && !importedKml ? t('undo.importGpx') : t('undo.importKeyholeMarkup'), async () => {
try { await placesApi.bulkDelete(tripId, createdIds) } catch {}
try {
if (ext === 'gpx') {
const result = await placesApi.importGpx(tripId, file, gpxOpts)
await loadTrip(tripId)
})
if (result.count === 0 && result.skipped > 0) {
toast.warning(t('places.importAllSkipped'))
} else {
toast.success(t('places.gpxImported', { count: result.count }))
}
if (result.places?.length > 0) {
const importedIds: number[] = result.places.map((p: { id: number }) => p.id)
pushUndo?.(t('undo.importGpx'), async () => {
try { await placesApi.bulkDelete(tripId, importedIds) } catch {}
await loadTrip(tripId)
})
}
handleClose()
} else {
const result = await placesApi.importMapFile(tripId, file, kmlOpts)
await loadTrip(tripId)
setSummary(result.summary || null)
if (result.count === 0 && (result.summary?.skippedCount ?? 0) > 0) {
toast.warning(t('places.importAllSkipped'))
} else {
toast.success(t('places.kmlKmzImported', { count: result.count }))
}
if (result.summary?.errors?.length > 0) {
setError(result.summary.errors.join('\n'))
}
if (result.places?.length > 0) {
const importedIds: number[] = result.places.map((p: { id: number }) => p.id)
pushUndo?.(t('undo.importKeyholeMarkup'), async () => {
try { await placesApi.bulkDelete(tripId, importedIds) } catch {}
await loadTrip(tripId)
})
}
}
} catch (err: any) {
const responseSummary = err?.response?.data?.summary as PlacesImportSummary | undefined
if (responseSummary) setSummary(responseSummary)
const message = err?.response?.data?.error || t('places.importFileError')
setError(message)
toast.error(message)
} finally {
setLoading(false)
}
if (totalCreated > 0) {
const key = importedKml && !importedGpx ? 'places.kmlKmzImported' : 'places.gpxImported'
toast.success(t(key, { count: totalCreated }))
} else if (totalSkipped > 0 && errors.length === 0) {
toast.warning(t('places.importAllSkipped'))
}
if (mergedSummary) setSummary(mergedSummary)
if (errors.length > 0) {
setError(errors.join('\n'))
toast.error(errors[0])
}
setLoading(false)
// Close once everything succeeded and there's no KML summary left to surface.
if (errors.length === 0 && !mergedSummary) handleClose()
}
const exts = files.map(f => f.name.toLowerCase().split('.').pop() ?? '')
const isGpx = exts.includes('gpx')
const isKml = exts.some(e => e === 'kml' || e === 'kmz')
const fileExt = file?.name.toLowerCase().split('.').pop() ?? ''
const isGpx = fileExt === 'gpx'
const isKml = fileExt === 'kml' || fileExt === 'kmz'
const gpxNoneSelected = isGpx && !gpxOpts.waypoints && !gpxOpts.routes && !gpxOpts.tracks
const kmlNoneSelected = isKml && !kmlOpts.points && !kmlOpts.paths
const canImport = files.length > 0 && !loading && !gpxNoneSelected && !kmlNoneSelected
const canImport = !!file && !loading && !gpxNoneSelected && !kmlNoneSelected
if (!isOpen) return null
@@ -237,7 +206,6 @@ export default function FileImportModal({ isOpen, onClose, tripId, pushUndo, ini
ref={fileInputRef}
type="file"
accept=".gpx,.kml,.kmz"
multiple
style={{ display: 'none' }}
onChange={handleInputChange}
/>
@@ -272,8 +240,8 @@ export default function FileImportModal({ isOpen, onClose, tripId, pushUndo, ini
<Upload size={18} strokeWidth={1.8} color={isDragOver ? 'var(--accent)' : 'var(--text-faint)'} style={{ pointerEvents: 'none' }} />
{isDragOver ? (
<span className="text-accent" style={{ pointerEvents: 'none' }}>{t('places.importFileDropActive')}</span>
) : files.length > 0 ? (
<span style={{ color: 'var(--text-primary)', textAlign: 'center', wordBreak: 'break-all', pointerEvents: 'none' }}>{files.map(f => f.name).join(', ')}</span>
) : file ? (
<span style={{ color: 'var(--text-primary)', textAlign: 'center', wordBreak: 'break-all', pointerEvents: 'none' }}>{file.name}</span>
) : (
<span style={{ color: 'var(--text-faint)', textAlign: 'center', pointerEvents: 'none' }}>{t('places.importFileDropHere')}</span>
)}
@@ -225,16 +225,13 @@ describe('PlaceFormModal', () => {
expect(screen.getByDisplayValue('48.8584')).toBeInTheDocument();
});
it('FE-PLANNER-PLACEFORM-021: maps search error surfaces the server-provided reason', async () => {
it('FE-PLANNER-PLACEFORM-021: maps search error shows toast', async () => {
const addToast = vi.fn();
window.__addToast = addToast;
const user = userEvent.setup();
// The backend forwards the real upstream error (e.g. a Google Places API message);
// the modal must show it instead of a generic "search failed" so the cause is visible.
server.use(
http.post('/api/maps/search', () =>
HttpResponse.json({ error: 'Places API (New) has not been used in project 123 or it is disabled' }, { status: 403 })),
http.post('/api/maps/search', () => HttpResponse.json({ error: 'fail' }, { status: 500 })),
);
render(<PlaceFormModal {...defaultProps} />);
@@ -244,7 +241,7 @@ describe('PlaceFormModal', () => {
await waitFor(() => {
expect(addToast).toHaveBeenCalledWith(
expect.stringMatching(/Places API \(New\) has not been used/i),
expect.stringMatching(/search failed/i),
'error',
undefined,
);
@@ -10,7 +10,6 @@ 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 { getApiErrorMessage } from '../../utils/apiError'
import type { Place, Category, Assignment } from '../../types'
// The submit payload mirrors the form, but lat/lng are parsed to numbers and
@@ -189,7 +188,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
const result = await mapsApi.search(mapsSearch, language)
setMapsResults(result.places || [])
} catch (err: unknown) {
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
toast.error(t('places.mapsSearchError'))
} finally {
setIsSearchingMaps(false)
}
@@ -229,7 +228,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
} catch (err) {
console.error('Failed to fetch place details:', err)
setMapsSearch(previousSearch)
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
toast.error(t('places.mapsSearchError'))
} finally {
setIsSearchingMaps(false)
}
+2 -2
View File
@@ -222,7 +222,7 @@ export default function TodoListPanel({ tripId, items, addItemSignal = 0 }: { tr
)}
{isAddingNew && !selectedItem && !isMobile && ReactDOM.createPortal(
<div onClick={e => { if (e.target === e.currentTarget) setIsAddingNew(false) }}
className="trek-modal-backdrop"
className="modal-backdrop"
style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(15,23,42,0.5)', display: 'flex', justifyContent: 'center', alignItems: 'flex-start', paddingTop: 'calc(var(--nav-h) + 60px)', paddingBottom: 40 }}>
<div style={{ width: 'min(520px, 92vw)', maxHeight: 'calc(100vh - var(--nav-h) - 120px)', overflow: 'auto', borderRadius: 16, boxShadow: '0 20px 60px rgba(0,0,0,0.25)' }}
ref={el => { if (el) { const child = el.firstElementChild as HTMLElement; if (child) { child.style.width = '100%'; child.style.borderLeft = 'none'; child.style.borderRadius = '16px' } } }}>
@@ -240,7 +240,7 @@ export default function TodoListPanel({ tripId, items, addItemSignal = 0 }: { tr
)}
{isAddingNew && !selectedItem && isMobile && ReactDOM.createPortal(
<div onClick={e => { if (e.target === e.currentTarget) setIsAddingNew(false) }}
className="trek-modal-backdrop"
className="modal-backdrop"
style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(0,0,0,0.4)', display: 'flex', justifyContent: 'center', alignItems: 'flex-end', paddingBottom: 'var(--bottom-nav-h)' }}>
<div style={{ width: '100%', maxHeight: '85vh', borderRadius: '16px 16px 0 0', overflow: 'auto' }}
ref={el => { if (el) { const child = el.firstElementChild as HTMLElement; if (child) { child.style.width = '100%'; child.style.borderLeft = 'none'; child.style.borderRadius = '16px 16px 0 0' } } }}>
@@ -260,9 +260,7 @@ describe('TripFormModal', () => {
items: [{ type: 'image/png', getAsFile: () => file }],
},
});
// Cover selection now normalizes the file (HEIC -> JPEG) before previewing, so the
// createObjectURL call lands a microtask later; a non-HEIC file passes through unchanged.
await waitFor(() => expect(mockCreateObjectURL).toHaveBeenCalledWith(file));
expect(mockCreateObjectURL).toHaveBeenCalledWith(file);
Object.defineProperty(URL, 'createObjectURL', { writable: true, configurable: true, value: original });
});
@@ -8,7 +8,6 @@ import { useCanDo } from '../../store/permissionsStore'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import { CustomDatePicker } from '../shared/CustomDateTimePicker'
import { normalizeImageFile } from '../../utils/convertHeic'
import type { Trip } from '../../types'
import type { TripCreateRequest } from '@trek/shared'
@@ -142,17 +141,15 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp
}
}
const handleCoverSelect = async (file) => {
const handleCoverSelect = (file) => {
if (!file) return
// HEIC/HEIF from iOS can't be rendered or stored as-is — convert to JPEG first
const normalized = await normalizeImageFile(file)
if (isEditing && trip?.id) {
// Existing trip: upload immediately
uploadCoverNow(normalized)
uploadCoverNow(file)
} else {
// New trip: stage for upload after creation
setPendingCoverFile(normalized)
setCoverPreview(URL.createObjectURL(normalized))
setPendingCoverFile(file)
setCoverPreview(URL.createObjectURL(file))
}
}
+1 -1
View File
@@ -56,7 +56,7 @@ describe('Modal', () => {
it('FE-COMP-MODAL-008: clicking the backdrop calls onClose', () => {
render(<Modal isOpen={true} onClose={onClose}><p>inner</p></Modal>);
const backdrop = document.querySelector('.trek-modal-backdrop') as HTMLElement;
const backdrop = document.querySelector('.modal-backdrop') as HTMLElement;
// Simulate mousedown then click on the backdrop itself
fireEvent.mouseDown(backdrop, { target: backdrop });
fireEvent.click(backdrop);
+1 -1
View File
@@ -51,7 +51,7 @@ export default function Modal({
return ReactDOM.createPortal(
<div
className="fixed inset-0 z-[200] flex items-start sm:items-center justify-center px-4 trek-modal-backdrop trek-backdrop-enter bg-[rgba(15,23,42,0.5)]"
className="fixed inset-0 z-[200] flex items-start sm:items-center justify-center px-4 modal-backdrop trek-backdrop-enter bg-[rgba(15,23,42,0.5)]"
style={{ paddingTop: 70, paddingBottom: 'calc(20px + var(--bottom-nav-h))', overflow: 'hidden' }}
onMouseDown={e => { mouseDownTarget.current = e.target }}
onClick={e => {
+3 -3
View File
@@ -734,7 +734,7 @@ img[alt="TREK"] {
.dark .min-h-screen { background-color: var(--bg-primary) !important; }
/* Modal-Hintergrund */
.dark .trek-modal-backdrop { background: rgba(0,0,0,0.6); }
.dark .modal-backdrop { background: rgba(0,0,0,0.6); }
/* ── Dark: Fallback für Komponenten die noch nicht auf CSS-Variablen umgestellt sind ── */
.dark {
@@ -766,8 +766,8 @@ img[alt="TREK"] {
animation: slide-out-right 0.3s ease-in forwards;
}
/* Modal-Hintergrund (eigener Namespace, sonst blenden Content-Blocker .modal-backdrop aus) */
.trek-modal-backdrop {
/* Modal-Hintergrund */
.modal-backdrop {
backdrop-filter: blur(4px);
}
+2 -5
View File
@@ -141,10 +141,7 @@ export function useAtlas() {
for (const f of geo.features) {
const a2 = f.properties?.ISO_A2
const a3 = f.properties?.ADM0_A3 || f.properties?.ISO_A3
// Only real 2-letter ISO codes: natural-earth uses subdivision-style
// values like "CN-TW" for Taiwan, which would otherwise overwrite the
// legitimate TWN->TW reverse mapping and break the country (#1049).
if (a2 && a3 && a2.length === 2 && a2 !== '-99' && a3 !== '-99' && !A2_TO_A3[a2]) {
if (a2 && a3 && a2 !== '-99' && a3 !== '-99' && !A2_TO_A3[a2]) {
A2_TO_A3[a2] = a3
}
}
@@ -622,7 +619,7 @@ export function useAtlas() {
try {
const result = await mapsApi.search(bucketSearch, language)
setBucketSearchResults(result.places || [])
} catch (err) { console.error('Bucket-list place search failed:', err) } finally { setBucketSearching(false) }
} catch {} finally { setBucketSearching(false) }
}
const handleSelectBucketPoi = (result: any) => {
-9
View File
@@ -1,9 +0,0 @@
/**
* Pulls the server-provided error string out of an axios-style error so the UI can
* surface the real reason (e.g. a Google Places API message such as "Places API (New)
* has not been used in project or it is disabled") instead of a generic fallback.
*/
export function getApiErrorMessage(err: unknown, fallback: string): string {
const message = (err as { response?: { data?: { error?: unknown } } })?.response?.data?.error
return typeof message === 'string' && message.trim() ? message : fallback
}
+1 -1
View File
@@ -117,7 +117,7 @@ export class PlacesController {
if (!importWaypoints && !importRoutes && !importTracks) {
throw new HttpException({ error: 'No import types selected' }, 400);
}
const result = this.places.importGpx(tripId, file.buffer, { importWaypoints, importRoutes, importTracks, defaultName: file.originalname });
const result = this.places.importGpx(tripId, file.buffer, { importWaypoints, importRoutes, importTracks });
if (!result) {
throw new HttpException({ error: 'No matching places found in GPX file' }, 400);
}
+1 -5
View File
@@ -52,11 +52,7 @@ export class PlacesService {
return svc.deletePlacesMany(tripId, ids);
}
importGpx(
tripId: string,
buffer: Buffer,
opts: { importWaypoints: boolean; importRoutes: boolean; importTracks: boolean; defaultName?: string },
) {
importGpx(tripId: string, buffer: Buffer, opts: { importWaypoints: boolean; importRoutes: boolean; importTracks: boolean }) {
return svc.importGpx(tripId, buffer, opts);
}
+20 -50
View File
@@ -534,18 +534,13 @@ const geocodingInFlight = new Set<number>();
const regionCache = new Map<string, RegionInfo | null>();
// A zoom-8 reverse geocode of a GB place only resolves to the constituent country
// (England/Scotland/Wales/Northern Ireland). Natural Earth's admin-1 polygons for GB
// are counties and boroughs, so those four codes match no polygon and never highlight.
const GB_CONSTITUENT_CODES = new Set(['GB-ENG', 'GB-SCT', 'GB-WLS', 'GB-NIR']);
// Returns the OSM address object, {} for an "ok but empty" response (so it is cached as
// a definitive miss), or null for a transient failure (so it is retried next time).
async function fetchNominatimAddress(lat: number, lng: number, zoom: number): Promise<Record<string, string> | null> {
async function reverseGeocodeRegion(lat: number, lng: number): Promise<RegionInfo | null> {
const key = roundKey(lat, lng);
if (regionCache.has(key)) return regionCache.get(key)!;
await throttleNominatim();
try {
const res = await fetch(
`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&zoom=${zoom}&accept-language=en`,
`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&zoom=8&accept-language=en`,
{
headers: { 'User-Agent': 'TREK Travel Planner (https://github.com/mauriceboe/TREK)' },
signal: AbortSignal.timeout(10_000),
@@ -553,52 +548,27 @@ async function fetchNominatimAddress(lat: number, lng: number, zoom: number): Pr
);
if (!res.ok) return null;
const data = await res.json() as { address?: Record<string, string> };
return data.address ?? {};
const countryCode = data.address?.country_code?.toUpperCase() || null;
// Try finest ISO level first (lvl6 = departments/provinces), then lvl5, then lvl4 (states/regions)
let regionCode = data.address?.['ISO3166-2-lvl6'] || data.address?.['ISO3166-2-lvl5'] || data.address?.['ISO3166-2-lvl4'] || null;
// Normalize: FR-75C → FR-75 (strip trailing letter suffixes for GeoJSON compatibility)
if (regionCode && /^[A-Z]{2}-\d+[A-Z]$/i.test(regionCode)) {
regionCode = regionCode.replace(/[A-Z]$/i, '');
}
const regionName = data.address?.state || data.address?.province || data.address?.region || data.address?.county || data.address?.city || null;
if (!countryCode || !regionName) { regionCache.set(key, null); return null; }
const info: RegionInfo = {
country_code: countryCode,
region_code: regionCode || `${countryCode}-${regionName.substring(0, 3).toUpperCase()}`,
region_name: regionName,
};
regionCache.set(key, info);
return info;
} catch {
return null;
}
}
function buildRegionInfo(address: Record<string, string>, preferFinest: boolean): RegionInfo | null {
const countryCode = address.country_code?.toUpperCase() || null;
// Coarse path (almost every country) lands on the admin-1 level that matches Natural
// Earth directly; the finest path is used only to rescue codes that are too broad.
let regionCode = preferFinest
? (address['ISO3166-2-lvl8'] || address['ISO3166-2-lvl7'] || address['ISO3166-2-lvl6'] || address['ISO3166-2-lvl5'] || null)
: (address['ISO3166-2-lvl6'] || address['ISO3166-2-lvl5'] || address['ISO3166-2-lvl4'] || null);
// Normalize: FR-75C → FR-75 (strip trailing letter suffixes for GeoJSON compatibility)
if (regionCode && /^[A-Z]{2}-\d+[A-Z]$/i.test(regionCode)) {
regionCode = regionCode.replace(/[A-Z]$/i, '');
}
const regionName = preferFinest
? (address.city || address.county || address.state_district || address.borough || address.state || address.province || address.region || null)
: (address.state || address.province || address.region || address.county || address.city || null);
if (!countryCode || !regionName) return null;
return {
country_code: countryCode,
region_code: regionCode || `${countryCode}-${regionName.substring(0, 3).toUpperCase()}`,
region_name: regionName,
};
}
async function reverseGeocodeRegion(lat: number, lng: number): Promise<RegionInfo | null> {
const key = roundKey(lat, lng);
if (regionCache.has(key)) return regionCache.get(key)!;
const address = await fetchNominatimAddress(lat, lng, 8);
if (!address) return null; // transient failure — leave uncached so a later call retries
let info = buildRegionInfo(address, false);
// GB constituent-country codes map to no admin-1 polygon, so re-resolve them at a finer
// zoom where Nominatim exposes the county/borough code (GB-LND, GB-MAN, GB-CON, …) that
// the polygons actually carry.
if (info && info.country_code === 'GB' && GB_CONSTITUENT_CODES.has(info.region_code)) {
const finerAddress = await fetchNominatimAddress(lat, lng, 10);
const finer = finerAddress ? buildRegionInfo(finerAddress, true) : null;
if (finer && !GB_CONSTITUENT_CODES.has(finer.region_code)) info = finer;
}
regionCache.set(key, info);
return info;
}
export async function getVisitedRegions(userId: number): Promise<{ regions: Record<string, { code: string; name: string; placeCount: number }[]> }> {
const trips = getUserTrips(userId);
const tripIds = trips.map(t => t.id);
+3 -19
View File
@@ -346,8 +346,6 @@ export interface GpxImportOptions {
importWaypoints?: boolean;
importRoutes?: boolean;
importTracks?: boolean;
/** Source filename used to name unnamed routes/tracks (keeps multiple imports distinct). */
defaultName?: string;
}
export interface KmlImportOptions {
@@ -356,7 +354,7 @@ export interface KmlImportOptions {
}
export function importGpx(tripId: string, fileBuffer: Buffer, opts: GpxImportOptions = {}) {
const { importWaypoints = true, importRoutes = true, importTracks = true, defaultName } = opts;
const { importWaypoints = true, importRoutes = true, importTracks = true } = opts;
const parsed = gpxParser.parse(fileBuffer.toString('utf-8'));
const gpx = parsed?.gpx;
@@ -365,20 +363,6 @@ export function importGpx(tripId: string, fileBuffer: Buffer, opts: GpxImportOpt
const str = (v: unknown) => (v != null ? String(v).trim() : null);
const num = (v: unknown) => { const n = parseFloat(String(v)); return isNaN(n) ? null : n; };
// Routes and tracks rarely carry their own <name>. Without one they all fall back to the
// same generic label, so name-based dedup drops every import after the first. Derive a
// base from the source filename (the requested behaviour) and suffix an index so multiple
// geometries from one file stay distinct.
const rawName = str(defaultName);
const baseName = rawName ? rawName.replace(/\.[^.]+$/, '').trim() || rawName : null;
let geoSeq = 0;
const geoName = (explicit: string | null, fallback: string): string => {
if (explicit) return explicit;
geoSeq++;
const base = baseName || fallback;
return geoSeq === 1 ? base : `${base} ${geoSeq}`;
};
type WaypointEntry = { name: string; lat: number; lng: number; description: string | null; routeGeometry?: string };
const waypoints: WaypointEntry[] = [];
@@ -401,7 +385,7 @@ export function importGpx(tripId: string, fileBuffer: Buffer, opts: GpxImportOpt
if (pts.length === 0) continue;
const hasAllEle = pts.every(p => p.ele !== null);
const routeGeometry = pts.map(p => hasAllEle ? [p.lat, p.lng, p.ele] : [p.lat, p.lng]);
waypoints.push({ lat: pts[0].lat, lng: pts[0].lng, name: geoName(str(rte.name), 'GPX Route'), description: str(rte.desc), routeGeometry: JSON.stringify(routeGeometry) });
waypoints.push({ lat: pts[0].lat, lng: pts[0].lng, name: str(rte.name) || 'GPX Route', description: str(rte.desc), routeGeometry: JSON.stringify(routeGeometry) });
}
}
@@ -421,7 +405,7 @@ export function importGpx(tripId: string, fileBuffer: Buffer, opts: GpxImportOpt
const start = trackPoints[0];
const hasAllEle = trackPoints.every(p => p.ele !== null);
const routeGeometry = trackPoints.map(p => hasAllEle ? [p.lat, p.lng, p.ele] : [p.lat, p.lng]);
waypoints.push({ lat: start.lat, lng: start.lng, name: geoName(str(trk.name), 'GPX Track'), description: str(trk.desc), routeGeometry: JSON.stringify(routeGeometry) });
waypoints.push({ lat: start.lat, lng: start.lng, name: str(trk.name) || 'GPX Track', description: str(trk.desc), routeGeometry: JSON.stringify(routeGeometry) });
}
}
+2 -16
View File
@@ -122,26 +122,12 @@ export function generateDays(tripId: number | bigint | string, startDate: string
del.run(dated[i].id);
}
// Any remaining unused dateless days: drop the empty placeholders so day_count
// reflects the dated range, but keep ones that still hold content (assignments,
// notes, accommodations) — mirrors the dateless-path trimming above (#1083).
// Any remaining unused dateless days: keep as dateless, just renumber.
// Base must be max(targetDates.length, dated.length) to avoid colliding with
// positives already assigned by the main loop or the overflow loop above.
const isEmptyDay = db.prepare(
`SELECT NOT EXISTS (SELECT 1 FROM day_assignments da WHERE da.day_id = @id)
AND NOT EXISTS (SELECT 1 FROM day_notes dn WHERE dn.day_id = @id)
AND NOT EXISTS (SELECT 1 FROM day_accommodations dac WHERE dac.start_day_id = @id OR dac.end_day_id = @id) AS empty`
);
const maxAssigned = Math.max(targetDates.length, dated.length);
let keptDateless = 0;
for (let i = datelessIdx; i < dateless.length; i++) {
const empty = (isEmptyDay.get({ id: dateless[i].id }) as { empty: number }).empty;
if (empty) {
del.run(dateless[i].id);
} else {
setDayNumber.run(maxAssigned + keptDateless + 1, dateless[i].id);
keptDateless++;
}
setDayNumber.run(maxAssigned + (i - datelessIdx) + 1, dateless[i].id);
}
// Final renumber to compact and eliminate any gaps/negatives
@@ -505,33 +505,4 @@ describe('getVisitedRegions', () => {
const codes = result.regions['FR'].map((r: any) => r.code);
expect(codes).toContain('FR-75');
});
it('ATLAS-UNIT-021: GB places resolving to a constituent country are re-resolved to the finer admin-1 code', async () => {
vi.useFakeTimers();
// A zoom-8 lookup only yields the constituent country (GB-ENG); the zoom-10 lookup
// exposes the borough code (GB-MAN) that Natural Earth's polygons actually carry.
vi.stubGlobal('fetch', vi.fn().mockImplementation((url: string) => Promise.resolve({
ok: true,
json: async () => ({
address: url.includes('zoom=10')
? { country_code: 'gb', 'ISO3166-2-lvl8': 'GB-MAN', city: 'Manchester', state: 'England', 'ISO3166-2-lvl4': 'GB-ENG' }
: { country_code: 'gb', 'ISO3166-2-lvl4': 'GB-ENG', state: 'England' },
}),
})));
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Manchester Trip' });
insertPlaceWithCoords(testDb, trip.id, 'Old Trafford', 53.4631, -2.2913);
await getVisitedRegions(user.id);
await vi.runAllTimersAsync();
const result = await getVisitedRegions(user.id);
expect(result.regions['GB']).toBeDefined();
const codes = result.regions['GB'].map((r: any) => r.code);
expect(codes).toContain('GB-MAN');
expect(codes).not.toContain('GB-ENG');
vi.useRealTimers();
});
});
@@ -346,39 +346,6 @@ describe('importGpx', () => {
const result = importGpx(String(trip.id), gpx);
expect(result).toBeNull();
});
it('PLACE-SVC-037 — multiple unnamed tracks in one file get distinct names instead of collapsing to one', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<trk><trkseg>
<trkpt lat="48.8566" lon="2.3522"></trkpt>
<trkpt lat="48.8570" lon="2.3530"></trkpt>
</trkseg></trk>
<trk><trkseg>
<trkpt lat="40.0000" lon="-3.0000"></trkpt>
<trkpt lat="40.1000" lon="-3.1000"></trkpt>
</trkseg></trk>
</gpx>`);
const result = importGpx(String(trip.id), gpx) as any;
expect(result.places).toHaveLength(2);
const names = result.places.map((p: any) => p.name);
expect(new Set(names).size).toBe(2);
});
it('PLACE-SVC-038 — unnamed tracks fall back to the source filename', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<trk><trkseg>
<trkpt lat="48.8566" lon="2.3522"></trkpt>
<trkpt lat="48.8570" lon="2.3530"></trkpt>
</trkseg></trk>
</gpx>`);
const result = importGpx(String(trip.id), gpx, { defaultName: 'morning-hike.gpx' }) as any;
expect(result.places).toHaveLength(1);
expect(result.places[0].name).toBe('morning-hike');
});
});
// ── importGoogleList ──────────────────────────────────────────────────────────
@@ -242,33 +242,6 @@ describe('generateDays', () => {
const nums = daysAfter.map(d => d.day_number).sort((a, b) => a - b);
expect(nums).toEqual([1, 2, 3, 4, 5]);
});
it('TRIP-SVC-017: switching a dateless trip to a shorter dated range drops empty leftover days but keeps ones with content (#1083)', () => {
const { user } = createUser(testDb);
// A 7-day trip, then cleared to dateless placeholders (day_count = 7).
const trip = createTrip(testDb, user.id, { start_date: '2025-12-01', end_date: '2025-12-07' });
generateDays(trip.id, null, null);
const dateless = getDays(trip.id);
expect(dateless).toHaveLength(7);
expect(dateless.every(d => d.date === null)).toBe(true);
// Give the LAST dateless day real content so it must be preserved.
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, dateless[6].id, place.id);
// Now set an explicit 2-day range. The first two dateless days are reused for
// the dates; the four empty leftovers must be removed, the one with content kept.
generateDays(trip.id, '2026-01-10', '2026-01-11');
const daysAfter = getDays(trip.id);
const dated = daysAfter.filter(d => d.date !== null);
const stillDateless = daysAfter.filter(d => d.date === null);
expect(dated.map(d => d.date)).toEqual(['2026-01-10', '2026-01-11']);
// day_count is COUNT(*) FROM days: 2 dated + 1 content-bearing dateless = 3 (not the stale 7)
expect(daysAfter).toHaveLength(3);
expect(stillDateless).toHaveLength(1);
expect(getAssignments(stillDateless[0].id)[0].id).toBe(assignment.id);
});
});
describe('exportICS', () => {