Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

refactoring: TypeScript migration, security fixes,

Maurice8396a752232e
diff --git a/Dockerfile b/Dockerfile
index 3a6c7ff15..b45bd59b2 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -26,8 +26,9 @@ COPY --from=client-builder /app/client/dist ./public
# Fonts für PDF-Export kopieren
COPY --from=client-builder /app/client/public/fonts ./public/fonts
-# Verzeichnisse erstellen
-RUN mkdir -p /app/data /app/uploads/files /app/uploads/covers
+# Verzeichnisse erstellen + Symlink für Abwärtskompatibilität (alte docker-compose mounten nach /app/server/uploads)
+RUN mkdir -p /app/data /app/uploads/files /app/uploads/covers /app/uploads/avatars /app/uploads/photos && \
+ mkdir -p /app/server && ln -s /app/uploads /app/server/uploads && ln -s /app/data /app/server/data
# Umgebung setzen
ENV NODE_ENV=production
@@ -35,4 +36,4 @@ ENV PORT=3000
EXPOSE 3000
-CMD ["node", "src/index.js"]
+CMD ["node", "--import", "tsx", "src/index.ts"]
diff --git a/client/index.html b/client/index.html
index 59b5ef492..89c3c5831 100644
--- a/client/index.html
+++ b/client/index.html
@@ -25,6 +25,6 @@
</head>
<body>
<div id="root"></div>
- <script type="module" src="/src/main.jsx"></script>
+ <script type="module" src="/src/main.tsx"></script>
</body>
</html>
diff --git a/client/package-lock.json b/client/package-lock.json
index af87f94a0..b3defeb5f 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -26,11 +26,13 @@
"@types/leaflet": "^1.9.8",
"@types/react": "^18.2.61",
"@types/react-dom": "^18.2.19",
+ "@types/react-window": "^1.8.8",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.18",
"postcss": "^8.4.35",
"sharp": "^0.33.0",
"tailwindcss": "^3.4.1",
+ "typescript": "^6.0.2",
"vite": "^5.1.4",
"vite-plugin-pwa": "^0.21.0"
}
@@ -3266,6 +3268,16 @@
"@types/react": "^18.0.0"
}
},
+ "node_modules/@types/react-window": {
+ "version": "1.8.8",
+ "resolved": "https://registry.npmjs.org/@types/react-window/-/react-window-1.8.8.tgz",
+ "integrity": "sha512-8Ls660bHR1AUA2kuRvVG9D/4XpRC6wjAaPT9dil7Ckc76eP9TKWZwwmgfq8Q1LANX3QNDnoU4Zp48A3w+zK69Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/react": "*"
+ }
+ },
"node_modules/@types/resolve": {
"version": "1.20.2",
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz",
@@ -7534,6 +7546,20 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/typescript": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.2.tgz",
+ "integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
"node_modules/unbox-primitive": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz",
diff --git a/client/package.json b/client/package.json
index 5420606f4..febb80b52 100644
--- a/client/package.json
+++ b/client/package.json
@@ -1,6 +1,6 @@
{
"name": "nomad-client",
- "version": "2.6.0",
+ "version": "2.6.1",
"private": true,
"type": "module",
"scripts": {
@@ -28,11 +28,13 @@
"@types/leaflet": "^1.9.8",
"@types/react": "^18.2.61",
"@types/react-dom": "^18.2.19",
+ "@types/react-window": "^1.8.8",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.18",
"postcss": "^8.4.35",
"sharp": "^0.33.0",
"tailwindcss": "^3.4.1",
+ "typescript": "^6.0.2",
"vite": "^5.1.4",
"vite-plugin-pwa": "^0.21.0"
}
diff --git a/client/src/App.jsx b/client/src/App.tsx
similarity index 91%
rename from client/src/App.jsx
rename to client/src/App.tsx
index 9f593019f..1c09ed7cf 100644
--- a/client/src/App.jsx
+++ b/client/src/App.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect } from 'react'
+import React, { useEffect, ReactNode } from 'react'
import { Routes, Route, Navigate, useLocation } from 'react-router-dom'
import { useAuthStore } from './store/authStore'
import { useSettingsStore } from './store/settingsStore'
@@ -6,7 +6,6 @@ import LoginPage from './pages/LoginPage'
import RegisterPage from './pages/RegisterPage'
import DashboardPage from './pages/DashboardPage'
import TripPlannerPage from './pages/TripPlannerPage'
-// PhotosPage removed - replaced by Finanzplan
import FilesPage from './pages/FilesPage'
import AdminPage from './pages/AdminPage'
import SettingsPage from './pages/SettingsPage'
@@ -17,7 +16,12 @@ import { TranslationProvider, useTranslation } from './i18n'
import DemoBanner from './components/Layout/DemoBanner'
import { authApi } from './api/client'
-function ProtectedRoute({ children, adminRequired = false }) {
+interface ProtectedRouteProps {
+ children: ReactNode
+ adminRequired?: boolean
+}
+
+function ProtectedRoute({ children, adminRequired = false }: ProtectedRouteProps) {
const { isAuthenticated, user, isLoading } = useAuthStore()
const { t } = useTranslation()
@@ -40,7 +44,7 @@ function ProtectedRoute({ children, adminRequired = false }) {
return <Navigate to="/dashboard" replace />
}
- return children
+ return <>{children}</>
}
function RootRedirect() {
@@ -65,7 +69,7 @@ export default function App() {
if (token) {
loadUser()
}
- authApi.getAppConfig().then(config => {
+ authApi.getAppConfig().then((config: { demo_mode?: boolean; has_maps_key?: boolean }) => {
if (config?.demo_mode) setDemoMode(true)
if (config?.has_maps_key !== undefined) setHasMapsKey(config.has_maps_key)
}).catch(() => {})
@@ -79,10 +83,9 @@ export default function App() {
}
}, [isAuthenticated])
- // Apply dark mode class to <html> + update PWA theme-color
useEffect(() => {
const mode = settings.dark_mode
- const applyDark = (isDark) => {
+ const applyDark = (isDark: boolean) => {
document.documentElement.classList.toggle('dark', isDark)
const meta = document.querySelector('meta[name="theme-color"]')
if (meta) meta.setAttribute('content', isDark ? '#09090b' : '#ffffff')
@@ -91,11 +94,10 @@ export default function App() {
if (mode === 'auto') {
const mq = window.matchMedia('(prefers-color-scheme: dark)')
applyDark(mq.matches)
- const handler = (e) => applyDark(e.matches)
+ const handler = (e: MediaQueryListEvent) => applyDark(e.matches)
mq.addEventListener('change', handler)
return () => mq.removeEventListener('change', handler)
}
- // Support legacy boolean + new string values
applyDark(mode === true || mode === 'dark')
}, [settings.dark_mode])
diff --git a/client/src/api/client.js b/client/src/api/client.js
deleted file mode 100644
index 7b4477765..000000000
--- a/client/src/api/client.js
+++ /dev/null
@@ -1,251 +0,0 @@
-import axios from 'axios'
-import { getSocketId } from './websocket'
-
-const apiClient = axios.create({
- baseURL: '/api',
- headers: {
- 'Content-Type': 'application/json',
- },
-})
-
-// Request interceptor - add auth token and socket ID
-apiClient.interceptors.request.use(
- (config) => {
- const token = localStorage.getItem('auth_token')
- if (token) {
- config.headers.Authorization = `Bearer ${token}`
- }
- const sid = getSocketId()
- if (sid) {
- config.headers['X-Socket-Id'] = sid
- }
- return config
- },
- (error) => Promise.reject(error)
-)
-
-// Response interceptor - handle 401
-apiClient.interceptors.response.use(
- (response) => response,
- (error) => {
- if (error.response?.status === 401) {
- localStorage.removeItem('auth_token')
- if (!window.location.pathname.includes('/login') && !window.location.pathname.includes('/register')) {
- window.location.href = '/login'
- }
- }
- return Promise.reject(error)
- }
-)
-
-export const authApi = {
- register: (data) => apiClient.post('/auth/register', data).then(r => r.data),
- login: (data) => apiClient.post('/auth/login', data).then(r => r.data),
- me: () => apiClient.get('/auth/me').then(r => r.data),
- updateMapsKey: (key) => apiClient.put('/auth/me/maps-key', { maps_api_key: key }).then(r => r.data),
- updateApiKeys: (data) => apiClient.put('/auth/me/api-keys', data).then(r => r.data),
- updateSettings: (data) => apiClient.put('/auth/me/settings', data).then(r => r.data),
- getSettings: () => apiClient.get('/auth/me/settings').then(r => r.data),
- listUsers: () => apiClient.get('/auth/users').then(r => r.data),
- uploadAvatar: (formData) => apiClient.post('/auth/avatar', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data),
- deleteAvatar: () => apiClient.delete('/auth/avatar').then(r => r.data),
- getAppConfig: () => apiClient.get('/auth/app-config').then(r => r.data),
- updateAppSettings: (data) => apiClient.put('/auth/app-settings', data).then(r => r.data),
- validateKeys: () => apiClient.get('/auth/validate-keys').then(r => r.data),
- travelStats: () => apiClient.get('/auth/travel-stats').then(r => r.data),
- changePassword: (data) => apiClient.put('/auth/me/password', data).then(r => r.data),
- deleteOwnAccount: () => apiClient.delete('/auth/me').then(r => r.data),
- demoLogin: () => apiClient.post('/auth/demo-login').then(r => r.data),
-}
-
-export const tripsApi = {
- list: (params) => apiClient.get('/trips', { params }).then(r => r.data),
- create: (data) => apiClient.post('/trips', data).then(r => r.data),
- get: (id) => apiClient.get(`/trips/${id}`).then(r => r.data),
- update: (id, data) => apiClient.put(`/trips/${id}`, data).then(r => r.data),
- delete: (id) => apiClient.delete(`/trips/${id}`).then(r => r.data),
- uploadCover: (id, formData) => apiClient.post(`/trips/${id}/cover`, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data),
- archive: (id) => apiClient.put(`/trips/${id}`, { is_archived: true }).then(r => r.data),
- unarchive: (id) => apiClient.put(`/trips/${id}`, { is_archived: false }).then(r => r.data),
- getMembers: (id) => apiClient.get(`/trips/${id}/members`).then(r => r.data),
- addMember: (id, identifier) => apiClient.post(`/trips/${id}/members`, { identifier }).then(r => r.data),
- removeMember: (id, userId) => apiClient.delete(`/trips/${id}/members/${userId}`).then(r => r.data),
-}
-
-export const daysApi = {
- list: (tripId) => apiClient.get(`/trips/${tripId}/days`).then(r => r.data),
- create: (tripId, data) => apiClient.post(`/trips/${tripId}/days`, data).then(r => r.data),
- update: (tripId, dayId, data) => apiClient.put(`/trips/${tripId}/days/${dayId}`, data).then(r => r.data),
- delete: (tripId, dayId) => apiClient.delete(`/trips/${tripId}/days/${dayId}`).then(r => r.data),
-}
-
-export const placesApi = {
- list: (tripId, params) => apiClient.get(`/trips/${tripId}/places`, { params }).then(r => r.data),
- create: (tripId, data) => apiClient.post(`/trips/${tripId}/places`, data).then(r => r.data),
- get: (tripId, id) => apiClient.get(`/trips/${tripId}/places/${id}`).then(r => r.data),
- update: (tripId, id, data) => apiClient.put(`/trips/${tripId}/places/${id}`, data).then(r => r.data),
- delete: (tripId, id) => apiClient.delete(`/trips/${tripId}/places/${id}`).then(r => r.data),
- searchImage: (tripId, id) => apiClient.get(`/trips/${tripId}/places/${id}/image`).then(r => r.data),
-}
-
-export const assignmentsApi = {
- list: (tripId, dayId) => apiClient.get(`/trips/${tripId}/days/${dayId}/assignments`).then(r => r.data),
- create: (tripId, dayId, data) => apiClient.post(`/trips/${tripId}/days/${dayId}/assignments`, data).then(r => r.data),
- delete: (tripId, dayId, id) => apiClient.delete(`/trips/${tripId}/days/${dayId}/assignments/${id}`).then(r => r.data),
- reorder: (tripId, dayId, orderedIds) => apiClient.put(`/trips/${tripId}/days/${dayId}/assignments/reorder`, { orderedIds }).then(r => r.data),
- move: (tripId, assignmentId, newDayId, orderIndex) => apiClient.put(`/trips/${tripId}/assignments/${assignmentId}/move`, { new_day_id: newDayId, order_index: orderIndex }).then(r => r.data),
- update: (tripId, dayId, id, data) => apiClient.put(`/trips/${tripId}/days/${dayId}/assignments/${id}`, data).then(r => r.data),
- getParticipants: (tripId, id) => apiClient.get(`/trips/${tripId}/assignments/${id}/participants`).then(r => r.data),
- setParticipants: (tripId, id, userIds) => apiClient.put(`/trips/${tripId}/assignments/${id}/participants`, { user_ids: userIds }).then(r => r.data),
- updateTime: (tripId, id, times) => apiClient.put(`/trips/${tripId}/assignments/${id}/time`, times).then(r => r.data),
-}
-
-export const packingApi = {
- list: (tripId) => apiClient.get(`/trips/${tripId}/packing`).then(r => r.data),
- create: (tripId, data) => apiClient.post(`/trips/${tripId}/packing`, data).then(r => r.data),
- update: (tripId, id, data) => apiClient.put(`/trips/${tripId}/packing/${id}`, data).then(r => r.data),
- delete: (tripId, id) => apiClient.delete(`/trips/${tripId}/packing/${id}`).then(r => r.data),
- reorder: (tripId, orderedIds) => apiClient.put(`/trips/${tripId}/packing/reorder`, { orderedIds }).then(r => r.data),
-}
-
-export const tagsApi = {
- list: () => apiClient.get('/tags').then(r => r.data),
- create: (data) => apiClient.post('/tags', data).then(r => r.data),
- update: (id, data) => apiClient.put(`/tags/${id}`, data).then(r => r.data),
- delete: (id) => apiClient.delete(`/tags/${id}`).then(r => r.data),
-}
-
-export const categoriesApi = {
- list: () => apiClient.get('/categories').then(r => r.data),
- create: (data) => apiClient.post('/categories', data).then(r => r.data),
- update: (id, data) => apiClient.put(`/categories/${id}`, data).then(r => r.data),
- delete: (id) => apiClient.delete(`/categories/${id}`).then(r => r.data),
-}
-
-export const adminApi = {
- users: () => apiClient.get('/admin/users').then(r => r.data),
- createUser: (data) => apiClient.post('/admin/users', data).then(r => r.data),
- updateUser: (id, data) => apiClient.put(`/admin/users/${id}`, data).then(r => r.data),
- deleteUser: (id) => apiClient.delete(`/admin/users/${id}`).then(r => r.data),
- stats: () => apiClient.get('/admin/stats').then(r => r.data),
- saveDemoBaseline: () => apiClient.post('/admin/save-demo-baseline').then(r => r.data),
- getOidc: () => apiClient.get('/admin/oidc').then(r => r.data),
- updateOidc: (data) => apiClient.put('/admin/oidc', data).then(r => r.data),
- addons: () => apiClient.get('/admin/addons').then(r => r.data),
- updateAddon: (id, data) => apiClient.put(`/admin/addons/${id}`, data).then(r => r.data),
- checkVersion: () => apiClient.get('/admin/version-check').then(r => r.data),
- installUpdate: () => apiClient.post('/admin/update', {}, { timeout: 300000 }).then(r => r.data),
-}
-
-export const addonsApi = {
- enabled: () => apiClient.get('/addons').then(r => r.data),
-}
-
-export const mapsApi = {
- search: (query, lang) => apiClient.post(`/maps/search?lang=${lang || 'en'}`, { query }).then(r => r.data),
- details: (placeId, lang) => apiClient.get(`/maps/details/${placeId}`, { params: { lang } }).then(r => r.data),
- placePhoto: (placeId) => apiClient.get(`/maps/place-photo/${placeId}`).then(r => r.data),
-}
-
-export const budgetApi = {
- list: (tripId) => apiClient.get(`/trips/${tripId}/budget`).then(r => r.data),
- create: (tripId, data) => apiClient.post(`/trips/${tripId}/budget`, data).then(r => r.data),
- update: (tripId, id, data) => apiClient.put(`/trips/${tripId}/budget/${id}`, data).then(r => r.data),
- delete: (tripId, id) => apiClient.delete(`/trips/${tripId}/budget/${id}`).then(r => r.data),
- setMembers: (tripId, id, userIds) => apiClient.put(`/trips/${tripId}/budget/${id}/members`, { user_ids: userIds }).then(r => r.data),
- togglePaid: (tripId, id, userId, paid) => apiClient.put(`/trips/${tripId}/budget/${id}/members/${userId}/paid`, { paid }).then(r => r.data),
- perPersonSummary: (tripId) => apiClient.get(`/trips/${tripId}/budget/summary/per-person`).then(r => r.data),
-}
-
-export const filesApi = {
- list: (tripId) => apiClient.get(`/trips/${tripId}/files`).then(r => r.data),
- upload: (tripId, formData) => apiClient.post(`/trips/${tripId}/files`, formData, {
- headers: { 'Content-Type': 'multipart/form-data' }
- }).then(r => r.data),
- update: (tripId, id, data) => apiClient.put(`/trips/${tripId}/files/${id}`, data).then(r => r.data),
- delete: (tripId, id) => apiClient.delete(`/trips/${tripId}/files/${id}`).then(r => r.data),
-}
-
-export const reservationsApi = {
- list: (tripId) => apiClient.get(`/trips/${tripId}/reservations`).then(r => r.data),
- create: (tripId, data) => apiClient.post(`/trips/${tripId}/reservations`, data).then(r => r.data),
- update: (tripId, id, data) => apiClient.put(`/trips/${tripId}/reservations/${id}`, data).then(r => r.data),
- delete: (tripId, id) => apiClient.delete(`/trips/${tripId}/reservations/${id}`).then(r => r.data),
-}
-
-export const weatherApi = {
- get: (lat, lng, date) => apiClient.get('/weather', { params: { lat, lng, date } }).then(r => r.data),
- getDetailed: (lat, lng, date, lang) => apiClient.get('/weather/detailed', { params: { lat, lng, date, lang } }).then(r => r.data),
-}
-
-export const settingsApi = {
- get: () => apiClient.get('/settings').then(r => r.data),
- set: (key, value) => apiClient.put('/settings', { key, value }).then(r => r.data),
- setBulk: (settings) => apiClient.post('/settings/bulk', { settings }).then(r => r.data),
-}
-
-export const accommodationsApi = {
- list: (tripId) => apiClient.get(`/trips/${tripId}/accommodations`).then(r => r.data),
- create: (tripId, data) => apiClient.post(`/trips/${tripId}/accommodations`, data).then(r => r.data),
- update: (tripId, id, data) => apiClient.put(`/trips/${tripId}/accommodations/${id}`, data).then(r => r.data),
- delete: (tripId, id) => apiClient.delete(`/trips/${tripId}/accommodations/${id}`).then(r => r.data),
-}
-
-export const dayNotesApi = {
- list: (tripId, dayId) => apiClient.get(`/trips/${tripId}/days/${dayId}/notes`).then(r => r.data),
- create: (tripId, dayId, data) => apiClient.post(`/trips/${tripId}/days/${dayId}/notes`, data).then(r => r.data),
- update: (tripId, dayId, id, data) => apiClient.put(`/trips/${tripId}/days/${dayId}/notes/${id}`, data).then(r => r.data),
- delete: (tripId, dayId, id) => apiClient.delete(`/trips/${tripId}/days/${dayId}/notes/${id}`).then(r => r.data),
-}
-
-export const collabApi = {
- // Notes
- getNotes: (tripId) => apiClient.get(`/trips/${tripId}/collab/notes`).then(r => r.data),
- createNote: (tripId, data) => apiClient.post(`/trips/${tripId}/collab/notes`, data).then(r => r.data),
- updateNote: (tripId, id, data) => apiClient.put(`/trips/${tripId}/collab/notes/${id}`, data).then(r => r.data),
- deleteNote: (tripId, id) => apiClient.delete(`/trips/${tripId}/collab/notes/${id}`).then(r => r.data),
- uploadNoteFile: (tripId, noteId, formData) => apiClient.post(`/trips/${tripId}/collab/notes/${noteId}/files`, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data),
- deleteNoteFile: (tripId, noteId, fileId) => apiClient.delete(`/trips/${tripId}/collab/notes/${noteId}/files/${fileId}`).then(r => r.data),
- // Polls
- getPolls: (tripId) => apiClient.get(`/trips/${tripId}/collab/polls`).then(r => r.data),
- createPoll: (tripId, data) => apiClient.post(`/trips/${tripId}/collab/polls`, data).then(r => r.data),
- votePoll: (tripId, id, optionIndex) => apiClient.post(`/trips/${tripId}/collab/polls/${id}/vote`, { option_index: optionIndex }).then(r => r.data),
- closePoll: (tripId, id) => apiClient.put(`/trips/${tripId}/collab/polls/${id}/close`).then(r => r.data),
- deletePoll: (tripId, id) => apiClient.delete(`/trips/${tripId}/collab/polls/${id}`).then(r => r.data),
- // Chat
- getMessages: (tripId, before) => apiClient.get(`/trips/${tripId}/collab/messages${before ? `?before=${before}` : ''}`).then(r => r.data),
- sendMessage: (tripId, data) => apiClient.post(`/trips/${tripId}/collab/messages`, data).then(r => r.data),
- deleteMessage: (tripId, id) => apiClient.delete(`/trips/${tripId}/collab/messages/${id}`).then(r => r.data),
- reactMessage: (tripId, id, emoji) => apiClient.post(`/trips/${tripId}/collab/messages/${id}/react`, { emoji }).then(r => r.data),
- linkPreview: (tripId, url) => apiClient.get(`/trips/${tripId}/collab/link-preview?url=${encodeURIComponent(url)}`).then(r => r.data),
-}
-
-export const backupApi = {
- list: () => apiClient.get('/backup/list').then(r => r.data),
- create: () => apiClient.post('/backup/create').then(r => r.data),
- download: async (filename) => {
- const token = localStorage.getItem('auth_token')
- const res = await fetch(`/api/backup/download/${filename}`, {
- headers: { Authorization: `Bearer ${token}` },
- })
- if (!res.ok) throw new Error('Download failed')
- const blob = await res.blob()
- const url = URL.createObjectURL(blob)
- const a = document.createElement('a')
- a.href = url
- a.download = filename
- a.click()
- URL.revokeObjectURL(url)
- },
- delete: (filename) => apiClient.delete(`/backup/${filename}`).then(r => r.data),
- restore: (filename) => apiClient.post(`/backup/restore/${filename}`).then(r => r.data),
- uploadRestore: (file) => {
- const form = new FormData()
- form.append('backup', file)
- return apiClient.post('/backup/upload-restore', form, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data)
- },
- getAutoSettings: () => apiClient.get('/backup/auto-settings').then(r => r.data),
- setAutoSettings: (settings) => apiClient.put('/backup/auto-settings', settings).then(r => r.data),
-}
-
-export default apiClient
diff --git a/client/src/api/client.ts b/client/src/api/client.ts
new file mode 100644
index 000000000..534fca00e
--- /dev/null
+++ b/client/src/api/client.ts
@@ -0,0 +1,248 @@
+import axios, { AxiosInstance } from 'axios'
+import { getSocketId } from './websocket'
+
+const apiClient: AxiosInstance = axios.create({
+ baseURL: '/api',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+})
+
+// Request interceptor - add auth token and socket ID
+apiClient.interceptors.request.use(
+ (config) => {
+ const token = localStorage.getItem('auth_token')
+ if (token) {
+ config.headers.Authorization = `Bearer ${token}`
+ }
+ const sid = getSocketId()
+ if (sid) {
+ config.headers['X-Socket-Id'] = sid
+ }
+ return config
+ },
+ (error) => Promise.reject(error)
+)
+
+// Response interceptor - handle 401
+apiClient.interceptors.response.use(
+ (response) => response,
+ (error) => {
+ if (error.response?.status === 401) {
+ localStorage.removeItem('auth_token')
+ if (!window.location.pathname.includes('/login') && !window.location.pathname.includes('/register')) {
+ window.location.href = '/login'
+ }
+ }
+ return Promise.reject(error)
+ }
+)
+
+export const authApi = {
+ register: (data: { username: string; email: string; password: string }) => apiClient.post('/auth/register', data).then(r => r.data),
+ login: (data: { email: string; password: string }) => apiClient.post('/auth/login', data).then(r => r.data),
+ me: () => apiClient.get('/auth/me').then(r => r.data),
+ updateMapsKey: (key: string | null) => apiClient.put('/auth/me/maps-key', { maps_api_key: key }).then(r => r.data),
+ updateApiKeys: (data: Record<string, string | null>) => apiClient.put('/auth/me/api-keys', data).then(r => r.data),
+ updateSettings: (data: Record<string, unknown>) => apiClient.put('/auth/me/settings', data).then(r => r.data),
+ getSettings: () => apiClient.get('/auth/me/settings').then(r => r.data),
+ listUsers: () => apiClient.get('/auth/users').then(r => r.data),
+ uploadAvatar: (formData: FormData) => apiClient.post('/auth/avatar', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data),
+ deleteAvatar: () => apiClient.delete('/auth/avatar').then(r => r.data),
+ getAppConfig: () => apiClient.get('/auth/app-config').then(r => r.data),
+ updateAppSettings: (data: Record<string, unknown>) => apiClient.put('/auth/app-settings', data).then(r => r.data),
+ validateKeys: () => apiClient.get('/auth/validate-keys').then(r => r.data),
+ travelStats: () => apiClient.get('/auth/travel-stats').then(r => r.data),
+ changePassword: (data: { current_password: string; new_password: string }) => apiClient.put('/auth/me/password', data).then(r => r.data),
+ deleteOwnAccount: () => apiClient.delete('/auth/me').then(r => r.data),
+ demoLogin: () => apiClient.post('/auth/demo-login').then(r => r.data),
+}
+
+export const tripsApi = {
+ list: (params?: Record<string, unknown>) => apiClient.get('/trips', { params }).then(r => r.data),
+ create: (data: Record<string, unknown>) => apiClient.post('/trips', data).then(r => r.data),
+ get: (id: number | string) => apiClient.get(`/trips/${id}`).then(r => r.data),
+ update: (id: number | string, data: Record<string, unknown>) => apiClient.put(`/trips/${id}`, data).then(r => r.data),
+ delete: (id: number | string) => apiClient.delete(`/trips/${id}`).then(r => r.data),
+ uploadCover: (id: number | string, formData: FormData) => apiClient.post(`/trips/${id}/cover`, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data),
+ archive: (id: number | string) => apiClient.put(`/trips/${id}`, { is_archived: true }).then(r => r.data),
+ unarchive: (id: number | string) => apiClient.put(`/trips/${id}`, { is_archived: false }).then(r => r.data),
+ getMembers: (id: number | string) => apiClient.get(`/trips/${id}/members`).then(r => r.data),
+ addMember: (id: number | string, identifier: string) => apiClient.post(`/trips/${id}/members`, { identifier }).then(r => r.data),
+ removeMember: (id: number | string, userId: number) => apiClient.delete(`/trips/${id}/members/${userId}`).then(r => r.data),
+}
+
+export const daysApi = {
+ list: (tripId: number | string) => apiClient.get(`/trips/${tripId}/days`).then(r => r.data),
+ create: (tripId: number | string, data: Record<string, unknown>) => apiClient.post(`/trips/${tripId}/days`, data).then(r => r.data),
+ update: (tripId: number | string, dayId: number | string, data: Record<string, unknown>) => apiClient.put(`/trips/${tripId}/days/${dayId}`, data).then(r => r.data),
+ delete: (tripId: number | string, dayId: number | string) => apiClient.delete(`/trips/${tripId}/days/${dayId}`).then(r => r.data),
+}
+
+export const placesApi = {
+ list: (tripId: number | string, params?: Record<string, unknown>) => apiClient.get(`/trips/${tripId}/places`, { params }).then(r => r.data),
+ create: (tripId: number | string, data: Record<string, unknown>) => apiClient.post(`/trips/${tripId}/places`, data).then(r => r.data),
+ get: (tripId: number | string, id: number | string) => apiClient.get(`/trips/${tripId}/places/${id}`).then(r => r.data),
+ update: (tripId: number | string, id: number | string, data: Record<string, unknown>) => apiClient.put(`/trips/${tripId}/places/${id}`, data).then(r => r.data),
+ delete: (tripId: number | string, id: number | string) => apiClient.delete(`/trips/${tripId}/places/${id}`).then(r => r.data),
+ searchImage: (tripId: number | string, id: number | string) => apiClient.get(`/trips/${tripId}/places/${id}/image`).then(r => r.data),
+}
+
+export const assignmentsApi = {
+ list: (tripId: number | string, dayId: number | string) => apiClient.get(`/trips/${tripId}/days/${dayId}/assignments`).then(r => r.data),
+ create: (tripId: number | string, dayId: number | string, data: { place_id: number | string }) => apiClient.post(`/trips/${tripId}/days/${dayId}/assignments`, data).then(r => r.data),
+ delete: (tripId: number | string, dayId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/days/${dayId}/assignments/${id}`).then(r => r.data),
+ reorder: (tripId: number | string, dayId: number | string, orderedIds: number[]) => apiClient.put(`/trips/${tripId}/days/${dayId}/assignments/reorder`, { orderedIds }).then(r => r.data),
+ move: (tripId: number | string, assignmentId: number, newDayId: number | string, orderIndex: number | null) => apiClient.put(`/trips/${tripId}/assignments/${assignmentId}/move`, { new_day_id: newDayId, order_index: orderIndex }).then(r => r.data),
+ update: (tripId: number | string, dayId: number | string, id: number, data: Record<string, unknown>) => apiClient.put(`/trips/${tripId}/days/${dayId}/assignments/${id}`, data).then(r => r.data),
+ getParticipants: (tripId: number | string, id: number) => apiClient.get(`/trips/${tripId}/assignments/${id}/participants`).then(r => r.data),
+ setParticipants: (tripId: number | string, id: number, userIds: number[]) => apiClient.put(`/trips/${tripId}/assignments/${id}/participants`, { user_ids: userIds }).then(r => r.data),
+ updateTime: (tripId: number | string, id: number, times: Record<string, unknown>) => apiClient.put(`/trips/${tripId}/assignments/${id}/time`, times).then(r => r.data),
+}
+
+export const packingApi = {
+ list: (tripId: number | string) => apiClient.get(`/trips/${tripId}/packing`).then(r => r.data),
+ create: (tripId: number | string, data: Record<string, unknown>) => apiClient.post(`/trips/${tripId}/packing`, data).then(r => r.data),
+ update: (tripId: number | string, id: number, data: Record<string, unknown>) => apiClient.put(`/trips/${tripId}/packing/${id}`, data).then(r => r.data),
+ delete: (tripId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/packing/${id}`).then(r => r.data),
+ reorder: (tripId: number | string, orderedIds: number[]) => apiClient.put(`/trips/${tripId}/packing/reorder`, { orderedIds }).then(r => r.data),
+}
+
+export const tagsApi = {
+ list: () => apiClient.get('/tags').then(r => r.data),
+ create: (data: Record<string, unknown>) => apiClient.post('/tags', data).then(r => r.data),
+ update: (id: number, data: Record<string, unknown>) => apiClient.put(`/tags/${id}`, data).then(r => r.data),
+ delete: (id: number) => apiClient.delete(`/tags/${id}`).then(r => r.data),
+}
+
+export const categoriesApi = {
+ list: () => apiClient.get('/categories').then(r => r.data),
+ create: (data: Record<string, unknown>) => apiClient.post('/categories', data).then(r => r.data),
+ update: (id: number, data: Record<string, unknown>) => apiClient.put(`/categories/${id}`, data).then(r => r.data),
+ delete: (id: number) => apiClient.delete(`/categories/${id}`).then(r => r.data),
+}
+
+export const adminApi = {
+ users: () => apiClient.get('/admin/users').then(r => r.data),
+ createUser: (data: Record<string, unknown>) => apiClient.post('/admin/users', data).then(r => r.data),
+ updateUser: (id: number, data: Record<string, unknown>) => apiClient.put(`/admin/users/${id}`, data).then(r => r.data),
+ deleteUser: (id: number) => apiClient.delete(`/admin/users/${id}`).then(r => r.data),
+ stats: () => apiClient.get('/admin/stats').then(r => r.data),
+ saveDemoBaseline: () => apiClient.post('/admin/save-demo-baseline').then(r => r.data),
+ getOidc: () => apiClient.get('/admin/oidc').then(r => r.data),
+ updateOidc: (data: Record<string, unknown>) => apiClient.put('/admin/oidc', data).then(r => r.data),
+ addons: () => apiClient.get('/admin/addons').then(r => r.data),
+ updateAddon: (id: number | string, data: Record<string, unknown>) => apiClient.put(`/admin/addons/${id}`, data).then(r => r.data),
+ checkVersion: () => apiClient.get('/admin/version-check').then(r => r.data),
+ installUpdate: () => apiClient.post('/admin/update', {}, { timeout: 300000 }).then(r => r.data),
+}
+
+export const addonsApi = {
+ enabled: () => apiClient.get('/addons').then(r => r.data),
+}
+
+export const mapsApi = {
+ search: (query: string, lang?: string) => apiClient.post(`/maps/search?lang=${lang || 'en'}`, { query }).then(r => r.data),
+ details: (placeId: string, lang?: string) => apiClient.get(`/maps/details/${placeId}`, { params: { lang } }).then(r => r.data),
+ placePhoto: (placeId: string) => apiClient.get(`/maps/place-photo/${placeId}`).then(r => r.data),
+}
+
+export const budgetApi = {
+ list: (tripId: number | string) => apiClient.get(`/trips/${tripId}/budget`).then(r => r.data),
+ create: (tripId: number | string, data: Record<string, unknown>) => apiClient.post(`/trips/${tripId}/budget`, data).then(r => r.data),
+ update: (tripId: number | string, id: number, data: Record<string, unknown>) => apiClient.put(`/trips/${tripId}/budget/${id}`, data).then(r => r.data),
+ delete: (tripId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/budget/${id}`).then(r => r.data),
+ setMembers: (tripId: number | string, id: number, userIds: number[]) => apiClient.put(`/trips/${tripId}/budget/${id}/members`, { user_ids: userIds }).then(r => r.data),
+ togglePaid: (tripId: number | string, id: number, userId: number, paid: boolean) => apiClient.put(`/trips/${tripId}/budget/${id}/members/${userId}/paid`, { paid }).then(r => r.data),
+ perPersonSummary: (tripId: number | string) => apiClient.get(`/trips/${tripId}/budget/summary/per-person`).then(r => r.data),
+}
+
+export const filesApi = {
+ list: (tripId: number | string) => apiClient.get(`/trips/${tripId}/files`).then(r => r.data),
+ upload: (tripId: number | string, formData: FormData) => apiClient.post(`/trips/${tripId}/files`, formData, {
+ headers: { 'Content-Type': 'multipart/form-data' }
+ }).then(r => r.data),
+ update: (tripId: number | string, id: number, data: Record<string, unknown>) => apiClient.put(`/trips/${tripId}/files/${id}`, data).then(r => r.data),
+ delete: (tripId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/files/${id}`).then(r => r.data),
+}
+
+export const reservationsApi = {
+ list: (tripId: number | string) => apiClient.get(`/trips/${tripId}/reservations`).then(r => r.data),
+ create: (tripId: number | string, data: Record<string, unknown>) => apiClient.post(`/trips/${tripId}/reservations`, data).then(r => r.data),
+ update: (tripId: number | string, id: number, data: Record<string, unknown>) => apiClient.put(`/trips/${tripId}/reservations/${id}`, data).then(r => r.data),
+ delete: (tripId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/reservations/${id}`).then(r => r.data),
+}
+
+export const weatherApi = {
+ get: (lat: number, lng: number, date: string) => apiClient.get('/weather', { params: { lat, lng, date } }).then(r => r.data),
+ getDetailed: (lat: number, lng: number, date: string, lang?: string) => apiClient.get('/weather/detailed', { params: { lat, lng, date, lang } }).then(r => r.data),
+}
+
+export const settingsApi = {
+ get: () => apiClient.get('/settings').then(r => r.data),
+ set: (key: string, value: unknown) => apiClient.put('/settings', { key, value }).then(r => r.data),
+ setBulk: (settings: Record<string, unknown>) => apiClient.post('/settings/bulk', { settings }).then(r => r.data),
+}
+
+export const accommodationsApi = {
+ list: (tripId: number | string) => apiClient.get(`/trips/${tripId}/accommodations`).then(r => r.data),
+ create: (tripId: number | string, data: Record<string, unknown>) => apiClient.post(`/trips/${tripId}/accommodations`, data).then(r => r.data),
+ update: (tripId: number | string, id: number, data: Record<string, unknown>) => apiClient.put(`/trips/${tripId}/accommodations/${id}`, data).then(r => r.data),
+ delete: (tripId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/accommodations/${id}`).then(r => r.data),
+}
+
+export const dayNotesApi = {
+ list: (tripId: number | string, dayId: number | string) => apiClient.get(`/trips/${tripId}/days/${dayId}/notes`).then(r => r.data),
+ create: (tripId: number | string, dayId: number | string, data: Record<string, unknown>) => apiClient.post(`/trips/${tripId}/days/${dayId}/notes`, data).then(r => r.data),
+ update: (tripId: number | string, dayId: number | string, id: number, data: Record<string, unknown>) => apiClient.put(`/trips/${tripId}/days/${dayId}/notes/${id}`, data).then(r => r.data),
+ delete: (tripId: number | string, dayId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/days/${dayId}/notes/${id}`).then(r => r.data),
+}
+
+export const collabApi = {
+ getNotes: (tripId: number | string) => apiClient.get(`/trips/${tripId}/collab/notes`).then(r => r.data),
+ createNote: (tripId: number | string, data: Record<string, unknown>) => apiClient.post(`/trips/${tripId}/collab/notes`, data).then(r => r.data),
+ updateNote: (tripId: number | string, id: number, data: Record<string, unknown>) => apiClient.put(`/trips/${tripId}/collab/notes/${id}`, data).then(r => r.data),
+ deleteNote: (tripId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/collab/notes/${id}`).then(r => r.data),
+ uploadNoteFile: (tripId: number | string, noteId: number, formData: FormData) => apiClient.post(`/trips/${tripId}/collab/notes/${noteId}/files`, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data),
+ deleteNoteFile: (tripId: number | string, noteId: number, fileId: number) => apiClient.delete(`/trips/${tripId}/collab/notes/${noteId}/files/${fileId}`).then(r => r.data),
+ getPolls: (tripId: number | string) => apiClient.get(`/trips/${tripId}/collab/polls`).then(r => r.data),
+ createPoll: (tripId: number | string, data: Record<string, unknown>) => apiClient.post(`/trips/${tripId}/collab/polls`, data).then(r => r.data),
+ votePoll: (tripId: number | string, id: number, optionIndex: number) => apiClient.post(`/trips/${tripId}/collab/polls/${id}/vote`, { option_index: optionIndex }).then(r => r.data),
+ closePoll: (tripId: number | string, id: number) => apiClient.put(`/trips/${tripId}/collab/polls/${id}/close`).then(r => r.data),
+ deletePoll: (tripId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/collab/polls/${id}`).then(r => r.data),
+ getMessages: (tripId: number | string, before?: string) => apiClient.get(`/trips/${tripId}/collab/messages${before ? `?before=${before}` : ''}`).then(r => r.data),
+ sendMessage: (tripId: number | string, data: Record<string, unknown>) => apiClient.post(`/trips/${tripId}/collab/messages`, data).then(r => r.data),
+ deleteMessage: (tripId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/collab/messages/${id}`).then(r => r.data),
+ reactMessage: (tripId: number | string, id: number, emoji: string) => apiClient.post(`/trips/${tripId}/collab/messages/${id}/react`, { emoji }).then(r => r.data),
+ linkPreview: (tripId: number | string, url: string) => apiClient.get(`/trips/${tripId}/collab/link-preview?url=${encodeURIComponent(url)}`).then(r => r.data),
+}
+
+export const backupApi = {
+ list: () => apiClient.get('/backup/list').then(r => r.data),
+ create: () => apiClient.post('/backup/create').then(r => r.data),
+ download: async (filename: string): Promise<void> => {
+ const token = localStorage.getItem('auth_token')
+ const res = await fetch(`/api/backup/download/${filename}`, {
+ headers: { Authorization: `Bearer ${token}` },
+ })
+ if (!res.ok) throw new Error('Download failed')
+ const blob = await res.blob()
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = filename
+ a.click()
+ URL.revokeObjectURL(url)
+ },
+ delete: (filename: string) => apiClient.delete(`/backup/${filename}`).then(r => r.data),
+ restore: (filename: string) => apiClient.post(`/backup/restore/${filename}`).then(r => r.data),
+ uploadRestore: (file: File) => {
+ const form = new FormData()
+ form.append('backup', file)
+ return apiClient.post('/backup/upload-restore', form, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data)
+ },
+ getAutoSettings: () => apiClient.get('/backup/auto-settings').then(r => r.data),
+ setAutoSettings: (settings: Record<string, unknown>) => apiClient.put('/backup/auto-settings', settings).then(r => r.data),
+}
+
+export default apiClient
diff --git a/client/src/api/websocket.js b/client/src/api/websocket.ts
similarity index 65%
rename from client/src/api/websocket.js
rename to client/src/api/websocket.ts
index c0c187105..bde981510 100644
--- a/client/src/api/websocket.js
+++ b/client/src/api/websocket.ts
@@ -1,45 +1,47 @@
// Singleton WebSocket manager for real-time collaboration
-let socket = null
-let reconnectTimer = null
+type WebSocketListener = (event: Record<string, unknown>) => void
+type RefetchCallback = (tripId: string) => void
+
+let socket: WebSocket | null = null
+let reconnectTimer: ReturnType<typeof setTimeout> | null = null
let reconnectDelay = 1000
const MAX_RECONNECT_DELAY = 30000
-const listeners = new Set()
-const activeTrips = new Set()
-let currentToken = null
-let refetchCallback = null
-let mySocketId = null
+const listeners = new Set<WebSocketListener>()
+const activeTrips = new Set<string>()
+let currentToken: string | null = null
+let refetchCallback: RefetchCallback | null = null
+let mySocketId: string | null = null
-export function getSocketId() {
+export function getSocketId(): string | null {
return mySocketId
}
-export function setRefetchCallback(fn) {
+export function setRefetchCallback(fn: RefetchCallback | null): void {
refetchCallback = fn
}
-function getWsUrl(token) {
+function getWsUrl(token: string): string {
const protocol = location.protocol === 'https:' ? 'wss' : 'ws'
return `${protocol}://${location.host}/ws?token=${token}`
}
-function handleMessage(event) {
+function handleMessage(event: MessageEvent): void {
try {
const parsed = JSON.parse(event.data)
- // Store our socket ID from welcome message
if (parsed.type === 'welcome') {
mySocketId = parsed.socketId
return
}
listeners.forEach(fn => {
- try { fn(parsed) } catch (err) { console.error('WebSocket listener error:', err) }
+ try { fn(parsed) } catch (err: unknown) { console.error('WebSocket listener error:', err) }
})
- } catch (err) {
+ } catch (err: unknown) {
console.error('WebSocket message parse error:', err)
}
}
-function scheduleReconnect() {
+function scheduleReconnect(): void {
if (reconnectTimer) return
reconnectTimer = setTimeout(() => {
reconnectTimer = null
@@ -50,7 +52,7 @@ function scheduleReconnect() {
reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY)
}
-function connectInternal(token, isReconnect = false) {
+function connectInternal(token: string, _isReconnect = false): void {
if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) {
return
}
@@ -59,20 +61,16 @@ function connectInternal(token, isReconnect = false) {
socket = new WebSocket(url)
socket.onopen = () => {
- // connection established
reconnectDelay = 1000
- // Join active trips on any connect (initial or reconnect)
if (activeTrips.size > 0) {
activeTrips.forEach(tripId => {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ type: 'join', tripId }))
- // joined trip room
}
})
- // Refetch trip data for active trips
if (refetchCallback) {
activeTrips.forEach(tripId => {
- try { refetchCallback(tripId) } catch (err) {
+ try { refetchCallback!(tripId) } catch (err: unknown) {
console.error('Failed to refetch trip data on reconnect:', err)
}
})
@@ -94,7 +92,7 @@ function connectInternal(token, isReconnect = false) {
}
}
-export function connect(token) {
+export function connect(token: string): void {
currentToken = token
reconnectDelay = 1000
if (reconnectTimer) {
@@ -104,7 +102,7 @@ export function connect(token) {
connectInternal(token, false)
}
-export function disconnect() {
+export function disconnect(): void {
currentToken = null
if (reconnectTimer) {
clearTimeout(reconnectTimer)
@@ -112,30 +110,30 @@ export function disconnect() {
}
activeTrips.clear()
if (socket) {
- socket.onclose = null // prevent reconnect
+ socket.onclose = null
socket.close()
socket = null
}
}
-export function joinTrip(tripId) {
+export function joinTrip(tripId: number | string): void {
activeTrips.add(String(tripId))
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ type: 'join', tripId: String(tripId) }))
}
}
-export function leaveTrip(tripId) {
+export function leaveTrip(tripId: number | string): void {
activeTrips.delete(String(tripId))
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ type: 'leave', tripId: String(tripId) }))
}
}
-export function addListener(fn) {
+export function addListener(fn: WebSocketListener): void {
listeners.add(fn)
}
-export function removeListener(fn) {
+export function removeListener(fn: WebSocketListener): void {
listeners.delete(fn)
}
diff --git a/client/src/components/Admin/AddonManager.jsx b/client/src/components/Admin/AddonManager.tsx
similarity index 93%
rename from client/src/components/Admin/AddonManager.jsx
rename to client/src/components/Admin/AddonManager.tsx
index 82a82a4ff..c1e46f1d4 100644
--- a/client/src/components/Admin/AddonManager.jsx
+++ b/client/src/components/Admin/AddonManager.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useState } from 'react'
+import { useEffect, useState } from 'react'
import { adminApi } from '../../api/client'
import { useTranslation } from '../../i18n'
import { useSettingsStore } from '../../store/settingsStore'
@@ -9,7 +9,20 @@ const ICON_MAP = {
ListChecks, Wallet, FileText, CalendarDays, Puzzle, Globe, Briefcase,
}
-function AddonIcon({ name, size = 20 }) {
+interface Addon {
+ id: string
+ name: string
+ description: string
+ icon: string
+ enabled: boolean
+}
+
+interface AddonIconProps {
+ name: string
+ size?: number
+}
+
+function AddonIcon({ name, size = 20 }: AddonIconProps) {
const Icon = ICON_MAP[name] || Puzzle
return <Icon size={size} />
}
@@ -31,7 +44,7 @@ export default function AddonManager() {
try {
const data = await adminApi.addons()
setAddons(data.addons)
- } catch (err) {
+ } catch (err: unknown) {
toast.error(t('admin.addons.toast.error'))
} finally {
setLoading(false)
@@ -46,7 +59,7 @@ export default function AddonManager() {
await adminApi.updateAddon(addon.id, { enabled: newEnabled })
window.dispatchEvent(new Event('addons-changed'))
toast.success(t('admin.addons.toast.updated'))
- } catch (err) {
+ } catch (err: unknown) {
// Rollback
setAddons(prev => prev.map(a => a.id === addon.id ? { ...a, enabled: !newEnabled } : a))
toast.error(t('admin.addons.toast.error'))
@@ -117,7 +130,13 @@ export default function AddonManager() {
)
}
-function AddonRow({ addon, onToggle, t }) {
+interface AddonRowProps {
+ addon: Addon
+ onToggle: (addonId: string) => void
+ t: (key: string) => string
+}
+
+function AddonRow({ addon, onToggle, t }: AddonRowProps) {
const isComingSoon = false
return (
<div className="flex items-center gap-4 px-6 py-4 border-b transition-colors hover:opacity-95" style={{ borderColor: 'var(--border-secondary)', opacity: isComingSoon ? 0.5 : 1, pointerEvents: isComingSoon ? 'none' : 'auto' }}>
diff --git a/client/src/components/Admin/BackupPanel.jsx b/client/src/components/Admin/BackupPanel.tsx
similarity index 98%
rename from client/src/components/Admin/BackupPanel.jsx
rename to client/src/components/Admin/BackupPanel.tsx
index 84ec57adf..89af8983d 100644
--- a/client/src/components/Admin/BackupPanel.jsx
+++ b/client/src/components/Admin/BackupPanel.tsx
@@ -1,8 +1,9 @@
-import React, { useState, useEffect, useRef } from 'react'
+import { useState, useEffect, useRef } from 'react'
import { backupApi } from '../../api/client'
import { useToast } from '../shared/Toast'
import { Download, Trash2, Plus, RefreshCw, RotateCcw, Upload, Clock, Check, HardDrive, AlertTriangle } from 'lucide-react'
import { useTranslation } from '../../i18n'
+import { getApiErrorMessage } from '../../types'
const INTERVAL_OPTIONS = [
{ value: 'hourly', labelKey: 'backup.interval.hourly' },
@@ -73,7 +74,7 @@ export default function BackupPanel() {
}
const handleUploadRestore = (e) => {
- const file = e.target.files?.[0]
+ const file = (e.target as HTMLInputElement).files?.[0]
if (!file) return
e.target.value = ''
setRestoreConfirm({ type: 'upload', filename: file.name, file })
@@ -90,8 +91,8 @@ export default function BackupPanel() {
await backupApi.restore(filename)
toast.success(t('backup.toast.restored'))
setTimeout(() => window.location.reload(), 1500)
- } catch (err) {
- toast.error(err.response?.data?.error || t('backup.toast.restoreError'))
+ } catch (err: unknown) {
+ toast.error(getApiErrorMessage(err, t('backup.toast.restoreError')))
setRestoringFile(null)
}
} else {
@@ -100,8 +101,8 @@ export default function BackupPanel() {
await backupApi.uploadRestore(file)
toast.success(t('backup.toast.restored'))
setTimeout(() => window.location.reload(), 1500)
- } catch (err) {
- toast.error(err.response?.data?.error || t('backup.toast.uploadError'))
+ } catch (err: unknown) {
+ toast.error(getApiErrorMessage(err, t('backup.toast.uploadError')))
setIsUploading(false)
}
}
diff --git a/client/src/components/Admin/CategoryManager.jsx b/client/src/components/Admin/CategoryManager.tsx
similarity index 96%
rename from client/src/components/Admin/CategoryManager.jsx
rename to client/src/components/Admin/CategoryManager.tsx
index 7b0ad8979..8857f7d22 100644
--- a/client/src/components/Admin/CategoryManager.jsx
+++ b/client/src/components/Admin/CategoryManager.tsx
@@ -1,9 +1,10 @@
-import React, { useState, useEffect, useRef } from 'react'
+import { useState, useEffect, useRef } from 'react'
import { categoriesApi } from '../../api/client'
import { useToast } from '../shared/Toast'
import { Plus, Edit2, Trash2, Pipette } from 'lucide-react'
import { CATEGORY_ICON_MAP, ICON_LABELS, getCategoryIcon } from '../shared/categoryIcons'
import { useTranslation } from '../../i18n'
+import { getApiErrorMessage } from '../../types'
const PRESET_COLORS = [
'#6366f1', '#8b5cf6', '#ec4899', '#ef4444', '#f97316',
@@ -31,7 +32,7 @@ export default function CategoryManager() {
try {
const data = await categoriesApi.list()
setCategories(data.categories || [])
- } catch (err) {
+ } catch (err: unknown) {
toast.error(t('categories.toast.loadError'))
} finally {
setIsLoading(false)
@@ -71,8 +72,8 @@ export default function CategoryManager() {
toast.success(t('categories.toast.created'))
}
setForm({ name: '', color: '#6366f1', icon: 'MapPin' })
- } catch (err) {
- toast.error(err.response?.data?.error || t('categories.toast.saveError'))
+ } catch (err: unknown) {
+ toast.error(getApiErrorMessage(err, t('categories.toast.saveError')))
} finally {
setIsSaving(false)
}
@@ -84,8 +85,8 @@ export default function CategoryManager() {
await categoriesApi.delete(id)
setCategories(prev => prev.filter(c => c.id !== id))
toast.success(t('categories.toast.deleted'))
- } catch (err) {
- toast.error(err.response?.data?.error || t('categories.toast.deleteError'))
+ } catch (err: unknown) {
+ toast.error(getApiErrorMessage(err, t('categories.toast.deleteError')))
}
}
diff --git a/client/src/components/Admin/GitHubPanel.jsx b/client/src/components/Admin/GitHubPanel.tsx
similarity index 98%
rename from client/src/components/Admin/GitHubPanel.jsx
rename to client/src/components/Admin/GitHubPanel.tsx
index ea24e30f4..492a0f3fb 100644
--- a/client/src/components/Admin/GitHubPanel.jsx
+++ b/client/src/components/Admin/GitHubPanel.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from 'react'
+import { useState, useEffect } from 'react'
import { Tag, Calendar, ExternalLink, ChevronDown, ChevronUp, Loader2 } from 'lucide-react'
import { useTranslation } from '../../i18n'
@@ -22,8 +22,8 @@ export default function GitHubPanel() {
const data = await res.json()
setReleases(prev => append ? [...prev, ...data] : data)
setHasMore(data.length === PER_PAGE)
- } catch (err) {
- setError(err.message)
+ } catch (err: unknown) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
}
}
diff --git a/client/src/components/Budget/BudgetPanel.jsx b/client/src/components/Budget/BudgetPanel.tsx
similarity index 95%
rename from client/src/components/Budget/BudgetPanel.jsx
rename to client/src/components/Budget/BudgetPanel.tsx
index e5dbb0c62..db34077da 100644
--- a/client/src/components/Budget/BudgetPanel.jsx
+++ b/client/src/components/Budget/BudgetPanel.tsx
@@ -1,10 +1,31 @@
-import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react'
import ReactDOM from 'react-dom'
+import { useState, useEffect, useRef, useMemo, useCallback } from 'react'
+import DOM from 'react-dom'
import { useTripStore } from '../../store/tripStore'
import { useTranslation } from '../../i18n'
import { Plus, Trash2, Calculator, Wallet, Pencil, Users, Check } from 'lucide-react'
import CustomSelect from '../shared/CustomSelect'
import { budgetApi } from '../../api/client'
+import type { BudgetItem, BudgetMember } from '../../types'
+
+interface TripMember {
+ id: number
+ username: string
+ avatar_url?: string | null
+}
+
+interface PieSegment {
+ label: string
+ value: number
+ color: string
+}
+
+interface PerPersonSummaryEntry {
+ user_id: number
+ username: string
+ avatar_url: string | null
+ total_assigned: number
+}
// ── Helpers ──────────────────────────────────────────────────────────────────
const CURRENCIES = ['EUR', 'USD', 'GBP', 'JPY', 'CHF', 'CZK', 'PLN', 'SEK', 'NOK', 'DKK', 'TRY', 'THB', 'AUD', 'CAD']
@@ -60,7 +81,12 @@ function InlineEditCell({ value, onSave, type = 'text', style = {}, placeholder
}
// ── Add Item Row ─────────────────────────────────────────────────────────────
-function AddItemRow({ onAdd, t }) {
+interface AddItemRowProps {
+ onAdd: (data: { name: string; total_price: number; persons: number | null; days: number | null; note: string | null }) => void
+ t: (key: string) => string
+}
+
+function AddItemRow({ onAdd, t }: AddItemRowProps) {
const [name, setName] = useState('')
const [price, setPrice] = useState('')
const [persons, setPersons] = useState('')
@@ -113,7 +139,13 @@ function AddItemRow({ onAdd, t }) {
}
// ── Chip with custom tooltip ─────────────────────────────────────────────────
-function ChipWithTooltip({ label, avatarUrl, size = 20 }) {
+interface ChipWithTooltipProps {
+ label: string
+ avatarUrl: string | null
+ size?: number
+}
+
+function ChipWithTooltip({ label, avatarUrl, size = 20 }: ChipWithTooltipProps) {
const [hover, setHover] = useState(false)
const [pos, setPos] = useState({ top: 0, left: 0 })
const ref = useRef(null)
@@ -156,7 +188,14 @@ function ChipWithTooltip({ label, avatarUrl, size = 20 }) {
}
// ── Budget Member Chips (for Persons column) ────────────────────────────────
-function BudgetMemberChips({ members = [], tripMembers = [], onSetMembers, compact = true }) {
+interface BudgetMemberChipsProps {
+ members?: BudgetMember[]
+ tripMembers?: TripMember[]
+ onSetMembers: (memberIds: number[]) => void
+ compact?: boolean
+}
+
+function BudgetMemberChips({ members = [], tripMembers = [], onSetMembers, compact = true }: BudgetMemberChipsProps) {
const chipSize = compact ? 20 : 30
const btnSize = compact ? 18 : 28
const iconSize = compact ? (members.length > 0 ? 8 : 9) : (members.length > 0 ? 12 : 14)
@@ -246,7 +285,14 @@ function BudgetMemberChips({ members = [], tripMembers = [], onSetMembers, compa
}
// ── Per-Person Inline (inside total card) ────────────────────────────────────
-function PerPersonInline({ tripId, budgetItems, currency, locale }) {
+interface PerPersonInlineProps {
+ tripId: number
+ budgetItems: BudgetItem[]
+ currency: string
+ locale: string
+}
+
+function PerPersonInline({ tripId, budgetItems, currency, locale }: PerPersonInlineProps) {
const [data, setData] = useState(null)
const fmt = (v) => fmtNum(v, locale, currency)
@@ -279,7 +325,13 @@ function PerPersonInline({ tripId, budgetItems, currency, locale }) {
}
// ── Pie Chart (pure CSS conic-gradient) ──────────────────────────────────────
-function PieChart({ segments, size = 200, totalLabel }) {
+interface PieChartProps {
+ segments: PieSegment[]
+ size?: number
+ totalLabel: string
+}
+
+function PieChart({ segments, size = 200, totalLabel }: PieChartProps) {
if (!segments.length) return null
const total = segments.reduce((s, x) => s + x.value, 0)
@@ -316,7 +368,12 @@ function PieChart({ segments, size = 200, totalLabel }) {
}
// ── Main Component ───────────────────────────────────────────────────────────
-export default function BudgetPanel({ tripId, tripMembers = [] }) {
+interface BudgetPanelProps {
+ tripId: number
+ tripMembers?: TripMember[]
+}
+
+export default function BudgetPanel({ tripId, tripMembers = [] }: BudgetPanelProps) {
const { trip, budgetItems, addBudgetItem, updateBudgetItem, deleteBudgetItem, loadBudgetItems, updateTrip, setBudgetItemMembers } = useTripStore()
const { t, locale } = useTranslation()
const [newCategoryName, setNewCategoryName] = useState('')
@@ -355,12 +412,12 @@ export default function BudgetPanel({ tripId, tripMembers = [] }) {
const handleDeleteItem = async (id) => { try { await deleteBudgetItem(tripId, id) } catch {} }
const handleDeleteCategory = async (cat) => {
const items = grouped[cat] || []
- for (const item of items) await deleteBudgetItem(tripId, item.id)
+ for (const item of Array.from(items)) await deleteBudgetItem(tripId, item.id)
}
const handleRenameCategory = async (oldName, newName) => {
if (!newName.trim() || newName.trim() === oldName) return
const items = grouped[oldName] || []
- for (const item of items) await updateBudgetItem(tripId, item.id, { category: newName.trim() })
+ for (const item of Array.from(items)) await updateBudgetItem(tripId, item.id, { category: newName.trim() })
}
const handleAddCategory = () => {
if (!newCategoryName.trim()) return
diff --git a/client/src/components/Collab/CollabChat.jsx b/client/src/components/Collab/CollabChat.tsx
similarity index 96%
rename from client/src/components/Collab/CollabChat.jsx
rename to client/src/components/Collab/CollabChat.tsx
index 45c2efd39..9528547d2 100644
--- a/client/src/components/Collab/CollabChat.jsx
+++ b/client/src/components/Collab/CollabChat.tsx
@@ -5,6 +5,25 @@ import { collabApi } from '../../api/client'
import { useSettingsStore } from '../../store/settingsStore'
import { addListener, removeListener } from '../../api/websocket'
import { useTranslation } from '../../i18n'
+import type { User } from '../../types'
+
+interface ChatReaction {
+ emoji: string
+ count: number
+ users: { id: number; username: string }[]
+}
+
+interface ChatMessage {
+ id: number
+ trip_id: number
+ user_id: number
+ text: string
+ reply_to_id: number | null
+ reactions: ChatReaction[]
+ created_at: string
+ user?: { username: string; avatar_url: string | null }
+ reply_to?: ChatMessage | null
+}
// ── Twemoji helper (Apple-style emojis via CDN) ──
function emojiToCodepoint(emoji) {
@@ -75,7 +94,14 @@ function shouldShowDateSeparator(msg, prevMsg) {
}
/* ── Emoji Picker ── */
-function EmojiPicker({ onSelect, onClose, anchorRef, containerRef }) {
+interface EmojiPickerProps {
+ onSelect: (emoji: string) => void
+ onClose: () => void
+ anchorRef: React.RefObject<HTMLElement | null>
+ containerRef: React.RefObject<HTMLElement | null>
+}
+
+function EmojiPicker({ onSelect, onClose, anchorRef, containerRef }: EmojiPickerProps) {
const [cat, setCat] = useState(Object.keys(EMOJI_CATEGORIES)[0])
const ref = useRef(null)
@@ -142,7 +168,14 @@ function EmojiPicker({ onSelect, onClose, anchorRef, containerRef }) {
/* ── Reaction Quick Menu (right-click) ── */
const QUICK_REACTIONS = ['❤️', '😂', '👍', '😮', '😢', '🔥', '👏', '🎉']
-function ReactionMenu({ x, y, onReact, onClose }) {
+interface ReactionMenuProps {
+ x: number
+ y: number
+ onReact: (emoji: string) => void
+ onClose: () => void
+}
+
+function ReactionMenu({ x, y, onReact, onClose }: ReactionMenuProps) {
const ref = useRef(null)
useEffect(() => {
@@ -179,7 +212,11 @@ function ReactionMenu({ x, y, onReact, onClose }) {
}
/* ── Message Text with clickable URLs ── */
-function MessageText({ text }) {
+interface MessageTextProps {
+ text: string
+}
+
+function MessageText({ text }: MessageTextProps) {
const parts = text.split(URL_REGEX)
const urls = text.match(URL_REGEX) || []
const result = []
@@ -198,7 +235,14 @@ function MessageText({ text }) {
const URL_REGEX = /https?:\/\/[^\s<>"']+/g
const previewCache = {}
-function LinkPreview({ url, tripId, own, onLoad }) {
+interface LinkPreviewProps {
+ url: string
+ tripId: number
+ own: boolean
+ onLoad: (() => void) | undefined
+}
+
+function LinkPreview({ url, tripId, own, onLoad }: LinkPreviewProps) {
const [data, setData] = useState(previewCache[url] || null)
const [loading, setLoading] = useState(!previewCache[url])
@@ -252,7 +296,13 @@ function LinkPreview({ url, tripId, own, onLoad }) {
}
/* ── Reaction Badge with NOMAD tooltip ── */
-function ReactionBadge({ reaction, currentUserId, onReact }) {
+interface ReactionBadgeProps {
+ reaction: ChatReaction
+ currentUserId: number
+ onReact: () => void
+}
+
+function ReactionBadge({ reaction, currentUserId, onReact }: ReactionBadgeProps) {
const [hover, setHover] = useState(false)
const [pos, setPos] = useState({ top: 0, left: 0 })
const ref = useRef(null)
@@ -295,7 +345,12 @@ function ReactionBadge({ reaction, currentUserId, onReact }) {
}
/* ── Main Component ── */
-export default function CollabChat({ tripId, currentUser }) {
+interface CollabChatProps {
+ tripId: number
+ currentUser: User
+}
+
+export default function CollabChat({ tripId, currentUser }: CollabChatProps) {
const { t } = useTranslation()
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
diff --git a/client/src/components/Collab/CollabNotes.jsx b/client/src/components/Collab/CollabNotes.tsx
similarity index 94%
rename from client/src/components/Collab/CollabNotes.jsx
rename to client/src/components/Collab/CollabNotes.tsx
index 8423a8c89..ea78eb160 100644
--- a/client/src/components/Collab/CollabNotes.jsx
+++ b/client/src/components/Collab/CollabNotes.tsx
@@ -1,16 +1,56 @@
-import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react'
import ReactDOM from 'react-dom'
+import { useState, useEffect, useCallback, useRef, useMemo } from 'react'
+import DOM from 'react-dom'
import { Plus, Trash2, Pin, PinOff, Pencil, X, Check, StickyNote, Settings, ExternalLink } from 'lucide-react'
import { collabApi } from '../../api/client'
import { addListener, removeListener } from '../../api/websocket'
import { useTranslation } from '../../i18n'
+import type { User } from '../../types'
+
+interface NoteFile {
+ id: number
+ filename: string
+ original_name: string
+ mime_type: string
+ url?: string
+}
+
+interface CollabNote {
+ id: number
+ trip_id: number
+ title: string
+ content: string
+ category: string
+ website: string | null
+ pinned: boolean
+ color: string | null
+ username: string
+ avatar_url: string | null
+ avatar: string | null
+ user_id: number
+ created_at: string
+ author?: { username: string; avatar: string | null }
+ user?: { username: string; avatar: string | null }
+ files?: NoteFile[]
+}
+
+interface NoteAuthor {
+ username: string
+ avatar?: string | null
+}
const FONT = "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif"
// ── Website Thumbnail (fetches OG image) ────────────────────────────────────
const ogCache = {}
-function WebsiteThumbnail({ url, tripId, color }) {
+interface WebsiteThumbnailProps {
+ url: string
+ tripId: number
+ color: string
+}
+
+function WebsiteThumbnail({ url, tripId, color }: WebsiteThumbnailProps) {
const [data, setData] = useState(ogCache[url] || null)
const [failed, setFailed] = useState(false)
@@ -46,7 +86,12 @@ function WebsiteThumbnail({ url, tripId, color }) {
}
// ── File Preview Portal ─────────────────────────────────────────────────────
-function FilePreviewPortal({ file, onClose }) {
+interface FilePreviewPortalProps {
+ file: NoteFile | null
+ onClose: () => void
+}
+
+function FilePreviewPortal({ file, onClose }: FilePreviewPortalProps) {
if (!file) return null
const url = file.url || `/uploads/${file.filename}`
const isImage = file.mime_type?.startsWith('image/')
@@ -120,7 +165,12 @@ const formatTimestamp = (ts, t, locale) => {
}
// ── Avatar ──────────────────────────────────────────────────────────────────
-function UserAvatar({ user, size = 14 }) {
+interface UserAvatarProps {
+ user: NoteAuthor | null
+ size?: number
+}
+
+function UserAvatar({ user, size = 14 }: UserAvatarProps) {
if (!user) return null
if (user.avatar) {
return (
@@ -161,7 +211,19 @@ function UserAvatar({ user, size = 14 }) {
}
// ── New Note Modal (portal to body) ─────────────────────────────────────────
-function NoteFormModal({ onClose, onSubmit, onDeleteFile, existingCategories, categoryColors, getCategoryColor, note, tripId, t }) {
+interface NoteFormModalProps {
+ onClose: () => void
+ onSubmit: (data: { title: string; content: string; category: string; website: string; files?: File[] }) => Promise<void>
+ onDeleteFile: (noteId: number, fileId: number) => Promise<void>
+ existingCategories: string[]
+ categoryColors: Record<string, string>
+ getCategoryColor: (category: string) => string
+ note: CollabNote | null
+ tripId: number
+ t: (key: string) => string
+}
+
+function NoteFormModal({ onClose, onSubmit, onDeleteFile, existingCategories, categoryColors, getCategoryColor, note, tripId, t }: NoteFormModalProps) {
const isEdit = !!note
const allCategories = [...new Set([...existingCategories, ...Object.keys(categoryColors || {})])].filter(Boolean)
@@ -236,7 +298,7 @@ function NoteFormModal({ onClose, onSubmit, onDeleteFile, existingCategories, ca
onPaste={e => {
const items = e.clipboardData?.items
if (!items) return
- for (const item of items) {
+ for (const item of Array.from(items)) {
if (item.type.startsWith('image/') || item.type === 'application/pdf') {
e.preventDefault()
const file = item.getAsFile()
@@ -390,7 +452,7 @@ function NoteFormModal({ onClose, onSubmit, onDeleteFile, existingCategories, ca
<div style={{ fontSize: 9, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4, fontFamily: FONT }}>
{t('collab.notes.attachFiles')}
</div>
- <input id="note-file-input" ref={fileRef} type="file" multiple style={{ display: 'none' }} onChange={e => { setPendingFiles(prev => [...prev, ...Array.from(e.target.files)]); e.target.value = '' }} />
+ <input id="note-file-input" ref={fileRef} type="file" multiple style={{ display: 'none' }} onChange={e => { setPendingFiles(prev => [...prev, ...Array.from((e.target as HTMLInputElement).files)]); e.target.value = '' }} />
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
{/* Existing attachments (edit mode) */}
{existingAttachments.map(a => {
@@ -448,7 +510,12 @@ function NoteFormModal({ onClose, onSubmit, onDeleteFile, existingCategories, ca
)
}
-function EditableCatName({ name, onRename }) {
+interface EditableCatNameProps {
+ name: string
+ onRename: (newName: string) => void
+}
+
+function EditableCatName({ name, onRename }: EditableCatNameProps) {
const [editing, setEditing] = useState(false)
const [value, setValue] = useState(name)
const inputRef = useRef(null)
@@ -477,7 +544,16 @@ function EditableCatName({ name, onRename }) {
}
// ── Category Settings Modal ──────────────────────────────────────────────────
-function CategorySettingsModal({ onClose, categories, categoryColors, onSave, onRenameCategory, t }) {
+interface CategorySettingsModalProps {
+ onClose: () => void
+ categories: string[]
+ categoryColors: Record<string, string>
+ onSave: (colors: Record<string, string>) => void
+ onRenameCategory: (oldName: string, newName: string) => Promise<void>
+ t: (key: string) => string
+}
+
+function CategorySettingsModal({ onClose, categories, categoryColors, onSave, onRenameCategory, t }: CategorySettingsModalProps) {
const [localColors, setLocalColors] = useState({ ...categoryColors })
const [renames, setRenames] = useState({}) // { oldName: newName }
const [newCatName, setNewCatName] = useState('')
@@ -608,7 +684,19 @@ function CategorySettingsModal({ onClose, categories, categoryColors, onSave, on
}
// ── Note Card ───────────────────────────────────────────────────────────────
-function NoteCard({ note, currentUser, onUpdate, onDelete, onEdit, onPreviewFile, getCategoryColor, tripId, t }) {
+interface NoteCardProps {
+ note: CollabNote
+ currentUser: User
+ onUpdate: (noteId: number, data: Partial<CollabNote>) => Promise<void>
+ onDelete: (noteId: number) => Promise<void>
+ onEdit: (note: CollabNote) => void
+ onPreviewFile: (file: NoteFile) => void
+ getCategoryColor: (category: string) => string
+ tripId: number
+ t: (key: string) => string
+}
+
+function NoteCard({ note, currentUser, onUpdate, onDelete, onEdit, onPreviewFile, getCategoryColor, tripId, t }: NoteCardProps) {
const [hovered, setHovered] = useState(false)
const author = note.author || note.user || { username: note.username, avatar: note.avatar_url || (note.avatar ? `/uploads/avatars/${note.avatar}` : null) }
@@ -773,7 +861,12 @@ function NoteCard({ note, currentUser, onUpdate, onDelete, onEdit, onPreviewFile
}
// ── Main Component ──────────────────────────────────────────────────────────
-export default function CollabNotes({ tripId, currentUser }) {
+interface CollabNotesProps {
+ tripId: number
+ currentUser: User
+}
+
+export default function CollabNotes({ tripId, currentUser }: CollabNotesProps) {
const { t } = useTranslation()
const [notes, setNotes] = useState([])
const [loading, setLoading] = useState(true)
diff --git a/client/src/components/Collab/CollabPanel.jsx b/client/src/components/Collab/CollabPanel.tsx
similarity index 94%
rename from client/src/components/Collab/CollabPanel.jsx
rename to client/src/components/Collab/CollabPanel.tsx
index c640c1755..e67dd825d 100644
--- a/client/src/components/Collab/CollabPanel.jsx
+++ b/client/src/components/Collab/CollabPanel.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from 'react'
+import { useState, useEffect } from 'react'
import { useAuthStore } from '../../store/authStore'
import { useTranslation } from '../../i18n'
import { MessageCircle, StickyNote, BarChart3, Sparkles } from 'lucide-react'
@@ -23,7 +23,18 @@ const card = {
overflow: 'hidden', minHeight: 0,
}
-export default function CollabPanel({ tripId, tripMembers = [] }) {
+interface TripMember {
+ id: number
+ username: string
+ avatar_url?: string | null
+}
+
+interface CollabPanelProps {
+ tripId: number
+ tripMembers?: TripMember[]
+}
+
+export default function CollabPanel({ tripId, tripMembers = [] }: CollabPanelProps) {
const { user } = useAuthStore()
const { t } = useTranslation()
const [mobileTab, setMobileTab] = useState('chat')
diff --git a/client/src/components/Collab/CollabPolls.jsx b/client/src/components/Collab/CollabPolls.tsx
similarity index 94%
rename from client/src/components/Collab/CollabPolls.jsx
rename to client/src/components/Collab/CollabPolls.tsx
index fff4d72bb..66083efd6 100644
--- a/client/src/components/Collab/CollabPolls.jsx
+++ b/client/src/components/Collab/CollabPolls.tsx
@@ -4,6 +4,30 @@ import { collabApi } from '../../api/client'
import { addListener, removeListener } from '../../api/websocket'
import { useTranslation } from '../../i18n'
import ReactDOM from 'react-dom'
+import type { User } from '../../types'
+
+interface PollVoter {
+ user_id: number
+ username: string
+ avatar_url: string | null
+}
+
+interface PollOption {
+ id: number
+ text: string
+ voters: PollVoter[]
+}
+
+interface Poll {
+ id: number
+ question: string
+ options: PollOption[]
+ multi_choice: boolean
+ is_closed: boolean
+ deadline: string | null
+ created_by: number
+ created_at: string
+}
const FONT = "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif"
@@ -29,7 +53,13 @@ function totalVotes(poll) {
}
// ── Create Poll Modal ────────────────────────────────────────────────────────
-function CreatePollModal({ onClose, onCreate, t }) {
+interface CreatePollModalProps {
+ onClose: () => void
+ onCreate: (data: { question: string; options: string[]; multi_choice: boolean }) => Promise<void>
+ t: (key: string) => string
+}
+
+function CreatePollModal({ onClose, onCreate, t }: CreatePollModalProps) {
const [question, setQuestion] = useState('')
const [options, setOptions] = useState(['', ''])
const [multiChoice, setMultiChoice] = useState(false)
@@ -111,7 +141,12 @@ function CreatePollModal({ onClose, onCreate, t }) {
}
// ── Voter Chip with custom tooltip ────────────────────────────────────────────
-function VoterChip({ voter, offset }) {
+interface VoterChipProps {
+ voter: PollVoter
+ offset: boolean
+}
+
+function VoterChip({ voter, offset }: VoterChipProps) {
const [hover, setHover] = useState(false)
const ref = React.useRef(null)
const [pos, setPos] = useState({ top: 0, left: 0 })
@@ -152,7 +187,16 @@ function VoterChip({ voter, offset }) {
}
// ── Poll Card ────────────────────────────────────────────────────────────────
-function PollCard({ poll, currentUser, onVote, onClose, onDelete, t }) {
+interface PollCardProps {
+ poll: Poll
+ currentUser: User
+ onVote: (pollId: number, optionId: number) => Promise<void>
+ onClose: (pollId: number) => Promise<void>
+ onDelete: (pollId: number) => Promise<void>
+ t: (key: string) => string
+}
+
+function PollCard({ poll, currentUser, onVote, onClose, onDelete, t }: PollCardProps) {
const total = totalVotes(poll)
const isClosed = poll.is_closed || isExpired(poll.deadline)
const remaining = timeRemaining(poll.deadline)
@@ -286,7 +330,12 @@ function PollCard({ poll, currentUser, onVote, onClose, onDelete, t }) {
}
// ── Main Component ───────────────────────────────────────────────────────────
-export default function CollabPolls({ tripId, currentUser }) {
+interface CollabPollsProps {
+ tripId: number
+ currentUser: User
+}
+
+export default function CollabPolls({ tripId, currentUser }: CollabPollsProps) {
const { t } = useTranslation()
const [polls, setPolls] = useState([])
const [loading, setLoading] = useState(true)
diff --git a/client/src/components/Collab/WhatsNextWidget.jsx b/client/src/components/Collab/WhatsNextWidget.tsx
similarity index 97%
rename from client/src/components/Collab/WhatsNextWidget.jsx
rename to client/src/components/Collab/WhatsNextWidget.tsx
index 411483de9..6ad678df3 100644
--- a/client/src/components/Collab/WhatsNextWidget.jsx
+++ b/client/src/components/Collab/WhatsNextWidget.tsx
@@ -26,7 +26,17 @@ function formatDayLabel(date, t, locale) {
return d.toLocaleDateString(locale || undefined, { weekday: 'short', day: 'numeric', month: 'short' })
}
-export default function WhatsNextWidget({ tripMembers = [] }) {
+interface TripMember {
+ id: number
+ username: string
+ avatar_url?: string | null
+}
+
+interface WhatsNextWidgetProps {
+ tripMembers?: TripMember[]
+}
+
+export default function WhatsNextWidget({ tripMembers = [] }: WhatsNextWidgetProps) {
const { days, assignments } = useTripStore()
const { t, locale } = useTranslation()
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
diff --git a/client/src/components/Dashboard/CurrencyWidget.jsx b/client/src/components/Dashboard/CurrencyWidget.tsx
similarity index 98%
rename from client/src/components/Dashboard/CurrencyWidget.jsx
rename to client/src/components/Dashboard/CurrencyWidget.tsx
index 0b3f2441e..a9a648d01 100644
--- a/client/src/components/Dashboard/CurrencyWidget.jsx
+++ b/client/src/components/Dashboard/CurrencyWidget.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect, useCallback } from 'react'
+import { useState, useEffect, useCallback } from 'react'
import { ArrowRightLeft, RefreshCw } from 'lucide-react'
import { useTranslation } from '../../i18n'
import CustomSelect from '../shared/CustomSelect'
diff --git a/client/src/components/Dashboard/TimezoneWidget.jsx b/client/src/components/Dashboard/TimezoneWidget.tsx
similarity index 99%
rename from client/src/components/Dashboard/TimezoneWidget.jsx
rename to client/src/components/Dashboard/TimezoneWidget.tsx
index b1694c459..70ffff4f4 100644
--- a/client/src/components/Dashboard/TimezoneWidget.jsx
+++ b/client/src/components/Dashboard/TimezoneWidget.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from 'react'
+import { useState, useEffect } from 'react'
import { Clock, Plus, X } from 'lucide-react'
import { useTranslation } from '../../i18n'
diff --git a/client/src/components/Dashboard/TravelStats.jsx b/client/src/components/Dashboard/TravelStats.jsx
deleted file mode 100644
index 4a7845ef3..000000000
--- a/client/src/components/Dashboard/TravelStats.jsx
+++ /dev/null
@@ -1,194 +0,0 @@
-import React, { useState, useEffect, useMemo, useRef } from 'react'
-import { Globe, MapPin, Plane } from 'lucide-react'
-import { authApi } from '../../api/client'
-import { useTranslation } from '../../i18n'
-import { useSettingsStore } from '../../store/settingsStore'
-
-// Numeric ISO → country name lookup (countries-110m uses numeric IDs)
-const NUMERIC_TO_NAME = {"004":"Afghanistan","008":"Albania","012":"Algeria","024":"Angola","032":"Argentina","036":"Australia","040":"Austria","050":"Bangladesh","056":"Belgium","064":"Bhutan","068":"Bolivia","070":"Bosnia and Herzegovina","072":"Botswana","076":"Brazil","100":"Bulgaria","104":"Myanmar","108":"Burundi","112":"Belarus","116":"Cambodia","120":"Cameroon","124":"Canada","140":"Central African Republic","144":"Sri Lanka","148":"Chad","152":"Chile","156":"China","170":"Colombia","178":"Congo","180":"Democratic Republic of the Congo","188":"Costa Rica","191":"Croatia","192":"Cuba","196":"Cyprus","203":"Czech Republic","204":"Benin","208":"Denmark","214":"Dominican Republic","218":"Ecuador","818":"Egypt","222":"El Salvador","226":"Equatorial Guinea","232":"Eritrea","233":"Estonia","231":"Ethiopia","238":"Falkland Islands","246":"Finland","250":"France","266":"Gabon","270":"Gambia","268":"Georgia","276":"Germany","288":"Ghana","300":"Greece","320":"Guatemala","324":"Guinea","328":"Guyana","332":"Haiti","340":"Honduras","348":"Hungary","352":"Iceland","356":"India","360":"Indonesia","364":"Iran","368":"Iraq","372":"Ireland","376":"Israel","380":"Italy","384":"Ivory Coast","388":"Jamaica","392":"Japan","400":"Jordan","398":"Kazakhstan","404":"Kenya","408":"North Korea","410":"South Korea","414":"Kuwait","417":"Kyrgyzstan","418":"Laos","422":"Lebanon","426":"Lesotho","430":"Liberia","434":"Libya","440":"Lithuania","442":"Luxembourg","450":"Madagascar","454":"Malawi","458":"Malaysia","466":"Mali","478":"Mauritania","484":"Mexico","496":"Mongolia","498":"Moldova","504":"Morocco","508":"Mozambique","516":"Namibia","524":"Nepal","528":"Netherlands","540":"New Caledonia","554":"New Zealand","558":"Nicaragua","562":"Niger","566":"Nigeria","578":"Norway","512":"Oman","586":"Pakistan","591":"Panama","598":"Papua New Guinea","600":"Paraguay","604":"Peru","608":"Philippines","616":"Poland","620":"Portugal","630":"Puerto Rico","634":"Qatar","642":"Romania","643":"Russia","646":"Rwanda","682":"Saudi Arabia","686":"Senegal","688":"Serbia","694":"Sierra Leone","703":"Slovakia","705":"Slovenia","706":"Somalia","710":"South Africa","724":"Spain","729":"Sudan","740":"Suriname","748":"Swaziland","752":"Sweden","756":"Switzerland","760":"Syria","762":"Tajikistan","764":"Thailand","768":"Togo","780":"Trinidad and Tobago","788":"Tunisia","792":"Turkey","795":"Turkmenistan","800":"Uganda","804":"Ukraine","784":"United Arab Emirates","826":"United Kingdom","840":"United States of America","858":"Uruguay","860":"Uzbekistan","862":"Venezuela","704":"Vietnam","887":"Yemen","894":"Zambia","716":"Zimbabwe"}
-
-// Our country names from addresses → match against GeoJSON names
-function isCountryMatch(geoName, visitedCountries) {
- if (!geoName) return false
- const lower = geoName.toLowerCase()
- return visitedCountries.some(c => {
- const cl = c.toLowerCase()
- return lower === cl || lower.includes(cl) || cl.includes(lower)
- // Handle common mismatches
- || (cl === 'usa' && lower.includes('united states'))
- || (cl === 'uk' && lower === 'united kingdom')
- || (cl === 'south korea' && lower === 'korea' || lower === 'south korea')
- || (cl === 'deutschland' && lower === 'germany')
- || (cl === 'frankreich' && lower === 'france')
- || (cl === 'italien' && lower === 'italy')
- || (cl === 'spanien' && lower === 'spain')
- || (cl === 'österreich' && lower === 'austria')
- || (cl === 'schweiz' && lower === 'switzerland')
- || (cl === 'niederlande' && lower === 'netherlands')
- || (cl === 'türkei' && (lower === 'turkey' || lower === 'türkiye'))
- || (cl === 'griechenland' && lower === 'greece')
- || (cl === 'tschechien' && (lower === 'czech republic' || lower === 'czechia'))
- || (cl === 'ägypten' && lower === 'egypt')
- || (cl === 'südkorea' && lower.includes('korea'))
- || (cl === 'indien' && lower === 'india')
- || (cl === 'brasilien' && lower === 'brazil')
- || (cl === 'argentinien' && lower === 'argentina')
- || (cl === 'russland' && lower === 'russia')
- || (cl === 'australien' && lower === 'australia')
- || (cl === 'kanada' && lower === 'canada')
- || (cl === 'mexiko' && lower === 'mexico')
- || (cl === 'neuseeland' && lower === 'new zealand')
- || (cl === 'singapur' && lower === 'singapore')
- || (cl === 'kroatien' && lower === 'croatia')
- || (cl === 'ungarn' && lower === 'hungary')
- || (cl === 'rumänien' && lower === 'romania')
- || (cl === 'polen' && lower === 'poland')
- || (cl === 'schweden' && lower === 'sweden')
- || (cl === 'norwegen' && lower === 'norway')
- || (cl === 'dänemark' && lower === 'denmark')
- || (cl === 'finnland' && lower === 'finland')
- || (cl === 'irland' && lower === 'ireland')
- || (cl === 'portugal' && lower === 'portugal')
- || (cl === 'belgien' && lower === 'belgium')
- })
-}
-
-const TOTAL_COUNTRIES = 195
-
-// Simple Mercator projection for SVG
-function project(lon, lat, width, height) {
- const clampedLat = Math.max(-75, Math.min(83, lat))
- const x = ((lon + 180) / 360) * width
- const latRad = (clampedLat * Math.PI) / 180
- const mercN = Math.log(Math.tan(Math.PI / 4 + latRad / 2))
- const y = (height / 2) - (width * mercN) / (2 * Math.PI)
- return [x, y]
-}
-
-function geoToPath(coords, width, height) {
- return coords.map((ring) => {
- // Split ring at dateline crossings to avoid horizontal stripes
- const segments = [[]]
- for (let i = 0; i < ring.length; i++) {
- const [lon, lat] = ring[i]
- if (i > 0) {
- const prevLon = ring[i - 1][0]
- if (Math.abs(lon - prevLon) > 180) {
- // Dateline crossing — start new segment
- segments.push([])
- }
- }
- const [x, y] = project(lon, Math.max(-75, Math.min(83, lat)), width, height)
- segments[segments.length - 1].push(`${x.toFixed(1)},${y.toFixed(1)}`)
- }
- return segments
- .filter(s => s.length > 2)
- .map(s => 'M' + s.join('L') + 'Z')
- .join(' ')
- }).join(' ')
-}
-
-let geoJsonCache = null
-async function loadGeoJson() {
- if (geoJsonCache) return geoJsonCache
- try {
- const res = await fetch('https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json')
- const topo = await res.json()
- const { feature } = await import('topojson-client')
- const geo = feature(topo, topo.objects.countries)
- geo.features.forEach(f => {
- f.properties.name = NUMERIC_TO_NAME[f.id] || f.properties?.name || ''
- })
- geoJsonCache = geo
- return geo
- } catch { return null }
-}
-
-export default function TravelStats() {
- const { t } = useTranslation()
- const dm = useSettingsStore(s => s.settings.dark_mode)
- const dark = dm === true || dm === 'dark' || (dm === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)
- const [stats, setStats] = useState(null)
- const [geoData, setGeoData] = useState(null)
-
- useEffect(() => {
- authApi.travelStats().then(setStats).catch(() => {})
- loadGeoJson().then(setGeoData)
- }, [])
-
- const countryCount = stats?.countries?.length || 0
- const worldPercent = ((countryCount / TOTAL_COUNTRIES) * 100).toFixed(1)
-
- if (!stats || stats.totalPlaces === 0) return null
-
- return (
- <div style={{ width: 340 }}>
- {/* Stats Card */}
- <div style={{
- borderRadius: 20, overflow: 'hidden', height: 300,
- display: 'flex', flexDirection: 'column', justifyContent: 'center',
- border: '1px solid var(--border-primary)',
- background: 'var(--bg-card)',
- padding: 16,
- }}>
- {/* Progress bar */}
- <div style={{ marginBottom: 14 }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
- <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-secondary)' }}>{t('stats.worldProgress')}</span>
- <span style={{ fontSize: 20, fontWeight: 800, color: 'var(--text-primary)' }}>{worldPercent}%</span>
- </div>
- <div style={{ height: 6, borderRadius: 99, background: 'var(--bg-hover)', overflow: 'hidden' }}>
- <div style={{
- height: '100%', borderRadius: 99,
- background: dark ? 'linear-gradient(90deg, #e2e8f0, #cbd5e1)' : 'linear-gradient(90deg, #111827, #374151)',
- width: `${Math.max(1, parseFloat(worldPercent))}%`,
- transition: 'width 0.5s ease',
- }} />
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
- <span style={{ fontSize: 10, color: 'var(--text-faint)' }}>{countryCount} {t('stats.visited')}</span>
- <span style={{ fontSize: 10, color: 'var(--text-faint)' }}>{TOTAL_COUNTRIES - countryCount} {t('stats.remaining')}</span>
- </div>
- </div>
-
- {/* Stat grid */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14 }}>
- <StatBox icon={Globe} value={countryCount} label={t('stats.countries')} />
- <StatBox icon={MapPin} value={stats.cities.length} label={t('stats.cities')} />
- <StatBox icon={Plane} value={stats.totalTrips} label={t('stats.trips')} />
- <StatBox icon={MapPin} value={stats.totalPlaces} label={t('stats.places')} />
- </div>
-
- {/* Country tags */}
- {stats.countries.length > 0 && (
- <>
- <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-muted)', marginBottom: 6 }}>{t('stats.visitedCountries')}</div>
- <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
- {stats.countries.map(c => (
- <span key={c} style={{
- fontSize: 10.5, fontWeight: 500, color: 'var(--text-secondary)',
- background: 'var(--bg-hover)', borderRadius: 99, padding: '3px 9px',
- }}>{c}</span>
- ))}
- </div>
- </>
- )}
- </div>
- </div>
- )
-}
-
-function StatBox({ icon: Icon, value, label }) {
- return (
- <div style={{
- display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px',
- borderRadius: 10, background: 'var(--bg-hover)',
- }}>
- <Icon size={14} style={{ color: 'var(--text-faint)', flexShrink: 0 }} />
- <div>
- <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text-primary)', lineHeight: 1 }}>{value}</div>
- <div style={{ fontSize: 10, color: 'var(--text-faint)', marginTop: 1 }}>{label}</div>
- </div>
- </div>
- )
-}
diff --git a/client/src/components/Files/FileManager.jsx b/client/src/components/Files/FileManager.tsx
similarity index 95%
rename from client/src/components/Files/FileManager.jsx
rename to client/src/components/Files/FileManager.tsx
index e8c28d047..a30f26c2a 100644
--- a/client/src/components/Files/FileManager.jsx
+++ b/client/src/components/Files/FileManager.tsx
@@ -1,9 +1,11 @@
-import React, { useState, useCallback } from 'react'
import ReactDOM from 'react-dom'
+import { useState, useCallback } from 'react'
+import DOM from 'react-dom'
import { useDropzone } from 'react-dropzone'
import { Upload, Trash2, ExternalLink, X, FileText, FileImage, File, MapPin, Ticket, StickyNote } from 'lucide-react'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
+import type { Place, Reservation, TripFile } from '../../types'
function isImage(mimeType) {
if (!mimeType) return false
@@ -32,7 +34,12 @@ function formatDateWithLocale(dateStr, locale) {
}
// Image lightbox
-function ImageLightbox({ file, onClose }) {
+interface ImageLightboxProps {
+ file: TripFile & { url: string }
+ onClose: () => void
+}
+
+function ImageLightbox({ file, onClose }: ImageLightboxProps) {
const { t } = useTranslation()
return (
<div
@@ -62,7 +69,12 @@ function ImageLightbox({ file, onClose }) {
}
// Source badge — unified style for both place and reservation
-function SourceBadge({ icon: Icon, label }) {
+interface SourceBadgeProps {
+ icon: React.ComponentType<{ size?: number; style?: React.CSSProperties }>
+ label: string
+}
+
+function SourceBadge({ icon: Icon, label }: SourceBadgeProps) {
return (
<span style={{
display: 'inline-flex', alignItems: 'center', gap: 4,
@@ -77,7 +89,18 @@ function SourceBadge({ icon: Icon, label }) {
)
}
-export default function FileManager({ files = [], onUpload, onDelete, onUpdate, places, reservations = [], tripId, allowedFileTypes }) {
+interface FileManagerProps {
+ files?: TripFile[]
+ onUpload: (fd: FormData) => Promise<void>
+ onDelete: (fileId: number) => Promise<void>
+ onUpdate: (fileId: number, data: Partial<TripFile>) => Promise<void>
+ places: Place[]
+ reservations?: Reservation[]
+ tripId: number
+ allowedFileTypes: Record<string, string[]>
+}
+
+export default function FileManager({ files = [], onUpload, onDelete, onUpdate, places, reservations = [], tripId, allowedFileTypes }: FileManagerProps) {
const [uploading, setUploading] = useState(false)
const [filterType, setFilterType] = useState('all')
const [lightboxFile, setLightboxFile] = useState(null)
@@ -112,7 +135,7 @@ export default function FileManager({ files = [], onUpload, onDelete, onUpdate,
const items = e.clipboardData?.items
if (!items) return
const files = []
- for (const item of items) {
+ for (const item of Array.from(items)) {
if (item.kind === 'file') {
const file = item.getAsFile()
if (file) files.push(file)
diff --git a/client/src/components/Layout/DemoBanner.jsx b/client/src/components/Layout/DemoBanner.tsx
similarity index 93%
rename from client/src/components/Layout/DemoBanner.jsx
rename to client/src/components/Layout/DemoBanner.tsx
index 4c5983b4c..fcb49a73d 100644
--- a/client/src/components/Layout/DemoBanner.jsx
+++ b/client/src/components/Layout/DemoBanner.tsx
@@ -2,7 +2,26 @@ import React, { useState, useEffect } from 'react'
import { Info, Github, Shield, Key, Users, Database, Upload, Clock, Puzzle, CalendarDays, Globe, ArrowRightLeft, Map, Briefcase, ListChecks, Wallet, FileText, Plane } from 'lucide-react'
import { useTranslation } from '../../i18n'
-const texts = {
+interface DemoTexts {
+ titleBefore: string
+ titleAfter: string
+ title: string
+ description: string
+ resetIn: string
+ minutes: string
+ uploadNote: string
+ fullVersionTitle: string
+ features: string[]
+ addonsTitle: string
+ addons: [string, string][]
+ whatIs: string
+ whatIsDesc: string
+ selfHost: string
+ selfHostLink: string
+ close: string
+}
+
+const texts: Record<string, DemoTexts> = {
de: {
titleBefore: 'Willkommen bei ',
titleAfter: '',
@@ -72,9 +91,9 @@ const texts = {
const featureIcons = [Upload, Key, Users, Database, Puzzle, Shield]
const addonIcons = [CalendarDays, Globe, ListChecks, Wallet, FileText, ArrowRightLeft]
-export default function DemoBanner() {
- const [dismissed, setDismissed] = useState(false)
- const [minutesLeft, setMinutesLeft] = useState(59 - new Date().getMinutes())
+export default function DemoBanner(): React.ReactElement | null {
+ const [dismissed, setDismissed] = useState<boolean>(false)
+ const [minutesLeft, setMinutesLeft] = useState<number>(59 - new Date().getMinutes())
const { language } = useTranslation()
const t = texts[language] || texts.en
@@ -98,7 +117,7 @@ export default function DemoBanner() {
maxWidth: 480, width: '100%',
boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
maxHeight: '90vh', overflow: 'auto',
- }} onClick={e => e.stopPropagation()}>
+ }} onClick={(e: React.MouseEvent<HTMLDivElement>) => e.stopPropagation()}>
{/* Header */}
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
diff --git a/client/src/components/Layout/Navbar.jsx b/client/src/components/Layout/Navbar.tsx
similarity index 95%
rename from client/src/components/Layout/Navbar.jsx
rename to client/src/components/Layout/Navbar.tsx
index 5e6e2b055..c07d1599a 100644
--- a/client/src/components/Layout/Navbar.jsx
+++ b/client/src/components/Layout/Navbar.tsx
@@ -6,18 +6,34 @@ import { useSettingsStore } from '../../store/settingsStore'
import { useTranslation } from '../../i18n'
import { addonsApi } from '../../api/client'
import { Plane, LogOut, Settings, ChevronDown, Shield, ArrowLeft, Users, Moon, Sun, Monitor, CalendarDays, Briefcase, Globe } from 'lucide-react'
+import type { LucideIcon } from 'lucide-react'
-const ADDON_ICONS = { CalendarDays, Briefcase, Globe }
+const ADDON_ICONS: Record<string, LucideIcon> = { CalendarDays, Briefcase, Globe }
-export default function Navbar({ tripTitle, tripId, onBack, showBack, onShare }) {
+interface NavbarProps {
+ tripTitle?: string
+ tripId?: string
+ onBack?: () => void
+ showBack?: boolean
+ onShare?: () => void
+}
+
+interface Addon {
+ id: string
+ name: string
+ icon: string
+ type: string
+}
+
+export default function Navbar({ tripTitle, tripId, onBack, showBack, onShare }: NavbarProps): React.ReactElement {
const { user, logout } = useAuthStore()
const { settings, updateSetting } = useSettingsStore()
const { t, locale } = useTranslation()
const navigate = useNavigate()
const location = useLocation()
- const [userMenuOpen, setUserMenuOpen] = useState(false)
- const [appVersion, setAppVersion] = useState(null)
- const [globalAddons, setGlobalAddons] = useState([])
+ const [userMenuOpen, setUserMenuOpen] = useState<boolean>(false)
+ const [appVersion, setAppVersion] = useState<string | null>(null)
+ const [globalAddons, setGlobalAddons] = useState<Addon[]>([])
const darkMode = settings.dark_mode
const dark = darkMode === true || darkMode === 'dark' || (darkMode === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)
diff --git a/client/src/components/Map/MapView.jsx b/client/src/components/Map/MapView.tsx
similarity index 92%
rename from client/src/components/Map/MapView.jsx
rename to client/src/components/Map/MapView.tsx
index 1bac23e39..67439653d 100644
--- a/client/src/components/Map/MapView.jsx
+++ b/client/src/components/Map/MapView.tsx
@@ -1,5 +1,5 @@
-import React, { useEffect, useRef, useState, useMemo } from 'react'
-import ReactDOM from 'react-dom'
+import { useEffect, useRef, useState, useMemo } from 'react'
+import DOM from 'react-dom'
import { MapContainer, TileLayer, Marker, Tooltip, Polyline, useMap } from 'react-leaflet'
import MarkerClusterGroup from 'react-leaflet-cluster'
import L from 'leaflet'
@@ -7,6 +7,7 @@ import 'leaflet.markercluster/dist/MarkerCluster.css'
import 'leaflet.markercluster/dist/MarkerCluster.Default.css'
import { mapsApi } from '../../api/client'
import { getCategoryIcon } from '../shared/categoryIcons'
+import type { Place } from '../../types'
// Fix default marker icons for vite
delete L.Icon.Default.prototype._getIconUrl
@@ -93,7 +94,14 @@ function createPlaceIcon(place, orderNumbers, isSelected) {
})
}
-function SelectionController({ places, selectedPlaceId, dayPlaces, paddingOpts }) {
+interface SelectionControllerProps {
+ places: Place[]
+ selectedPlaceId: number | null
+ dayPlaces: Place[]
+ paddingOpts: Record<string, number>
+}
+
+function SelectionController({ places, selectedPlaceId, dayPlaces, paddingOpts }: SelectionControllerProps) {
const map = useMap()
const prev = useRef(null)
@@ -117,7 +125,12 @@ function SelectionController({ places, selectedPlaceId, dayPlaces, paddingOpts }
return null
}
-function MapController({ center, zoom }) {
+interface MapControllerProps {
+ center: [number, number]
+ zoom: number
+}
+
+function MapController({ center, zoom }: MapControllerProps) {
const map = useMap()
const prevCenter = useRef(center)
@@ -132,7 +145,13 @@ function MapController({ center, zoom }) {
}
// Fit bounds when places change (fitKey triggers re-fit)
-function BoundsController({ places, fitKey, paddingOpts }) {
+interface BoundsControllerProps {
+ places: Place[]
+ fitKey: number
+ paddingOpts: Record<string, number>
+}
+
+function BoundsController({ places, fitKey, paddingOpts }: BoundsControllerProps) {
const map = useMap()
const prevFitKey = useRef(-1)
@@ -149,7 +168,11 @@ function BoundsController({ places, fitKey, paddingOpts }) {
return null
}
-function MapClickHandler({ onClick }) {
+interface MapClickHandlerProps {
+ onClick: ((e: L.LeafletMouseEvent) => void) | null
+}
+
+function MapClickHandler({ onClick }: MapClickHandlerProps) {
const map = useMap()
useEffect(() => {
if (!onClick) return
@@ -160,7 +183,13 @@ function MapClickHandler({ onClick }) {
}
// ── Route travel time label ──
-function RouteLabel({ midpoint, walkingText, drivingText }) {
+interface RouteLabelProps {
+ midpoint: [number, number]
+ walkingText: string
+ drivingText: string
+}
+
+function RouteLabel({ midpoint, walkingText, drivingText }: RouteLabelProps) {
const map = useMap()
const [visible, setVisible] = useState(map ? map.getZoom() >= 12 : false)
diff --git a/client/src/components/Map/RouteCalculator.js b/client/src/components/Map/RouteCalculator.ts
similarity index 55%
rename from client/src/components/Map/RouteCalculator.js
rename to client/src/components/Map/RouteCalculator.ts
index 5afb1bfde..6f79a97db 100644
--- a/client/src/components/Map/RouteCalculator.js
+++ b/client/src/components/Map/RouteCalculator.ts
@@ -1,19 +1,18 @@
-// OSRM routing utility - free, no API key required
+import type { RouteResult, RouteSegment, Waypoint } from '../../types'
+
const OSRM_BASE = 'https://router.project-osrm.org/route/v1'
-/**
- * Calculate a route between multiple waypoints using OSRM
- * @param {Array<{lat: number, lng: number}>} waypoints
- * @param {string} profile - 'driving' | 'walking' | 'cycling'
- * @returns {Promise<{coordinates: Array<[number,number]>, distance: number, duration: number, distanceText: string, durationText: string}>}
- */
-export async function calculateRoute(waypoints, profile = 'driving', { signal } = {}) {
+/** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */
+export async function calculateRoute(
+ waypoints: Waypoint[],
+ profile: 'driving' | 'walking' | 'cycling' = 'driving',
+ { signal }: { signal?: AbortSignal } = {}
+): Promise<RouteResult> {
if (!waypoints || waypoints.length < 2) {
throw new Error('At least 2 waypoints required')
}
- const coords = waypoints.map(p => `${p.lng},${p.lat}`).join(';')
- // OSRM public API only supports driving; we override duration for other modes
+ const coords = waypoints.map((p) => `${p.lng},${p.lat}`).join(';')
const url = `${OSRM_BASE}/driving/${coords}?overview=full&geometries=geojson&steps=false`
const response = await fetch(url, { signal })
@@ -28,21 +27,20 @@ export async function calculateRoute(waypoints, profile = 'driving', { signal }
}
const route = data.routes[0]
- const coordinates = route.geometry.coordinates.map(([lng, lat]) => [lat, lng])
+ const coordinates: [number, number][] = route.geometry.coordinates.map(([lng, lat]: [number, number]) => [lat, lng])
- const distance = route.distance // meters
- // Compute duration based on mode (walking: 5 km/h, cycling: 15 km/h)
- let duration
+ const distance: number = route.distance
+ let duration: number
if (profile === 'walking') {
duration = distance / (5000 / 3600)
} else if (profile === 'cycling') {
duration = distance / (15000 / 3600)
} else {
- duration = route.duration // driving: use OSRM value
+ duration = route.duration
}
- const walkingDuration = distance / (5000 / 3600) // 5 km/h
- const drivingDuration = route.duration // OSRM driving value
+ const walkingDuration = distance / (5000 / 3600)
+ const drivingDuration: number = route.duration
return {
coordinates,
@@ -55,29 +53,23 @@ export async function calculateRoute(waypoints, profile = 'driving', { signal }
}
}
-/**
- * Generate a Google Maps directions URL for the given places
- */
-export function generateGoogleMapsUrl(places) {
- const valid = places.filter(p => p.lat && p.lng)
+export function generateGoogleMapsUrl(places: Waypoint[]): string | null {
+ const valid = places.filter((p) => p.lat && p.lng)
if (valid.length === 0) return null
if (valid.length === 1) {
return `https://www.google.com/maps/search/?api=1&query=${valid[0].lat},${valid[0].lng}`
}
- // Use /dir/stop1/stop2/.../stopN format — all stops as path segments
- const stops = valid.map(p => `${p.lat},${p.lng}`).join('/')
+ const stops = valid.map((p) => `${p.lat},${p.lng}`).join('/')
return `https://www.google.com/maps/dir/${stops}`
}
-/**
- * Simple nearest-neighbor route optimization
- */
-export function optimizeRoute(places) {
- const valid = places.filter(p => p.lat && p.lng)
+/** Reorders waypoints using a nearest-neighbor heuristic to minimize total Euclidean distance. */
+export function optimizeRoute(places: Waypoint[]): Waypoint[] {
+ const valid = places.filter((p) => p.lat && p.lng)
if (valid.length <= 2) return places
- const visited = new Set()
- const result = []
+ const visited = new Set<number>()
+ const result: Waypoint[] = []
let current = valid[0]
visited.add(0)
result.push(current)
@@ -100,14 +92,14 @@ export function optimizeRoute(places) {
return result
}
-/**
- * Calculate per-leg travel times in a single OSRM request
- * Returns array of { mid, walkingText, drivingText } for each leg
- */
-export async function calculateSegments(waypoints, { signal } = {}) {
+/** Fetches per-leg distance/duration from OSRM and returns segment metadata (midpoints, walking/driving times). */
+export async function calculateSegments(
+ waypoints: Waypoint[],
+ { signal }: { signal?: AbortSignal } = {}
+): Promise<RouteSegment[]> {
if (!waypoints || waypoints.length < 2) return []
- const coords = waypoints.map(p => `${p.lng},${p.lat}`).join(';')
+ const coords = waypoints.map((p) => `${p.lng},${p.lat}`).join(';')
const url = `${OSRM_BASE}/driving/${coords}?overview=false&geometries=geojson&steps=false&annotations=distance,duration`
const response = await fetch(url, { signal })
@@ -117,11 +109,11 @@ export async function calculateSegments(waypoints, { signal } = {}) {
if (data.code !== 'Ok' || !data.routes?.[0]) throw new Error('No route found')
const legs = data.routes[0].legs
- return legs.map((leg, i) => {
- const from = [waypoints[i].lat, waypoints[i].lng]
- const to = [waypoints[i + 1].lat, waypoints[i + 1].lng]
- const mid = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]
- const walkingDuration = leg.distance / (5000 / 3600) // 5 km/h
+ return legs.map((leg: { distance: number; duration: number }, i: number): RouteSegment => {
+ const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
+ const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
+ const mid: [number, number] = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]
+ const walkingDuration = leg.distance / (5000 / 3600)
return {
mid, from, to,
walkingText: formatDuration(walkingDuration),
@@ -130,14 +122,14 @@ export async function calculateSegments(waypoints, { signal } = {}) {
})
}
-function formatDistance(meters) {
+function formatDistance(meters: number): string {
if (meters < 1000) {
return `${Math.round(meters)} m`
}
return `${(meters / 1000).toFixed(1)} km`
}
-function formatDuration(seconds) {
+function formatDuration(seconds: number): string {
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
if (h > 0) {
diff --git a/client/src/components/PDF/TripPDF.jsx b/client/src/components/PDF/TripPDF.tsx
similarity index 97%
rename from client/src/components/PDF/TripPDF.jsx
rename to client/src/components/PDF/TripPDF.tsx
index 1df45b543..abaf03f05 100644
--- a/client/src/components/PDF/TripPDF.jsx
+++ b/client/src/components/PDF/TripPDF.tsx
@@ -3,6 +3,7 @@ import { createElement } from 'react'
import { getCategoryIcon } from '../shared/categoryIcons'
import { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark } from 'lucide-react'
import { mapsApi } from '../../api/client'
+import type { Trip, Day, Place, Category, AssignmentsMap, DayNotesMap } from '../../types'
const NOTE_ICON_MAP = { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark }
function noteIconSvg(iconId) {
@@ -88,7 +89,18 @@ async function fetchPlacePhotos(assignments) {
return photoMap
}
-export async function downloadTripPDF({ trip, days, places, assignments, categories, dayNotes, t: _t, locale: _locale }) {
+interface downloadTripPDFProps {
+ trip: Trip
+ days: Day[]
+ places: Place[]
+ assignments: AssignmentsMap
+ categories: Category[]
+ dayNotes: DayNotesMap
+ t: (key: string, params?: Record<string, string | number>) => string
+ locale: string
+}
+
+export async function downloadTripPDF({ trip, days, places, assignments, categories, dayNotes, t: _t, locale: _locale }: downloadTripPDFProps) {
await ensureRenderer()
const loc = _locale || 'de-DE'
const tr = _t || (k => k)
diff --git a/client/src/components/Packing/PackingListPanel.jsx b/client/src/components/Packing/PackingListPanel.tsx
similarity index 96%
rename from client/src/components/Packing/PackingListPanel.jsx
rename to client/src/components/Packing/PackingListPanel.tsx
index 863baa83d..7a45653a3 100644
--- a/client/src/components/Packing/PackingListPanel.jsx
+++ b/client/src/components/Packing/PackingListPanel.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useMemo, useRef } from 'react'
+import { useState, useMemo, useRef } from 'react'
import { useTripStore } from '../../store/tripStore'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
@@ -6,6 +6,7 @@ import {
CheckSquare, Square, Trash2, Plus, ChevronDown, ChevronRight,
Sparkles, X, Pencil, Check, MoreHorizontal, CheckCheck, RotateCcw, Luggage,
} from 'lucide-react'
+import type { PackingItem } from '../../types'
const VORSCHLAEGE = [
{ name: 'Passport', category: 'Documents' },
@@ -64,7 +65,14 @@ function katColor(kat, allCategories) {
}
// ── Artikel-Zeile ──────────────────────────────────────────────────────────
-function ArtikelZeile({ item, tripId, categories, onCategoryChange }) {
+interface ArtikelZeileProps {
+ item: PackingItem
+ tripId: number
+ categories: string[]
+ onCategoryChange: () => void
+}
+
+function ArtikelZeile({ item, tripId, categories, onCategoryChange }: ArtikelZeileProps) {
const [editing, setEditing] = useState(false)
const [editName, setEditName] = useState(item.name)
const [hovered, setHovered] = useState(false)
@@ -178,7 +186,16 @@ function ArtikelZeile({ item, tripId, categories, onCategoryChange }) {
}
// ── Kategorie-Gruppe ───────────────────────────────────────────────────────
-function KategorieGruppe({ kategorie, items, tripId, allCategories, onRename, onDeleteAll }) {
+interface KategorieGruppeProps {
+ kategorie: string
+ items: PackingItem[]
+ tripId: number
+ allCategories: string[]
+ onRename: (oldName: string, newName: string) => Promise<void>
+ onDeleteAll: (items: PackingItem[]) => Promise<void>
+}
+
+function KategorieGruppe({ kategorie, items, tripId, allCategories, onRename, onDeleteAll }: KategorieGruppeProps) {
const [offen, setOffen] = useState(true)
const [editingName, setEditingName] = useState(false)
const [editKatName, setEditKatName] = useState(kategorie)
@@ -198,12 +215,12 @@ function KategorieGruppe({ kategorie, items, tripId, allCategories, onRename, on
}
const handleCheckAll = async () => {
- for (const item of items) {
+ for (const item of Array.from(items)) {
if (!item.checked) await togglePackingItem(tripId, item.id, true)
}
}
const handleUncheckAll = async () => {
- for (const item of items) {
+ for (const item of Array.from(items)) {
if (item.checked) await togglePackingItem(tripId, item.id, false)
}
}
@@ -272,7 +289,14 @@ function KategorieGruppe({ kategorie, items, tripId, allCategories, onRename, on
)
}
-function MenuItem({ icon, label, onClick, danger }) {
+interface MenuItemProps {
+ icon: React.ReactNode
+ label: string
+ onClick: () => void
+ danger: boolean
+}
+
+function MenuItem({ icon, label, onClick, danger }: MenuItemProps) {
return (
<button onClick={onClick} style={{
display: 'flex', alignItems: 'center', gap: 8, width: '100%',
@@ -289,7 +313,12 @@ function MenuItem({ icon, label, onClick, danger }) {
}
// ── Haupt-Panel ────────────────────────────────────────────────────────────
-export default function PackingListPanel({ tripId, items }) {
+interface PackingListPanelProps {
+ tripId: number
+ items: PackingItem[]
+}
+
+export default function PackingListPanel({ tripId, items }: PackingListPanelProps) {
const [neuerName, setNeuerName] = useState('')
const [neueKategorie, setNeueKategorie] = useState('')
const [zeigeVorschlaege, setZeigeVorschlaege] = useState(false)
diff --git a/client/src/components/Photos/PhotoGallery.jsx b/client/src/components/Photos/PhotoGallery.tsx
similarity index 89%
rename from client/src/components/Photos/PhotoGallery.jsx
rename to client/src/components/Photos/PhotoGallery.tsx
index e59e8ad62..fdbdf3530 100644
--- a/client/src/components/Photos/PhotoGallery.jsx
+++ b/client/src/components/Photos/PhotoGallery.tsx
@@ -1,11 +1,22 @@
-import React, { useState, useMemo } from 'react'
+import { useState, useMemo } from 'react'
import { PhotoLightbox } from './PhotoLightbox'
import { PhotoUpload } from './PhotoUpload'
import { Upload, Camera } from 'lucide-react'
import Modal from '../shared/Modal'
import { useTranslation } from '../../i18n'
+import type { Photo, Place, Day } from '../../types'
+
+interface PhotoGalleryProps {
+ photos: Photo[]
+ onUpload: (fd: FormData) => Promise<void>
+ onDelete: (photoId: number) => Promise<void>
+ onUpdate: (photoId: number, data: Partial<Photo>) => Promise<void>
+ places: Place[]
+ days: Day[]
+ tripId: number
+}
-export default function PhotoGallery({ photos, onUpload, onDelete, onUpdate, places, days, tripId }) {
+export default function PhotoGallery({ photos, onUpload, onDelete, onUpdate, places, days, tripId }: PhotoGalleryProps) {
const { t } = useTranslation()
const [lightboxIndex, setLightboxIndex] = useState(null)
const [showUpload, setShowUpload] = useState(false)
@@ -153,7 +164,14 @@ export default function PhotoGallery({ photos, onUpload, onDelete, onUpdate, pla
)
}
-function PhotoThumbnail({ photo, days, places, onClick }) {
+interface PhotoThumbnailProps {
+ photo: Photo
+ days: Day[]
+ places: Place[]
+ onClick: () => void
+}
+
+function PhotoThumbnail({ photo, days, places, onClick }: PhotoThumbnailProps) {
const day = days?.find(d => d.id === photo.day_id)
const place = places?.find(p => p.id === photo.place_id)
@@ -168,8 +186,8 @@ function PhotoThumbnail({ photo, days, places, onClick }) {
className="w-full h-full object-cover transition-transform duration-200 group-hover:scale-105"
loading="lazy"
onError={e => {
- e.target.style.display = 'none'
- e.target.nextSibling && (e.target.nextSibling.style.display = 'flex')
+ (e.target as HTMLImageElement).style.display = 'none'
+ const next = (e.target as HTMLImageElement).nextSibling as HTMLElement; if (next) next.style.display = 'flex'
}}
/>
diff --git a/client/src/components/Photos/PhotoLightbox.jsx b/client/src/components/Photos/PhotoLightbox.tsx
similarity index 94%
rename from client/src/components/Photos/PhotoLightbox.jsx
rename to client/src/components/Photos/PhotoLightbox.tsx
index 5bb7b4fc8..ed1842fda 100644
--- a/client/src/components/Photos/PhotoLightbox.jsx
+++ b/client/src/components/Photos/PhotoLightbox.tsx
@@ -1,8 +1,20 @@
-import React, { useState, useEffect, useCallback } from 'react'
+import { useState, useEffect, useCallback } from 'react'
import { X, ChevronLeft, ChevronRight, Edit2, Trash2, Check } from 'lucide-react'
import { useTranslation } from '../../i18n'
+import type { Photo, Place, Day } from '../../types'
+
+interface PhotoLightboxProps {
+ photos: Photo[]
+ initialIndex: number
+ onClose: () => void
+ onUpdate: (photoId: number, data: Partial<Photo>) => Promise<void>
+ onDelete: (photoId: number) => Promise<void>
+ days: Day[]
+ places: Place[]
+ tripId: number
+}
-export function PhotoLightbox({ photos, initialIndex, onClose, onUpdate, onDelete, days, places, tripId }) {
+export function PhotoLightbox({ photos, initialIndex, onClose, onUpdate, onDelete, days, places, tripId }: PhotoLightboxProps) {
const { t } = useTranslation()
const [index, setIndex] = useState(initialIndex || 0)
const [editCaption, setEditCaption] = useState(false)
diff --git a/client/src/components/Photos/PhotoUpload.jsx b/client/src/components/Photos/PhotoUpload.tsx
similarity index 96%
rename from client/src/components/Photos/PhotoUpload.jsx
rename to client/src/components/Photos/PhotoUpload.tsx
index 3d758cd25..aee2e9fce 100644
--- a/client/src/components/Photos/PhotoUpload.jsx
+++ b/client/src/components/Photos/PhotoUpload.tsx
@@ -1,9 +1,18 @@
-import React, { useState, useCallback } from 'react'
+import { useState, useCallback } from 'react'
import { useDropzone } from 'react-dropzone'
import { Upload, X, Image } from 'lucide-react'
import { useTranslation } from '../../i18n'
+import type { Place, Day } from '../../types'
-export function PhotoUpload({ tripId, days, places, onUpload, onClose }) {
+interface PhotoUploadProps {
+ tripId: number
+ days: Day[]
+ places: Place[]
+ onUpload: (fd: FormData) => Promise<void>
+ onClose: () => void
+}
+
+export function PhotoUpload({ tripId, days, places, onUpload, onClose }: PhotoUploadProps) {
const { t } = useTranslation()
const [files, setFiles] = useState([])
const [dayId, setDayId] = useState('')
@@ -48,7 +57,7 @@ export function PhotoUpload({ tripId, days, places, onUpload, onClose }) {
await onUpload(formData)
files.forEach(f => URL.revokeObjectURL(f.preview))
setFiles([])
- } catch (err) {
+ } catch (err: unknown) {
console.error('Upload failed:', err)
} finally {
setUploading(false)
diff --git a/client/src/components/Places/PlaceFormModal.jsx b/client/src/components/Places/PlaceFormModal.jsx
deleted file mode 100644
index 2b4289ad3..000000000
--- a/client/src/components/Places/PlaceFormModal.jsx
+++ /dev/null
@@ -1,503 +0,0 @@
-import React, { useState, useEffect } from 'react'
-import Modal from '../shared/Modal'
-import { mapsApi, tagsApi, categoriesApi } from '../../api/client'
-import { useToast } from '../shared/Toast'
-import { useAuthStore } from '../../store/authStore'
-import { useTranslation } from '../../i18n'
-import { Search, Plus, MapPin, Loader } from 'lucide-react'
-
-const STATUSES = [
- { value: 'none', label: 'None' },
- { value: 'pending', label: 'Pending' },
- { value: 'confirmed', label: 'Confirmed' },
-]
-
-export default function PlaceFormModal({
- isOpen,
- onClose,
- onSave,
- place,
- tripId,
- categories: initialCategories = [],
- tags: initialTags = [],
- onCategoryCreated,
- onTagCreated,
-}) {
- const isEditing = !!place
- const { user, hasMapsKey } = useAuthStore()
- const { t } = useTranslation()
- const toast = useToast()
-
- const [categories, setCategories] = useState(initialCategories)
- const [tags, setTags] = useState(initialTags)
-
- useEffect(() => { setCategories(initialCategories) }, [initialCategories])
- useEffect(() => { setTags(initialTags) }, [initialTags])
-
- const emptyForm = {
- name: '',
- description: '',
- address: '',
- lat: '',
- lng: '',
- category_id: '',
- place_time: '',
- reservation_status: 'none',
- reservation_notes: '',
- reservation_datetime: '',
- google_place_id: '',
- website: '',
- tags: [],
- }
-
- const [formData, setFormData] = useState(emptyForm)
- const [isLoading, setIsLoading] = useState(false)
- const [error, setError] = useState('')
-
- // Maps search state
- const [mapQuery, setMapQuery] = useState('')
- const [mapResults, setMapResults] = useState([])
- const [mapSearching, setMapSearching] = useState(false)
-
- // New category/tag
- const [newCategoryName, setNewCategoryName] = useState('')
- const [newCategoryColor, setNewCategoryColor] = useState('#374151')
- const [showNewCategory, setShowNewCategory] = useState(false)
- const [newTagName, setNewTagName] = useState('')
- const [newTagColor, setNewTagColor] = useState('#374151')
- const [showNewTag, setShowNewTag] = useState(false)
-
- useEffect(() => {
- if (place && isOpen) {
- setFormData({
- name: place.name || '',
- description: place.description || '',
- address: place.address || '',
- lat: place.lat ?? '',
- lng: place.lng ?? '',
- category_id: place.category_id || '',
- place_time: place.place_time || '',
- reservation_status: place.reservation_status || 'none',
- reservation_notes: place.reservation_notes || '',
- reservation_datetime: place.reservation_datetime || '',
- google_place_id: place.google_place_id || '',
- website: place.website || '',
- tags: (place.tags || []).map(t => t.id),
- })
- } else if (!place && isOpen) {
- setFormData(emptyForm)
- }
- setError('')
- setMapResults([])
- setMapQuery('')
- }, [place, isOpen])
-
- const update = (field, value) => setFormData(prev => ({ ...prev, [field]: value }))
-
- const toggleTag = (tagId) => {
- setFormData(prev => ({
- ...prev,
- tags: prev.tags.includes(tagId)
- ? prev.tags.filter(id => id !== tagId)
- : [...prev.tags, tagId]
- }))
- }
-
- const handleSubmit = async (e) => {
- e.preventDefault()
- if (!formData.name.trim()) {
- setError('Place name is required')
- return
- }
- setIsLoading(true)
- setError('')
- try {
- await onSave({
- ...formData,
- lat: formData.lat !== '' ? parseFloat(formData.lat) : null,
- lng: formData.lng !== '' ? parseFloat(formData.lng) : null,
- category_id: formData.category_id || null,
- })
- onClose()
- } catch (err) {
- setError(err.message || 'Failed to save place')
- } finally {
- setIsLoading(false)
- }
- }
-
- const [searchSource, setSearchSource] = useState(null)
-
- const handleMapSearch = async () => {
- if (!mapQuery.trim()) return
- setMapSearching(true)
- try {
- const data = await mapsApi.search(mapQuery)
- setMapResults(data.places || [])
- setSearchSource(data.source || 'google')
- } catch (err) {
- toast.error(err.response?.data?.error || t('places.mapsSearchError'))
- } finally {
- setMapSearching(false)
- }
- }
-
- const selectMapPlace = (p) => {
- setFormData(prev => ({
- ...prev,
- name: p.name || prev.name,
- address: p.address || prev.address,
- lat: p.lat ?? prev.lat,
- lng: p.lng ?? prev.lng,
- google_place_id: p.google_place_id || prev.google_place_id,
- website: p.website || prev.website,
- }))
- setMapResults([])
- setMapQuery('')
- }
-
- const handleCreateCategory = async () => {
- if (!newCategoryName.trim()) return
- try {
- const data = await categoriesApi.create({ name: newCategoryName, color: newCategoryColor, icon: 'MapPin' })
- setCategories(prev => [...prev, data.category])
- if (onCategoryCreated) onCategoryCreated(data.category)
- setFormData(prev => ({ ...prev, category_id: data.category.id }))
- setNewCategoryName('')
- setShowNewCategory(false)
- toast.success('Category created')
- } catch (err) {
- toast.error('Failed to create category')
- }
- }
-
- const handleCreateTag = async () => {
- if (!newTagName.trim()) return
- try {
- const data = await tagsApi.create({ name: newTagName, color: newTagColor })
- setTags(prev => [...prev, data.tag])
- if (onTagCreated) onTagCreated(data.tag)
- setFormData(prev => ({ ...prev, tags: [...prev.tags, data.tag.id] }))
- setNewTagName('')
- setShowNewTag(false)
- toast.success('Tag created')
- } catch (err) {
- toast.error('Failed to create tag')
- }
- }
-
- return (
- <Modal
- isOpen={isOpen}
- onClose={onClose}
- title={isEditing ? 'Edit Place' : 'Add Place'}
- size="xl"
- footer={
- <div className="flex gap-3 justify-end">
- <button
- type="button"
- onClick={onClose}
- className="px-4 py-2 text-sm text-slate-600 border border-slate-200 rounded-lg hover:bg-slate-50"
- >
- Cancel
- </button>
- <button
- onClick={handleSubmit}
- disabled={isLoading}
- className="px-4 py-2 text-sm bg-slate-900 hover:bg-slate-700 disabled:bg-slate-400 text-white rounded-lg flex items-center gap-2"
- >
- {isLoading ? (
- <>
- <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
- Saving...
- </>
- ) : isEditing ? 'Save Changes' : 'Add Place'}
- </button>
- </div>
- }
- >
- <div className="space-y-5">
- {error && (
- <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600">
- {error}
- </div>
- )}
-
- {/* Place search — Google Maps or OpenStreetMap fallback */}
- <div className="bg-slate-50 rounded-xl p-3 border border-slate-200">
- {!hasMapsKey && (
- <p className="mb-2 text-xs" style={{ color: 'var(--text-faint)' }}>
- {t('places.osmActive')}
- </p>
- )}
- <div className="flex gap-2">
- <div className="relative flex-1">
- <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
- <input
- type="text"
- value={mapQuery}
- onChange={e => setMapQuery(e.target.value)}
- onKeyDown={e => e.key === 'Enter' && handleMapSearch()}
- placeholder={t('places.mapsSearchPlaceholder')}
- className="w-full pl-8 pr-3 py-2 text-sm border border-slate-200 rounded-lg focus:ring-2 focus:ring-slate-400 focus:border-transparent bg-white"
- />
- </div>
- <button
- onClick={handleMapSearch}
- disabled={mapSearching}
- className="px-3 py-2 bg-slate-900 text-white text-sm rounded-lg hover:bg-slate-700 disabled:opacity-50"
- >
- {mapSearching ? <Loader className="w-4 h-4 animate-spin" /> : t('common.search')}
- </button>
- </div>
-
- {mapResults.length > 0 && (
- <div className="bg-white rounded-lg border border-slate-200 max-h-48 overflow-y-auto mt-2">
- {mapResults.map((p, i) => (
- <button
- key={p.google_place_id || i}
- onClick={() => selectMapPlace(p)}
- className="w-full text-left px-3 py-2.5 hover:bg-slate-50 transition-colors border-b border-slate-100 last:border-0"
- >
- <p className="text-sm font-medium text-slate-900">{p.name}</p>
- <p className="text-xs text-slate-500 truncate flex items-center gap-1 mt-0.5">
- <MapPin className="w-3 h-3" />
- {p.address}
- </p>
- {p.rating && (
- <p className="text-xs text-amber-600 mt-0.5">★ {p.rating}</p>
- )}
- </button>
- ))}
- </div>
- )}
- </div>
-
- {/* Name */}
- <div>
- <label className="block text-sm font-medium text-slate-700 mb-1.5">
- Name <span className="text-red-500">*</span>
- </label>
- <input
- type="text"
- value={formData.name}
- onChange={e => update('name', e.target.value)}
- required
- placeholder="e.g. Eiffel Tower"
- className="w-full px-3 py-2.5 border border-slate-300 rounded-lg text-slate-900 placeholder-slate-400 focus:ring-2 focus:ring-slate-400 focus:border-transparent"
- />
- </div>
-
- {/* Description */}
- <div>
- <label className="block text-sm font-medium text-slate-700 mb-1.5">Description</label>
- <textarea
- value={formData.description}
- onChange={e => update('description', e.target.value)}
- placeholder="Notes about this place..."
- rows={2}
- className="w-full px-3 py-2.5 border border-slate-300 rounded-lg text-slate-900 placeholder-slate-400 focus:ring-2 focus:ring-slate-400 focus:border-transparent resize-none"
- />
- </div>
-
- {/* Address */}
- <div>
- <label className="block text-sm font-medium text-slate-700 mb-1.5">Address</label>
- <input
- type="text"
- value={formData.address}
- onChange={e => update('address', e.target.value)}
- placeholder="Street address"
- className="w-full px-3 py-2.5 border border-slate-300 rounded-lg text-slate-900 placeholder-slate-400 focus:ring-2 focus:ring-slate-400 focus:border-transparent"
- />
- </div>
-
- {/* Lat / Lng */}
- <div className="grid grid-cols-2 gap-3">
- <div>
- <label className="block text-sm font-medium text-slate-700 mb-1.5">Latitude</label>
- <input
- type="number"
- step="any"
- value={formData.lat}
- onChange={e => update('lat', e.target.value)}
- placeholder="e.g. 48.8584"
- className="w-full px-3 py-2.5 border border-slate-300 rounded-lg text-slate-900 placeholder-slate-400 focus:ring-2 focus:ring-slate-400 focus:border-transparent"
- />
- </div>
- <div>
- <label className="block text-sm font-medium text-slate-700 mb-1.5">Longitude</label>
- <input
- type="number"
- step="any"
- value={formData.lng}
- onChange={e => update('lng', e.target.value)}
- placeholder="e.g. 2.2945"
- className="w-full px-3 py-2.5 border border-slate-300 rounded-lg text-slate-900 placeholder-slate-400 focus:ring-2 focus:ring-slate-400 focus:border-transparent"
- />
- </div>
- </div>
-
- {/* Category */}
- <div>
- <label className="block text-sm font-medium text-slate-700 mb-1.5">Category</label>
- <div className="flex gap-2">
- <select
- value={formData.category_id}
- onChange={e => update('category_id', e.target.value)}
- className="flex-1 px-3 py-2.5 border border-slate-300 rounded-lg text-slate-900 focus:ring-2 focus:ring-slate-400 focus:border-transparent bg-white"
- >
- <option value="">No category</option>
- {categories.map(cat => (
- <option key={cat.id} value={cat.id}>{cat.name}</option>
- ))}
- </select>
- <button
- type="button"
- onClick={() => setShowNewCategory(!showNewCategory)}
- className="px-3 py-2.5 border border-slate-300 rounded-lg text-slate-500 hover:text-slate-700 hover:border-slate-400 transition-colors"
- title="Create new category"
- >
- <Plus className="w-4 h-4" />
- </button>
- </div>
-
- {showNewCategory && (
- <div className="mt-2 flex gap-2">
- <input
- type="text"
- value={newCategoryName}
- onChange={e => setNewCategoryName(e.target.value)}
- placeholder="Category name"
- className="flex-1 px-3 py-2 text-sm border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-400 focus:border-transparent"
- />
- <input
- type="color"
- value={newCategoryColor}
- onChange={e => setNewCategoryColor(e.target.value)}
- className="w-10 h-10 border border-slate-300 rounded-lg cursor-pointer p-1"
- title="Category color"
- />
- <button
- type="button"
- onClick={handleCreateCategory}
- className="px-3 py-2 bg-slate-900 text-white text-sm rounded-lg hover:bg-slate-700"
- >
- Add
- </button>
- </div>
- )}
- </div>
-
- {/* Tags */}
- <div>
- <label className="block text-sm font-medium text-slate-700 mb-1.5">Tags</label>
- <div className="flex flex-wrap gap-1.5 mb-2">
- {tags.map(tag => (
- <button
- key={tag.id}
- type="button"
- onClick={() => toggleTag(tag.id)}
- className={`text-xs px-2.5 py-1 rounded-full font-medium transition-all ${
- formData.tags.includes(tag.id)
- ? 'text-white shadow-sm ring-2 ring-offset-1'
- : 'text-white opacity-50 hover:opacity-80'
- }`}
- style={{
- backgroundColor: tag.color || '#374151',
- ringColor: formData.tags.includes(tag.id) ? tag.color : 'transparent'
- }}
- >
- {tag.name}
- </button>
- ))}
- <button
- type="button"
- onClick={() => setShowNewTag(!showNewTag)}
- className="text-xs px-2.5 py-1 border border-dashed border-slate-300 rounded-full text-slate-500 hover:border-slate-400 hover:text-slate-700 transition-colors"
- >
- <Plus className="inline w-3 h-3 mr-0.5" />
- New tag
- </button>
- </div>
-
- {showNewTag && (
- <div className="flex gap-2">
- <input
- type="text"
- value={newTagName}
- onChange={e => setNewTagName(e.target.value)}
- placeholder="Tag name"
- className="flex-1 px-3 py-2 text-sm border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-400 focus:border-transparent"
- />
- <input
- type="color"
- value={newTagColor}
- onChange={e => setNewTagColor(e.target.value)}
- className="w-10 h-10 border border-slate-300 rounded-lg cursor-pointer p-1"
- />
- <button
- type="button"
- onClick={handleCreateTag}
- className="px-3 py-2 bg-slate-900 text-white text-sm rounded-lg hover:bg-slate-700"
- >
- Add
- </button>
- </div>
- )}
- </div>
-
- {/* Reservation */}
- <div className="grid grid-cols-1 gap-3">
- <div>
- <label className="block text-sm font-medium text-slate-700 mb-1.5">Reservation</label>
- <select
- value={formData.reservation_status}
- onChange={e => update('reservation_status', e.target.value)}
- className="w-full px-3 py-2.5 border border-slate-300 rounded-lg text-slate-900 focus:ring-2 focus:ring-slate-400 focus:border-transparent bg-white"
- >
- {STATUSES.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
- </select>
- </div>
- </div>
-
- {/* Reservation details */}
- {formData.reservation_status !== 'none' && (
- <div className="space-y-3 p-3 bg-amber-50 rounded-lg border border-amber-200">
- <div>
- <label className="block text-sm font-medium text-slate-700 mb-1.5">Reservation Date & Time</label>
- <input
- type="datetime-local"
- value={formData.reservation_datetime}
- onChange={e => update('reservation_datetime', e.target.value)}
- className="w-full px-3 py-2.5 border border-slate-300 rounded-lg text-slate-900 focus:ring-2 focus:ring-slate-400 focus:border-transparent bg-white"
- />
- </div>
- <div>
- <label className="block text-sm font-medium text-slate-700 mb-1.5">Reservation Notes</label>
- <textarea
- value={formData.reservation_notes}
- onChange={e => update('reservation_notes', e.target.value)}
- placeholder="Confirmation number, special requests..."
- rows={2}
- className="w-full px-3 py-2.5 border border-slate-300 rounded-lg text-slate-900 placeholder-slate-400 focus:ring-2 focus:ring-slate-400 focus:border-transparent resize-none bg-white"
- />
- </div>
- </div>
- )}
-
- {/* Website */}
- <div>
- <label className="block text-sm font-medium text-slate-700 mb-1.5">Website</label>
- <input
- type="url"
- value={formData.website}
- onChange={e => update('website', e.target.value)}
- placeholder="https://..."
- className="w-full px-3 py-2.5 border border-slate-300 rounded-lg text-slate-900 placeholder-slate-400 focus:ring-2 focus:ring-slate-400 focus:border-transparent"
- />
- </div>
- </div>
- </Modal>
- )
-}
diff --git a/client/src/components/Planner/AssignedPlaceItem.jsx b/client/src/components/Planner/AssignedPlaceItem.jsx
deleted file mode 100644
index d4dc99b8a..000000000
--- a/client/src/components/Planner/AssignedPlaceItem.jsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import React from 'react'
-import { useSortable } from '@dnd-kit/sortable'
-import { CSS } from '@dnd-kit/utilities'
-import { GripVertical, X, Edit2, Clock, DollarSign, MapPin } from 'lucide-react'
-
-export default function AssignedPlaceItem({ assignment, dayId, onRemove, onEdit }) {
- const { place } = assignment
-
- const {
- attributes,
- listeners,
- setNodeRef,
- transform,
- transition,
- isDragging,
- } = useSortable({
- id: `assignment-${assignment.id}`,
- data: {
- type: 'assignment',
- dayId: dayId,
- assignment,
- },
- })
-
- const style = {
- transform: CSS.Transform.toString(transform),
- transition,
- }
-
- return (
- <div
- ref={setNodeRef}
- style={style}
- className={`
- group bg-white border rounded-lg p-2.5 transition-all
- ${isDragging
- ? 'opacity-40 border-slate-300 shadow-lg'
- : 'border-slate-200 hover:border-slate-300 hover:shadow-sm'
- }
- `}
- >
- <div className="flex items-start gap-2">
- {/* Drag handle */}
- <button
- {...attributes}
- {...listeners}
- className="drag-handle mt-0.5 p-0.5 text-slate-300 hover:text-slate-500 flex-shrink-0 rounded touch-none"
- tabIndex={-1}
- >
- <GripVertical className="w-4 h-4" />
- </button>
-
- {/* Content */}
- <div className="flex-1 min-w-0">
- {/* Name row */}
- <div className="flex items-center gap-1.5 mb-1">
- {place.category && (
- <div
- className="w-2 h-2 rounded-full flex-shrink-0"
- style={{ backgroundColor: place.category.color || '#6366f1' }}
- />
- )}
- <span className="text-sm font-medium text-slate-800 truncate">{place.name}</span>
- </div>
-
- {/* Time & price row */}
- <div className="flex items-center gap-2 mb-1">
- {place.place_time && (
- <span className="flex items-center gap-1 text-xs text-slate-600 bg-slate-50 px-1.5 py-0.5 rounded">
- <Clock className="w-3 h-3" />
- {place.place_time}
- </span>
- )}
- {place.price != null && (
- <span className="flex items-center gap-1 text-xs text-emerald-700 bg-emerald-50 px-1.5 py-0.5 rounded">
- <DollarSign className="w-3 h-3" />
- {Number(place.price).toLocaleString()} {place.currency || ''}
- </span>
- )}
- </div>
-
- {/* Address */}
- {place.address && (
- <p className="text-xs text-slate-400 truncate flex items-center gap-1">
- <MapPin className="w-3 h-3 flex-shrink-0" />
- {place.address}
- </p>
- )}
-
- {/* Category badge */}
- {place.category && (
- <span
- className="inline-block mt-1 text-xs px-1.5 py-0.5 rounded text-white text-[10px] font-medium"
- style={{ backgroundColor: place.category.color || '#6366f1' }}
- >
- {place.category.name}
- </span>
- )}
-
- {/* Tags */}
- {place.tags && place.tags.length > 0 && (
- <div className="flex flex-wrap gap-1 mt-1">
- {place.tags.map(tag => (
- <span
- key={tag.id}
- className="text-[10px] px-1.5 py-0.5 rounded-full text-white font-medium"
- style={{ backgroundColor: tag.color || '#6366f1' }}
- >
- {tag.name}
- </span>
- ))}
- </div>
- )}
- </div>
-
- {/* Action buttons */}
- <div className="flex flex-col gap-1 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0">
- {onEdit && (
- <button
- onClick={() => onEdit(place, assignment.id)}
- className="p-1 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded transition-colors"
- title="Edit place"
- >
- <Edit2 className="w-3.5 h-3.5" />
- </button>
- )}
- <button
- onClick={() => onRemove(assignment.id)}
- className="p-1 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded transition-colors"
- title="Remove from day"
- >
- <X className="w-3.5 h-3.5" />
- </button>
- </div>
- </div>
- </div>
- )
-}
diff --git a/client/src/components/Planner/DayColumn.jsx b/client/src/components/Planner/DayColumn.jsx
deleted file mode 100644
index ccc09bd7b..000000000
--- a/client/src/components/Planner/DayColumn.jsx
+++ /dev/null
@@ -1,177 +0,0 @@
-import React, { useState } from 'react'
-import { useDroppable } from '@dnd-kit/core'
-import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'
-import AssignedPlaceItem from './AssignedPlaceItem'
-import { ChevronDown, ChevronUp, Plus, FileText, Package, DollarSign } from 'lucide-react'
-
-export default function DayColumn({
- day,
- assignments,
- tripId,
- onRemoveAssignment,
- onEditPlace,
- onQuickAdd,
-}) {
- const [isCollapsed, setIsCollapsed] = useState(false)
- const [showNotes, setShowNotes] = useState(false)
- const [notes, setNotes] = useState(day.notes || '')
- const [notesEditing, setNotesEditing] = useState(false)
-
- const { isOver, setNodeRef } = useDroppable({
- id: `day-${day.id}`,
- data: {
- type: 'day',
- dayId: day.id,
- },
- })
-
- const sortableIds = (assignments || []).map(a => `assignment-${a.id}`)
-
- const totalCost = (assignments || []).reduce((sum, a) => {
- return sum + (a.place?.price ? Number(a.place.price) : 0)
- }, 0)
-
- const formatDate = (dateStr) => {
- if (!dateStr) return null
- const d = new Date(dateStr + 'T00:00:00')
- return d.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })
- }
-
- return (
- <div
- className={`
- flex-shrink-0 w-72 flex flex-col rounded-xl border-2 transition-all duration-150
- ${isOver
- ? 'border-slate-400 bg-slate-50 shadow-lg shadow-slate-100'
- : 'border-transparent bg-white shadow-sm'
- }
- `}
- >
- {/* Header */}
- <div
- className={`
- px-3 py-2.5 border-b flex items-center gap-2 rounded-t-xl
- ${isOver ? 'border-slate-200 bg-slate-50' : 'border-slate-100 bg-slate-50'}
- `}
- >
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-1.5">
- <span className="text-sm font-bold text-slate-900">Day {day.day_number}</span>
- <span className="text-xs bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded-full font-medium">
- {assignments?.length || 0}
- </span>
- </div>
- {day.date && (
- <p className="text-xs text-slate-500 mt-0.5">{formatDate(day.date)}</p>
- )}
- </div>
-
- <div className="flex items-center gap-1">
- {totalCost > 0 && (
- <span className="flex items-center gap-0.5 text-xs text-emerald-700 bg-emerald-50 px-1.5 py-0.5 rounded">
- <DollarSign className="w-3 h-3" />
- {totalCost.toLocaleString()}
- </span>
- )}
- <button
- onClick={() => setShowNotes(!showNotes)}
- className={`p-1 rounded transition-colors ${showNotes ? 'text-slate-700 bg-slate-100' : 'text-slate-400 hover:text-slate-600 hover:bg-slate-100'}`}
- title="Notes"
- >
- <FileText className="w-4 h-4" />
- </button>
- <button
- onClick={() => setIsCollapsed(!isCollapsed)}
- className="p-1 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded transition-colors"
- >
- {isCollapsed ? <ChevronDown className="w-4 h-4" /> : <ChevronUp className="w-4 h-4" />}
- </button>
- </div>
- </div>
-
- {/* Notes area */}
- {showNotes && (
- <div className="px-3 py-2 border-b border-slate-100 bg-amber-50">
- <textarea
- value={notes}
- onChange={e => setNotes(e.target.value)}
- onBlur={() => setNotesEditing(false)}
- onFocus={() => setNotesEditing(true)}
- placeholder="Add notes for this day..."
- rows={2}
- className="w-full text-xs text-slate-600 bg-transparent resize-none focus:outline-none placeholder-amber-400"
- />
- {notesEditing && (
- <div className="flex gap-2 mt-1">
- <button
- onMouseDown={(e) => {
- e.preventDefault()
- // Parent will handle save via onUpdateNotes if passed
- }}
- className="text-xs text-slate-600 hover:text-slate-900"
- >
- Save
- </button>
- </div>
- )}
- </div>
- )}
-
- {/* Assignments list */}
- {!isCollapsed && (
- <div
- ref={setNodeRef}
- className={`
- flex-1 p-2 flex flex-col gap-2 min-h-24 transition-colors duration-150
- ${isOver ? 'bg-slate-50' : 'bg-transparent'}
- `}
- >
- {assignments && assignments.length > 0 ? (
- <SortableContext items={sortableIds} strategy={verticalListSortingStrategy}>
- {assignments.map(assignment => (
- <AssignedPlaceItem
- key={assignment.id}
- assignment={assignment}
- dayId={day.id}
- onRemove={(id) => onRemoveAssignment(day.id, id)}
- onEdit={onEditPlace}
- />
- ))}
- </SortableContext>
- ) : (
- <div className={`
- flex-1 flex flex-col items-center justify-center py-6 rounded-lg border-2 border-dashed
- text-xs text-center transition-colors
- ${isOver
- ? 'border-slate-400 bg-slate-100 text-slate-500'
- : 'border-slate-200 text-slate-400'
- }
- `}>
- <Package className="w-8 h-8 mb-2 opacity-50" />
- <p className="font-medium">Drop places here</p>
- <p className="text-[10px] mt-0.5 opacity-70">or drag from the left panel</p>
- </div>
- )}
-
- {/* Quick add button */}
- <button
- onClick={() => onQuickAdd(day)}
- className="flex items-center justify-center gap-1 py-1.5 text-xs text-slate-400 hover:text-slate-700 hover:bg-slate-50 rounded-lg border border-dashed border-slate-200 hover:border-slate-300 transition-all mt-1"
- >
- <Plus className="w-3.5 h-3.5" />
- Add place
- </button>
- </div>
- )}
-
- {isCollapsed && (
- <div
- className="px-3 py-2 text-xs text-slate-400 cursor-pointer hover:bg-slate-50"
- onClick={() => setIsCollapsed(false)}
- >
- {assignments?.length || 0} place{(assignments?.length || 0) !== 1 ? 's' : ''} — click to expand
- </div>
- )}
- </div>
- )
-}
diff --git a/client/src/components/Planner/DayDetailPanel.jsx b/client/src/components/Planner/DayDetailPanel.tsx
similarity index 97%
rename from client/src/components/Planner/DayDetailPanel.jsx
rename to client/src/components/Planner/DayDetailPanel.tsx
index 2170b7cc0..7cb9d5a28 100644
--- a/client/src/components/Planner/DayDetailPanel.jsx
+++ b/client/src/components/Planner/DayDetailPanel.tsx
@@ -9,13 +9,19 @@ import CustomSelect from '../shared/CustomSelect'
import CustomTimePicker from '../shared/CustomTimePicker'
import { useSettingsStore } from '../../store/settingsStore'
import { useTranslation } from '../../i18n'
+import type { Day, Place, Category, Reservation, AssignmentsMap } from '../../types'
const WEATHER_ICON_MAP = {
Clear: Sun, Clouds: Cloud, Rain: CloudRain, Drizzle: CloudDrizzle,
Thunderstorm: CloudLightning, Snow: CloudSnow, Mist: Wind, Fog: Wind, Haze: Wind,
}
-function WIcon({ main, size = 14 }) {
+interface WIconProps {
+ main: string
+ size?: number
+}
+
+function WIcon({ main, size = 14 }: WIconProps) {
const Icon = WEATHER_ICON_MAP[main] || Cloud
return <Icon size={size} strokeWidth={1.8} />
}
@@ -32,7 +38,21 @@ function formatTime12(val, is12h) {
return `${h12}:${String(m).padStart(2, '0')} ${period}`
}
-export default function DayDetailPanel({ day, days, places, categories = [], tripId, assignments, reservations = [], lat, lng, onClose, onAccommodationChange }) {
+interface DayDetailPanelProps {
+ day: Day
+ days: Day[]
+ places: Place[]
+ categories?: Category[]
+ tripId: number
+ assignments: AssignmentsMap
+ reservations?: Reservation[]
+ lat: number | null
+ lng: number | null
+ onClose: () => void
+ onAccommodationChange: () => void
+}
+
+export default function DayDetailPanel({ day, days, places, categories = [], tripId, assignments, reservations = [], lat, lng, onClose, onAccommodationChange }: DayDetailPanelProps) {
const { t, language } = useTranslation()
const isFahrenheit = useSettingsStore(s => s.settings.temperature_unit) === 'fahrenheit'
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
@@ -504,7 +524,12 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri
)
}
-function Chip({ icon: Icon, value }) {
+interface ChipProps {
+ icon: React.ComponentType<{ size?: number; style?: React.CSSProperties }>
+ value: string
+}
+
+function Chip({ icon: Icon, value }: ChipProps) {
return (
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '4px 8px', borderRadius: 8, background: 'var(--bg-secondary)', fontSize: 11, color: 'var(--text-muted)' }}>
<Icon size={11} style={{ flexShrink: 0, opacity: 0.6 }} />
@@ -513,7 +538,16 @@ function Chip({ icon: Icon, value }) {
)
}
-function InfoChip({ icon: Icon, label, value, placeholder, onEdit, type }) {
+interface InfoChipProps {
+ icon: React.ComponentType<{ size?: number; style?: React.CSSProperties }>
+ label: string
+ value: string
+ placeholder: string
+ onEdit: (value: string) => void
+ type: 'text' | 'time'
+}
+
+function InfoChip({ icon: Icon, label, value, placeholder, onEdit, type }: InfoChipProps) {
const [editing, setEditing] = React.useState(false)
const [val, setVal] = React.useState(value || '')
const inputRef = React.useRef(null)
diff --git a/client/src/components/Planner/DayPlanSidebar.jsx b/client/src/components/Planner/DayPlanSidebar.tsx
similarity index 93%
rename from client/src/components/Planner/DayPlanSidebar.jsx
rename to client/src/components/Planner/DayPlanSidebar.tsx
index 7ae78892e..8859e0d01 100644
--- a/client/src/components/Planner/DayPlanSidebar.jsx
+++ b/client/src/components/Planner/DayPlanSidebar.tsx
@@ -1,3 +1,7 @@
+/* eslint-disable @typescript-eslint/no-unnecessary-type-assertion */
+interface DragDataPayload { placeId?: string; assignmentId?: string; noteId?: string; fromDayId?: string }
+declare global { interface Window { __dragData: DragDataPayload | null } }
+
import React, { useState, useEffect, useRef } from 'react'
import ReactDOM from 'react-dom'
import { ChevronDown, ChevronRight, ChevronUp, Navigation, RotateCcw, ExternalLink, Clock, Pencil, GripVertical, Ticket, Plus, FileText, Check, Trash2, Info, MapPin, Star, Heart, Camera, Lightbulb, Flag, Bookmark, Train, Bus, Plane, Car, Ship, Coffee, ShoppingBag, AlertTriangle, FileDown, Lock, Hotel, Utensils, Users } from 'lucide-react'
@@ -13,36 +17,9 @@ import { getCategoryIcon } from '../shared/categoryIcons'
import { useTripStore } from '../../store/tripStore'
import { useSettingsStore } from '../../store/settingsStore'
import { useTranslation } from '../../i18n'
-
-function formatDate(dateStr, locale) {
- if (!dateStr) return null
- return new Date(dateStr + 'T00:00:00').toLocaleDateString(locale, {
- weekday: 'short', day: 'numeric', month: 'short',
- })
-}
-
-function formatTime(timeStr, locale, timeFormat) {
- if (!timeStr) return ''
- try {
- const parts = timeStr.split(':')
- const h = Number(parts[0]) || 0
- const m = Number(parts[1]) || 0
- if (isNaN(h)) return timeStr
- if (timeFormat === '12h') {
- const period = h >= 12 ? 'PM' : 'AM'
- const h12 = h === 0 ? 12 : h > 12 ? h - 12 : h
- return `${h12}:${String(m).padStart(2, '0')} ${period}`
- }
- const str = `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`
- return locale?.startsWith('de') ? `${str} Uhr` : str
- } catch { return timeStr }
-}
-
-function dayTotalCost(dayId, assignments, currency) {
- const da = assignments[String(dayId)] || []
- const total = da.reduce((s, a) => s + (parseFloat(a.place?.price) || 0), 0)
- return total > 0 ? `${total.toFixed(0)} ${currency}` : null
-}
+import { formatDate, formatTime, dayTotalCost } from '../../utils/formatters'
+import { useDayNotes } from '../../hooks/useDayNotes'
+import type { Trip, Day, Place, Category, Assignment, Reservation, AssignmentsMap, RouteResult } from '../../types'
const NOTE_ICONS = [
{ id: 'FileText', Icon: FileText },
@@ -74,6 +51,31 @@ const TYPE_ICONS = {
car: '🚗', cruise: '🚢', event: '🎫', other: '📋',
}
+interface DayPlanSidebarProps {
+ tripId: number
+ trip: Trip
+ days: Day[]
+ places: Place[]
+ categories: Category[]
+ assignments: AssignmentsMap
+ selectedDayId: number | null
+ selectedPlaceId: number | null
+ selectedAssignmentId: number | null
+ onSelectDay: (dayId: number | null) => void
+ onPlaceClick: (placeId: number) => void
+ onDayDetail: (day: Day) => void
+ accommodations?: Assignment[]
+ onReorder: (dayId: number, orderedIds: number[]) => void
+ onUpdateDayTitle: (dayId: number, title: string) => void
+ onRouteCalculated: (dayId: number, route: RouteResult | null) => void
+ onAssignToDay: (placeId: number, dayId: number) => void
+ onRemoveAssignment: (assignmentId: number, dayId: number) => void
+ onEditPlace: (place: Place) => void
+ onDeletePlace: (placeId: number) => void
+ reservations?: Reservation[]
+ onAddReservation: () => void
+}
+
export default function DayPlanSidebar({
tripId,
trip, days, places, categories, assignments,
@@ -83,14 +85,14 @@ export default function DayPlanSidebar({
onAssignToDay, onRemoveAssignment, onEditPlace, onDeletePlace,
reservations = [],
onAddReservation,
-}) {
+}: DayPlanSidebarProps) {
const toast = useToast()
const { t, language, locale } = useTranslation()
const ctxMenu = useContextMenu()
const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'
const tripStore = useTripStore()
- const dayNotes = tripStore.dayNotes || {}
+ const { noteUi, setNoteUi, noteInputRef, dayNotes, openAddNote: _openAddNote, openEditNote: _openEditNote, cancelNote, saveNote, deleteNote: _deleteNote, moveNote: _moveNote } = useDayNotes(tripId)
const [expandedDays, setExpandedDays] = useState(() => {
try {
@@ -109,9 +111,7 @@ export default function DayPlanSidebar({
const [dropTargetKey, setDropTargetKey] = useState(null)
const [dragOverDayId, setDragOverDayId] = useState(null)
const [hoveredId, setHoveredId] = useState(null)
- const [noteUi, setNoteUi] = useState({}) // { [dayId]: { mode, text, time, noteId?, sortOrder? } }
const inputRef = useRef(null)
- const noteInputRef = useRef(null)
const dragDataRef = useRef(null) // Speichert Drag-Daten als Backup (dataTransfer geht bei Re-Render verloren)
const currency = trip?.currency || 'EUR'
@@ -190,40 +190,19 @@ export default function DayPlanSidebar({
const openAddNote = (dayId, e) => {
e?.stopPropagation()
- const merged = getMergedItems(dayId)
- const maxKey = merged.length > 0 ? Math.max(...merged.map(i => i.sortKey)) : -1
- setNoteUi(prev => ({ ...prev, [dayId]: { mode: 'add', text: '', time: '', icon: 'FileText', sortOrder: maxKey + 1 } }))
- if (!expandedDays.has(dayId)) setExpandedDays(prev => new Set([...prev, dayId]))
- setTimeout(() => noteInputRef.current?.focus(), 50)
+ _openAddNote(dayId, getMergedItems, (id) => {
+ if (!expandedDays.has(id)) setExpandedDays(prev => new Set([...prev, id]))
+ })
}
const openEditNote = (dayId, note, e) => {
e?.stopPropagation()
- setNoteUi(prev => ({ ...prev, [dayId]: { mode: 'edit', noteId: note.id, text: note.text, time: note.time || '', icon: note.icon || 'FileText' } }))
- setTimeout(() => noteInputRef.current?.focus(), 50)
- }
-
- const cancelNote = (dayId) => {
- setNoteUi(prev => { const n = { ...prev }; delete n[dayId]; return n })
- }
-
- const saveNote = async (dayId) => {
- const ui = noteUi[dayId]
- if (!ui?.text?.trim()) return
- try {
- if (ui.mode === 'add') {
- await tripStore.addDayNote(tripId, dayId, { text: ui.text.trim(), time: ui.time || null, icon: ui.icon || 'FileText', sort_order: ui.sortOrder })
- } else {
- await tripStore.updateDayNote(tripId, dayId, ui.noteId, { text: ui.text.trim(), time: ui.time || null, icon: ui.icon || 'FileText' })
- }
- cancelNote(dayId)
- } catch (err) { toast.error(err.message) }
+ _openEditNote(dayId, note)
}
const deleteNote = async (dayId, noteId, e) => {
e?.stopPropagation()
- try { await tripStore.deleteDayNote(tripId, dayId, noteId) }
- catch (err) { toast.error(err.message) }
+ await _deleteNote(dayId, noteId)
}
const handleMergedDrop = async (dayId, fromType, fromId, toType, toId, insertAfter = false) => {
@@ -263,26 +242,14 @@ export default function DayPlanSidebar({
for (const n of noteChanges) {
await tripStore.updateDayNote(tripId, dayId, n.id, { sort_order: n.sort_order })
}
- } catch (err) { toast.error(err.message) }
+ } catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Unknown error') }
setDraggingId(null)
setDropTargetKey(null)
dragDataRef.current = null
}
const moveNote = async (dayId, noteId, direction) => {
- const merged = getMergedItems(dayId)
- const idx = merged.findIndex(i => i.type === 'note' && i.data.id === noteId)
- if (idx === -1) return
- let newSortOrder
- if (direction === 'up') {
- if (idx === 0) return
- newSortOrder = idx >= 2 ? (merged[idx - 2].sortKey + merged[idx - 1].sortKey) / 2 : merged[idx - 1].sortKey - 1
- } else {
- if (idx >= merged.length - 1) return
- newSortOrder = idx < merged.length - 2 ? (merged[idx + 1].sortKey + merged[idx + 2].sortKey) / 2 : merged[idx + 1].sortKey + 1
- }
- try { await tripStore.updateDayNote(tripId, dayId, noteId, { sort_order: newSortOrder }) }
- catch (err) { toast.error(err.message) }
+ await _moveNote(dayId, noteId, direction, getMergedItems)
}
const startEditTitle = (day, e) => {
@@ -369,9 +336,9 @@ export default function DayPlanSidebar({
if (placeId) {
onAssignToDay?.(parseInt(placeId), dayId)
} else if (assignmentId && fromDayId !== dayId) {
- tripStore.moveAssignment(tripId, Number(assignmentId), fromDayId, dayId).catch(err => toast.error(err.message))
+ tripStore.moveAssignment(tripId, Number(assignmentId), fromDayId, dayId).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error'))
} else if (noteId && fromDayId !== dayId) {
- tripStore.moveDayNote(tripId, fromDayId, dayId, Number(noteId)).catch(err => toast.error(err.message))
+ tripStore.moveDayNote(tripId, fromDayId, dayId, Number(noteId)).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error'))
}
setDraggingId(null)
setDropTargetKey(null)
@@ -573,11 +540,11 @@ export default function DayPlanSidebar({
const { assignmentId, noteId, fromDayId } = getDragData(e)
if (!assignmentId && !noteId) { dragDataRef.current = null; window.__dragData = null; return }
if (assignmentId && fromDayId !== day.id) {
- tripStore.moveAssignment(tripId, Number(assignmentId), fromDayId, day.id).catch(err => toast.error(err.message))
+ tripStore.moveAssignment(tripId, Number(assignmentId), fromDayId, day.id).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error'))
setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; return
}
if (noteId && fromDayId !== day.id) {
- tripStore.moveDayNote(tripId, fromDayId, day.id, Number(noteId)).catch(err => toast.error(err.message))
+ tripStore.moveDayNote(tripId, fromDayId, day.id, Number(noteId)).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error'))
setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; return
}
const m = getMergedItems(day.id)
@@ -652,7 +619,7 @@ export default function DayPlanSidebar({
setDropTargetKey(null); window.__dragData = null
} else if (fromAssignmentId && fromDayId !== day.id) {
const toIdx = getDayAssignments(day.id).findIndex(a => a.id === assignment.id)
- tripStore.moveAssignment(tripId, Number(fromAssignmentId), fromDayId, day.id, toIdx).catch(err => toast.error(err.message))
+ tripStore.moveAssignment(tripId, Number(fromAssignmentId), fromDayId, day.id, toIdx).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error'))
setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null
} else if (fromAssignmentId) {
handleMergedDrop(day.id, 'place', Number(fromAssignmentId), 'place', assignment.id)
@@ -660,7 +627,7 @@ export default function DayPlanSidebar({
const tm = getMergedItems(day.id)
const toIdx = tm.findIndex(i => i.type === 'place' && i.data.id === assignment.id)
const so = toIdx <= 0 ? (tm[0]?.sortKey ?? 0) - 1 : (tm[toIdx - 1].sortKey + tm[toIdx].sortKey) / 2
- tripStore.moveDayNote(tripId, fromDayId, day.id, Number(noteId), so).catch(err => toast.error(err.message))
+ tripStore.moveDayNote(tripId, fromDayId, day.id, Number(noteId), so).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error'))
setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null
} else if (noteId) {
handleMergedDrop(day.id, 'note', Number(noteId), 'place', assignment.id)
@@ -822,7 +789,7 @@ export default function DayPlanSidebar({
const tm = getMergedItems(day.id)
const toIdx = tm.findIndex(i => i.type === 'note' && i.data.id === note.id)
const so = toIdx <= 0 ? (tm[0]?.sortKey ?? 0) - 1 : (tm[toIdx - 1].sortKey + tm[toIdx].sortKey) / 2
- tripStore.moveDayNote(tripId, fromDayId, day.id, Number(fromNoteId), so).catch(err => toast.error(err.message))
+ tripStore.moveDayNote(tripId, fromDayId, day.id, Number(fromNoteId), so).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error'))
setDraggingId(null); setDropTargetKey(null)
} else if (fromNoteId && fromNoteId !== String(note.id)) {
handleMergedDrop(day.id, 'note', Number(fromNoteId), 'note', note.id)
@@ -830,7 +797,7 @@ export default function DayPlanSidebar({
const tm = getMergedItems(day.id)
const noteIdx = tm.findIndex(i => i.type === 'note' && i.data.id === note.id)
const toIdx = tm.slice(0, noteIdx).filter(i => i.type === 'place').length
- tripStore.moveAssignment(tripId, Number(fromAssignmentId), fromDayId, day.id, toIdx).catch(err => toast.error(err.message))
+ tripStore.moveAssignment(tripId, Number(fromAssignmentId), fromDayId, day.id, toIdx).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error'))
setDraggingId(null); setDropTargetKey(null)
} else if (fromAssignmentId) {
handleMergedDrop(day.id, 'place', Number(fromAssignmentId), 'note', note.id)
@@ -895,11 +862,11 @@ export default function DayPlanSidebar({
}
if (!assignmentId && !noteId) { dragDataRef.current = null; window.__dragData = null; return }
if (assignmentId && fromDayId !== day.id) {
- tripStore.moveAssignment(tripId, Number(assignmentId), fromDayId, day.id).catch(err => toast.error(err.message))
+ tripStore.moveAssignment(tripId, Number(assignmentId), fromDayId, day.id).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error'))
setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; return
}
if (noteId && fromDayId !== day.id) {
- tripStore.moveDayNote(tripId, fromDayId, day.id, Number(noteId)).catch(err => toast.error(err.message))
+ tripStore.moveDayNote(tripId, fromDayId, day.id, Number(noteId)).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error'))
setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; return
}
const m = getMergedItems(day.id)
diff --git a/client/src/components/Planner/DaysList.jsx b/client/src/components/Planner/DaysList.jsx
deleted file mode 100644
index 089cbbbf1..000000000
--- a/client/src/components/Planner/DaysList.jsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import React from 'react'
-import { CalendarDays, MapPin, Plus } from 'lucide-react'
-import WeatherWidget from '../Weather/WeatherWidget'
-import { useTranslation } from '../../i18n'
-
-function formatDate(dateStr) {
- if (!dateStr) return null
- return new Date(dateStr + 'T00:00:00').toLocaleDateString('de-DE', {
- weekday: 'short',
- day: 'numeric',
- month: 'short',
- })
-}
-
-function dayTotal(dayId, assignments) {
- const dayAssignments = assignments[String(dayId)] || []
- return dayAssignments.reduce((sum, a) => {
- const cost = parseFloat(a.place?.cost) || 0
- return sum + cost
- }, 0)
-}
-
-export function DaysList({ days, selectedDayId, onSelectDay, assignments, trip }) {
- const { t } = useTranslation()
- const totalCost = days.reduce((sum, d) => sum + dayTotal(d.id, assignments), 0)
- const currency = trip?.currency || 'EUR'
-
- return (
- <div className="flex flex-col h-full">
- {/* Header */}
- <div className="px-4 py-3 border-b border-gray-100 flex-shrink-0">
- <h2 className="text-sm font-semibold text-gray-700">{t('planner.dayPlan')}</h2>
- <p className="text-xs text-gray-400 mt-0.5">{t('planner.dayCount', { n: days.length })}</p>
- </div>
-
- {/* All places overview option */}
- <button
- onClick={() => onSelectDay(null)}
- className={`w-full text-left px-4 py-3 border-b border-gray-100 transition-colors flex items-center gap-2 flex-shrink-0 ${
- selectedDayId === null
- ? 'bg-slate-50 border-l-2 border-l-slate-900'
- : 'hover:bg-gray-50'
- }`}
- >
- <MapPin className={`w-4 h-4 flex-shrink-0 ${selectedDayId === null ? 'text-slate-900' : 'text-gray-400'}`} />
- <div>
- <p className={`text-sm font-medium ${selectedDayId === null ? 'text-slate-900' : 'text-gray-700'}`}>
- {t('planner.allPlaces')}
- </p>
- <p className="text-xs text-gray-400">{t('planner.overview')}</p>
- </div>
- </button>
-
- {/* Day list */}
- <div className="flex-1 overflow-y-auto">
- {days.length === 0 ? (
- <div className="px-4 py-6 text-center">
- <CalendarDays className="w-8 h-8 text-gray-300 mx-auto mb-2" />
- <p className="text-xs text-gray-400">{t('planner.noDays')}</p>
- <p className="text-xs text-gray-300 mt-1">{t('planner.editTripToAddDays')}</p>
- </div>
- ) : (
- days.map((day, index) => {
- const isSelected = selectedDayId === day.id
- const dayAssignments = assignments[String(day.id)] || []
- const cost = dayTotal(day.id, assignments)
- const placeCount = dayAssignments.length
-
- return (
- <button
- key={day.id}
- onClick={() => onSelectDay(day.id)}
- className={`w-full text-left px-4 py-3 border-b border-gray-50 transition-colors ${
- isSelected
- ? 'bg-slate-50 border-l-2 border-l-slate-900'
- : 'hover:bg-gray-50'
- }`}
- >
- <div className="flex items-start justify-between gap-2">
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-1.5">
- <span className={`text-xs font-bold px-1.5 py-0.5 rounded ${
- isSelected ? 'bg-slate-900 text-white' : 'bg-gray-200 text-gray-600'
- }`}>
- {index + 1}
- </span>
- <span className={`text-sm font-medium truncate ${isSelected ? 'text-slate-900' : 'text-gray-700'}`}>
- {day.title || `Tag ${index + 1}`}
- </span>
- </div>
-
- {day.date && (
- <p className="text-xs text-gray-400 mt-1 ml-0.5">
- {formatDate(day.date)}
- </p>
- )}
-
- <div className="flex items-center gap-3 mt-1.5">
- {placeCount > 0 && (
- <span className="text-xs text-gray-400">
- {placeCount === 1 ? t('planner.placeOne') : t('planner.placeN', { n: placeCount })}
- </span>
- )}
- {cost > 0 && (
- <span className="text-xs text-emerald-600 font-medium">
- {cost.toFixed(0)} {currency}
- </span>
- )}
- </div>
- </div>
- </div>
-
- {/* Weather for this day */}
- {day.date && isSelected && (
- <div className="mt-2">
- <WeatherWidget date={day.date} compact />
- </div>
- )}
- </button>
- )
- })
- )}
- </div>
-
- {/* Budget summary footer */}
- {totalCost > 0 && (
- <div className="flex-shrink-0 border-t border-gray-100 px-4 py-3 bg-gray-50">
- <div className="flex items-center justify-between">
- <span className="text-xs text-gray-500">{t('planner.totalCost')}</span>
- <span className="text-sm font-semibold text-gray-800">
- {totalCost.toFixed(2)} {currency}
- </span>
- </div>
- </div>
- )}
- </div>
- )
-}
diff --git a/client/src/components/Planner/DraggablePlaceCard.jsx b/client/src/components/Planner/DraggablePlaceCard.jsx
deleted file mode 100644
index eee5c2576..000000000
--- a/client/src/components/Planner/DraggablePlaceCard.jsx
+++ /dev/null
@@ -1,107 +0,0 @@
-import React from 'react'
-import { useDraggable } from '@dnd-kit/core'
-import { MapPin, DollarSign, Check } from 'lucide-react'
-
-export default function DraggablePlaceCard({ place, isAssigned, onEdit }) {
- const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
- id: `place-${place.id}`,
- data: {
- type: 'place',
- place,
- },
- })
-
- const style = transform ? {
- transform: `translate3d(${transform.x}px, ${transform.y}px, 0)`,
- zIndex: isDragging ? 999 : undefined,
- } : undefined
-
- return (
- <div
- ref={setNodeRef}
- style={style}
- {...listeners}
- {...attributes}
- className={`
- group relative bg-white border rounded-lg p-3 cursor-grab active:cursor-grabbing
- transition-all select-none
- ${isDragging
- ? 'opacity-50 shadow-2xl border-slate-400 scale-105'
- : 'border-slate-200 hover:border-slate-300 hover:shadow-md place-card-hover'
- }
- `}
- onClick={e => {
- if (!isDragging && onEdit) {
- e.stopPropagation()
- onEdit(place)
- }
- }}
- >
- {/* Category left border accent */}
- {place.category && (
- <div
- className="absolute left-0 top-3 bottom-3 w-0.5 rounded-r"
- style={{ backgroundColor: place.category.color || '#6366f1' }}
- />
- )}
-
- <div className="pl-1">
- {/* Header */}
- <div className="flex items-start justify-between gap-1 mb-1">
- <p className="text-sm font-medium text-slate-800 leading-tight line-clamp-2 flex-1">
- {place.name}
- </p>
- {isAssigned && (
- <span className="flex-shrink-0 w-5 h-5 bg-emerald-100 rounded-full flex items-center justify-center" title="Already assigned to a day">
- <Check className="w-3 h-3 text-emerald-600" />
- </span>
- )}
- </div>
-
- {/* Address */}
- {place.address && (
- <p className="text-xs text-slate-400 truncate flex items-center gap-1 mb-1.5">
- <MapPin className="w-3 h-3 flex-shrink-0" />
- {place.address}
- </p>
- )}
-
- {/* Category badge */}
- {place.category && (
- <span
- className="inline-block text-[10px] px-1.5 py-0.5 rounded text-white font-medium mr-1"
- style={{ backgroundColor: place.category.color || '#6366f1' }}
- >
- {place.category.name}
- </span>
- )}
-
- {/* Price */}
- {place.price != null && (
- <span className="inline-flex items-center gap-0.5 text-[10px] text-emerald-700 bg-emerald-50 px-1.5 py-0.5 rounded">
- <DollarSign className="w-2.5 h-2.5" />
- {Number(place.price).toLocaleString()} {place.currency || ''}
- </span>
- )}
-
- {/* Tags */}
- {place.tags && place.tags.length > 0 && (
- <div className="flex flex-wrap gap-1 mt-1.5">
- {place.tags.slice(0, 3).map(tag => (
- <span
- key={tag.id}
- className="text-[10px] px-1.5 py-0.5 rounded-full text-white font-medium"
- style={{ backgroundColor: tag.color || '#6366f1' }}
- >
- {tag.name}
- </span>
- ))}
- {place.tags.length > 3 && (
- <span className="text-[10px] text-slate-400">+{place.tags.length - 3}</span>
- )}
- </div>
- )}
- </div>
- </div>
- )
-}
diff --git a/client/src/components/Planner/PlaceDetailPanel.jsx b/client/src/components/Planner/PlaceDetailPanel.jsx
deleted file mode 100644
index 595bfd6fe..000000000
--- a/client/src/components/Planner/PlaceDetailPanel.jsx
+++ /dev/null
@@ -1,225 +0,0 @@
-import React, { useState, useEffect } from 'react'
-import { X, ExternalLink, Phone, MapPin, Clock, Euro, Edit2, Trash2, Plus, Minus } from 'lucide-react'
-import { mapsApi } from '../../api/client'
-import { useTranslation } from '../../i18n'
-
-export function PlaceDetailPanel({
- place, categories, tags, selectedDayId, dayAssignments,
- onClose, onEdit, onDelete, onAssignToDay, onRemoveAssignment,
-}) {
- const { t } = useTranslation()
- const [googlePhoto, setGooglePhoto] = useState(null)
- const [photoAttribution, setPhotoAttribution] = useState(null)
-
- useEffect(() => {
- if (!place?.google_place_id || place?.image_url) {
- setGooglePhoto(null)
- return
- }
- mapsApi.placePhoto(place.google_place_id)
- .then(data => {
- setGooglePhoto(data.photoUrl || null)
- setPhotoAttribution(data.attribution || null)
- })
- .catch(() => setGooglePhoto(null))
- }, [place?.google_place_id, place?.image_url])
-
- if (!place) return null
-
- const displayPhoto = place.image_url || googlePhoto
- const category = categories?.find(c => c.id === place.category_id)
- const placeTags = (place.tags || []).map(t =>
- tags?.find(tg => tg.id === (t.id || t)) || t
- ).filter(Boolean)
-
- const assignmentInDay = selectedDayId
- ? dayAssignments?.find(a => a.place?.id === place.id)
- : null
-
- return (
- <div className="bg-white">
- {/* Image */}
- {displayPhoto ? (
- <div className="relative">
- <img
- src={displayPhoto}
- alt={place.name}
- className="w-full h-40 object-cover"
- onError={e => { e.target.style.display = 'none' }}
- />
- <button
- onClick={onClose}
- className="absolute top-2 right-2 bg-white/90 rounded-full p-1.5 shadow"
- >
- <X className="w-4 h-4 text-gray-600" />
- </button>
- {photoAttribution && !place.image_url && (
- <div className="absolute bottom-1 right-2 text-[10px] text-white/70">
- © {photoAttribution}
- </div>
- )}
- </div>
- ) : (
- <div
- className="h-24 flex items-center justify-center relative"
- style={{ backgroundColor: category?.color ? `${category.color}20` : '#f0f0ff' }}
- >
- <span className="text-4xl">{category?.icon || '📍'}</span>
- <button
- onClick={onClose}
- className="absolute top-2 right-2 bg-white/90 rounded-full p-1.5 shadow"
- >
- <X className="w-4 h-4 text-gray-600" />
- </button>
- </div>
- )}
-
- {/* Content */}
- <div className="p-4 space-y-3">
- {/* Name + category */}
- <div>
- <h3 className="font-bold text-gray-900 text-base leading-snug">{place.name}</h3>
- {category && (
- <span
- className="inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full mt-1"
- style={{ backgroundColor: `${category.color}20`, color: category.color }}
- >
- {category.icon} {category.name}
- </span>
- )}
- </div>
-
- {/* Quick info row */}
- <div className="flex flex-wrap gap-2">
- {place.place_time && (
- <div className="flex items-center gap-1 text-xs text-gray-600 bg-gray-50 px-2 py-1 rounded-lg">
- <Clock className="w-3 h-3" />
- {place.place_time}
- </div>
- )}
- {place.price > 0 && (
- <div className="flex items-center gap-1 text-xs text-emerald-700 bg-emerald-50 px-2 py-1 rounded-lg">
- <Euro className="w-3 h-3" />
- {place.price} {place.currency}
- </div>
- )}
- </div>
-
- {/* Address */}
- {place.address && (
- <div className="flex items-start gap-1.5 text-xs text-gray-600">
- <MapPin className="w-3.5 h-3.5 flex-shrink-0 mt-0.5 text-gray-400" />
- <span>{place.address}</span>
- </div>
- )}
-
- {/* Coordinates */}
- {place.lat && place.lng && (
- <div className="text-xs text-gray-400">
- {Number(place.lat).toFixed(6)}, {Number(place.lng).toFixed(6)}
- </div>
- )}
-
- {/* Links */}
- <div className="flex gap-2">
- {place.website && (
- <a
- href={place.website}
- target="_blank"
- rel="noopener noreferrer"
- className="flex items-center gap-1 text-xs text-slate-700 hover:underline"
- >
- <ExternalLink className="w-3 h-3" />
- Website
- </a>
- )}
- {place.phone && (
- <a
- href={`tel:${place.phone}`}
- className="flex items-center gap-1 text-xs text-slate-700 hover:underline"
- >
- <Phone className="w-3 h-3" />
- {place.phone}
- </a>
- )}
- </div>
-
- {/* Description */}
- {place.description && (
- <p className="text-xs text-gray-600 leading-relaxed">{place.description}</p>
- )}
-
- {/* Notes */}
- {place.notes && (
- <div className="bg-amber-50 border border-amber-100 rounded-lg px-3 py-2">
- <p className="text-xs text-amber-800 leading-relaxed">📝 {place.notes}</p>
- </div>
- )}
-
- {/* Tags */}
- {placeTags.length > 0 && (
- <div className="flex flex-wrap gap-1">
- {placeTags.map((tag, i) => (
- <span
- key={tag.id || i}
- className="text-xs px-2 py-0.5 rounded-full"
- style={{ backgroundColor: `${tag.color || '#6366f1'}20`, color: tag.color || '#6366f1' }}
- >
- {tag.name}
- </span>
- ))}
- </div>
- )}
-
- {/* Day assignment actions */}
- {selectedDayId && (
- <div className="pt-1">
- {assignmentInDay ? (
- <button
- onClick={() => onRemoveAssignment(selectedDayId, assignmentInDay.id)}
- className="w-full flex items-center justify-center gap-2 py-2 text-sm text-red-600 border border-red-200 rounded-lg hover:bg-red-50"
- >
- <Minus className="w-4 h-4" />
- {t('planner.removeFromDay')}
- </button>
- ) : (
- <button
- onClick={() => onAssignToDay(place.id)}
- className="w-full flex items-center justify-center gap-2 py-2 text-sm text-white bg-slate-900 rounded-lg hover:bg-slate-700"
- >
- <Plus className="w-4 h-4" />
- {t('planner.addToThisDay')}
- </button>
- )}
- </div>
- )}
-
- {/* Edit / Delete */}
- <div className="flex gap-2 pt-1">
- <button
- onClick={onEdit}
- className="flex-1 flex items-center justify-center gap-1.5 py-2 text-xs text-gray-700 border border-gray-200 rounded-lg hover:bg-gray-50"
- >
- <Edit2 className="w-3.5 h-3.5" />
- {t('common.edit')}
- </button>
- <button
- onClick={onDelete}
- className="flex items-center justify-center gap-1.5 py-2 px-3 text-xs text-red-600 border border-red-200 rounded-lg hover:bg-red-50"
- >
- <Trash2 className="w-3.5 h-3.5" />
- </button>
- </div>
- </div>
- </div>
- )
-}
-
-function formatDateTime(dt) {
- if (!dt) return ''
- try {
- return new Date(dt).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })
- } catch {
- return dt
- }
-}
diff --git a/client/src/components/Planner/PlaceFormModal.jsx b/client/src/components/Planner/PlaceFormModal.tsx
similarity index 91%
rename from client/src/components/Planner/PlaceFormModal.jsx
rename to client/src/components/Planner/PlaceFormModal.tsx
index 0dc650542..a40ce4858 100644
--- a/client/src/components/Planner/PlaceFormModal.jsx
+++ b/client/src/components/Planner/PlaceFormModal.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect, useRef, useMemo } from 'react'
+import { useState, useEffect, useRef, useMemo } from 'react'
import Modal from '../shared/Modal'
import CustomSelect from '../shared/CustomSelect'
import { mapsApi } from '../../api/client'
@@ -7,8 +7,23 @@ import { useToast } from '../shared/Toast'
import { Search, Paperclip, X, AlertTriangle } from 'lucide-react'
import { useTranslation } from '../../i18n'
import CustomTimePicker from '../shared/CustomTimePicker'
+import type { Place, Category, Assignment } from '../../types'
-const DEFAULT_FORM = {
+interface PlaceFormData {
+ name: string
+ description: string
+ address: string
+ lat: string
+ lng: string
+ category_id: string
+ place_time: string
+ end_time: string
+ notes: string
+ transport_mode: string
+ website: string
+}
+
+const DEFAULT_FORM: PlaceFormData = {
name: '',
description: '',
address: '',
@@ -22,10 +37,22 @@ const DEFAULT_FORM = {
website: '',
}
+interface PlaceFormModalProps {
+ isOpen: boolean
+ onClose: () => void
+ onSave: (data: PlaceFormData, files?: File[]) => Promise<void> | void
+ place: Place | null
+ tripId: number
+ categories: Category[]
+ onCategoryCreated: (category: Category) => void
+ assignmentId: number | null
+ dayAssignments?: Assignment[]
+}
+
export default function PlaceFormModal({
isOpen, onClose, onSave, place, tripId, categories,
onCategoryCreated, assignmentId, dayAssignments = [],
-}) {
+}: PlaceFormModalProps) {
const [form, setForm] = useState(DEFAULT_FORM)
const [mapsSearch, setMapsSearch] = useState('')
const [mapsResults, setMapsResults] = useState([])
@@ -70,7 +97,7 @@ export default function PlaceFormModal({
try {
const result = await mapsApi.search(mapsSearch, language)
setMapsResults(result.places || [])
- } catch (err) {
+ } catch (err: unknown) {
toast.error(t('places.mapsSearchError'))
} finally {
setIsSearchingMaps(false)
@@ -97,13 +124,13 @@ export default function PlaceFormModal({
if (cat) setForm(prev => ({ ...prev, category_id: cat.id }))
setNewCategoryName('')
setShowNewCategory(false)
- } catch (err) {
+ } catch (err: unknown) {
toast.error(t('places.categoryCreateError'))
}
}
const handleFileAdd = (e) => {
- const files = Array.from(e.target.files || [])
+ const files = Array.from((e.target as HTMLInputElement).files || [])
setPendingFiles(prev => [...prev, ...files])
e.target.value = ''
}
@@ -116,7 +143,7 @@ export default function PlaceFormModal({
const handlePaste = (e) => {
const items = e.clipboardData?.items
if (!items) return
- for (const item of items) {
+ for (const item of Array.from(items)) {
if (item.type.startsWith('image/') || item.type === 'application/pdf') {
e.preventDefault()
const file = item.getAsFile()
@@ -144,8 +171,8 @@ export default function PlaceFormModal({
_pendingFiles: pendingFiles.length > 0 ? pendingFiles : undefined,
})
onClose()
- } catch (err) {
- toast.error(err.message || t('places.saveError'))
+ } catch (err: unknown) {
+ toast.error(err instanceof Error ? err.message : t('places.saveError'))
} finally {
setIsSaving(false)
}
@@ -371,7 +398,16 @@ export default function PlaceFormModal({
)
}
-function TimeSection({ form, handleChange, assignmentId, dayAssignments, hasTimeError, t }) {
+interface TimeSectionProps {
+ form: PlaceFormData
+ handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => 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 []
diff --git a/client/src/components/Planner/PlaceInspector.jsx b/client/src/components/Planner/PlaceInspector.tsx
similarity index 94%
rename from client/src/components/Planner/PlaceInspector.jsx
rename to client/src/components/Planner/PlaceInspector.tsx
index 1ee8c99b5..68dff2dd7 100644
--- a/client/src/components/Planner/PlaceInspector.jsx
+++ b/client/src/components/Planner/PlaceInspector.tsx
@@ -5,6 +5,7 @@ import { mapsApi } from '../../api/client'
import { useSettingsStore } from '../../store/settingsStore'
import { getCategoryIcon } from '../shared/categoryIcons'
import { useTranslation } from '../../i18n'
+import type { Place, Category, Day, Assignment, Reservation, TripFile, AssignmentsMap } from '../../types'
const detailsCache = new Map()
@@ -97,11 +98,37 @@ function formatFileSize(bytes) {
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}
+interface TripMember {
+ id: number
+ username: string
+ avatar_url?: string | null
+}
+
+interface PlaceInspectorProps {
+ place: Place | null
+ categories: Category[]
+ days: Day[]
+ selectedDayId: number | null
+ selectedAssignmentId: number | null
+ assignments: AssignmentsMap
+ reservations?: Reservation[]
+ onClose: () => void
+ onEdit: () => void
+ onDelete: () => void
+ onAssignToDay: (placeId: number, dayId: number) => void
+ onRemoveAssignment: (assignmentId: number, dayId: number) => void
+ files: TripFile[]
+ onFileUpload: (fd: FormData) => Promise<void>
+ tripMembers?: TripMember[]
+ onSetParticipants: (assignmentId: number, dayId: number, participantIds: number[]) => void
+ onUpdatePlace: (placeId: number, data: Partial<Place>) => void
+}
+
export default function PlaceInspector({
place, categories, days, selectedDayId, selectedAssignmentId, assignments, reservations = [],
onClose, onEdit, onDelete, onAssignToDay, onRemoveAssignment,
files, onFileUpload, tripMembers = [], onSetParticipants, onUpdatePlace,
-}) {
+}: PlaceInspectorProps) {
const { t, locale, language } = useTranslation()
const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'
const [hoursExpanded, setHoursExpanded] = useState(false)
@@ -147,7 +174,7 @@ export default function PlaceInspector({
const placeFiles = (files || []).filter(f => String(f.place_id) === String(place.id))
const handleFileUpload = useCallback(async (e) => {
- const selectedFiles = Array.from(e.target.files || [])
+ const selectedFiles = Array.from((e.target as HTMLInputElement).files || [])
if (!selectedFiles.length || !onFileUpload) return
setIsUploading(true)
try {
@@ -158,7 +185,7 @@ export default function PlaceInspector({
await onFileUpload(fd)
}
setFilesExpanded(true)
- } catch (err) {
+ } catch (err: unknown) {
console.error('Upload failed', err)
} finally {
setIsUploading(false)
@@ -488,7 +515,14 @@ export default function PlaceInspector({
)
}
-function Chip({ icon, text, color = 'var(--text-secondary)', bg = 'var(--bg-hover)' }) {
+interface ChipProps {
+ icon: React.ReactNode
+ text: React.ReactNode
+ color?: string
+ bg?: string
+}
+
+function Chip({ icon, text, color = 'var(--text-secondary)', bg = 'var(--bg-hover)' }: ChipProps) {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '3px 9px', borderRadius: 99, background: bg, color, fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minWidth: 0 }}>
<span style={{ flexShrink: 0, display: 'flex' }}>{icon}</span>
@@ -497,7 +531,12 @@ function Chip({ icon, text, color = 'var(--text-secondary)', bg = 'var(--bg-hove
)
}
-function Row({ icon, children }) {
+interface RowProps {
+ icon: React.ReactNode
+ children: React.ReactNode
+}
+
+function Row({ icon, children }: RowProps) {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<div style={{ flexShrink: 0 }}>{icon}</div>
@@ -506,7 +545,14 @@ function Row({ icon, children }) {
)
}
-function ActionButton({ onClick, variant, icon, label }) {
+interface ActionButtonProps {
+ onClick: () => void
+ variant: 'primary' | 'ghost' | 'danger'
+ icon: React.ReactNode
+ label: React.ReactNode
+}
+
+function ActionButton({ onClick, variant, icon, label }: ActionButtonProps) {
const base = {
primary: { background: 'var(--accent)', color: 'var(--accent-text)', border: 'none', hoverBg: 'var(--text-secondary)' },
ghost: { background: 'var(--bg-hover)', color: 'var(--text-secondary)', border: 'none', hoverBg: 'var(--bg-tertiary)' },
@@ -531,7 +577,17 @@ function ActionButton({ onClick, variant, icon, label }) {
)
}
-function ParticipantsBox({ tripMembers, participantIds, allJoined, onSetParticipants, selectedAssignmentId, selectedDayId, t }) {
+interface ParticipantsBoxProps {
+ tripMembers: TripMember[]
+ participantIds: number[]
+ allJoined: boolean
+ onSetParticipants: (assignmentId: number, dayId: number, participantIds: number[]) => void
+ selectedAssignmentId: number | null
+ selectedDayId: number | null
+ t: (key: string) => string
+}
+
+function ParticipantsBox({ tripMembers, participantIds, allJoined, onSetParticipants, selectedAssignmentId, selectedDayId, t }: ParticipantsBoxProps) {
const [showAdd, setShowAdd] = React.useState(false)
const [hoveredId, setHoveredId] = React.useState(null)
diff --git a/client/src/components/Planner/PlacesPanel.jsx b/client/src/components/Planner/PlacesPanel.jsx
deleted file mode 100644
index e217f630f..000000000
--- a/client/src/components/Planner/PlacesPanel.jsx
+++ /dev/null
@@ -1,223 +0,0 @@
-import React, { useState, useMemo } from 'react'
-import DraggablePlaceCard from './DraggablePlaceCard'
-import { Search, Plus, Filter, Map, X, SlidersHorizontal } from 'lucide-react'
-
-export default function PlacesPanel({
- places,
- categories,
- tags,
- assignments,
- tripId,
- onAddPlace,
- onEditPlace,
- hasMapKey,
- onSearchMaps,
-}) {
- const [search, setSearch] = useState('')
- const [selectedCategory, setSelectedCategory] = useState('')
- const [selectedTags, setSelectedTags] = useState([])
- const [showFilters, setShowFilters] = useState(false)
-
- // Get set of assigned place IDs (for any day)
- const assignedPlaceIds = useMemo(() => {
- const ids = new Set()
- Object.values(assignments || {}).forEach(dayAssignments => {
- dayAssignments.forEach(a => {
- if (a.place?.id) ids.add(a.place.id)
- })
- })
- return ids
- }, [assignments])
-
- const filteredPlaces = useMemo(() => {
- return places.filter(place => {
- if (search) {
- const q = search.toLowerCase()
- if (!place.name.toLowerCase().includes(q) &&
- !place.address?.toLowerCase().includes(q) &&
- !place.description?.toLowerCase().includes(q)) {
- return false
- }
- }
- if (selectedCategory && place.category_id !== parseInt(selectedCategory)) {
- return false
- }
- if (selectedTags.length > 0) {
- const placeTags = (place.tags || []).map(t => t.id)
- if (!selectedTags.every(tagId => placeTags.includes(tagId))) {
- return false
- }
- }
- return true
- })
- }, [places, search, selectedCategory, selectedTags])
-
- const toggleTag = (tagId) => {
- setSelectedTags(prev =>
- prev.includes(tagId) ? prev.filter(id => id !== tagId) : [...prev, tagId]
- )
- }
-
- const clearFilters = () => {
- setSearch('')
- setSelectedCategory('')
- setSelectedTags([])
- }
-
- const hasActiveFilters = search || selectedCategory || selectedTags.length > 0
-
- return (
- <div className="flex flex-col h-full bg-white border-r border-slate-200">
- {/* Header */}
- <div className="p-3 border-b border-slate-100">
- <div className="flex items-center justify-between mb-2">
- <h2 className="text-sm font-semibold text-slate-800">
- Places
- <span className="ml-1.5 text-xs font-normal text-slate-400">
- ({filteredPlaces.length}{filteredPlaces.length !== places.length ? `/${places.length}` : ''})
- </span>
- </h2>
- <div className="flex gap-1">
- {hasMapKey && (
- <button
- onClick={onSearchMaps}
- className="p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-50 rounded-lg transition-colors"
- title="Search Google Maps"
- >
- <Map className="w-4 h-4" />
- </button>
- )}
- <button
- onClick={() => setShowFilters(!showFilters)}
- className={`p-1.5 rounded-lg transition-colors ${
- showFilters || hasActiveFilters
- ? 'text-slate-700 bg-slate-50'
- : 'text-slate-400 hover:text-slate-600 hover:bg-slate-100'
- }`}
- title="Filters"
- >
- <SlidersHorizontal className="w-4 h-4" />
- </button>
- </div>
- </div>
-
- {/* Search */}
- <div className="relative">
- <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
- <input
- type="text"
- value={search}
- onChange={e => setSearch(e.target.value)}
- placeholder="Search places..."
- className="w-full pl-8 pr-3 py-1.5 text-sm border border-slate-200 rounded-lg focus:ring-2 focus:ring-slate-900 focus:border-transparent transition-all"
- />
- {search && (
- <button
- onClick={() => setSearch('')}
- className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
- >
- <X className="w-3.5 h-3.5" />
- </button>
- )}
- </div>
-
- {/* Filters */}
- {showFilters && (
- <div className="mt-2 space-y-2">
- {/* Category filter */}
- {categories.length > 0 && (
- <select
- value={selectedCategory}
- onChange={e => setSelectedCategory(e.target.value)}
- className="w-full px-2.5 py-1.5 text-sm border border-slate-200 rounded-lg focus:ring-2 focus:ring-slate-900 focus:border-transparent bg-white"
- >
- <option value="">All categories</option>
- {categories.map(cat => (
- <option key={cat.id} value={cat.id}>{cat.name}</option>
- ))}
- </select>
- )}
-
- {/* Tag filters */}
- {tags.length > 0 && (
- <div className="flex flex-wrap gap-1">
- {tags.map(tag => (
- <button
- key={tag.id}
- onClick={() => toggleTag(tag.id)}
- className={`text-xs px-2 py-0.5 rounded-full font-medium transition-all ${
- selectedTags.includes(tag.id)
- ? 'text-white shadow-sm'
- : 'text-white opacity-50 hover:opacity-80'
- }`}
- style={{ backgroundColor: tag.color || '#6366f1' }}
- >
- {tag.name}
- </button>
- ))}
- </div>
- )}
-
- {hasActiveFilters && (
- <button
- onClick={clearFilters}
- className="text-xs text-slate-500 hover:text-red-500 flex items-center gap-1"
- >
- <X className="w-3 h-3" />
- Clear filters
- </button>
- )}
- </div>
- )}
- </div>
-
- {/* Add place button */}
- <div className="px-3 py-2 border-b border-slate-100">
- <button
- onClick={onAddPlace}
- className="w-full flex items-center justify-center gap-2 py-2 text-sm text-slate-700 hover:text-slate-900 bg-slate-50 hover:bg-slate-100 rounded-lg transition-colors font-medium"
- >
- <Plus className="w-4 h-4" />
- Add Place
- </button>
- </div>
-
- {/* Places list */}
- <div className="flex-1 overflow-y-auto p-3 space-y-2 scroll-container">
- {filteredPlaces.length === 0 ? (
- <div className="text-center py-8">
- <div className="w-12 h-12 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-3">
- <Search className="w-6 h-6 text-slate-400" />
- </div>
- {places.length === 0 ? (
- <>
- <p className="text-sm font-medium text-slate-600">No places yet</p>
- <p className="text-xs text-slate-400 mt-1">Add places and drag them to days</p>
- <button
- onClick={onAddPlace}
- className="mt-3 text-sm text-slate-700 hover:text-slate-900 font-medium"
- >
- + Add your first place
- </button>
- </>
- ) : (
- <>
- <p className="text-sm font-medium text-slate-600">No matches found</p>
- <p className="text-xs text-slate-400 mt-1">Try adjusting your filters</p>
- </>
- )}
- </div>
- ) : (
- filteredPlaces.map(place => (
- <DraggablePlaceCard
- key={place.id}
- place={place}
- isAssigned={assignedPlaceIds.has(place.id)}
- onEdit={onEditPlace}
- />
- ))
- )}
- </div>
- </div>
- )
-}
diff --git a/client/src/components/Planner/PlacesSidebar.jsx b/client/src/components/Planner/PlacesSidebar.tsx
similarity index 95%
rename from client/src/components/Planner/PlacesSidebar.jsx
rename to client/src/components/Planner/PlacesSidebar.tsx
index 7cb23a13d..62c054f3e 100644
--- a/client/src/components/Planner/PlacesSidebar.jsx
+++ b/client/src/components/Planner/PlacesSidebar.tsx
@@ -1,16 +1,33 @@
-import React, { useState } from 'react'
import ReactDOM from 'react-dom'
+import { useState } from 'react'
+import DOM from 'react-dom'
import { Search, Plus, X, CalendarDays, Pencil, Trash2, ExternalLink, Navigation } from 'lucide-react'
import PlaceAvatar from '../shared/PlaceAvatar'
import { getCategoryIcon } from '../shared/categoryIcons'
import { useTranslation } from '../../i18n'
import CustomSelect from '../shared/CustomSelect'
import { useContextMenu, ContextMenu } from '../shared/ContextMenu'
+import type { Place, Category, Day, AssignmentsMap } from '../../types'
+
+interface PlacesSidebarProps {
+ places: Place[]
+ categories: Category[]
+ assignments: AssignmentsMap
+ selectedDayId: number | null
+ selectedPlaceId: number | null
+ onPlaceClick: (placeId: number | null) => void
+ onAddPlace: () => void
+ onAssignToDay: (placeId: number, dayId: number) => void
+ onEditPlace: (place: Place) => void
+ onDeletePlace: (placeId: number) => void
+ days: Day[]
+ isMobile: boolean
+}
export default function PlacesSidebar({
places, categories, assignments, selectedDayId, selectedPlaceId,
onPlaceClick, onAddPlace, onAssignToDay, onEditPlace, onDeletePlace, days, isMobile,
-}) {
+}: PlacesSidebarProps) {
const { t } = useTranslation()
const ctxMenu = useContextMenu()
const [search, setSearch] = useState('')
diff --git a/client/src/components/Planner/PlannerSidebar.jsx b/client/src/components/Planner/PlannerSidebar.jsx
deleted file mode 100644
index c0d6ef638..000000000
--- a/client/src/components/Planner/PlannerSidebar.jsx
+++ /dev/null
@@ -1,876 +0,0 @@
-import React, { useState, useCallback, useEffect, useRef, useMemo, useLayoutEffect } from 'react'
-import { FixedSizeList } from 'react-window'
-import {
- Plus, Search, X, Navigation, RotateCcw, ExternalLink,
- ChevronDown, ChevronRight, ChevronUp, Clock, MapPin,
- CalendarDays, FileText, Check, Pencil, Trash2,
-} from 'lucide-react'
-import { calculateRoute, generateGoogleMapsUrl, optimizeRoute } from '../Map/RouteCalculator'
-import PackingListPanel from '../Packing/PackingListPanel'
-import FileManager from '../Files/FileManager'
-import { ReservationModal } from './ReservationModal'
-import { PlaceDetailPanel } from './PlaceDetailPanel'
-import WeatherWidget from '../Weather/WeatherWidget'
-import { useTripStore } from '../../store/tripStore'
-import { useToast } from '../shared/Toast'
-import { useTranslation } from '../../i18n'
-
-function formatShortDate(dateStr) {
- if (!dateStr) return ''
- return new Date(dateStr + 'T00:00:00').toLocaleDateString('de-DE', {
- day: 'numeric', month: 'short',
- })
-}
-
-function formatDateTime(dt) {
- if (!dt) return ''
- try {
- return new Date(dt).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })
- } catch { return dt }
-}
-
-export default function PlannerSidebar({
- trip, days, places, categories, tags,
- assignments, reservations, packingItems,
- selectedDayId, selectedPlaceId,
- onSelectDay, onPlaceClick, onPlaceEdit, onPlaceDelete,
- onAssignToDay, onRemoveAssignment, onReorder,
- onAddPlace, onEditTrip, onRouteCalculated, tripId,
-}) {
- const [activeSegment, setActiveSegment] = useState('plan')
- const [search, setSearch] = useState('')
- const [categoryFilter, setCategoryFilter] = useState('')
- const [isCalculatingRoute, setIsCalculatingRoute] = useState(false)
- const [showReservationModal, setShowReservationModal] = useState(false)
- const [editingReservation, setEditingReservation] = useState(null)
- const [routeInfo, setRouteInfo] = useState(null)
- const [expandedDays, setExpandedDays] = useState(new Set())
- // Day notes inline UI state: { [dayId]: { mode: 'add'|'edit', noteId?, text, time } }
- const [noteUi, setNoteUi] = useState({})
- const noteInputRef = useRef(null)
-
- const tripStore = useTripStore()
- const toast = useToast()
- const { t } = useTranslation()
-
- const SEGMENTS = [
- { id: 'plan', label: 'Plan' },
- { id: 'orte', label: t('planner.places') },
- { id: 'reservierungen', label: t('planner.bookings') },
- { id: 'packliste', label: t('planner.packingList') },
- { id: 'dokumente', label: t('planner.documents') },
- ]
-
- const dayNotes = tripStore.dayNotes || {}
- const placesListRef = useRef(null)
- const [placesListHeight, setPlacesListHeight] = useState(400)
-
- useLayoutEffect(() => {
- if (!placesListRef.current) return
- const ro = new ResizeObserver(([entry]) => {
- setPlacesListHeight(entry.contentRect.height)
- })
- ro.observe(placesListRef.current)
- return () => ro.disconnect()
- }, [activeSegment])
-
- // Auto-expand selected day
- useEffect(() => {
- if (selectedDayId) {
- setExpandedDays(prev => new Set([...prev, selectedDayId]))
- }
- }, [selectedDayId])
-
- const toggleDay = (dayId) => {
- setExpandedDays(prev => {
- const next = new Set(prev)
- if (next.has(dayId)) next.delete(dayId)
- else next.add(dayId)
- return next
- })
- }
-
- const getDayAssignments = (dayId) =>
- (assignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index)
-
- const selectedDayAssignments = selectedDayId ? getDayAssignments(selectedDayId) : []
- const selectedDay = selectedDayId ? days.find(d => d.id === selectedDayId) : null
-
- const filteredPlaces = useMemo(() => places.filter(p => {
- const matchSearch = !search || p.name.toLowerCase().includes(search.toLowerCase()) ||
- (p.address || '').toLowerCase().includes(search.toLowerCase())
- const matchCat = !categoryFilter || String(p.category_id) === String(categoryFilter)
- return matchSearch && matchCat
- }), [places, search, categoryFilter])
-
- const isAssignedToDay = (placeId) =>
- selectedDayId && selectedDayAssignments.some(a => a.place?.id === placeId)
-
- const totalCost = days.reduce((sum, d) => {
- const da = assignments[String(d.id)] || []
- return sum + da.reduce((s, a) => s + (parseFloat(a.place?.price) || 0), 0)
- }, 0)
- const currency = trip?.currency || 'EUR'
-
- const filteredReservations = selectedDayId
- ? reservations.filter(r => String(r.day_id) === String(selectedDayId) || !r.day_id)
- : reservations
-
- // Get representative location for a day (first place with coords)
- const getDayLocation = (dayId) => {
- const da = getDayAssignments(dayId)
- const p = da.find(a => a.place?.lat && a.place?.lng)
- return p ? { lat: p.place.lat, lng: p.place.lng } : null
- }
-
- // Route handlers
- const handleCalculateRoute = async () => {
- if (!selectedDayId) return
- const waypoints = selectedDayAssignments
- .map(a => a.place)
- .filter(p => p?.lat && p?.lng)
- .map(p => ({ lat: p.lat, lng: p.lng }))
- if (waypoints.length < 2) {
- toast.error(t('planner.minTwoPlaces'))
- return
- }
- setIsCalculatingRoute(true)
- try {
- const result = await calculateRoute(waypoints, 'walking')
- setRouteInfo({ distance: result.distanceText, duration: result.durationText })
- onRouteCalculated?.(result)
- toast.success(t('planner.routeCalculated'))
- } catch {
- toast.error(t('planner.routeCalcFailed'))
- } finally {
- setIsCalculatingRoute(false)
- }
- }
-
- const handleOptimizeRoute = async () => {
- if (!selectedDayId || selectedDayAssignments.length < 3) return
- const withCoords = selectedDayAssignments.map(a => a.place).filter(p => p?.lat && p?.lng)
- const optimized = optimizeRoute(withCoords)
- const reorderedIds = optimized
- .map(p => selectedDayAssignments.find(a => a.place?.id === p.id)?.id)
- .filter(Boolean)
- // Append assignments without coordinates at end
- for (const a of selectedDayAssignments) {
- if (!reorderedIds.includes(a.id)) reorderedIds.push(a.id)
- }
- await onReorder(selectedDayId, reorderedIds)
- toast.success(t('planner.routeOptimized'))
- }
-
- const handleOpenGoogleMaps = () => {
- const ps = selectedDayAssignments.map(a => a.place).filter(p => p?.lat && p?.lng)
- const url = generateGoogleMapsUrl(ps)
- if (url) window.open(url, '_blank')
- else toast.error(t('planner.noGeoPlaces'))
- }
-
- const handleMoveUp = async (dayId, idx) => {
- const da = getDayAssignments(dayId)
- if (idx === 0) return
- const ids = da.map(a => a.id)
- ;[ids[idx - 1], ids[idx]] = [ids[idx], ids[idx - 1]]
- await onReorder(dayId, ids)
- }
-
- const handleMoveDown = async (dayId, idx) => {
- const da = getDayAssignments(dayId)
- if (idx === da.length - 1) return
- const ids = da.map(a => a.id)
- ;[ids[idx], ids[idx + 1]] = [ids[idx + 1], ids[idx]]
- await onReorder(dayId, ids)
- }
-
- // Merge place assignments + day notes into a single sorted list
- const getMergedDayItems = (dayId) => {
- const da = getDayAssignments(dayId)
- const dn = (dayNotes[String(dayId)] || []).slice().sort((a, b) => a.sort_order - b.sort_order)
- return [
- ...da.map(a => ({ type: 'place', sortKey: a.order_index, data: a })),
- ...dn.map(n => ({ type: 'note', sortKey: n.sort_order, data: n })),
- ].sort((a, b) => a.sortKey - b.sortKey)
- }
-
- const openAddNote = (dayId) => {
- const merged = getMergedDayItems(dayId)
- const maxKey = merged.length > 0 ? Math.max(...merged.map(i => i.sortKey)) : -1
- setNoteUi(prev => ({ ...prev, [dayId]: { mode: 'add', text: '', time: '', sortOrder: maxKey + 1 } }))
- setTimeout(() => noteInputRef.current?.focus(), 50)
- }
-
- const openEditNote = (dayId, note) => {
- setNoteUi(prev => ({ ...prev, [dayId]: { mode: 'edit', noteId: note.id, text: note.text, time: note.time || '' } }))
- setTimeout(() => noteInputRef.current?.focus(), 50)
- }
-
- const cancelNote = (dayId) => {
- setNoteUi(prev => { const n = { ...prev }; delete n[dayId]; return n })
- }
-
- const saveNote = async (dayId) => {
- const ui = noteUi[dayId]
- if (!ui?.text?.trim()) return
- try {
- if (ui.mode === 'add') {
- await tripStore.addDayNote(tripId, dayId, { text: ui.text.trim(), time: ui.time || null, sort_order: ui.sortOrder })
- } else {
- await tripStore.updateDayNote(tripId, dayId, ui.noteId, { text: ui.text.trim(), time: ui.time || null })
- }
- cancelNote(dayId)
- } catch (err) {
- toast.error(err.message)
- }
- }
-
- const handleDeleteNote = async (dayId, noteId) => {
- try {
- await tripStore.deleteDayNote(tripId, dayId, noteId)
- } catch (err) {
- toast.error(err.message)
- }
- }
-
- const handleNoteMoveUp = async (dayId, noteId) => {
- const merged = getMergedDayItems(dayId)
- const idx = merged.findIndex(item => item.type === 'note' && item.data.id === noteId)
- if (idx <= 0) return
- const newSortOrder = idx >= 2
- ? (merged[idx - 2].sortKey + merged[idx - 1].sortKey) / 2
- : merged[idx - 1].sortKey - 1
- try {
- await tripStore.updateDayNote(tripId, dayId, noteId, { sort_order: newSortOrder })
- } catch (err) {
- toast.error(err.message)
- }
- }
-
- const handleNoteMoveDown = async (dayId, noteId) => {
- const merged = getMergedDayItems(dayId)
- const idx = merged.findIndex(item => item.type === 'note' && item.data.id === noteId)
- if (idx === -1 || idx >= merged.length - 1) return
- const newSortOrder = idx < merged.length - 2
- ? (merged[idx + 1].sortKey + merged[idx + 2].sortKey) / 2
- : merged[idx + 1].sortKey + 1
- try {
- await tripStore.updateDayNote(tripId, dayId, noteId, { sort_order: newSortOrder })
- } catch (err) {
- toast.error(err.message)
- }
- }
-
- const handleSaveReservation = async (data) => {
- try {
- if (editingReservation) {
- await tripStore.updateReservation(tripId, editingReservation.id, data)
- toast.success(t('planner.reservationUpdated'))
- } else {
- await tripStore.addReservation(tripId, { ...data, day_id: selectedDayId || null })
- toast.success(t('planner.reservationAdded'))
- }
- setShowReservationModal(false)
- } catch (err) {
- toast.error(err.message)
- }
- }
-
- const handleDeleteReservation = async (id) => {
- if (!confirm(t('planner.confirmDeleteReservation'))) return
- try {
- await tripStore.deleteReservation(tripId, id)
- toast.success(t('planner.reservationDeleted'))
- } catch (err) {
- toast.error(err.message)
- }
- }
-
- const selectedPlace = selectedPlaceId ? places.find(p => p.id === selectedPlaceId) : null
-
- return (
- <div className="flex flex-col h-full bg-white relative overflow-hidden" style={{ fontFamily: "-apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Segoe UI', system-ui, sans-serif" }}>
-
- <div className="px-4 pt-4 pb-3 flex-shrink-0 border-b border-gray-100">
- <button onClick={onEditTrip} className="w-full text-left group">
- <h1 className="font-semibold text-gray-900 text-[15px] leading-tight truncate group-hover:text-slate-600 transition-colors">
- {trip?.title}
- </h1>
- {(trip?.start_date || trip?.end_date) && (
- <p className="text-xs text-gray-400 mt-0.5">
- {trip.start_date && formatShortDate(trip.start_date)}
- {trip.start_date && trip.end_date && ' – '}
- {trip.end_date && formatShortDate(trip.end_date)}
- {days.length > 0 && ` · ${days.length} ${t('planner.days')}`}
- </p>
- )}
- </button>
- </div>
-
- <div className="px-3 py-2 flex-shrink-0 border-b border-gray-100">
- <div className="flex bg-gray-100 rounded-[10px] p-0.5 gap-0.5">
- {SEGMENTS.map(seg => (
- <button
- key={seg.id}
- onClick={() => setActiveSegment(seg.id)}
- className={`flex-1 py-[5px] text-[11px] font-medium rounded-[8px] transition-all duration-150 leading-none ${
- activeSegment === seg.id
- ? 'bg-white shadow-sm text-gray-900'
- : 'text-gray-500 hover:text-gray-700'
- }`}
- >
- {seg.label}
- </button>
- ))}
- </div>
- </div>
-
- <div className="flex-1 overflow-y-auto min-h-0">
-
- {/* ── PLAN ── */}
- {activeSegment === 'plan' && (
- <div className="pb-4">
- <button
- onClick={() => onSelectDay(null)}
- className={`w-full text-left px-4 py-3 flex items-center gap-3 transition-colors border-b border-gray-50 ${
- selectedDayId === null ? 'bg-slate-100/70' : 'hover:bg-gray-50/80'
- }`}
- >
- <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
- selectedDayId === null ? 'bg-slate-900' : 'bg-gray-100'
- }`}>
- <MapPin className={`w-4 h-4 ${selectedDayId === null ? 'text-white' : 'text-gray-400'}`} />
- </div>
- <div className="flex-1 min-w-0">
- <p className={`text-sm font-medium ${selectedDayId === null ? 'text-slate-900' : 'text-gray-700'}`}>
- {t('planner.allPlaces')}
- </p>
- <p className="text-xs text-gray-400">{t('planner.totalPlaces', { n: places.length })}</p>
- </div>
- </button>
-
- {days.length === 0 ? (
- <div className="px-4 py-10 text-center">
- <CalendarDays className="w-10 h-10 text-gray-200 mx-auto mb-3" />
- <p className="text-sm text-gray-400">{t('planner.noDaysPlanned')}</p>
- <button onClick={onEditTrip} className="mt-2 text-slate-700 text-sm">
- {t('planner.editTrip')}
- </button>
- </div>
- ) : (
- days.map((day, index) => {
- const isSelected = selectedDayId === day.id
- const isExpanded = expandedDays.has(day.id)
- const da = getDayAssignments(day.id)
- const cost = da.reduce((s, a) => s + (parseFloat(a.place?.price) || 0), 0)
- const loc = getDayLocation(day.id)
- const merged = getMergedDayItems(day.id)
- const dayNoteUi = noteUi[day.id]
- const placeItems = merged.filter(i => i.type === 'place')
-
- return (
- <div key={day.id} className="border-b border-gray-50">
- <div
- className={`flex items-center gap-3 px-4 py-3 cursor-pointer select-none transition-colors ${
- isSelected ? 'bg-slate-100/60' : 'hover:bg-gray-50/80'
- }`}
- onClick={() => {
- onSelectDay(day.id)
- if (!isExpanded) toggleDay(day.id)
- }}
- >
- <div className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0 ${
- isSelected ? 'bg-slate-900 text-white' : 'bg-gray-100 text-gray-500'
- }`}>
- {index + 1}
- </div>
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <p className={`text-sm font-medium truncate ${isSelected ? 'text-slate-900' : 'text-gray-800'}`}>
- {day.title || `Tag ${index + 1}`}
- </p>
- {da.length > 0 && (
- <span className="text-xs text-gray-400 flex-shrink-0">
- {da.length === 1 ? t('planner.placeOne') : t('planner.placeN', { n: da.length })}
- </span>
- )}
- </div>
- <div className="flex items-center gap-2 mt-0.5 flex-wrap">
- {day.date && <span className="text-xs text-gray-400">{formatShortDate(day.date)}</span>}
- {cost > 0 && <span className="text-xs text-emerald-600">{cost.toFixed(0)} {currency}</span>}
- {day.date && loc && (
- <WeatherWidget lat={loc.lat} lng={loc.lng} date={day.date} compact />
- )}
- </div>
- </div>
- <button
- onClick={e => { e.stopPropagation(); openAddNote(day.id); if (!isExpanded) toggleDay(day.id) }}
- title={t('planner.addNote')}
- className="p-1 text-gray-300 hover:text-amber-500 flex-shrink-0 transition-colors"
- >
- <FileText className="w-4 h-4" />
- </button>
- <button
- onClick={e => { e.stopPropagation(); toggleDay(day.id) }}
- className="p-1 text-gray-300 hover:text-gray-500 flex-shrink-0"
- >
- {isExpanded
- ? <ChevronDown className="w-4 h-4" />
- : <ChevronRight className="w-4 h-4" />
- }
- </button>
- </div>
-
- {isExpanded && (
- <div className="bg-gray-50/40">
- {merged.length === 0 && !dayNoteUi ? (
- <div className="px-4 py-4 text-center">
- <p className="text-xs text-gray-400">{t('planner.noEntries')}</p>
- <button
- onClick={() => { onSelectDay(day.id); setActiveSegment('orte') }}
- className="mt-1 text-xs text-slate-700"
- >
- {t('planner.addPlaceShort')}
- </button>
- </div>
- ) : (
- <div className="divide-y divide-gray-100/60">
- {merged.map((item, idx) => {
- if (item.type === 'place') {
- const assignment = item.data
- const place = assignment.place
- if (!place) return null
- const category = categories.find(c => c.id === place.category_id)
- const isPlaceSelected = place.id === selectedPlaceId
- const placeIdx = placeItems.findIndex(i => i.data.id === assignment.id)
-
- return (
- <div
- key={`place-${assignment.id}`}
- className={`group flex items-center gap-2.5 pl-4 pr-3 py-2.5 cursor-pointer transition-colors ${
- isPlaceSelected ? 'bg-slate-50' : 'hover:bg-white/80'
- }`}
- onClick={() => onPlaceClick(isPlaceSelected ? null : place.id)}
- >
- <div
- className="w-9 h-9 rounded-[10px] overflow-hidden flex items-center justify-center flex-shrink-0"
- style={{ backgroundColor: (category?.color || '#6366f1') + '22' }}
- >
- {place.image_url ? (
- <img src={place.image_url} alt={place.name} className="w-full h-full object-cover" />
- ) : (
- <span className="text-lg">{category?.icon || '📍'}</span>
- )}
- </div>
- <div className="flex-1 min-w-0">
- <p className={`text-[13px] font-medium truncate leading-snug ${isPlaceSelected ? 'text-slate-900' : 'text-gray-800'}`}>
- {place.name}
- </p>
- {(place.description || place.notes) && (
- <p className="text-[11px] text-gray-400 mt-0.5 leading-snug line-clamp-2">
- {place.description || place.notes}
- </p>
- )}
- <div className="flex items-center gap-2 mt-0.5 flex-wrap">
- {place.place_time && (
- <span className="text-[11px] text-slate-600 font-medium">{place.place_time}{place.end_time ? ` – ${place.end_time}` : ''}</span>
- )}
- {place.price > 0 && (
- <span className="text-[11px] text-gray-400">{place.price} {place.currency || currency}</span>
- )}
- </div>
- </div>
- <div className="flex flex-col gap-0 flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
- <button
- onClick={e => { e.stopPropagation(); handleMoveUp(day.id, placeIdx) }}
- disabled={placeIdx === 0}
- className="p-0.5 text-gray-300 hover:text-gray-600 disabled:opacity-20"
- >
- <ChevronUp className="w-3.5 h-3.5" />
- </button>
- <button
- onClick={e => { e.stopPropagation(); handleMoveDown(day.id, placeIdx) }}
- disabled={placeIdx === placeItems.length - 1}
- className="p-0.5 text-gray-300 hover:text-gray-600 disabled:opacity-20"
- >
- <ChevronDown className="w-3.5 h-3.5" />
- </button>
- </div>
- </div>
- )
- }
-
- const note = item.data
- const isEditingThis = dayNoteUi?.mode === 'edit' && dayNoteUi.noteId === note.id
- if (isEditingThis) {
- return (
- <div key={`note-edit-${note.id}`} className="px-3 py-2 bg-amber-50/60">
- <div className="flex gap-2 mb-1.5">
- <input
- type="text"
- value={dayNoteUi.time}
- onChange={e => setNoteUi(prev => ({ ...prev, [day.id]: { ...prev[day.id], time: e.target.value } }))}
- placeholder={t('planner.noteTimePlaceholder')}
- className="w-24 text-[11px] border border-amber-200 rounded-lg px-2 py-1 bg-white focus:outline-none focus:ring-1 focus:ring-amber-300"
- />
- </div>
- <textarea
- ref={noteInputRef}
- value={dayNoteUi.text}
- onChange={e => setNoteUi(prev => ({ ...prev, [day.id]: { ...prev[day.id], text: e.target.value } }))}
- onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); saveNote(day.id) } if (e.key === 'Escape') cancelNote(day.id) }}
- placeholder={t('planner.notePlaceholder')}
- rows={2}
- className="w-full text-[12px] border border-amber-200 rounded-lg px-2 py-1.5 bg-white focus:outline-none focus:ring-1 focus:ring-amber-300 resize-none"
- />
- <div className="flex gap-1.5 mt-1.5">
- <button onClick={() => saveNote(day.id)} className="flex items-center gap-1 text-[11px] bg-amber-500 text-white px-2.5 py-1 rounded-lg hover:bg-amber-600">
- <Check className="w-3 h-3" /> {t('common.save')}
- </button>
- <button onClick={() => cancelNote(day.id)} className="text-[11px] text-gray-500 px-2.5 py-1 rounded-lg hover:bg-gray-100">
- {t('common.cancel')}
- </button>
- </div>
- </div>
- )
- }
-
- return (
- <div key={`note-${note.id}`} className="group flex items-start gap-2 pl-4 pr-3 py-2 bg-amber-50/40 hover:bg-amber-50/70 transition-colors">
- <FileText className="w-3.5 h-3.5 text-amber-400 flex-shrink-0 mt-0.5" />
- <div className="flex-1 min-w-0">
- {note.time && (
- <span className="text-[11px] font-semibold text-amber-600 mr-1.5">{note.time}</span>
- )}
- <span className="text-[12px] text-gray-700 leading-snug">{note.text}</span>
- </div>
- <div className="flex flex-col gap-0 flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
- <button onClick={e => { e.stopPropagation(); handleNoteMoveUp(day.id, note.id) }} className="p-0.5 text-gray-300 hover:text-gray-600">
- <ChevronUp className="w-3.5 h-3.5" />
- </button>
- <button onClick={e => { e.stopPropagation(); handleNoteMoveDown(day.id, note.id) }} className="p-0.5 text-gray-300 hover:text-gray-600">
- <ChevronDown className="w-3.5 h-3.5" />
- </button>
- </div>
- <div className="flex gap-0.5 flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
- <button onClick={e => { e.stopPropagation(); openEditNote(day.id, note) }} className="p-1 text-gray-300 hover:text-amber-500 rounded">
- <Pencil className="w-3 h-3" />
- </button>
- <button onClick={e => { e.stopPropagation(); handleDeleteNote(day.id, note.id) }} className="p-1 text-gray-300 hover:text-red-500 rounded">
- <Trash2 className="w-3 h-3" />
- </button>
- </div>
- </div>
- )
- })}
- </div>
- )}
-
- {dayNoteUi?.mode === 'add' && (
- <div className="px-3 py-2 border-t border-amber-100 bg-amber-50/60">
- <div className="flex gap-2 mb-1.5">
- <input
- type="text"
- value={dayNoteUi.time}
- onChange={e => setNoteUi(prev => ({ ...prev, [day.id]: { ...prev[day.id], time: e.target.value } }))}
- placeholder={t('planner.noteTimePlaceholder')}
- className="w-24 text-[11px] border border-amber-200 rounded-lg px-2 py-1 bg-white focus:outline-none focus:ring-1 focus:ring-amber-300"
- />
- </div>
- <textarea
- ref={noteInputRef}
- value={dayNoteUi.text}
- onChange={e => setNoteUi(prev => ({ ...prev, [day.id]: { ...prev[day.id], text: e.target.value } }))}
- onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); saveNote(day.id) } if (e.key === 'Escape') cancelNote(day.id) }}
- placeholder={t('planner.noteExamplePlaceholder')}
- rows={2}
- className="w-full text-[12px] border border-amber-200 rounded-lg px-2 py-1.5 bg-white focus:outline-none focus:ring-1 focus:ring-amber-300 resize-none"
- />
- <div className="flex gap-1.5 mt-1.5">
- <button onClick={() => saveNote(day.id)} className="flex items-center gap-1 text-[11px] bg-amber-500 text-white px-2.5 py-1 rounded-lg hover:bg-amber-600">
- <Check className="w-3 h-3" /> {t('common.add')}
- </button>
- <button onClick={() => cancelNote(day.id)} className="text-[11px] text-gray-500 px-2.5 py-1 rounded-lg hover:bg-gray-100">
- {t('common.cancel')}
- </button>
- </div>
- </div>
- )}
-
- {!dayNoteUi && (
- <div className="px-4 py-2 border-t border-gray-100/60 flex gap-2">
- <button
- onClick={() => openAddNote(day.id)}
- className="flex items-center gap-1 text-[11px] text-amber-600 hover:text-amber-700 py-1"
- >
- <FileText className="w-3 h-3" />
- {t('planner.addNote')}
- </button>
- </div>
- )}
-
- {/* Route tools — only for the selected day */}
- {isSelected && da.length >= 2 && (
- <div className="px-4 py-3 space-y-2 border-t border-gray-100/60">
- {routeInfo && (
- <div className="flex items-center justify-center gap-3 text-xs bg-slate-50 rounded-lg px-3 py-2">
- <span className="text-slate-900">🛣️ {routeInfo.distance}</span>
- <span className="text-slate-300">·</span>
- <span className="text-slate-900">⏱️ {routeInfo.duration}</span>
- </div>
- )}
- <div className="grid grid-cols-2 gap-1.5">
- <button
- onClick={handleCalculateRoute}
- disabled={isCalculatingRoute}
- className="flex items-center justify-center gap-1.5 bg-slate-900 text-white text-xs py-2 rounded-lg hover:bg-slate-700 disabled:opacity-60 transition-colors"
- >
- <Navigation className="w-3.5 h-3.5" />
- {isCalculatingRoute ? t('planner.calculating') : t('planner.route')}
- </button>
- <button
- onClick={handleOptimizeRoute}
- className="flex items-center justify-center gap-1.5 bg-emerald-600 text-white text-xs py-2 rounded-lg hover:bg-emerald-700 transition-colors"
- >
- <RotateCcw className="w-3.5 h-3.5" />
- {t('planner.optimize')}
- </button>
- </div>
- <button
- onClick={handleOpenGoogleMaps}
- className="w-full flex items-center justify-center gap-1.5 border border-gray-200 text-gray-600 text-xs py-2 rounded-lg hover:bg-gray-50 transition-colors"
- >
- <ExternalLink className="w-3.5 h-3.5" />
- {t('planner.openGoogleMaps')}
- </button>
- </div>
- )}
- </div>
- )}
- </div>
- )
- })
- )}
-
- {totalCost > 0 && (
- <div className="px-4 py-3 border-t border-gray-100 flex items-center justify-between">
- <span className="text-xs text-gray-500">{t('planner.totalCost')}</span>
- <span className="text-sm font-semibold text-gray-800">{totalCost.toFixed(2)} {currency}</span>
- </div>
- )}
- </div>
- )}
-
- {/* ── ORTE ── */}
- {activeSegment === 'orte' && (
- <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
- <div className="p-3 space-y-2 border-b border-gray-100">
- <div className="relative">
- <Search className="absolute left-3 top-[9px] w-3.5 h-3.5 text-gray-400 pointer-events-none" />
- <input
- type="text"
- value={search}
- onChange={e => setSearch(e.target.value)}
- placeholder={t('planner.searchPlaces')}
- className="w-full pl-8 pr-8 py-2 bg-gray-100 rounded-[10px] text-sm focus:outline-none focus:bg-white focus:ring-2 focus:ring-slate-400 transition-colors"
- />
- {search && (
- <button onClick={() => setSearch('')} className="absolute right-3 top-[9px]">
- <X className="w-3.5 h-3.5 text-gray-400" />
- </button>
- )}
- </div>
- <div className="flex items-center gap-2">
- <select
- value={categoryFilter}
- onChange={e => setCategoryFilter(e.target.value)}
- className="flex-1 bg-gray-100 rounded-lg text-xs py-2 px-2 focus:outline-none text-gray-600"
- >
- <option value="">{t('planner.allCategories')}</option>
- {categories.map(c => (
- <option key={c.id} value={c.id}>{c.icon} {c.name}</option>
- ))}
- </select>
- <button
- onClick={onAddPlace}
- className="flex items-center gap-1 bg-slate-900 text-white text-xs px-3 py-2 rounded-lg hover:bg-slate-700 whitespace-nowrap transition-colors"
- >
- <Plus className="w-3.5 h-3.5" />
- {t('planner.new')}
- </button>
- </div>
- </div>
-
- {filteredPlaces.length === 0 ? (
- <div className="flex flex-col items-center justify-center py-12 text-gray-400">
- <span className="text-3xl mb-2">📍</span>
- <p className="text-sm">{t('planner.noPlacesFound')}</p>
- <button onClick={onAddPlace} className="mt-3 text-slate-700 text-sm">
- {t('planner.addFirstPlace')}
- </button>
- </div>
- ) : (
- <div ref={placesListRef} style={{ flex: 1, minHeight: 0 }}>
- <FixedSizeList
- height={placesListHeight}
- itemCount={filteredPlaces.length}
- itemSize={68}
- overscanCount={10}
- width="100%"
- >
- {({ index, style }) => {
- const place = filteredPlaces[index]
- const category = categories.find(c => c.id === place.category_id)
- const inDay = isAssignedToDay(place.id)
- const isSelected = place.id === selectedPlaceId
- return (
- <div
- style={style}
- key={place.id}
- onClick={() => onPlaceClick(isSelected ? null : place.id)}
- className={`flex items-center gap-3 px-4 py-2.5 cursor-pointer transition-colors border-b border-gray-50 ${
- isSelected ? 'bg-slate-50' : 'hover:bg-gray-50'
- }`}
- >
- <div
- className="w-9 h-9 rounded-[10px] overflow-hidden flex items-center justify-center flex-shrink-0"
- style={{ backgroundColor: (category?.color || '#6366f1') + '22' }}
- >
- {place.image_url ? (
- <img src={place.image_url} alt={place.name} className="w-full h-full object-cover" />
- ) : (
- <span className="text-lg">{category?.icon || '📍'}</span>
- )}
- </div>
- <div className="flex-1 min-w-0">
- <div className="flex items-center justify-between gap-1">
- <span className="font-medium text-[13px] text-gray-900 truncate">{place.name}</span>
- <div className="flex items-center gap-1 flex-shrink-0">
- {inDay
- ? <span className="text-[11px] text-emerald-600 bg-emerald-50 px-1.5 py-0.5 rounded-full">✓</span>
- : selectedDayId && (
- <button
- onClick={e => { e.stopPropagation(); onAssignToDay(place.id) }}
- className="text-[11px] text-slate-700 bg-slate-50 px-1.5 py-0.5 rounded hover:bg-slate-100 transition-colors"
- >
- {t('planner.addToDay')}
- </button>
- )
- }
- </div>
- </div>
- {category && <p className="text-xs text-gray-500 mt-0.5">{category.icon} {category.name}</p>}
- {place.address && <p className="text-xs text-gray-400 truncate">{place.address}</p>}
- </div>
- </div>
- )
- }}
- </FixedSizeList>
- </div>
- )}
- </div>
- )}
-
- {/* ── RESERVIERUNGEN ── */}
- {activeSegment === 'reservierungen' && (
- <div>
- <div className="px-4 py-3 flex items-center justify-between border-b border-gray-100">
- <h3 className="font-medium text-sm text-gray-900">
- {t('planner.reservations')}
- {selectedDay && <span className="text-gray-400 font-normal"> · Tag {selectedDay.day_number}</span>}
- </h3>
- <button
- onClick={() => { setEditingReservation(null); setShowReservationModal(true) }}
- className="flex items-center gap-1 bg-slate-900 text-white text-xs px-2.5 py-1.5 rounded-lg hover:bg-slate-700 transition-colors"
- >
- <Plus className="w-3.5 h-3.5" />
- {t('common.add')}
- </button>
- </div>
- {filteredReservations.length === 0 ? (
- <div className="flex flex-col items-center justify-center py-12 text-gray-400">
- <span className="text-3xl mb-2">🎫</span>
- <p className="text-sm">{t('planner.noReservations')}</p>
- </div>
- ) : (
- <div className="p-3 space-y-2.5">
- {filteredReservations.map(r => (
- <div key={r.id} className="bg-white border border-gray-100 rounded-2xl p-3.5 shadow-sm">
- <div className="flex items-start justify-between gap-2">
- <div className="flex-1 min-w-0">
- <div className="font-semibold text-[13px] text-gray-900">{r.title}</div>
- {r.reservation_time && (
- <div className="flex items-center gap-1 mt-1 text-xs text-slate-700">
- <Clock className="w-3 h-3" />
- {formatDateTime(r.reservation_time)}
- {r.reservation_end_time && ` – ${r.reservation_end_time}`}
- </div>
- )}
- {r.location && <div className="text-xs text-gray-500 mt-0.5">📍 {r.location}</div>}
- {r.confirmation_number && (
- <div className="text-xs text-emerald-600 mt-1 bg-emerald-50 rounded-lg px-2 py-0.5 inline-block">
- # {r.confirmation_number}
- </div>
- )}
- {r.notes && <p className="text-xs text-gray-500 mt-1.5 leading-relaxed">{r.notes}</p>}
- </div>
- <div className="flex gap-1 flex-shrink-0">
- <button
- onClick={() => { setEditingReservation(r); setShowReservationModal(true) }}
- className="p-1.5 text-gray-400 hover:text-slate-700 rounded-lg hover:bg-slate-50 transition-colors"
- >✏️</button>
- <button
- onClick={() => handleDeleteReservation(r.id)}
- className="p-1.5 text-gray-400 hover:text-red-600 rounded-lg hover:bg-red-50 transition-colors"
- >🗑️</button>
- </div>
- </div>
- </div>
- ))}
- </div>
- )}
- </div>
- )}
-
- {/* ── PACKLISTE ── */}
- {activeSegment === 'packliste' && (
- <PackingListPanel tripId={tripId} items={packingItems} />
- )}
-
- {/* ── DOKUMENTE ── */}
- {activeSegment === 'dokumente' && (
- <FileManager tripId={tripId} />
- )}
- </div>
-
- {/* ── INSPECTOR OVERLAY ── */}
- {selectedPlace && (
- <div className="absolute inset-0 bg-white z-10 overflow-y-auto">
- <PlaceDetailPanel
- place={selectedPlace}
- categories={categories}
- tags={tags}
- selectedDayId={selectedDayId}
- dayAssignments={selectedDayAssignments}
- onClose={() => onPlaceClick(null)}
- onEdit={() => onPlaceEdit(selectedPlace)}
- onDelete={() => onPlaceDelete(selectedPlace.id)}
- onAssignToDay={onAssignToDay}
- onRemoveAssignment={onRemoveAssignment}
- />
- </div>
- )}
-
- <ReservationModal
- isOpen={showReservationModal}
- onClose={() => { setShowReservationModal(false); setEditingReservation(null) }}
- onSave={handleSaveReservation}
- reservation={editingReservation}
- days={days}
- places={places}
- selectedDayId={selectedDayId}
- />
- </div>
- )
-}
diff --git a/client/src/components/Planner/ReservationModal.jsx b/client/src/components/Planner/ReservationModal.tsx
similarity index 95%
rename from client/src/components/Planner/ReservationModal.jsx
rename to client/src/components/Planner/ReservationModal.tsx
index 1115f8141..eb6d772bd 100644
--- a/client/src/components/Planner/ReservationModal.jsx
+++ b/client/src/components/Planner/ReservationModal.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect, useRef, useMemo } from 'react'
+import { useState, useEffect, useRef, useMemo } from 'react'
import Modal from '../shared/Modal'
import CustomSelect from '../shared/CustomSelect'
import { Plane, Hotel, Utensils, Train, Car, Ship, Ticket, FileText, Users, Paperclip, X, ExternalLink, Link2 } from 'lucide-react'
@@ -6,6 +6,7 @@ import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import { CustomDatePicker } from '../shared/CustomDateTimePicker'
import CustomTimePicker from '../shared/CustomTimePicker'
+import type { Day, Place, Reservation, TripFile, AssignmentsMap } from '../../types'
const TYPE_OPTIONS = [
{ value: 'flight', labelKey: 'reservations.type.flight', Icon: Plane },
@@ -45,7 +46,21 @@ function buildAssignmentOptions(days, assignments, t, locale) {
return options
}
-export function ReservationModal({ isOpen, onClose, onSave, reservation, days, places, assignments, selectedDayId, files = [], onFileUpload, onFileDelete }) {
+interface ReservationModalProps {
+ isOpen: boolean
+ onClose: () => void
+ onSave: (data: Record<string, string | number | null>) => Promise<void> | void
+ reservation: Reservation | null
+ days: Day[]
+ places: Place[]
+ assignments: AssignmentsMap
+ selectedDayId: number | null
+ files?: TripFile[]
+ onFileUpload: (fd: FormData) => Promise<void>
+ onFileDelete: (fileId: number) => Promise<void>
+}
+
+export function ReservationModal({ isOpen, onClose, onSave, reservation, days, places, assignments, selectedDayId, files = [], onFileUpload, onFileDelete }: ReservationModalProps) {
const toast = useToast()
const { t, locale } = useTranslation()
const fileInputRef = useRef(null)
@@ -113,7 +128,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
}
const handleFileChange = async (e) => {
- const file = e.target.files?.[0]
+ const file = (e.target as HTMLInputElement).files?.[0]
if (!file) return
if (reservation?.id) {
setUploadingFile(true)
diff --git a/client/src/components/Planner/ReservationsPanel.jsx b/client/src/components/Planner/ReservationsPanel.tsx
similarity index 93%
rename from client/src/components/Planner/ReservationsPanel.jsx
rename to client/src/components/Planner/ReservationsPanel.tsx
index b7fd10bc5..86fae5188 100644
--- a/client/src/components/Planner/ReservationsPanel.jsx
+++ b/client/src/components/Planner/ReservationsPanel.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useMemo } from 'react'
+import { useState, useMemo } from 'react'
import { useTripStore } from '../../store/tripStore'
import { useSettingsStore } from '../../store/settingsStore'
import { useToast } from '../shared/Toast'
@@ -8,6 +8,16 @@ import {
Calendar, Hash, CheckCircle2, Circle, Pencil, Trash2, Plus, ChevronDown, ChevronRight, Users,
ExternalLink, BookMarked, Lightbulb, Link2, Clock,
} from 'lucide-react'
+import type { Reservation, Day, TripFile, AssignmentsMap } from '../../types'
+
+interface AssignmentLookupEntry {
+ dayNumber: number
+ dayTitle: string | null
+ dayDate: string
+ placeName: string
+ startTime: string | null
+ endTime: string | null
+}
const TYPE_OPTIONS = [
{ value: 'flight', labelKey: 'reservations.type.flight', Icon: Plane, color: '#3b82f6' },
@@ -37,7 +47,17 @@ function buildAssignmentLookup(days, assignments) {
return map
}
-function ReservationCard({ r, tripId, onEdit, onDelete, files = [], onNavigateToFiles, assignmentLookup }) {
+interface ReservationCardProps {
+ r: Reservation
+ tripId: number
+ onEdit: (reservation: Reservation) => void
+ onDelete: (id: number) => void
+ files?: TripFile[]
+ onNavigateToFiles: () => void
+ assignmentLookup: Record<number, AssignmentLookupEntry>
+}
+
+function ReservationCard({ r, tripId, onEdit, onDelete, files = [], onNavigateToFiles, assignmentLookup }: ReservationCardProps) {
const { toggleReservationStatus } = useTripStore()
const toast = useToast()
const { t, locale } = useTranslation()
@@ -176,7 +196,15 @@ function ReservationCard({ r, tripId, onEdit, onDelete, files = [], onNavigateTo
)
}
-function Section({ title, count, children, defaultOpen = true, accent }) {
+interface SectionProps {
+ title: string
+ count: number
+ children: React.ReactNode
+ defaultOpen?: boolean
+ accent: 'green' | string
+}
+
+function Section({ title, count, children, defaultOpen = true, accent }: SectionProps) {
const [open, setOpen] = useState(defaultOpen)
return (
<div style={{ marginBottom: 16 }}>
@@ -197,7 +225,19 @@ function Section({ title, count, children, defaultOpen = true, accent }) {
)
}
-export default function ReservationsPanel({ tripId, reservations, days, assignments, files = [], onAdd, onEdit, onDelete, onNavigateToFiles }) {
+interface ReservationsPanelProps {
+ tripId: number
+ reservations: Reservation[]
+ days: Day[]
+ assignments: AssignmentsMap
+ files?: TripFile[]
+ onAdd: () => void
+ onEdit: (reservation: Reservation) => void
+ onDelete: (id: number) => void
+ onNavigateToFiles: () => void
+}
+
+export default function ReservationsPanel({ tripId, reservations, days, assignments, files = [], onAdd, onEdit, onDelete, onNavigateToFiles }: ReservationsPanelProps) {
const { t, locale } = useTranslation()
const [showHint, setShowHint] = useState(() => !localStorage.getItem('hideReservationHint'))
diff --git a/client/src/components/Planner/RightPanel.jsx b/client/src/components/Planner/RightPanel.jsx
deleted file mode 100644
index 0facf3d4c..000000000
--- a/client/src/components/Planner/RightPanel.jsx
+++ /dev/null
@@ -1,591 +0,0 @@
-import React, { useState, useCallback } from 'react'
-import { Plus, Search, ChevronUp, ChevronDown, X, Map, ExternalLink, Navigation, RotateCcw, Clock, Euro, FileText, Package } from 'lucide-react'
-import { calculateRoute, generateGoogleMapsUrl, optimizeRoute } from '../Map/RouteCalculator'
-import PackingListPanel from '../Packing/PackingListPanel'
-import { ReservationModal } from './ReservationModal'
-import { PlaceDetailPanel } from './PlaceDetailPanel'
-import { useTripStore } from '../../store/tripStore'
-import { useToast } from '../shared/Toast'
-import { useTranslation } from '../../i18n'
-
-export function RightPanel({
- trip, days, places, categories, tags,
- assignments, reservations, packingItems,
- selectedDay, selectedDayId, selectedPlaceId,
- onPlaceClick, onPlaceEdit, onPlaceDelete,
- onAssignToDay, onRemoveAssignment, onReorder,
- onAddPlace, onEditTrip, onRouteCalculated, tripId,
-}) {
- const [activeTab, setActiveTab] = useState('orte')
- const [search, setSearch] = useState('')
- const [categoryFilter, setCategoryFilter] = useState('')
- const [isCalculatingRoute, setIsCalculatingRoute] = useState(false)
- const [showReservationModal, setShowReservationModal] = useState(false)
- const [editingReservation, setEditingReservation] = useState(null)
- const [routeInfo, setRouteInfo] = useState(null)
-
- const tripStore = useTripStore()
- const toast = useToast()
- const { t } = useTranslation()
-
- const TABS = [
- { id: 'orte', label: t('planner.places'), icon: '📍' },
- { id: 'tagesplan', label: t('planner.dayPlan'), icon: '📅' },
- { id: 'reservierungen', label: t('planner.reservations'), icon: '🎫' },
- { id: 'packliste', label: t('planner.packingList'), icon: '🎒' },
- ]
-
- // Filtered places for Orte tab
- const filteredPlaces = places.filter(p => {
- const matchesSearch = !search || p.name.toLowerCase().includes(search.toLowerCase()) ||
- (p.address || '').toLowerCase().includes(search.toLowerCase())
- const matchesCategory = !categoryFilter || String(p.category_id) === String(categoryFilter)
- return matchesSearch && matchesCategory
- })
-
- // Ordered assignments for selected day
- const dayAssignments = selectedDayId
- ? (assignments[String(selectedDayId)] || []).slice().sort((a, b) => a.order_index - b.order_index)
- : []
-
- const isAssignedToSelectedDay = (placeId) =>
- selectedDayId && dayAssignments.some(a => a.place?.id === placeId)
-
- // Calculate schedule with times
- const getSchedule = () => {
- if (!dayAssignments.length) return []
- let currentTime = null
- return dayAssignments.map((assignment, idx) => {
- const place = assignment.place
- const startTime = place?.place_time || (currentTime ? currentTime : null)
- const duration = place?.duration_minutes || 60
- if (startTime) {
- const [h, m] = startTime.split(':').map(Number)
- const endMinutes = h * 60 + m + duration
- const endH = Math.floor(endMinutes / 60) % 24
- const endM = endMinutes % 60
- currentTime = `${String(endH).padStart(2, '0')}:${String(endM).padStart(2, '0')}`
- }
- return { assignment, startTime, endTime: currentTime }
- })
- }
-
- const handleCalculateRoute = async () => {
- if (!selectedDayId) return
- const waypoints = dayAssignments
- .map(a => a.place)
- .filter(p => p?.lat && p?.lng)
- .map(p => ({ lat: p.lat, lng: p.lng }))
-
- if (waypoints.length < 2) {
- toast.error(t('planner.minTwoPlaces'))
- return
- }
-
- setIsCalculatingRoute(true)
- try {
- const result = await calculateRoute(waypoints, 'walking')
- if (result) {
- setRouteInfo({ distance: result.distanceText, duration: result.durationText })
- onRouteCalculated?.(result)
- toast.success(t('planner.routeCalculated'))
- } else {
- toast.error(t('planner.routeCalcFailed'))
- }
- } catch (err) {
- toast.error(t('planner.routeError'))
- } finally {
- setIsCalculatingRoute(false)
- }
- }
-
- const handleOptimizeRoute = async () => {
- if (!selectedDayId || dayAssignments.length < 3) return
- const places = dayAssignments.map(a => a.place).filter(p => p?.lat && p?.lng)
- const optimized = optimizeRoute(places)
- const optimizedIds = optimized.map(p => {
- const a = dayAssignments.find(a => a.place?.id === p.id)
- return a?.id
- }).filter(Boolean)
- await onReorder(selectedDayId, optimizedIds)
- toast.success(t('planner.routeOptimized'))
- }
-
- const handleOpenGoogleMaps = () => {
- const places = dayAssignments.map(a => a.place).filter(p => p?.lat && p?.lng)
- const url = generateGoogleMapsUrl(places)
- if (url) window.open(url, '_blank')
- else toast.error(t('planner.noGeoPlaces'))
- }
-
- const handleMoveUp = async (idx) => {
- if (idx === 0) return
- const ids = dayAssignments.map(a => a.id)
- ;[ids[idx - 1], ids[idx]] = [ids[idx], ids[idx - 1]]
- await onReorder(selectedDayId, ids)
- }
-
- const handleMoveDown = async (idx) => {
- if (idx === dayAssignments.length - 1) return
- const ids = dayAssignments.map(a => a.id)
- ;[ids[idx], ids[idx + 1]] = [ids[idx + 1], ids[idx]]
- await onReorder(selectedDayId, ids)
- }
-
- const handleAddReservation = () => {
- setEditingReservation(null)
- setShowReservationModal(true)
- }
-
- const handleSaveReservation = async (data) => {
- try {
- if (editingReservation) {
- await tripStore.updateReservation(tripId, editingReservation.id, data)
- toast.success(t('planner.reservationUpdated'))
- } else {
- await tripStore.addReservation(tripId, { ...data, day_id: selectedDayId || null })
- toast.success(t('planner.reservationAdded'))
- }
- setShowReservationModal(false)
- } catch (err) {
- toast.error(err.message)
- }
- }
-
- const handleDeleteReservation = async (id) => {
- if (!confirm(t('planner.confirmDeleteReservation'))) return
- try {
- await tripStore.deleteReservation(tripId, id)
- toast.success(t('planner.reservationDeleted'))
- } catch (err) {
- toast.error(err.message)
- }
- }
-
- // Reservations for selected day (or all if no day selected)
- const filteredReservations = selectedDayId
- ? reservations.filter(r => String(r.day_id) === String(selectedDayId) || !r.day_id)
- : reservations
-
- const selectedPlace = selectedPlaceId ? places.find(p => p.id === selectedPlaceId) : null
-
- return (
- <div className="flex flex-col h-full bg-white">
- {/* Tabs */}
- <div className="flex border-b border-gray-200 flex-shrink-0">
- {TABS.map(tab => (
- <button
- key={tab.id}
- onClick={() => setActiveTab(tab.id)}
- className={`flex-1 py-2.5 text-xs font-medium transition-colors flex flex-col items-center gap-0.5 ${
- activeTab === tab.id
- ? 'text-slate-700 border-b-2 border-slate-700'
- : 'text-gray-500 hover:text-gray-700'
- }`}
- >
- <span className="text-base leading-none">{tab.icon}</span>
- <span>{tab.label}</span>
- </button>
- ))}
- </div>
-
- {/* Tab Content */}
- <div className="flex-1 overflow-y-auto">
-
- {/* ORTE TAB */}
- {activeTab === 'orte' && (
- <div className="flex flex-col h-full">
- {/* Place detail (when selected) */}
- {selectedPlace && (
- <div className="border-b border-gray-100">
- <PlaceDetailPanel
- place={selectedPlace}
- categories={categories}
- tags={tags}
- selectedDayId={selectedDayId}
- dayAssignments={dayAssignments}
- onClose={() => onPlaceClick(null)}
- onEdit={() => onPlaceEdit(selectedPlace)}
- onDelete={() => onPlaceDelete(selectedPlace.id)}
- onAssignToDay={onAssignToDay}
- onRemoveAssignment={onRemoveAssignment}
- />
- </div>
- )}
-
- {/* Search & filter */}
- <div className="p-3 space-y-2 border-b border-gray-100 flex-shrink-0">
- <div className="relative">
- <Search className="absolute left-2.5 top-2.5 w-4 h-4 text-gray-400" />
- <input
- type="text"
- value={search}
- onChange={e => setSearch(e.target.value)}
- placeholder={t('planner.searchPlaces')}
- className="w-full pl-8 pr-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-900"
- />
- {search && (
- <button onClick={() => setSearch('')} className="absolute right-2.5 top-2.5">
- <X className="w-4 h-4 text-gray-400" />
- </button>
- )}
- </div>
- <div className="flex items-center gap-2">
- <select
- value={categoryFilter}
- onChange={e => setCategoryFilter(e.target.value)}
- className="flex-1 border border-gray-200 rounded-lg text-xs py-1.5 px-2 focus:outline-none focus:ring-1 focus:ring-slate-900 text-gray-600"
- >
- <option value="">{t('planner.allCategories')}</option>
- {categories.map(c => (
- <option key={c.id} value={c.id}>{c.icon} {c.name}</option>
- ))}
- </select>
- <button
- onClick={onAddPlace}
- className="flex items-center gap-1 bg-slate-700 text-white text-xs px-3 py-1.5 rounded-lg hover:bg-slate-900 whitespace-nowrap"
- >
- <Plus className="w-3.5 h-3.5" />
- {t('planner.addPlace')}
- </button>
- </div>
- </div>
-
- {/* Places list */}
- <div className="flex-1 overflow-y-auto">
- {filteredPlaces.length === 0 ? (
- <div className="flex flex-col items-center justify-center py-12 text-gray-400">
- <span className="text-3xl mb-2">📍</span>
- <p className="text-sm">{t('planner.noPlacesFound')}</p>
- <button onClick={onAddPlace} className="mt-3 text-slate-700 text-sm hover:underline">
- {t('planner.addFirstPlace')}
- </button>
- </div>
- ) : (
- <div className="divide-y divide-gray-50">
- {filteredPlaces.map(place => {
- const category = categories.find(c => c.id === place.category_id)
- const isInDay = isAssignedToSelectedDay(place.id)
- const isSelected = place.id === selectedPlaceId
-
- return (
- <div
- key={place.id}
- onClick={() => onPlaceClick(isSelected ? null : place.id)}
- className={`px-3 py-2.5 cursor-pointer transition-colors ${
- isSelected ? 'bg-slate-50' : 'hover:bg-gray-50'
- }`}
- >
- <div className="flex items-start gap-2">
- {/* Category color bar */}
- <div
- className="w-1 rounded-full flex-shrink-0 mt-1 self-stretch"
- style={{ backgroundColor: category?.color || '#6366f1', minHeight: 16 }}
- />
- <div className="flex-1 min-w-0">
- <div className="flex items-center justify-between gap-1">
- <span className="font-medium text-sm text-gray-900 truncate">{place.name}</span>
- <div className="flex items-center gap-1 flex-shrink-0">
- {isInDay && (
- <span className="text-xs text-emerald-600 bg-emerald-50 px-1.5 py-0.5 rounded">✓</span>
- )}
- {!isInDay && selectedDayId && (
- <button
- onClick={e => { e.stopPropagation(); onAssignToDay(place.id) }}
- className="text-xs text-slate-700 bg-slate-50 px-1.5 py-0.5 rounded hover:bg-slate-100"
- >
- {t('planner.addToDay')}
- </button>
- )}
- </div>
- </div>
- {category && (
- <span className="text-xs text-gray-500">{category.icon} {category.name}</span>
- )}
- {place.address && (
- <p className="text-xs text-gray-400 truncate mt-0.5">{place.address}</p>
- )}
- <div className="flex items-center gap-2 mt-1">
- {place.place_time && (
- <span className="text-xs text-gray-500">🕐 {place.place_time}{place.end_time ? ` – ${place.end_time}` : ''}</span>
- )}
- {place.price > 0 && (
- <span className="text-xs text-gray-500">
- {place.price} {place.currency || trip?.currency}
- </span>
- )}
- </div>
- </div>
- </div>
- </div>
- )
- })}
- </div>
- )}
- </div>
- </div>
- )}
-
- {/* TAGESPLAN TAB */}
- {activeTab === 'tagesplan' && (
- <div className="flex flex-col h-full">
- {!selectedDayId ? (
- <div className="flex flex-col items-center justify-center py-16 text-gray-400 px-6">
- <span className="text-4xl mb-3">📅</span>
- <p className="text-sm text-center">{t('planner.selectDayHint')}</p>
- </div>
- ) : (
- <>
- {/* Day header */}
- <div className="px-4 py-3 bg-slate-50 border-b border-slate-100 flex-shrink-0">
- <h3 className="font-semibold text-slate-900 text-sm">
- Tag {selectedDay?.day_number}
- {selectedDay?.date && (
- <span className="font-normal text-slate-700 ml-2">
- {formatGermanDate(selectedDay.date)}
- </span>
- )}
- </h3>
- <p className="text-xs text-slate-700 mt-0.5">
- {dayAssignments.length === 1 ? t('planner.placeOne') : t('planner.placeN', { n: dayAssignments.length })}
- {dayAssignments.length > 0 && ` · ${dayAssignments.reduce((s, a) => s + (a.place?.duration_minutes || 60), 0)} ${t('planner.minTotal')}`}
- </p>
- </div>
-
- {/* Places list with order */}
- <div className="flex-1 overflow-y-auto">
- {dayAssignments.length === 0 ? (
- <div className="flex flex-col items-center justify-center py-12 text-gray-400">
- <span className="text-3xl mb-2">🗺️</span>
- <p className="text-sm">{t('planner.noPlacesForDay')}</p>
- <button
- onClick={() => setActiveTab('orte')}
- className="mt-3 text-slate-700 text-sm hover:underline"
- >
- {t('planner.addPlacesLink')}
- </button>
- </div>
- ) : (
- <div className="divide-y divide-gray-50">
- {getSchedule().map(({ assignment, startTime, endTime }, idx) => {
- const place = assignment.place
- if (!place) return null
- const category = categories.find(c => c.id === place.category_id)
-
- return (
- <div key={assignment.id} className="px-3 py-3 flex items-start gap-2">
- {/* Order number */}
- <div
- className="w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0 mt-0.5"
- style={{ backgroundColor: category?.color || '#6366f1' }}
- >
- {idx + 1}
- </div>
-
- {/* Place info */}
- <div className="flex-1 min-w-0">
- <div className="font-medium text-sm text-gray-900 truncate">{place.name}</div>
- <div className="flex items-center gap-2 mt-0.5">
- {startTime && (
- <span className="text-xs text-slate-700">🕐 {startTime}</span>
- )}
- <span className="text-xs text-gray-400">
- {place.duration_minutes || 60} Min.
- </span>
- {place.price > 0 && (
- <span className="text-xs text-gray-400">
- {place.price} {place.currency || trip?.currency}
- </span>
- )}
- </div>
- {place.address && (
- <p className="text-xs text-gray-400 mt-0.5 truncate">{place.address}</p>
- )}
- {assignment.notes && (
- <p className="text-xs text-gray-500 mt-1 bg-gray-50 rounded px-2 py-1">{assignment.notes}</p>
- )}
- </div>
-
- {/* Actions */}
- <div className="flex flex-col items-center gap-0.5 flex-shrink-0">
- <button
- onClick={() => handleMoveUp(idx)}
- disabled={idx === 0}
- className="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-30"
- >
- <ChevronUp className="w-3.5 h-3.5" />
- </button>
- <button
- onClick={() => handleMoveDown(idx)}
- disabled={idx === dayAssignments.length - 1}
- className="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-30"
- >
- <ChevronDown className="w-3.5 h-3.5" />
- </button>
- <button
- onClick={() => onRemoveAssignment(selectedDayId, assignment.id)}
- className="p-1 text-red-400 hover:text-red-600"
- >
- <X className="w-3.5 h-3.5" />
- </button>
- </div>
- </div>
- )
- })}
- </div>
- )}
- </div>
-
- {/* Route buttons */}
- {dayAssignments.length >= 2 && (
- <div className="p-3 border-t border-gray-100 flex-shrink-0 space-y-2">
- {routeInfo && (
- <div className="flex items-center justify-center gap-3 text-sm bg-slate-50 rounded-lg px-3 py-2">
- <span className="text-slate-900">🛣️ {routeInfo.distance}</span>
- <span className="text-slate-400">·</span>
- <span className="text-slate-900">⏱️ {routeInfo.duration}</span>
- </div>
- )}
- <div className="grid grid-cols-2 gap-2">
- <button
- onClick={handleCalculateRoute}
- disabled={isCalculatingRoute}
- className="flex items-center justify-center gap-1.5 bg-slate-700 text-white text-xs py-2 rounded-lg hover:bg-slate-900 disabled:opacity-60"
- >
- <Navigation className="w-3.5 h-3.5" />
- {isCalculatingRoute ? t('planner.calculating') : t('planner.route')}
- </button>
- <button
- onClick={handleOptimizeRoute}
- className="flex items-center justify-center gap-1.5 bg-emerald-600 text-white text-xs py-2 rounded-lg hover:bg-emerald-700"
- >
- <RotateCcw className="w-3.5 h-3.5" />
- {t('planner.optimize')}
- </button>
- </div>
- <button
- onClick={handleOpenGoogleMaps}
- className="w-full flex items-center justify-center gap-1.5 bg-white border border-gray-200 text-gray-700 text-xs py-2 rounded-lg hover:bg-gray-50"
- >
- <ExternalLink className="w-3.5 h-3.5" />
- {t('planner.openGoogleMaps')}
- </button>
- </div>
- )}
- </>
- )}
- </div>
- )}
-
- {/* RESERVIERUNGEN TAB */}
- {activeTab === 'reservierungen' && (
- <div className="flex flex-col h-full">
- <div className="p-3 flex items-center justify-between border-b border-gray-100 flex-shrink-0">
- <h3 className="font-medium text-sm text-gray-900">
- {t('planner.reservations')}
- {selectedDay && <span className="text-gray-500 font-normal"> · Tag {selectedDay.day_number}</span>}
- </h3>
- <button
- onClick={handleAddReservation}
- className="flex items-center gap-1 bg-slate-700 text-white text-xs px-2.5 py-1.5 rounded-lg hover:bg-slate-900"
- >
- <Plus className="w-3.5 h-3.5" />
- {t('common.add')}
- </button>
- </div>
-
- <div className="flex-1 overflow-y-auto">
- {filteredReservations.length === 0 ? (
- <div className="flex flex-col items-center justify-center py-12 text-gray-400">
- <span className="text-3xl mb-2">🎫</span>
- <p className="text-sm">{t('planner.noReservations')}</p>
- <button onClick={handleAddReservation} className="mt-3 text-slate-700 text-sm hover:underline">
- {t('planner.addFirstReservation')}
- </button>
- </div>
- ) : (
- <div className="p-3 space-y-3">
- {filteredReservations.map(reservation => (
- <div key={reservation.id} className="bg-white border border-gray-200 rounded-xl p-3 shadow-sm">
- <div className="flex items-start justify-between gap-2">
- <div className="flex-1 min-w-0">
- <div className="font-semibold text-sm text-gray-900">{reservation.title}</div>
- {reservation.reservation_time && (
- <div className="flex items-center gap-1 mt-1 text-xs text-slate-700">
- <Clock className="w-3 h-3" />
- {formatDateTime(reservation.reservation_time)}
- {reservation.reservation_end_time && ` – ${reservation.reservation_end_time}`}
- </div>
- )}
- {reservation.location && (
- <div className="text-xs text-gray-500 mt-0.5">📍 {reservation.location}</div>
- )}
- {reservation.confirmation_number && (
- <div className="text-xs text-emerald-600 mt-1 bg-emerald-50 rounded px-2 py-0.5 inline-block">
- # {reservation.confirmation_number}
- </div>
- )}
- {reservation.notes && (
- <p className="text-xs text-gray-500 mt-1.5 leading-relaxed">{reservation.notes}</p>
- )}
- </div>
- <div className="flex gap-1 flex-shrink-0">
- <button
- onClick={() => { setEditingReservation(reservation); setShowReservationModal(true) }}
- className="p-1.5 text-gray-400 hover:text-slate-700 hover:bg-slate-50 rounded-lg"
- >
- ✏️
- </button>
- <button
- onClick={() => handleDeleteReservation(reservation.id)}
- className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg"
- >
- 🗑️
- </button>
- </div>
- </div>
- </div>
- ))}
- </div>
- )}
- </div>
- </div>
- )}
-
- {/* PACKLISTE TAB */}
- {activeTab === 'packliste' && (
- <PackingListPanel
- tripId={tripId}
- items={packingItems}
- />
- )}
- </div>
-
- {/* Reservation Modal */}
- <ReservationModal
- isOpen={showReservationModal}
- onClose={() => { setShowReservationModal(false); setEditingReservation(null) }}
- onSave={handleSaveReservation}
- reservation={editingReservation}
- days={days}
- places={places}
- selectedDayId={selectedDayId}
- />
- </div>
- )
-}
-
-function formatGermanDate(dateStr) {
- if (!dateStr) return ''
- const date = new Date(dateStr + 'T00:00:00')
- return date.toLocaleDateString('de-DE', { weekday: 'long', day: 'numeric', month: 'long' })
-}
-
-function formatDateTime(dt) {
- if (!dt) return ''
- try {
- return new Date(dt).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })
- } catch {
- return dt
- }
-}
diff --git a/client/src/components/Trips/TripFormModal.jsx b/client/src/components/Trips/TripFormModal.tsx
similarity index 94%
rename from client/src/components/Trips/TripFormModal.jsx
rename to client/src/components/Trips/TripFormModal.tsx
index 90d13c4fe..fc434878f 100644
--- a/client/src/components/Trips/TripFormModal.jsx
+++ b/client/src/components/Trips/TripFormModal.tsx
@@ -1,12 +1,21 @@
-import React, { useState, useEffect, useRef } from 'react'
+import { useState, useEffect, useRef } from 'react'
import Modal from '../shared/Modal'
import { Calendar, Camera, X, Clipboard } from 'lucide-react'
import { tripsApi } from '../../api/client'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import { CustomDatePicker } from '../shared/CustomDateTimePicker'
+import type { Trip } from '../../types'
-export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUpdate }) {
+interface TripFormModalProps {
+ isOpen: boolean
+ onClose: () => void
+ onSave: (data: Record<string, string | number | null>) => Promise<void> | void
+ trip: Trip | null
+ onCoverUpdate: (tripId: number, coverUrl: string) => void
+}
+
+export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUpdate }: TripFormModalProps) {
const isEditing = !!trip
const fileRef = useRef(null)
const toast = useToast()
@@ -68,8 +77,8 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp
}
}
onClose()
- } catch (err) {
- setError(err.message || t('places.saveError'))
+ } catch (err: unknown) {
+ setError(err instanceof Error ? err.message : t('places.saveError'))
} finally {
setIsLoading(false)
}
@@ -88,7 +97,7 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp
}
const handleCoverChange = (e) => {
- handleCoverSelect(e.target.files?.[0])
+ handleCoverSelect((e.target as HTMLInputElement).files?.[0])
e.target.value = ''
}
@@ -128,7 +137,7 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp
const handlePaste = (e) => {
const items = e.clipboardData?.items
if (!items) return
- for (const item of items) {
+ for (const item of Array.from(items)) {
if (item.type.startsWith('image/')) {
e.preventDefault()
const file = item.getAsFile()
diff --git a/client/src/components/Trips/TripMembersModal.jsx b/client/src/components/Trips/TripMembersModal.tsx
similarity index 94%
rename from client/src/components/Trips/TripMembersModal.jsx
rename to client/src/components/Trips/TripMembersModal.tsx
index 37f1f8fa5..9180936b8 100644
--- a/client/src/components/Trips/TripMembersModal.jsx
+++ b/client/src/components/Trips/TripMembersModal.tsx
@@ -1,13 +1,20 @@
-import React, { useState, useEffect } from 'react'
+import { useState, useEffect } from 'react'
import Modal from '../shared/Modal'
import { tripsApi, authApi } from '../../api/client'
import { useToast } from '../shared/Toast'
import { useAuthStore } from '../../store/authStore'
import { Crown, UserMinus, UserPlus, Users, LogOut } from 'lucide-react'
import { useTranslation } from '../../i18n'
+import { getApiErrorMessage } from '../../types'
import CustomSelect from '../shared/CustomSelect'
-function Avatar({ username, avatarUrl, size = 32 }) {
+interface AvatarProps {
+ username: string
+ avatarUrl: string | null
+ size?: number
+}
+
+function Avatar({ username, avatarUrl, size = 32 }: AvatarProps) {
if (avatarUrl) {
return <img src={avatarUrl} alt="" style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flexShrink: 0 }} />
}
@@ -25,7 +32,14 @@ function Avatar({ username, avatarUrl, size = 32 }) {
)
}
-export default function TripMembersModal({ isOpen, onClose, tripId, tripTitle }) {
+interface TripMembersModalProps {
+ isOpen: boolean
+ onClose: () => void
+ tripId: number
+ tripTitle: string
+}
+
+export default function TripMembersModal({ isOpen, onClose, tripId, tripTitle }: TripMembersModalProps) {
const [data, setData] = useState(null)
const [allUsers, setAllUsers] = useState([])
const [loading, setLoading] = useState(false)
@@ -71,8 +85,8 @@ export default function TripMembersModal({ isOpen, onClose, tripId, tripTitle })
setSelectedUserId('')
await loadMembers()
toast.success(`${target.username} ${t('members.added')}`)
- } catch (err) {
- toast.error(err.response?.data?.error || t('members.addError'))
+ } catch (err: unknown) {
+ toast.error(getApiErrorMessage(err, t('members.addError')))
} finally {
setAdding(false)
}
diff --git a/client/src/components/Vacay/VacayCalendar.jsx b/client/src/components/Vacay/VacayCalendar.tsx
similarity index 98%
rename from client/src/components/Vacay/VacayCalendar.jsx
rename to client/src/components/Vacay/VacayCalendar.tsx
index 283bbb5e5..fd252e194 100644
--- a/client/src/components/Vacay/VacayCalendar.jsx
+++ b/client/src/components/Vacay/VacayCalendar.tsx
@@ -1,4 +1,4 @@
-import React, { useMemo, useState, useCallback } from 'react'
+import { useMemo, useState, useCallback } from 'react'
import { useVacayStore } from '../../store/vacayStore'
import { useTranslation } from '../../i18n'
import { isWeekend } from './holidays'
diff --git a/client/src/components/Vacay/VacayMonthCard.jsx b/client/src/components/Vacay/VacayMonthCard.tsx
similarity index 93%
rename from client/src/components/Vacay/VacayMonthCard.jsx
rename to client/src/components/Vacay/VacayMonthCard.tsx
index b3d4e21ea..a3f7894f3 100644
--- a/client/src/components/Vacay/VacayMonthCard.jsx
+++ b/client/src/components/Vacay/VacayMonthCard.tsx
@@ -1,16 +1,29 @@
-import React, { useMemo } from 'react'
+import { useMemo } from 'react'
import { useTranslation } from '../../i18n'
import { isWeekend } from './holidays'
+import type { HolidaysMap, VacayEntry } from '../../types'
const WEEKDAYS_EN = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']
const WEEKDAYS_DE = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So']
const MONTHS_EN = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
const MONTHS_DE = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']
+interface VacayMonthCardProps {
+ year: number
+ month: number
+ holidays: HolidaysMap
+ companyHolidaySet: Set<string>
+ companyHolidaysEnabled?: boolean
+ entryMap: Record<string, VacayEntry[]>
+ onCellClick: (date: string) => void
+ companyMode: boolean
+ blockWeekends: boolean
+}
+
export default function VacayMonthCard({
year, month, holidays, companyHolidaySet, companyHolidaysEnabled = true, entryMap,
onCellClick, companyMode, blockWeekends
-}) {
+}: VacayMonthCardProps) {
const { language } = useTranslation()
const weekdays = language === 'de' ? WEEKDAYS_DE : WEEKDAYS_EN
const monthNames = language === 'de' ? MONTHS_DE : MONTHS_EN
diff --git a/client/src/components/Vacay/VacayPersons.jsx b/client/src/components/Vacay/VacayPersons.tsx
similarity index 97%
rename from client/src/components/Vacay/VacayPersons.jsx
rename to client/src/components/Vacay/VacayPersons.tsx
index b02e08b18..0e5023d63 100644
--- a/client/src/components/Vacay/VacayPersons.jsx
+++ b/client/src/components/Vacay/VacayPersons.tsx
@@ -1,9 +1,11 @@
-import React, { useState, useEffect } from 'react'
import ReactDOM from 'react-dom'
+import { useState, useEffect } from 'react'
+import DOM from 'react-dom'
import { UserPlus, Unlink, Check, Loader2, Clock, X } from 'lucide-react'
import { useVacayStore } from '../../store/vacayStore'
import { useAuthStore } from '../../store/authStore'
import { useTranslation } from '../../i18n'
+import { getApiErrorMessage } from '../../types'
import { useToast } from '../shared/Toast'
import CustomSelect from '../shared/CustomSelect'
import apiClient from '../../api/client'
@@ -46,8 +48,8 @@ export default function VacayPersons() {
toast.success(t('vacay.inviteSent'))
setShowInvite(false)
setSelectedInviteUser(null)
- } catch (err) {
- toast.error(err.response?.data?.error || t('vacay.inviteError'))
+ } catch (err: unknown) {
+ toast.error(getApiErrorMessage(err, t('vacay.inviteError')))
} finally {
setInviting(false)
}
diff --git a/client/src/components/Vacay/VacaySettings.jsx b/client/src/components/Vacay/VacaySettings.tsx
similarity index 95%
rename from client/src/components/Vacay/VacaySettings.jsx
rename to client/src/components/Vacay/VacaySettings.tsx
index 88ce096f3..c700effc0 100644
--- a/client/src/components/Vacay/VacaySettings.jsx
+++ b/client/src/components/Vacay/VacaySettings.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from 'react'
+import { useState, useEffect } from 'react'
import { MapPin, CalendarOff, AlertCircle, Building2, Unlink, ArrowRightLeft, Globe } from 'lucide-react'
import { useVacayStore } from '../../store/vacayStore'
import { useTranslation } from '../../i18n'
@@ -6,7 +6,11 @@ import { useToast } from '../shared/Toast'
import CustomSelect from '../shared/CustomSelect'
import apiClient from '../../api/client'
-export default function VacaySettings({ onClose }) {
+interface VacaySettingsProps {
+ onClose: () => void
+}
+
+export default function VacaySettings({ onClose }: VacaySettingsProps) {
const { t } = useTranslation()
const toast = useToast()
const { plan, updatePlan, isFused, dissolve, users } = useVacayStore()
@@ -192,7 +196,15 @@ export default function VacaySettings({ onClose }) {
)
}
-function SettingToggle({ icon: Icon, label, hint, value, onChange }) {
+interface SettingToggleProps {
+ icon: React.ComponentType<{ size?: number; className?: string; style?: React.CSSProperties }>
+ label: string
+ hint: string
+ value: boolean
+ onChange: (value: boolean) => void
+}
+
+function SettingToggle({ icon: Icon, label, hint, value, onChange }: SettingToggleProps) {
return (
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2 min-w-0">
diff --git a/client/src/components/Vacay/VacayStats.jsx b/client/src/components/Vacay/VacayStats.tsx
similarity index 92%
rename from client/src/components/Vacay/VacayStats.jsx
rename to client/src/components/Vacay/VacayStats.tsx
index e0a3ea4eb..99d41cff8 100644
--- a/client/src/components/Vacay/VacayStats.jsx
+++ b/client/src/components/Vacay/VacayStats.tsx
@@ -1,8 +1,16 @@
-import React, { useEffect, useState } from 'react'
+import { useEffect, useState } from 'react'
import { Briefcase, Pencil } from 'lucide-react'
import { useVacayStore } from '../../store/vacayStore'
import { useAuthStore } from '../../store/authStore'
import { useTranslation } from '../../i18n'
+import type { VacayStat } from '../../types'
+
+interface VacayStatExtended extends VacayStat {
+ username: string
+ avatar_url: string | null
+ color: string | null
+ total_available: number
+}
export default function VacayStats() {
const { t } = useTranslation()
@@ -41,7 +49,16 @@ export default function VacayStats() {
)
}
-function StatCard({ stat: s, isMe, canEdit, selectedYear, onSave, t }) {
+interface StatCardProps {
+ stat: VacayStatExtended
+ isMe: boolean
+ canEdit: boolean
+ selectedYear: number
+ onSave: (userId: number, year: number, days: number) => Promise<void>
+ t: (key: string) => string
+}
+
+function StatCard({ stat: s, isMe, canEdit, selectedYear, onSave, t }: StatCardProps) {
const [editing, setEditing] = useState(false)
const [localDays, setLocalDays] = useState(s.vacation_days)
const pct = s.total_available > 0 ? Math.min(100, (s.used / s.total_available) * 100) : 0
diff --git a/client/src/components/Vacay/holidays.js b/client/src/components/Vacay/holidays.js
deleted file mode 100644
index 555ce65a8..000000000
--- a/client/src/components/Vacay/holidays.js
+++ /dev/null
@@ -1,146 +0,0 @@
-// German public holidays (Feiertage) calculation per Bundesland
-// Includes fixed and Easter-dependent movable holidays
-
-const BUNDESLAENDER = {
- BW: 'Baden-Württemberg',
- BY: 'Bayern',
- BE: 'Berlin',
- BB: 'Brandenburg',
- HB: 'Bremen',
- HH: 'Hamburg',
- HE: 'Hessen',
- MV: 'Mecklenburg-Vorpommern',
- NI: 'Niedersachsen',
- NW: 'Nordrhein-Westfalen',
- RP: 'Rheinland-Pfalz',
- SL: 'Saarland',
- SN: 'Sachsen',
- ST: 'Sachsen-Anhalt',
- SH: 'Schleswig-Holstein',
- TH: 'Thüringen',
-};
-
-// Gauss Easter algorithm
-function easterSunday(year) {
- const a = year % 19;
- const b = Math.floor(year / 100);
- const c = year % 100;
- const d = Math.floor(b / 4);
- const e = b % 4;
- const f = Math.floor((b + 8) / 25);
- const g = Math.floor((b - f + 1) / 3);
- const h = (19 * a + b - d - g + 15) % 30;
- const i = Math.floor(c / 4);
- const k = c % 4;
- const l = (32 + 2 * e + 2 * i - h - k) % 7;
- const m = Math.floor((a + 11 * h + 22 * l) / 451);
- const month = Math.floor((h + l - 7 * m + 114) / 31);
- const day = ((h + l - 7 * m + 114) % 31) + 1;
- return new Date(year, month - 1, day);
-}
-
-function addDays(date, days) {
- const d = new Date(date);
- d.setDate(d.getDate() + days);
- return d;
-}
-
-function fmt(date) {
- const y = date.getFullYear();
- const m = String(date.getMonth() + 1).padStart(2, '0');
- const d = String(date.getDate()).padStart(2, '0');
- return `${y}-${m}-${d}`;
-}
-
-export function getHolidays(year, bundesland = 'NW') {
- const easter = easterSunday(year);
- const holidays = {};
-
- // Fixed holidays (nationwide)
- holidays[`${year}-01-01`] = 'Neujahr';
- holidays[`${year}-05-01`] = 'Tag der Arbeit';
- holidays[`${year}-10-03`] = 'Tag der Deutschen Einheit';
- holidays[`${year}-12-25`] = '1. Weihnachtsfeiertag';
- holidays[`${year}-12-26`] = '2. Weihnachtsfeiertag';
-
- // Easter-dependent (nationwide)
- holidays[fmt(addDays(easter, -2))] = 'Karfreitag';
- holidays[fmt(addDays(easter, 1))] = 'Ostermontag';
- holidays[fmt(addDays(easter, 39))] = 'Christi Himmelfahrt';
- holidays[fmt(addDays(easter, 50))] = 'Pfingstmontag';
-
- // State-specific
- const bl = bundesland.toUpperCase();
-
- // Heilige Drei Könige (6. Jan) — BW, BY, ST
- if (['BW', 'BY', 'ST'].includes(bl)) {
- holidays[`${year}-01-06`] = 'Heilige Drei Könige';
- }
-
- // Internationaler Frauentag (8. März) — BE, MV
- if (['BE', 'MV'].includes(bl)) {
- holidays[`${year}-03-08`] = 'Internationaler Frauentag';
- }
-
- // Fronleichnam — BW, BY, HE, NW, RP, SL, SN (teilweise), TH (teilweise)
- if (['BW', 'BY', 'HE', 'NW', 'RP', 'SL'].includes(bl)) {
- holidays[fmt(addDays(easter, 60))] = 'Fronleichnam';
- }
-
- // Mariä Himmelfahrt (15. Aug) — SL, BY (teilweise)
- if (['SL'].includes(bl)) {
- holidays[`${year}-08-15`] = 'Mariä Himmelfahrt';
- }
-
- // Weltkindertag (20. Sep) — TH
- if (bl === 'TH') {
- holidays[`${year}-09-20`] = 'Weltkindertag';
- }
-
- // Reformationstag (31. Okt) — BB, HB, HH, MV, NI, SN, ST, SH, TH
- if (['BB', 'HB', 'HH', 'MV', 'NI', 'SN', 'ST', 'SH', 'TH'].includes(bl)) {
- holidays[`${year}-10-31`] = 'Reformationstag';
- }
-
- // Allerheiligen (1. Nov) — BW, BY, NW, RP, SL
- if (['BW', 'BY', 'NW', 'RP', 'SL'].includes(bl)) {
- holidays[`${year}-11-01`] = 'Allerheiligen';
- }
-
- // Buß- und Bettag — SN (Mittwoch vor dem 23. November)
- if (bl === 'SN') {
- const nov23 = new Date(year, 10, 23);
- let bbt = new Date(nov23);
- while (bbt.getDay() !== 3) bbt.setDate(bbt.getDate() - 1);
- holidays[fmt(bbt)] = 'Buß- und Bettag';
- }
-
- return holidays;
-}
-
-export function isWeekend(dateStr) {
- const d = new Date(dateStr + 'T00:00:00');
- const day = d.getDay();
- return day === 0 || day === 6;
-}
-
-export function getWeekday(dateStr) {
- const d = new Date(dateStr + 'T00:00:00');
- return ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'][d.getDay()];
-}
-
-export function getWeekdayFull(dateStr) {
- const d = new Date(dateStr + 'T00:00:00');
- return ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'][d.getDay()];
-}
-
-export function daysInMonth(year, month) {
- return new Date(year, month, 0).getDate();
-}
-
-export function formatDate(dateStr) {
- const d = new Date(dateStr + 'T00:00:00');
- return d.toLocaleDateString('de-DE', { weekday: 'short', day: '2-digit', month: '2-digit', year: 'numeric' });
-}
-
-export { BUNDESLAENDER };
diff --git a/client/src/components/Vacay/holidays.ts b/client/src/components/Vacay/holidays.ts
new file mode 100644
index 000000000..8d42b33ed
--- /dev/null
+++ b/client/src/components/Vacay/holidays.ts
@@ -0,0 +1,131 @@
+const BUNDESLAENDER: Record<string, string> = {
+ BW: 'Baden-Württemberg',
+ BY: 'Bayern',
+ BE: 'Berlin',
+ BB: 'Brandenburg',
+ HB: 'Bremen',
+ HH: 'Hamburg',
+ HE: 'Hessen',
+ MV: 'Mecklenburg-Vorpommern',
+ NI: 'Niedersachsen',
+ NW: 'Nordrhein-Westfalen',
+ RP: 'Rheinland-Pfalz',
+ SL: 'Saarland',
+ SN: 'Sachsen',
+ ST: 'Sachsen-Anhalt',
+ SH: 'Schleswig-Holstein',
+ TH: 'Thüringen',
+}
+
+function easterSunday(year: number): Date {
+ const a = year % 19
+ const b = Math.floor(year / 100)
+ const c = year % 100
+ const d = Math.floor(b / 4)
+ const e = b % 4
+ const f = Math.floor((b + 8) / 25)
+ const g = Math.floor((b - f + 1) / 3)
+ const h = (19 * a + b - d - g + 15) % 30
+ const i = Math.floor(c / 4)
+ const k = c % 4
+ const l = (32 + 2 * e + 2 * i - h - k) % 7
+ const m = Math.floor((a + 11 * h + 22 * l) / 451)
+ const month = Math.floor((h + l - 7 * m + 114) / 31)
+ const day = ((h + l - 7 * m + 114) % 31) + 1
+ return new Date(year, month - 1, day)
+}
+
+function addDays(date: Date, days: number): Date {
+ const d = new Date(date)
+ d.setDate(d.getDate() + days)
+ return d
+}
+
+function fmt(date: Date): string {
+ const y = date.getFullYear()
+ const m = String(date.getMonth() + 1).padStart(2, '0')
+ const d = String(date.getDate()).padStart(2, '0')
+ return `${y}-${m}-${d}`
+}
+
+export function getHolidays(year: number, bundesland: string = 'NW'): Record<string, string> {
+ const easter = easterSunday(year)
+ const holidays: Record<string, string> = {}
+
+ holidays[`${year}-01-01`] = 'Neujahr'
+ holidays[`${year}-05-01`] = 'Tag der Arbeit'
+ holidays[`${year}-10-03`] = 'Tag der Deutschen Einheit'
+ holidays[`${year}-12-25`] = '1. Weihnachtsfeiertag'
+ holidays[`${year}-12-26`] = '2. Weihnachtsfeiertag'
+
+ holidays[fmt(addDays(easter, -2))] = 'Karfreitag'
+ holidays[fmt(addDays(easter, 1))] = 'Ostermontag'
+ holidays[fmt(addDays(easter, 39))] = 'Christi Himmelfahrt'
+ holidays[fmt(addDays(easter, 50))] = 'Pfingstmontag'
+
+ const bl = bundesland.toUpperCase()
+
+ if (['BW', 'BY', 'ST'].includes(bl)) {
+ holidays[`${year}-01-06`] = 'Heilige Drei Könige'
+ }
+
+ if (['BE', 'MV'].includes(bl)) {
+ holidays[`${year}-03-08`] = 'Internationaler Frauentag'
+ }
+
+ if (['BW', 'BY', 'HE', 'NW', 'RP', 'SL'].includes(bl)) {
+ holidays[fmt(addDays(easter, 60))] = 'Fronleichnam'
+ }
+
+ if (['SL'].includes(bl)) {
+ holidays[`${year}-08-15`] = 'Mariä Himmelfahrt'
+ }
+
+ if (bl === 'TH') {
+ holidays[`${year}-09-20`] = 'Weltkindertag'
+ }
+
+ if (['BB', 'HB', 'HH', 'MV', 'NI', 'SN', 'ST', 'SH', 'TH'].includes(bl)) {
+ holidays[`${year}-10-31`] = 'Reformationstag'
+ }
+
+ if (['BW', 'BY', 'NW', 'RP', 'SL'].includes(bl)) {
+ holidays[`${year}-11-01`] = 'Allerheiligen'
+ }
+
+ if (bl === 'SN') {
+ const nov23 = new Date(year, 10, 23)
+ const bbt = new Date(nov23)
+ while (bbt.getDay() !== 3) bbt.setDate(bbt.getDate() - 1)
+ holidays[fmt(bbt)] = 'Buß- und Bettag'
+ }
+
+ return holidays
+}
+
+export function isWeekend(dateStr: string): boolean {
+ const d = new Date(dateStr + 'T00:00:00')
+ const day = d.getDay()
+ return day === 0 || day === 6
+}
+
+export function getWeekday(dateStr: string): string {
+ const d = new Date(dateStr + 'T00:00:00')
+ return ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'][d.getDay()]
+}
+
+export function getWeekdayFull(dateStr: string): string {
+ const d = new Date(dateStr + 'T00:00:00')
+ return ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'][d.getDay()]
+}
+
+export function daysInMonth(year: number, month: number): number {
+ return new Date(year, month, 0).getDate()
+}
+
+export function formatDate(dateStr: string): string {
+ const d = new Date(dateStr + 'T00:00:00')
+ return d.toLocaleDateString('de-DE', { weekday: 'short', day: '2-digit', month: '2-digit', year: 'numeric' })
+}
+
+export { BUNDESLAENDER }
diff --git a/client/src/components/Weather/WeatherWidget.jsx b/client/src/components/Weather/WeatherWidget.tsx
similarity index 92%
rename from client/src/components/Weather/WeatherWidget.jsx
rename to client/src/components/Weather/WeatherWidget.tsx
index 6f0e63184..ccdc295cf 100644
--- a/client/src/components/Weather/WeatherWidget.jsx
+++ b/client/src/components/Weather/WeatherWidget.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from 'react'
+import { useState, useEffect } from 'react'
import { Sun, Cloud, CloudRain, CloudSnow, CloudDrizzle, CloudLightning, Wind } from 'lucide-react'
import { weatherApi } from '../../api/client'
import { useSettingsStore } from '../../store/settingsStore'
@@ -15,7 +15,12 @@ const WEATHER_ICON_MAP = {
Haze: Wind,
}
-function WeatherIcon({ main, size = 13 }) {
+interface WeatherIconProps {
+ main: string
+ size?: number
+}
+
+function WeatherIcon({ main, size = 13 }: WeatherIconProps) {
const Icon = WEATHER_ICON_MAP[main] || Cloud
return <Icon size={size} strokeWidth={1.8} />
}
@@ -32,7 +37,14 @@ function setWeatherCache(key, value) {
try { sessionStorage.setItem(key, JSON.stringify(value)) } catch {}
}
-export default function WeatherWidget({ lat, lng, date, compact = false }) {
+interface WeatherWidgetProps {
+ lat: number | null
+ lng: number | null
+ date: string
+ compact?: boolean
+}
+
+export default function WeatherWidget({ lat, lng, date, compact = false }: WeatherWidgetProps) {
const [weather, setWeather] = useState(null)
const [loading, setLoading] = useState(false)
const [failed, setFailed] = useState(false)
diff --git a/client/src/components/shared/ConfirmDialog.jsx b/client/src/components/shared/ConfirmDialog.tsx
similarity index 90%
rename from client/src/components/shared/ConfirmDialog.jsx
rename to client/src/components/shared/ConfirmDialog.tsx
index 7d2a1b84d..144fbb55f 100644
--- a/client/src/components/shared/ConfirmDialog.jsx
+++ b/client/src/components/shared/ConfirmDialog.tsx
@@ -2,6 +2,17 @@ import React, { useEffect, useCallback } from 'react'
import { AlertTriangle } from 'lucide-react'
import { useTranslation } from '../../i18n'
+interface ConfirmDialogProps {
+ isOpen: boolean
+ onClose: () => void
+ onConfirm: () => void
+ title?: string
+ message?: string
+ confirmLabel?: string
+ cancelLabel?: string
+ danger?: boolean
+}
+
export default function ConfirmDialog({
isOpen,
onClose,
@@ -11,10 +22,10 @@ export default function ConfirmDialog({
confirmLabel,
cancelLabel,
danger = true,
-}) {
+}: ConfirmDialogProps) {
const { t } = useTranslation()
- const handleEsc = useCallback((e) => {
+ const handleEsc = useCallback((e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
}, [onClose])
diff --git a/client/src/components/shared/ContextMenu.jsx b/client/src/components/shared/ContextMenu.tsx
similarity index 81%
rename from client/src/components/shared/ContextMenu.jsx
rename to client/src/components/shared/ContextMenu.tsx
index a0c9a040d..a75d7f317 100644
--- a/client/src/components/shared/ContextMenu.jsx
+++ b/client/src/components/shared/ContextMenu.tsx
@@ -1,10 +1,25 @@
import React, { useState, useEffect, useRef } from 'react'
import ReactDOM from 'react-dom'
+import { LucideIcon } from 'lucide-react'
+
+interface MenuItem {
+ label?: string
+ icon?: LucideIcon
+ onClick?: () => void
+ danger?: boolean
+ divider?: boolean
+}
+
+interface MenuState {
+ x: number
+ y: number
+ items: MenuItem[]
+}
export function useContextMenu() {
- const [menu, setMenu] = useState(null) // { x, y, items }
+ const [menu, setMenu] = useState<MenuState | null>(null)
- const open = (e, items) => {
+ const open = (e: React.MouseEvent, items: MenuItem[]) => {
e.preventDefault()
e.stopPropagation()
setMenu({ x: e.clientX, y: e.clientY, items })
@@ -15,8 +30,13 @@ export function useContextMenu() {
return { menu, open, close }
}
-export function ContextMenu({ menu, onClose }) {
- const ref = useRef(null)
+interface ContextMenuProps {
+ menu: MenuState | null
+ onClose: () => void
+}
+
+export function ContextMenu({ menu, onClose }: ContextMenuProps) {
+ const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!menu) return
@@ -29,7 +49,6 @@ export function ContextMenu({ menu, onClose }) {
}
}, [menu, onClose])
- // Adjust position if menu would overflow viewport
useEffect(() => {
if (!menu || !ref.current) return
const el = ref.current
@@ -60,7 +79,7 @@ export function ContextMenu({ menu, onClose }) {
if (item.divider) return <div key={i} style={{ height: 1, background: 'var(--border-faint)', margin: '3px 6px' }} />
const Icon = item.icon
return (
- <button key={i} onClick={() => { item.onClick(); onClose() }} style={{
+ <button key={i} onClick={() => { item.onClick?.(); onClose() }} style={{
display: 'flex', alignItems: 'center', gap: 8, width: '100%',
padding: '7px 10px', borderRadius: 7, border: 'none',
background: 'none', cursor: 'pointer', fontFamily: 'inherit',
diff --git a/client/src/components/shared/CustomDateTimePicker.jsx b/client/src/components/shared/CustomDateTimePicker.tsx
similarity index 86%
rename from client/src/components/shared/CustomDateTimePicker.jsx
rename to client/src/components/shared/CustomDateTimePicker.tsx
index 5391d233a..0d52766b1 100644
--- a/client/src/components/shared/CustomDateTimePicker.jsx
+++ b/client/src/components/shared/CustomDateTimePicker.tsx
@@ -3,24 +3,30 @@ import ReactDOM from 'react-dom'
import { Calendar, Clock, ChevronLeft, ChevronRight, ChevronUp, ChevronDown } from 'lucide-react'
import { useTranslation } from '../../i18n'
-function daysInMonth(year, month) { return new Date(year, month + 1, 0).getDate() }
-function getWeekday(year, month, day) { return new Date(year, month, day).getDay() }
+function daysInMonth(year: number, month: number): number { return new Date(year, month + 1, 0).getDate() }
+function getWeekday(year: number, month: number, day: number): number { return new Date(year, month, day).getDay() }
+
+interface CustomDatePickerProps {
+ value: string
+ onChange: (value: string) => void
+ placeholder?: string
+ style?: React.CSSProperties
+}
-// ── Datum-Only Picker ────────────────────────────────────────────────────────
-export function CustomDatePicker({ value, onChange, placeholder, style = {} }) {
+export function CustomDatePicker({ value, onChange, placeholder, style = {} }: CustomDatePickerProps) {
const { locale, t } = useTranslation()
const [open, setOpen] = useState(false)
- const ref = useRef(null)
- const dropRef = useRef(null)
+ const ref = useRef<HTMLDivElement>(null)
+ const dropRef = useRef<HTMLDivElement>(null)
const parsed = value ? new Date(value + 'T00:00:00') : null
const [viewYear, setViewYear] = useState(parsed?.getFullYear() || new Date().getFullYear())
const [viewMonth, setViewMonth] = useState(parsed?.getMonth() ?? new Date().getMonth())
useEffect(() => {
- const handler = (e) => {
- if (ref.current?.contains(e.target)) return
- if (dropRef.current?.contains(e.target)) return
+ const handler = (e: MouseEvent) => {
+ if (ref.current?.contains(e.target as Node)) return
+ if (dropRef.current?.contains(e.target as Node)) return
setOpen(false)
}
if (open) document.addEventListener('mousedown', handler)
@@ -36,12 +42,12 @@ export function CustomDatePicker({ value, onChange, placeholder, style = {} }) {
const monthLabel = new Date(viewYear, viewMonth).toLocaleDateString(locale, { month: 'long', year: 'numeric' })
const days = daysInMonth(viewYear, viewMonth)
- const startDay = (getWeekday(viewYear, viewMonth, 1) + 6) % 7 // Mo=0
+ const startDay = (getWeekday(viewYear, viewMonth, 1) + 6) % 7
const weekdays = Array.from({ length: 7 }, (_, i) => new Date(2024, 0, i + 1).toLocaleDateString(locale, { weekday: 'narrow' }))
const displayValue = parsed ? parsed.toLocaleDateString(locale, { day: 'numeric', month: 'short', year: 'numeric' }) : null
- const selectDay = (day) => {
+ const selectDay = (day: number) => {
const y = String(viewYear)
const m = String(viewMonth + 1).padStart(2, '0')
const d = String(day).padStart(2, '0')
@@ -51,7 +57,7 @@ export function CustomDatePicker({ value, onChange, placeholder, style = {} }) {
const selectedDay = parsed && parsed.getFullYear() === viewYear && parsed.getMonth() === viewMonth ? parsed.getDate() : null
const today = new Date()
- const isToday = (d) => today.getFullYear() === viewYear && today.getMonth() === viewMonth && today.getDate() === d
+ const isToday = (d: number) => today.getFullYear() === viewYear && today.getMonth() === viewMonth && today.getDate() === d
return (
<div ref={ref} style={{ position: 'relative', ...style }}>
@@ -81,11 +87,8 @@ export function CustomDatePicker({ value, onChange, placeholder, style = {} }) {
const vh = window.innerHeight
let left = r.left
let top = r.bottom + 4
- // Keep within viewport horizontally
if (left + w > vw - pad) left = Math.max(pad, vw - w - pad)
- // If not enough space below, open above
if (top + 320 > vh) top = Math.max(pad, r.top - 320)
- // On very small screens, center horizontally
if (vw < 360) left = Math.max(pad, (vw - w) / 2)
return { top, left }
})(),
@@ -161,16 +164,21 @@ export function CustomDatePicker({ value, onChange, placeholder, style = {} }) {
)
}
-// ── DateTime Picker (Datum + Uhrzeit kombiniert) ─────────────────────────────
-export function CustomDateTimePicker({ value, onChange, placeholder, style = {} }) {
+interface CustomDateTimePickerProps {
+ value: string
+ onChange: (value: string) => void
+ placeholder?: string
+ style?: React.CSSProperties
+}
+
+export function CustomDateTimePicker({ value, onChange, placeholder, style = {} }: CustomDateTimePickerProps) {
const { locale } = useTranslation()
- // value = "2024-03-15T14:30" oder ""
const [datePart, timePart] = (value || '').split('T')
- const handleDateChange = (d) => {
+ const handleDateChange = (d: string) => {
onChange(d ? `${d}T${timePart || '12:00'}` : '')
}
- const handleTimeChange = (t) => {
+ const handleTimeChange = (t: string) => {
const d = datePart || new Date().toISOString().split('T')[0]
onChange(t ? `${d}T${t}` : d)
}
@@ -185,5 +193,4 @@ export function CustomDateTimePicker({ value, onChange, placeholder, style = {}
)
}
-// Inline re-export for convenience
import CustomTimePicker from './CustomTimePicker'
diff --git a/client/src/components/shared/CustomSelect.jsx b/client/src/components/shared/CustomSelect.tsx
similarity index 89%
rename from client/src/components/shared/CustomSelect.jsx
rename to client/src/components/shared/CustomSelect.tsx
index d6d25db72..da4d19390 100644
--- a/client/src/components/shared/CustomSelect.jsx
+++ b/client/src/components/shared/CustomSelect.tsx
@@ -2,29 +2,48 @@ import React, { useState, useRef, useEffect } from 'react'
import ReactDOM from 'react-dom'
import { ChevronDown, Check } from 'lucide-react'
+interface SelectOption {
+ value: string
+ label: string
+ icon?: React.ReactNode
+ isHeader?: boolean
+ searchLabel?: string
+ groupLabel?: string
+}
+
+interface CustomSelectProps {
+ value: string
+ onChange: (value: string) => void
+ options?: SelectOption[]
+ placeholder?: string
+ searchable?: boolean
+ style?: React.CSSProperties
+ size?: 'sm' | 'md'
+}
+
export default function CustomSelect({
value,
onChange,
- options = [], // [{ value, label, icon? }]
+ options = [],
placeholder = '',
searchable = false,
style = {},
- size = 'md', // 'sm' | 'md'
-}) {
+ size = 'md',
+}: CustomSelectProps) {
const [open, setOpen] = useState(false)
const [search, setSearch] = useState('')
- const ref = useRef(null)
- const dropRef = useRef(null)
- const searchRef = useRef(null)
+ const ref = useRef<HTMLDivElement>(null)
+ const dropRef = useRef<HTMLDivElement>(null)
+ const searchRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (open && searchable && searchRef.current) searchRef.current.focus()
}, [open, searchable])
useEffect(() => {
- const handleClick = (e) => {
- if (ref.current?.contains(e.target)) return
- if (dropRef.current?.contains(e.target)) return
+ const handleClick = (e: MouseEvent) => {
+ if (ref.current?.contains(e.target as Node)) return
+ if (dropRef.current?.contains(e.target as Node)) return
setOpen(false)
}
if (open) document.addEventListener('mousedown', handleClick)
@@ -35,8 +54,8 @@ export default function CustomSelect({
const filtered = searchable && search
? (() => {
const q = search.toLowerCase()
- const result = []
- let currentHeader = null
+ const result: SelectOption[] = []
+ let currentHeader: SelectOption | null = null
let headerAdded = false
for (const o of options) {
if (o.isHeader) {
@@ -44,7 +63,6 @@ export default function CustomSelect({
headerAdded = false
continue
}
- // Match against label, searchLabel, or groupLabel
const haystack = [o.label, o.searchLabel, o.groupLabel].filter(Boolean).join(' ').toLowerCase()
if (haystack.includes(q)) {
if (currentHeader && !headerAdded) {
diff --git a/client/src/components/shared/CustomTimePicker.jsx b/client/src/components/shared/CustomTimePicker.tsx
similarity index 93%
rename from client/src/components/shared/CustomTimePicker.jsx
rename to client/src/components/shared/CustomTimePicker.tsx
index 1b0bc5993..4509dc9f8 100644
--- a/client/src/components/shared/CustomTimePicker.jsx
+++ b/client/src/components/shared/CustomTimePicker.tsx
@@ -3,7 +3,7 @@ import ReactDOM from 'react-dom'
import { Clock, ChevronUp, ChevronDown } from 'lucide-react'
import { useSettingsStore } from '../../store/settingsStore'
-function formatDisplay(val, is12h) {
+function formatDisplay(val: string, is12h: boolean): string {
if (!val) return ''
const [h, m] = val.split(':').map(Number)
if (isNaN(h) || isNaN(m)) return val
@@ -13,28 +13,35 @@ function formatDisplay(val, is12h) {
return `${h12}:${String(m).padStart(2, '0')} ${period}`
}
-export default function CustomTimePicker({ value, onChange, placeholder = '00:00', style = {} }) {
+interface CustomTimePickerProps {
+ value: string
+ onChange: (value: string) => void
+ placeholder?: string
+ style?: React.CSSProperties
+}
+
+export default function CustomTimePicker({ value, onChange, placeholder = '00:00', style = {} }: CustomTimePickerProps) {
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
const [open, setOpen] = useState(false)
const [inputFocused, setInputFocused] = useState(false)
- const ref = useRef(null)
- const dropRef = useRef(null)
+ const ref = useRef<HTMLDivElement>(null)
+ const dropRef = useRef<HTMLDivElement>(null)
const [h, m] = (value || '').split(':').map(Number)
const hour = isNaN(h) ? null : h
const minute = isNaN(m) ? null : m
useEffect(() => {
- const handler = (e) => {
- if (ref.current?.contains(e.target)) return
- if (dropRef.current?.contains(e.target)) return
+ const handler = (e: MouseEvent) => {
+ if (ref.current?.contains(e.target as Node)) return
+ if (dropRef.current?.contains(e.target as Node)) return
setOpen(false)
}
if (open) document.addEventListener('mousedown', handler)
return () => document.removeEventListener('mousedown', handler)
}, [open])
- const update = (newH, newM) => {
+ const update = (newH: number, newM: number) => {
const hh = String(Math.max(0, Math.min(23, newH))).padStart(2, '0')
const mm = String(Math.max(0, Math.min(59, newM))).padStart(2, '0')
onChange(`${hh}:${mm}`)
@@ -53,16 +60,15 @@ export default function CustomTimePicker({ value, onChange, placeholder = '00:00
update(newH, newM)
}
- const btnStyle = {
+ const btnStyle: React.CSSProperties = {
background: 'none', border: 'none', cursor: 'pointer', padding: 2,
color: 'var(--text-faint)', display: 'flex', borderRadius: 4,
transition: 'color 0.15s',
}
- const handleInput = (e) => {
+ const handleInput = (e: React.ChangeEvent<HTMLInputElement>) => {
const raw = e.target.value
onChange(raw)
- // Auto-format: wenn "1430" → "14:30"
const clean = raw.replace(/[^0-9:]/g, '')
if (/^\d{2}:\d{2}$/.test(clean)) onChange(clean)
else if (/^\d{4}$/.test(clean)) onChange(clean.slice(0, 2) + ':' + clean.slice(2))
@@ -139,7 +145,7 @@ export default function CustomTimePicker({ value, onChange, placeholder = '00:00
animation: 'selectIn 0.15s ease-out',
backdropFilter: 'blur(24px)', WebkitBackdropFilter: 'blur(24px)',
}}>
- {/* Stunden */}
+ {/* Hours */}
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
<button type="button" onClick={incHour} style={btnStyle}
onMouseEnter={e => e.currentTarget.style.color = 'var(--text-primary)'}
@@ -163,7 +169,7 @@ export default function CustomTimePicker({ value, onChange, placeholder = '00:00
<span style={{ fontSize: 22, fontWeight: 700, color: 'var(--text-faint)', marginTop: -2 }}>:</span>
- {/* Minuten */}
+ {/* Minutes */}
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
<button type="button" onClick={incMin} style={btnStyle}
onMouseEnter={e => e.currentTarget.style.color = 'var(--text-primary)'}
diff --git a/client/src/components/shared/Modal.jsx b/client/src/components/shared/Modal.tsx
similarity index 87%
rename from client/src/components/shared/Modal.jsx
rename to client/src/components/shared/Modal.tsx
index c0f043ad3..7b39e1fcb 100644
--- a/client/src/components/shared/Modal.jsx
+++ b/client/src/components/shared/Modal.tsx
@@ -1,7 +1,7 @@
import React, { useEffect, useCallback, useRef } from 'react'
import { X } from 'lucide-react'
-const sizeClasses = {
+const sizeClasses: Record<string, string> = {
sm: 'max-w-sm',
md: 'max-w-md',
lg: 'max-w-lg',
@@ -9,6 +9,16 @@ const sizeClasses = {
'2xl': 'max-w-4xl',
}
+interface ModalProps {
+ isOpen: boolean
+ onClose: () => void
+ title?: React.ReactNode
+ children?: React.ReactNode
+ size?: string
+ footer?: React.ReactNode
+ hideCloseButton?: boolean
+}
+
export default function Modal({
isOpen,
onClose,
@@ -17,8 +27,8 @@ export default function Modal({
size = 'md',
footer,
hideCloseButton = false,
-}) {
- const handleEsc = useCallback((e) => {
+}: ModalProps) {
+ const handleEsc = useCallback((e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
}, [onClose])
@@ -33,7 +43,7 @@ export default function Modal({
}
}, [isOpen, handleEsc])
- const mouseDownTarget = useRef(null)
+ const mouseDownTarget = useRef<EventTarget | null>(null)
if (!isOpen) return null
diff --git a/client/src/components/shared/PlaceAvatar.jsx b/client/src/components/shared/PlaceAvatar.tsx
similarity index 69%
rename from client/src/components/shared/PlaceAvatar.jsx
rename to client/src/components/shared/PlaceAvatar.tsx
index 3bc597d29..57e18f201 100644
--- a/client/src/components/shared/PlaceAvatar.jsx
+++ b/client/src/components/shared/PlaceAvatar.tsx
@@ -1,25 +1,37 @@
import React, { useState, useEffect } from 'react'
import { mapsApi } from '../../api/client'
import { getCategoryIcon } from './categoryIcons'
+import type { Place } from '../../types'
-const googlePhotoCache = new Map()
+interface Category {
+ color?: string
+ icon?: string
+}
+
+interface PlaceAvatarProps {
+ place: Pick<Place, 'id' | 'name' | 'image_url' | 'google_place_id'>
+ size?: number
+ category?: Category | null
+}
+
+const googlePhotoCache = new Map<string, string>()
-export default function PlaceAvatar({ place, size = 32, category }) {
- const [photoSrc, setPhotoSrc] = useState(place.image_url || null)
+export default function PlaceAvatar({ place, size = 32, category }: PlaceAvatarProps) {
+ const [photoSrc, setPhotoSrc] = useState<string | null>(place.image_url || null)
useEffect(() => {
if (place.image_url) { setPhotoSrc(place.image_url); return }
if (!place.google_place_id) { setPhotoSrc(null); return }
if (googlePhotoCache.has(place.google_place_id)) {
- setPhotoSrc(googlePhotoCache.get(place.google_place_id))
+ setPhotoSrc(googlePhotoCache.get(place.google_place_id)!)
return
}
mapsApi.placePhoto(place.google_place_id)
- .then(data => {
+ .then((data: { photoUrl?: string }) => {
if (data.photoUrl) {
- googlePhotoCache.set(place.google_place_id, data.photoUrl)
+ googlePhotoCache.set(place.google_place_id!, data.photoUrl)
setPhotoSrc(data.photoUrl)
}
})
@@ -30,7 +42,7 @@ export default function PlaceAvatar({ place, size = 32, category }) {
const IconComp = getCategoryIcon(category?.icon)
const iconSize = Math.round(size * 0.46)
- const containerStyle = {
+ const containerStyle: React.CSSProperties = {
width: size, height: size,
borderRadius: '50%',
overflow: 'hidden',
diff --git a/client/src/components/shared/Toast.jsx b/client/src/components/shared/Toast.tsx
similarity index 70%
rename from client/src/components/shared/Toast.jsx
rename to client/src/components/shared/Toast.tsx
index 356eb0347..22d2c36dd 100644
--- a/client/src/components/shared/Toast.jsx
+++ b/client/src/components/shared/Toast.tsx
@@ -1,14 +1,28 @@
import React, { createContext, useContext, useState, useCallback, useEffect } from 'react'
import { CheckCircle, XCircle, AlertCircle, Info, X } from 'lucide-react'
-const ToastContext = createContext(null)
+type ToastType = 'success' | 'error' | 'warning' | 'info'
+
+interface Toast {
+ id: number
+ message: string
+ type: ToastType
+ duration: number
+ removing: boolean
+}
+
+declare global {
+ interface Window {
+ __addToast?: (message: string, type?: ToastType, duration?: number) => number
+ }
+}
let toastIdCounter = 0
export function ToastContainer() {
- const [toasts, setToasts] = useState([])
+ const [toasts, setToasts] = useState<Toast[]>([])
- const addToast = useCallback((message, type = 'info', duration = 3000) => {
+ const addToast = useCallback((message: string, type: ToastType = 'info', duration: number = 3000) => {
const id = ++toastIdCounter
setToasts(prev => [...prev, { id, message, type, duration, removing: false }])
@@ -24,27 +38,26 @@ export function ToastContainer() {
return id
}, [])
- const removeToast = useCallback((id) => {
+ const removeToast = useCallback((id: number) => {
setToasts(prev => prev.map(t => t.id === id ? { ...t, removing: true } : t))
setTimeout(() => {
setToasts(prev => prev.filter(t => t.id !== id))
}, 300)
}, [])
- // Make addToast globally accessible
useEffect(() => {
window.__addToast = addToast
return () => { delete window.__addToast }
}, [addToast])
- const icons = {
+ const icons: Record<ToastType, React.ReactNode> = {
success: <CheckCircle className="w-5 h-5 text-emerald-500 flex-shrink-0" />,
error: <XCircle className="w-5 h-5 text-red-500 flex-shrink-0" />,
warning: <AlertCircle className="w-5 h-5 text-amber-500 flex-shrink-0" />,
info: <Info className="w-5 h-5 text-blue-500 flex-shrink-0" />,
}
- const bgColors = {
+ const bgColors: Record<ToastType, string> = {
success: 'bg-white border-l-4 border-emerald-500',
error: 'bg-white border-l-4 border-red-500',
warning: 'bg-white border-l-4 border-amber-500',
@@ -78,17 +91,17 @@ export function ToastContainer() {
}
export const useToast = () => {
- const show = useCallback((message, type, duration) => {
+ const show = useCallback((message: string, type: ToastType, duration?: number) => {
if (window.__addToast) {
window.__addToast(message, type, duration)
}
}, [])
return {
- success: (message, duration) => show(message, 'success', duration),
- error: (message, duration) => show(message, 'error', duration),
- warning: (message, duration) => show(message, 'warning', duration),
- info: (message, duration) => show(message, 'info', duration),
+ success: (message: string, duration?: number) => show(message, 'success', duration),
+ error: (message: string, duration?: number) => show(message, 'error', duration),
+ warning: (message: string, duration?: number) => show(message, 'warning', duration),
+ info: (message: string, duration?: number) => show(message, 'info', duration),
}
}
diff --git a/client/src/components/shared/categoryIcons.js b/client/src/components/shared/categoryIcons.ts
similarity index 86%
rename from client/src/components/shared/categoryIcons.js
rename to client/src/components/shared/categoryIcons.ts
index 39c3f9027..29ed7503b 100644
--- a/client/src/components/shared/categoryIcons.js
+++ b/client/src/components/shared/categoryIcons.ts
@@ -9,9 +9,10 @@ import {
Church, Library, Store, Home, Cross,
Heart, Star, CreditCard, Wifi,
Luggage, Backpack, Zap,
+ LucideIcon,
} from 'lucide-react'
-export const CATEGORY_ICON_MAP = {
+export const CATEGORY_ICON_MAP: Record<string, LucideIcon> = {
MapPin, Building2, BedDouble, UtensilsCrossed, Landmark, ShoppingBag,
Bus, Train, Car, Plane, Ship, Bike,
Activity, Dumbbell, Mountain, Tent, Anchor,
@@ -24,7 +25,7 @@ export const CATEGORY_ICON_MAP = {
Luggage, Backpack, Zap,
}
-export const ICON_LABELS = {
+export const ICON_LABELS: Record<string, string> = {
MapPin: 'Pin', Building2: 'Building', BedDouble: 'Hotel', UtensilsCrossed: 'Restaurant',
Landmark: 'Attraction', ShoppingBag: 'Shopping', Bus: 'Bus', Train: 'Train',
Car: 'Car', Plane: 'Plane', Ship: 'Ship', Bike: 'Bicycle',
@@ -38,6 +39,6 @@ export const ICON_LABELS = {
Luggage: 'Luggage', Backpack: 'Backpack', Zap: 'Adventure',
}
-export function getCategoryIcon(iconName) {
- return CATEGORY_ICON_MAP[iconName] || MapPin
+export function getCategoryIcon(iconName: string | null | undefined): LucideIcon {
+ return (iconName && CATEGORY_ICON_MAP[iconName]) || MapPin
}
diff --git a/client/src/hooks/useDayNotes.ts b/client/src/hooks/useDayNotes.ts
new file mode 100644
index 000000000..296c197a2
--- /dev/null
+++ b/client/src/hooks/useDayNotes.ts
@@ -0,0 +1,78 @@
+import { useState, useRef } from 'react'
+import { useTripStore } from '../store/tripStore'
+import { useToast } from '../components/shared/Toast'
+import type { MergedItem, DayNotesMap, DayNote } from '../types'
+
+interface NoteUiState {
+ mode: 'add' | 'edit'
+ noteId?: number
+ text: string
+ time: string
+ icon: string
+ sortOrder?: number
+}
+
+interface NoteUiMap {
+ [dayId: string]: NoteUiState
+}
+
+export function useDayNotes(tripId: number | string) {
+ const [noteUi, setNoteUi] = useState<NoteUiMap>({})
+ const noteInputRef = useRef<HTMLInputElement | null>(null)
+ const tripStore = useTripStore()
+ const toast = useToast()
+ const dayNotes: DayNotesMap = tripStore.dayNotes || {}
+
+ const openAddNote = (dayId: number, getMergedItems: (dayId: number) => MergedItem[], expandDay?: (dayId: number) => void) => {
+ const merged = getMergedItems(dayId)
+ const maxKey = merged.length > 0 ? Math.max(...merged.map((i) => i.sortKey)) : -1
+ setNoteUi((prev) => ({ ...prev, [dayId]: { mode: 'add', text: '', time: '', icon: 'FileText', sortOrder: maxKey + 1 } }))
+ expandDay?.(dayId)
+ setTimeout(() => noteInputRef.current?.focus(), 50)
+ }
+
+ const openEditNote = (dayId: number, note: DayNote) => {
+ setNoteUi((prev) => ({ ...prev, [dayId]: { mode: 'edit', noteId: note.id, text: note.text, time: note.time || '', icon: note.icon || 'FileText' } }))
+ setTimeout(() => noteInputRef.current?.focus(), 50)
+ }
+
+ const cancelNote = (dayId: number) => {
+ setNoteUi((prev) => { const n = { ...prev }; delete n[dayId]; return n })
+ }
+
+ const saveNote = async (dayId: number) => {
+ const ui = noteUi[dayId]
+ if (!ui?.text?.trim()) return
+ try {
+ if (ui.mode === 'add') {
+ await tripStore.addDayNote(tripId, dayId, { text: ui.text.trim(), time: ui.time || null, icon: ui.icon || 'FileText', sort_order: ui.sortOrder })
+ } else {
+ await tripStore.updateDayNote(tripId, dayId, ui.noteId!, { text: ui.text.trim(), time: ui.time || null, icon: ui.icon || 'FileText' })
+ }
+ cancelNote(dayId)
+ } catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Unknown error') }
+ }
+
+ const deleteNote = async (dayId: number, noteId: number) => {
+ try { await tripStore.deleteDayNote(tripId, dayId, noteId) }
+ catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Unknown error') }
+ }
+
+ const moveNote = async (dayId: number, noteId: number, direction: 'up' | 'down', getMergedItems: (dayId: number) => MergedItem[]) => {
+ const merged = getMergedItems(dayId)
+ const idx = merged.findIndex((i) => i.type === 'note' && (i.data as DayNote).id === noteId)
+ if (idx === -1) return
+ let newSortOrder: number
+ if (direction === 'up') {
+ if (idx === 0) return
+ newSortOrder = idx >= 2 ? (merged[idx - 2].sortKey + merged[idx - 1].sortKey) / 2 : merged[idx - 1].sortKey - 1
+ } else {
+ if (idx >= merged.length - 1) return
+ newSortOrder = idx < merged.length - 2 ? (merged[idx + 1].sortKey + merged[idx + 2].sortKey) / 2 : merged[idx + 1].sortKey + 1
+ }
+ try { await tripStore.updateDayNote(tripId, dayId, noteId, { sort_order: newSortOrder }) }
+ catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Unknown error') }
+ }
+
+ return { noteUi, setNoteUi, noteInputRef, dayNotes, openAddNote, openEditNote, cancelNote, saveNote, deleteNote, moveNote }
+}
diff --git a/client/src/hooks/usePlaceSelection.ts b/client/src/hooks/usePlaceSelection.ts
new file mode 100644
index 000000000..bf2b23b5a
--- /dev/null
+++ b/client/src/hooks/usePlaceSelection.ts
@@ -0,0 +1,18 @@
+import { useState, useCallback } from 'react'
+
+export function usePlaceSelection() {
+ const [selectedPlaceId, _setSelectedPlaceId] = useState<number | null>(null)
+ const [selectedAssignmentId, setSelectedAssignmentId] = useState<number | null>(null)
+
+ const setSelectedPlaceId = useCallback((placeId: number | null) => {
+ _setSelectedPlaceId(placeId)
+ setSelectedAssignmentId(null)
+ }, [])
+
+ const selectAssignment = useCallback((assignmentId: number | null, placeId: number | null) => {
+ setSelectedAssignmentId(assignmentId)
+ _setSelectedPlaceId(placeId)
+ }, [])
+
+ return { selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment }
+}
diff --git a/client/src/hooks/useResizablePanels.ts b/client/src/hooks/useResizablePanels.ts
new file mode 100644
index 000000000..943d9f796
--- /dev/null
+++ b/client/src/hooks/useResizablePanels.ts
@@ -0,0 +1,45 @@
+import { useState, useEffect, useRef } from 'react'
+
+const MIN_SIDEBAR = 200
+const MAX_SIDEBAR = 520
+
+export function useResizablePanels() {
+ const [leftWidth, setLeftWidth] = useState<number>(() => parseInt(localStorage.getItem('sidebarLeftWidth') || '') || 340)
+ const [rightWidth, setRightWidth] = useState<number>(() => parseInt(localStorage.getItem('sidebarRightWidth') || '') || 300)
+ const [leftCollapsed, setLeftCollapsed] = useState(false)
+ const [rightCollapsed, setRightCollapsed] = useState(false)
+ const isResizingLeft = useRef(false)
+ const isResizingRight = useRef(false)
+
+ useEffect(() => {
+ const onMove = (e: MouseEvent) => {
+ if (isResizingLeft.current) {
+ const w = Math.max(MIN_SIDEBAR, Math.min(MAX_SIDEBAR, e.clientX - 10))
+ setLeftWidth(w)
+ localStorage.setItem('sidebarLeftWidth', String(w))
+ }
+ if (isResizingRight.current) {
+ const w = Math.max(MIN_SIDEBAR, Math.min(MAX_SIDEBAR, window.innerWidth - e.clientX - 10))
+ setRightWidth(w)
+ localStorage.setItem('sidebarRightWidth', String(w))
+ }
+ }
+ const onUp = () => {
+ isResizingLeft.current = false
+ isResizingRight.current = false
+ document.body.style.cursor = ''
+ document.body.style.userSelect = ''
+ }
+ document.addEventListener('mousemove', onMove)
+ document.addEventListener('mouseup', onUp)
+ return () => {
+ document.removeEventListener('mousemove', onMove)
+ document.removeEventListener('mouseup', onUp)
+ }
+ }, [])
+
+ const startResizeLeft = () => { isResizingLeft.current = true; document.body.style.cursor = 'col-resize'; document.body.style.userSelect = 'none' }
+ const startResizeRight = () => { isResizingRight.current = true; document.body.style.cursor = 'col-resize'; document.body.style.userSelect = 'none' }
+
+ return { leftWidth, rightWidth, leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed, startResizeLeft, startResizeRight }
+}
diff --git a/client/src/hooks/useRouteCalculation.ts b/client/src/hooks/useRouteCalculation.ts
new file mode 100644
index 000000000..2cd5c0e1b
--- /dev/null
+++ b/client/src/hooks/useRouteCalculation.ts
@@ -0,0 +1,44 @@
+import { useState, useCallback, useRef, useEffect } from 'react'
+import { useSettingsStore } from '../store/settingsStore'
+import { calculateSegments } from '../components/Map/RouteCalculator'
+import type { TripStoreState } from '../store/tripStore'
+import type { RouteSegment, RouteResult } from '../types'
+
+/**
+ * Manages route calculation state for a selected day. Extracts geo-coded waypoints from
+ * day assignments, draws a straight-line route, and optionally fetches per-segment
+ * driving/walking durations via OSRM. Aborts in-flight requests when the day changes.
+ */
+export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: number | null) {
+ const [route, setRoute] = useState<[number, number][] | null>(null)
+ const [routeInfo, setRouteInfo] = useState<RouteResult | null>(null)
+ const [routeSegments, setRouteSegments] = useState<RouteSegment[]>([])
+ const routeCalcEnabled = useSettingsStore((s) => s.settings.route_calculation) !== false
+ const routeAbortRef = useRef<AbortController | null>(null)
+
+ const updateRouteForDay = useCallback(async (dayId: number | null) => {
+ if (routeAbortRef.current) routeAbortRef.current.abort()
+ if (!dayId) { setRoute(null); setRouteSegments([]); return }
+ const da = (tripStore.assignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index)
+ const waypoints = da.map((a) => a.place).filter((p) => p?.lat && p?.lng)
+ if (waypoints.length < 2) { setRoute(null); setRouteSegments([]); return }
+ setRoute(waypoints.map((p) => [p.lat!, p.lng!]))
+ if (!routeCalcEnabled) { setRouteSegments([]); return }
+ const controller = new AbortController()
+ routeAbortRef.current = controller
+ try {
+ const segments = await calculateSegments(waypoints as { lat: number; lng: number }[], { signal: controller.signal })
+ if (!controller.signal.aborted) setRouteSegments(segments)
+ } catch (err: unknown) {
+ if (err instanceof Error && err.name !== 'AbortError') setRouteSegments([])
+ else if (!(err instanceof Error)) setRouteSegments([])
+ }
+ }, [tripStore, routeCalcEnabled])
+
+ useEffect(() => {
+ if (!selectedDayId) { setRoute(null); setRouteSegments([]); return }
+ updateRouteForDay(selectedDayId)
+ }, [selectedDayId, tripStore.assignments])
+
+ return { route, routeSegments, routeInfo, setRoute, setRouteInfo, updateRouteForDay }
+}
diff --git a/client/src/hooks/useTripWebSocket.ts b/client/src/hooks/useTripWebSocket.ts
new file mode 100644
index 000000000..5a226de79
--- /dev/null
+++ b/client/src/hooks/useTripWebSocket.ts
@@ -0,0 +1,29 @@
+import { useEffect } from 'react'
+import { useTripStore } from '../store/tripStore'
+import { joinTrip, leaveTrip, addListener, removeListener } from '../api/websocket'
+import type { WebSocketEvent } from '../types'
+
+export function useTripWebSocket(tripId: number | string | undefined) {
+ const tripStore = useTripStore()
+
+ useEffect(() => {
+ if (!tripId) return
+ const handler = useTripStore.getState().handleRemoteEvent
+ joinTrip(tripId)
+ addListener(handler)
+ const collabFileSync = (event: WebSocketEvent) => {
+ if (event?.type === 'collab:note:deleted' || event?.type === 'collab:note:updated') {
+ tripStore.loadFiles?.(tripId)
+ }
+ }
+ addListener(collabFileSync)
+ const localFileSync = () => tripStore.loadFiles?.(tripId)
+ window.addEventListener('collab-files-changed', localFileSync)
+ return () => {
+ leaveTrip(tripId)
+ removeListener(handler)
+ removeListener(collabFileSync)
+ window.removeEventListener('collab-files-changed', localFileSync)
+ }
+ }, [tripId])
+}
diff --git a/client/src/i18n/TranslationContext.jsx b/client/src/i18n/TranslationContext.jsx
deleted file mode 100644
index e42cd5806..000000000
--- a/client/src/i18n/TranslationContext.jsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import React, { createContext, useContext, useMemo } from 'react'
-import { useSettingsStore } from '../store/settingsStore'
-import de from './translations/de'
-import en from './translations/en'
-
-const translations = { de, en }
-const TranslationContext = createContext({ t: (k) => k, language: 'de', locale: 'de-DE' })
-
-export function TranslationProvider({ children }) {
- const language = useSettingsStore(s => s.settings.language) || 'de'
-
- const value = useMemo(() => {
- const strings = translations[language] || translations.de
- const fallback = translations.de
-
- function t(key, params) {
- let val = strings[key] ?? fallback[key] ?? key
- // Arrays/Objects direkt zurückgeben (z.B. Vorschläge-Liste)
- if (typeof val !== 'string') return val
- if (params) {
- Object.entries(params).forEach(([k, v]) => {
- val = val.replace(new RegExp(`\\{${k}\\}`, 'g'), v)
- })
- }
- return val
- }
-
- return { t, language, locale: language === 'en' ? 'en-US' : 'de-DE' }
- }, [language])
-
- return <TranslationContext.Provider value={value}>{children}</TranslationContext.Provider>
-}
-
-export function useTranslation() {
- return useContext(TranslationContext)
-}
diff --git a/client/src/i18n/TranslationContext.tsx b/client/src/i18n/TranslationContext.tsx
new file mode 100644
index 000000000..ffa7bdbee
--- /dev/null
+++ b/client/src/i18n/TranslationContext.tsx
@@ -0,0 +1,47 @@
+import React, { createContext, useContext, useMemo, ReactNode } from 'react'
+import { useSettingsStore } from '../store/settingsStore'
+import de from './translations/de'
+import en from './translations/en'
+
+type TranslationStrings = Record<string, string>
+
+const translations: Record<string, TranslationStrings> = { de, en }
+
+interface TranslationContextValue {
+ t: (key: string, params?: Record<string, string | number>) => string
+ language: string
+ locale: string
+}
+
+const TranslationContext = createContext<TranslationContextValue>({ t: (k: string) => k, language: 'de', locale: 'de-DE' })
+
+interface TranslationProviderProps {
+ children: ReactNode
+}
+
+export function TranslationProvider({ children }: TranslationProviderProps) {
+ const language = useSettingsStore((s) => s.settings.language) || 'de'
+
+ const value = useMemo((): TranslationContextValue => {
+ const strings = translations[language] || translations.de
+ const fallback = translations.de
+
+ function t(key: string, params?: Record<string, string | number>): string {
+ let val: string = strings[key] ?? fallback[key] ?? key
+ if (params) {
+ Object.entries(params).forEach(([k, v]) => {
+ val = val.replace(new RegExp(`\\{${k}\\}`, 'g'), String(v))
+ })
+ }
+ return val
+ }
+
+ return { t, language, locale: language === 'en' ? 'en-US' : 'de-DE' }
+ }, [language])
+
+ return <TranslationContext.Provider value={value}>{children}</TranslationContext.Provider>
+}
+
+export function useTranslation(): TranslationContextValue {
+ return useContext(TranslationContext)
+}
diff --git a/client/src/i18n/index.js b/client/src/i18n/index.ts
similarity index 100%
rename from client/src/i18n/index.js
rename to client/src/i18n/index.ts
diff --git a/client/src/i18n/translations/de.js b/client/src/i18n/translations/de.ts
similarity index 99%
rename from client/src/i18n/translations/de.js
rename to client/src/i18n/translations/de.ts
index 3d7618a87..2fc0d5b5b 100644
--- a/client/src/i18n/translations/de.js
+++ b/client/src/i18n/translations/de.ts
@@ -1,4 +1,4 @@
-const de = {
+const de: Record<string, string> = {
// Allgemein
'common.save': 'Speichern',
'common.cancel': 'Abbrechen',
@@ -138,12 +138,14 @@ const de = {
'settings.oidcLinked': 'Verknüpft mit',
'settings.changePassword': 'Passwort ändern',
'settings.currentPassword': 'Aktuelles Passwort',
+ 'settings.currentPasswordRequired': 'Aktuelles Passwort wird benötigt',
'settings.newPassword': 'Neues Passwort',
'settings.confirmPassword': 'Neues Passwort bestätigen',
'settings.updatePassword': 'Passwort aktualisieren',
'settings.passwordRequired': 'Bitte aktuelles und neues Passwort eingeben',
'settings.passwordTooShort': 'Passwort muss mindestens 8 Zeichen lang sein',
'settings.passwordMismatch': 'Passwörter stimmen nicht überein',
+ 'settings.passwordWeak': 'Passwort muss Groß-, Kleinbuchstaben und eine Zahl enthalten',
'settings.passwordChanged': 'Passwort erfolgreich geändert',
'settings.deleteAccount': 'Löschen',
'settings.deleteAccountTitle': 'Account wirklich löschen?',
diff --git a/client/src/i18n/translations/en.js b/client/src/i18n/translations/en.ts
similarity index 99%
rename from client/src/i18n/translations/en.js
rename to client/src/i18n/translations/en.ts
index d700f0af6..4e0a76e6c 100644
--- a/client/src/i18n/translations/en.js
+++ b/client/src/i18n/translations/en.ts
@@ -1,4 +1,4 @@
-const en = {
+const en: Record<string, string> = {
// Common
'common.save': 'Save',
'common.cancel': 'Cancel',
@@ -138,12 +138,14 @@ const en = {
'settings.oidcLinked': 'Linked with',
'settings.changePassword': 'Change Password',
'settings.currentPassword': 'Current password',
+ 'settings.currentPasswordRequired': 'Current password is required',
'settings.newPassword': 'New password',
'settings.confirmPassword': 'Confirm new password',
'settings.updatePassword': 'Update password',
'settings.passwordRequired': 'Please enter current and new password',
'settings.passwordTooShort': 'Password must be at least 8 characters',
'settings.passwordMismatch': 'Passwords do not match',
+ 'settings.passwordWeak': 'Password must contain uppercase, lowercase, and a number',
'settings.passwordChanged': 'Password changed successfully',
'settings.deleteAccount': 'Delete account',
'settings.deleteAccountTitle': 'Delete your account?',
diff --git a/client/src/main.jsx b/client/src/main.tsx
similarity index 72%
rename from client/src/main.jsx
rename to client/src/main.tsx
index f4fa3e5bb..fa94facec 100644
--- a/client/src/main.jsx
+++ b/client/src/main.tsx
@@ -1,10 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
-import App from './App.jsx'
+import App from './App'
import './index.css'
-ReactDOM.createRoot(document.getElementById('root')).render(
+ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<BrowserRouter>
<App />
diff --git a/client/src/pages/AdminPage.jsx b/client/src/pages/AdminPage.tsx
similarity index 92%
rename from client/src/pages/AdminPage.jsx
rename to client/src/pages/AdminPage.tsx
index ece53d8a3..8f72c836b 100644
--- a/client/src/pages/AdminPage.jsx
+++ b/client/src/pages/AdminPage.tsx
@@ -4,6 +4,7 @@ import { adminApi, authApi } from '../api/client'
import { useAuthStore } from '../store/authStore'
import { useSettingsStore } from '../store/settingsStore'
import { useTranslation } from '../i18n'
+import { getApiErrorMessage } from '../types'
import Navbar from '../components/Layout/Navbar'
import Modal from '../components/shared/Modal'
import { useToast } from '../components/shared/Toast'
@@ -14,7 +15,41 @@ import AddonManager from '../components/Admin/AddonManager'
import { Users, Map, Briefcase, Shield, Trash2, Edit2, Camera, FileText, Eye, EyeOff, Save, CheckCircle, XCircle, Loader2, UserPlus, ArrowUpCircle, ExternalLink, Download, AlertTriangle, RefreshCw, GitBranch, Sun } from 'lucide-react'
import CustomSelect from '../components/shared/CustomSelect'
-export default function AdminPage() {
+interface AdminUser {
+ id: number
+ username: string
+ email: string
+ role: 'admin' | 'user'
+ created_at: string
+ last_login?: string | null
+ online?: boolean
+ oidc_issuer?: string | null
+}
+
+interface AdminStats {
+ totalUsers: number
+ totalTrips: number
+ totalPlaces: number
+ totalFiles: number
+}
+
+interface OidcConfig {
+ issuer: string
+ client_id: string
+ client_secret: string
+ client_secret_set: boolean
+ display_name: string
+}
+
+interface UpdateInfo {
+ update_available: boolean
+ latest: string
+ current: string
+ release_url?: string
+ is_docker?: boolean
+}
+
+export default function AdminPage(): React.ReactElement {
const { demoMode } = useAuthStore()
const { t, locale } = useTranslation()
const hour12 = useSettingsStore(s => s.settings.time_format) === '12h'
@@ -27,39 +62,39 @@ export default function AdminPage() {
{ id: 'github', label: t('admin.tabs.github') },
]
- const [activeTab, setActiveTab] = useState('users')
- const [users, setUsers] = useState([])
- const [stats, setStats] = useState(null)
- const [isLoading, setIsLoading] = useState(true)
- const [editingUser, setEditingUser] = useState(null)
- const [editForm, setEditForm] = useState({ username: '', email: '', role: 'user', password: '' })
- const [showCreateUser, setShowCreateUser] = useState(false)
- const [createForm, setCreateForm] = useState({ username: '', email: '', password: '', role: 'user' })
+ const [activeTab, setActiveTab] = useState<string>('users')
+ const [users, setUsers] = useState<AdminUser[]>([])
+ const [stats, setStats] = useState<AdminStats | null>(null)
+ const [isLoading, setIsLoading] = useState<boolean>(true)
+ const [editingUser, setEditingUser] = useState<AdminUser | null>(null)
+ const [editForm, setEditForm] = useState<{ username: string; email: string; role: string; password: string }>({ username: '', email: '', role: 'user', password: '' })
+ const [showCreateUser, setShowCreateUser] = useState<boolean>(false)
+ const [createForm, setCreateForm] = useState<{ username: string; email: string; password: string; role: string }>({ username: '', email: '', password: '', role: 'user' })
// OIDC config
- const [oidcConfig, setOidcConfig] = useState({ issuer: '', client_id: '', client_secret: '', display_name: '' })
- const [savingOidc, setSavingOidc] = useState(false)
+ const [oidcConfig, setOidcConfig] = useState<OidcConfig>({ issuer: '', client_id: '', client_secret: '', client_secret_set: false, display_name: '' })
+ const [savingOidc, setSavingOidc] = useState<boolean>(false)
// Registration toggle
- const [allowRegistration, setAllowRegistration] = useState(true)
+ const [allowRegistration, setAllowRegistration] = useState<boolean>(true)
// File types
- const [allowedFileTypes, setAllowedFileTypes] = useState('jpg,jpeg,png,gif,webp,heic,pdf,doc,docx,xls,xlsx,txt,csv')
- const [savingFileTypes, setSavingFileTypes] = useState(false)
+ const [allowedFileTypes, setAllowedFileTypes] = useState<string>('jpg,jpeg,png,gif,webp,heic,pdf,doc,docx,xls,xlsx,txt,csv')
+ const [savingFileTypes, setSavingFileTypes] = useState<boolean>(false)
// API Keys
- const [mapsKey, setMapsKey] = useState('')
- const [weatherKey, setWeatherKey] = useState('')
- const [showKeys, setShowKeys] = useState({})
- const [savingKeys, setSavingKeys] = useState(false)
- const [validating, setValidating] = useState({})
- const [validation, setValidation] = useState({})
+ const [mapsKey, setMapsKey] = useState<string>('')
+ const [weatherKey, setWeatherKey] = useState<string>('')
+ const [showKeys, setShowKeys] = useState<Record<string, boolean>>({})
+ const [savingKeys, setSavingKeys] = useState<boolean>(false)
+ const [validating, setValidating] = useState<Record<string, boolean>>({})
+ const [validation, setValidation] = useState<Record<string, boolean | undefined>>({})
// Version check & update
- const [updateInfo, setUpdateInfo] = useState(null)
- const [showUpdateModal, setShowUpdateModal] = useState(false)
- const [updating, setUpdating] = useState(false)
- const [updateResult, setUpdateResult] = useState(null) // 'success' | 'error'
+ const [updateInfo, setUpdateInfo] = useState<UpdateInfo | null>(null)
+ const [showUpdateModal, setShowUpdateModal] = useState<boolean>(false)
+ const [updating, setUpdating] = useState<boolean>(false)
+ const [updateResult, setUpdateResult] = useState<'success' | 'error' | null>(null)
const { user: currentUser, updateApiKeys } = useAuthStore()
const navigate = useNavigate()
@@ -84,7 +119,7 @@ export default function AdminPage() {
])
setUsers(usersData.users)
setStats(statsData)
- } catch (err) {
+ } catch (err: unknown) {
toast.error(t('admin.toast.loadError'))
} finally {
setIsLoading(false)
@@ -96,7 +131,7 @@ export default function AdminPage() {
const config = await authApi.getAppConfig()
setAllowRegistration(config.allow_registration)
if (config.allowed_file_types) setAllowedFileTypes(config.allowed_file_types)
- } catch (err) {
+ } catch (err: unknown) {
// ignore
}
}
@@ -106,7 +141,7 @@ export default function AdminPage() {
const data = await authApi.getSettings()
setMapsKey(data.settings?.maps_api_key || '')
setWeatherKey(data.settings?.openweather_api_key || '')
- } catch (err) {
+ } catch (err: unknown) {
// ignore
}
}
@@ -135,9 +170,9 @@ export default function AdminPage() {
setAllowRegistration(value)
try {
await authApi.updateAppSettings({ allow_registration: value })
- } catch (err) {
+ } catch (err: unknown) {
setAllowRegistration(!value)
- toast.error(err.response?.data?.error || t('common.error'))
+ toast.error(getApiErrorMessage(err, t('common.error')))
}
}
@@ -153,8 +188,8 @@ export default function AdminPage() {
openweather_api_key: weatherKey,
})
toast.success(t('admin.keySaved'))
- } catch (err) {
- toast.error(err.message)
+ } catch (err: unknown) {
+ toast.error(err instanceof Error ? err.message : 'Unknown error')
} finally {
setSavingKeys(false)
}
@@ -167,7 +202,7 @@ export default function AdminPage() {
await updateApiKeys({ maps_api_key: mapsKey, openweather_api_key: weatherKey })
const result = await authApi.validateKeys()
setValidation(result)
- } catch (err) {
+ } catch (err: unknown) {
toast.error(t('common.error'))
} finally {
setValidating({})
@@ -181,7 +216,7 @@ export default function AdminPage() {
await updateApiKeys({ maps_api_key: mapsKey, openweather_api_key: weatherKey })
const result = await authApi.validateKeys()
setValidation(prev => ({ ...prev, [keyType]: result[keyType] }))
- } catch (err) {
+ } catch (err: unknown) {
toast.error(t('common.error'))
} finally {
setValidating(prev => ({ ...prev, [keyType]: false }))
@@ -199,8 +234,8 @@ export default function AdminPage() {
setShowCreateUser(false)
setCreateForm({ username: '', email: '', password: '', role: 'user' })
toast.success(t('admin.toast.userCreated'))
- } catch (err) {
- toast.error(err.response?.data?.error || t('admin.toast.createError'))
+ } catch (err: unknown) {
+ toast.error(getApiErrorMessage(err, t('admin.toast.createError')))
}
}
@@ -221,8 +256,8 @@ export default function AdminPage() {
setUsers(prev => prev.map(u => u.id === editingUser.id ? data.user : u))
setEditingUser(null)
toast.success(t('admin.toast.userUpdated'))
- } catch (err) {
- toast.error(err.response?.data?.error || t('admin.toast.updateError'))
+ } catch (err: unknown) {
+ toast.error(getApiErrorMessage(err, t('admin.toast.updateError')))
}
}
@@ -236,8 +271,8 @@ export default function AdminPage() {
await adminApi.deleteUser(user.id)
setUsers(prev => prev.filter(u => u.id !== user.id))
toast.success(t('admin.toast.userDeleted'))
- } catch (err) {
- toast.error(err.response?.data?.error || t('admin.toast.deleteError'))
+ } catch (err: unknown) {
+ toast.error(getApiErrorMessage(err, t('admin.toast.deleteError')))
}
}
@@ -676,6 +711,7 @@ export default function AdminPage() {
type="password"
value={oidcConfig.client_secret}
onChange={e => setOidcConfig(c => ({ ...c, client_secret: e.target.value }))}
+ placeholder={oidcConfig.client_secret_set ? '••••••••' : ''}
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
/>
</div>
@@ -683,10 +719,12 @@ export default function AdminPage() {
onClick={async () => {
setSavingOidc(true)
try {
- await adminApi.updateOidc(oidcConfig)
+ const payload = { issuer: oidcConfig.issuer, client_id: oidcConfig.client_id, display_name: oidcConfig.display_name }
+ if (oidcConfig.client_secret) payload.client_secret = oidcConfig.client_secret
+ await adminApi.updateOidc(payload)
toast.success(t('admin.oidcSaved'))
- } catch (err) {
- toast.error(err.response?.data?.error || t('common.error'))
+ } catch (err: unknown) {
+ toast.error(getApiErrorMessage(err, t('common.error')))
} finally {
setSavingOidc(false)
}
diff --git a/client/src/pages/AtlasPage.jsx b/client/src/pages/AtlasPage.tsx
similarity index 86%
rename from client/src/pages/AtlasPage.jsx
rename to client/src/pages/AtlasPage.tsx
index 025771bee..d8bfe752a 100644
--- a/client/src/pages/AtlasPage.jsx
+++ b/client/src/pages/AtlasPage.tsx
@@ -6,9 +6,43 @@ import Navbar from '../components/Layout/Navbar'
import apiClient from '../api/client'
import { Globe, MapPin, Briefcase, Calendar, Flag, ChevronRight, PanelLeftOpen, PanelLeftClose, X } from 'lucide-react'
import L from 'leaflet'
+import type { AtlasPlace, GeoJsonFeatureCollection, TranslationFn } from '../types'
// Convert country code to flag emoji
-function MobileStats({ data, stats, countries, resolveName, t, dark }) {
+interface AtlasCountry {
+ code: string
+ tripCount: number
+ placeCount: number
+ firstVisit?: string | null
+ lastVisit?: string | null
+}
+
+interface AtlasStats {
+ totalTrips: number
+ totalPlaces: number
+ totalCountries: number
+ totalDays: number
+ totalCities?: number
+}
+
+interface AtlasData {
+ countries: AtlasCountry[]
+ stats: AtlasStats
+ mostVisited?: AtlasCountry | null
+ continents?: Record<string, number>
+ lastTrip?: { id: number; title: string; countryCode?: string } | null
+ nextTrip?: { id: number; title: string; countryCode?: string } | null
+ streak?: number
+ firstYear?: number
+ tripsThisYear?: number
+}
+
+interface CountryDetail {
+ places: AtlasPlace[]
+ trips: { id: number; title: string }[]
+}
+
+function MobileStats({ data, stats, countries, resolveName, t, dark }: { data: AtlasData | null; stats: AtlasStats; countries: AtlasCountry[]; resolveName: (code: string) => string; t: TranslationFn; dark: boolean }): React.ReactElement {
const tp = dark ? '#f1f5f9' : '#0f172a'
const tf = dark ? '#475569' : '#94a3b8'
const { continents, lastTrip, nextTrip, streak, firstYear, tripsThisYear } = data || {}
@@ -57,40 +91,40 @@ function MobileStats({ data, stats, countries, resolveName, t, dark }) {
)
}
-function countryCodeToFlag(code) {
+function countryCodeToFlag(code: string): string {
if (!code || code.length !== 2) return ''
return String.fromCodePoint(...[...code.toUpperCase()].map(c => 0x1F1E6 + c.charCodeAt(0) - 65))
}
-function useCountryNames(language) {
- const [resolver, setResolver] = useState(() => (code) => code)
+function useCountryNames(language: string): (code: string) => string {
+ const [resolver, setResolver] = useState<(code: string) => string>(() => (code: string) => code)
useEffect(() => {
try {
const dn = new Intl.DisplayNames([language === 'de' ? 'de' : 'en'], { type: 'region' })
- setResolver(() => (code) => { try { return dn.of(code) } catch { return code } })
+ setResolver(() => (code: string) => { try { return dn.of(code) || code } catch { return code } })
} catch { /* */ }
}, [language])
return resolver
}
// Map visited country codes to ISO-3166 alpha3 (GeoJSON uses alpha3)
-const A2_TO_A3 = {"AF":"AFG","AL":"ALB","DZ":"DZA","AD":"AND","AO":"AGO","AR":"ARG","AM":"ARM","AU":"AUS","AT":"AUT","AZ":"AZE","BR":"BRA","BE":"BEL","BG":"BGR","CA":"CAN","CL":"CHL","CN":"CHN","CO":"COL","HR":"HRV","CZ":"CZE","DK":"DNK","EG":"EGY","EE":"EST","FI":"FIN","FR":"FRA","DE":"DEU","GR":"GRC","HU":"HUN","IS":"ISL","IN":"IND","ID":"IDN","IR":"IRN","IQ":"IRQ","IE":"IRL","IL":"ISR","IT":"ITA","JP":"JPN","KE":"KEN","KR":"KOR","LV":"LVA","LT":"LTU","LU":"LUX","MY":"MYS","MX":"MEX","MA":"MAR","NL":"NLD","NZ":"NZL","NO":"NOR","PK":"PAK","PE":"PER","PH":"PHL","PL":"POL","PT":"PRT","RO":"ROU","RU":"RUS","SA":"SAU","RS":"SRB","SK":"SVK","SI":"SVN","ZA":"ZAF","ES":"ESP","SE":"SWE","CH":"CHE","TH":"THA","TR":"TUR","UA":"UKR","AE":"ARE","GB":"GBR","US":"USA","VN":"VNM","NG":"NGA"}
+const A2_TO_A3: Record<string, string> = {"AF":"AFG","AL":"ALB","DZ":"DZA","AD":"AND","AO":"AGO","AR":"ARG","AM":"ARM","AU":"AUS","AT":"AUT","AZ":"AZE","BR":"BRA","BE":"BEL","BG":"BGR","CA":"CAN","CL":"CHL","CN":"CHN","CO":"COL","HR":"HRV","CZ":"CZE","DK":"DNK","EG":"EGY","EE":"EST","FI":"FIN","FR":"FRA","DE":"DEU","GR":"GRC","HU":"HUN","IS":"ISL","IN":"IND","ID":"IDN","IR":"IRN","IQ":"IRQ","IE":"IRL","IL":"ISR","IT":"ITA","JP":"JPN","KE":"KEN","KR":"KOR","LV":"LVA","LT":"LTU","LU":"LUX","MY":"MYS","MX":"MEX","MA":"MAR","NL":"NLD","NZ":"NZL","NO":"NOR","PK":"PAK","PE":"PER","PH":"PHL","PL":"POL","PT":"PRT","RO":"ROU","RU":"RUS","SA":"SAU","RS":"SRB","SK":"SVK","SI":"SVN","ZA":"ZAF","ES":"ESP","SE":"SWE","CH":"CHE","TH":"THA","TR":"TUR","UA":"UKR","AE":"ARE","GB":"GBR","US":"USA","VN":"VNM","NG":"NGA"}
-export default function AtlasPage() {
+export default function AtlasPage(): React.ReactElement {
const { t, language } = useTranslation()
const { settings } = useSettingsStore()
const navigate = useNavigate()
const resolveName = useCountryNames(language)
const dm = settings.dark_mode
const dark = dm === true || dm === 'dark' || (dm === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)
- const mapRef = useRef(null)
- const mapInstance = useRef(null)
- const geoLayerRef = useRef(null)
- const glareRef = useRef(null)
- const borderGlareRef = useRef(null)
- const panelRef = useRef(null)
-
- const handlePanelMouseMove = (e) => {
+ const mapRef = useRef<HTMLDivElement>(null)
+ const mapInstance = useRef<L.Map | null>(null)
+ const geoLayerRef = useRef<L.GeoJSON | null>(null)
+ const glareRef = useRef<HTMLDivElement>(null)
+ const borderGlareRef = useRef<HTMLDivElement>(null)
+ const panelRef = useRef<HTMLDivElement>(null)
+
+ const handlePanelMouseMove = (e: React.MouseEvent<HTMLDivElement>): void => {
if (!panelRef.current || !glareRef.current || !borderGlareRef.current) return
const rect = panelRef.current.getBoundingClientRect()
const x = e.clientX - rect.left
@@ -108,13 +142,13 @@ export default function AtlasPage() {
if (borderGlareRef.current) borderGlareRef.current.style.opacity = '0'
}
- const [data, setData] = useState(null)
- const [loading, setLoading] = useState(true)
- const [sidebarOpen, setSidebarOpen] = useState(true)
- const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false)
- const [selectedCountry, setSelectedCountry] = useState(null)
- const [countryDetail, setCountryDetail] = useState(null)
- const [geoData, setGeoData] = useState(null)
+ const [data, setData] = useState<AtlasData | null>(null)
+ const [loading, setLoading] = useState<boolean>(true)
+ const [sidebarOpen, setSidebarOpen] = useState<boolean>(true)
+ const [mobileSidebarOpen, setMobileSidebarOpen] = useState<boolean>(false)
+ const [selectedCountry, setSelectedCountry] = useState<string | null>(null)
+ const [countryDetail, setCountryDetail] = useState<CountryDetail | null>(null)
+ const [geoData, setGeoData] = useState<GeoJsonFeatureCollection | null>(null)
// Load atlas data
useEffect(() => {
@@ -256,7 +290,7 @@ export default function AtlasPage() {
}).addTo(mapInstance.current)
}, [geoData, data, dark])
- const loadCountryDetail = async (code) => {
+ const loadCountryDetail = async (code: string): Promise<void> => {
setSelectedCountry(code)
try {
const r = await apiClient.get(`/addons/atlas/country/${code}`)
@@ -345,7 +379,20 @@ export default function AtlasPage() {
)
}
-function SidebarContent({ data, stats, countries, selectedCountry, countryDetail, resolveName, onCountryClick, onTripClick, t, dark }) {
+interface SidebarContentProps {
+ data: AtlasData | null
+ stats: AtlasStats
+ countries: AtlasCountry[]
+ selectedCountry: string | null
+ countryDetail: CountryDetail | null
+ resolveName: (code: string) => string
+ onCountryClick: (code: string) => void
+ onTripClick: (id: number) => void
+ t: TranslationFn
+ dark: boolean
+}
+
+function SidebarContent({ data, stats, countries, selectedCountry, countryDetail, resolveName, onCountryClick, onTripClick, t, dark }: SidebarContentProps): React.ReactElement {
const bg = (o) => dark ? `rgba(255,255,255,${o})` : `rgba(0,0,0,${o})`
const tp = dark ? '#f1f5f9' : '#0f172a'
const tm = dark ? '#94a3b8' : '#64748b'
diff --git a/client/src/pages/DashboardPage.jsx b/client/src/pages/DashboardPage.tsx
similarity index 90%
rename from client/src/pages/DashboardPage.jsx
rename to client/src/pages/DashboardPage.tsx
index dbfdda209..072fd839b 100644
--- a/client/src/pages/DashboardPage.jsx
+++ b/client/src/pages/DashboardPage.tsx
@@ -4,6 +4,7 @@ import { tripsApi } from '../api/client'
import { useAuthStore } from '../store/authStore'
import { useSettingsStore } from '../store/settingsStore'
import { useTranslation } from '../i18n'
+import { getApiErrorMessage } from '../types'
import Navbar from '../components/Layout/Navbar'
import DemoBanner from '../components/Layout/DemoBanner'
import CurrencyWidget from '../components/Dashboard/CurrencyWidget'
@@ -15,16 +16,33 @@ import {
Archive, ArchiveRestore, Clock, MapPin, Settings, X, ArrowRightLeft,
} from 'lucide-react'
-const font = { fontFamily: "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif" }
+interface DashboardTrip {
+ id: number
+ title: string
+ description?: string | null
+ start_date?: string | null
+ end_date?: string | null
+ cover_image?: string | null
+ is_archived?: boolean
+ is_owner?: boolean
+ owner_username?: string
+ day_count?: number
+ place_count?: number
+ [key: string]: string | number | boolean | null | undefined
+}
+
+const font: React.CSSProperties = { fontFamily: "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif" }
+
+const MS_PER_DAY = 86400000
-function daysUntil(dateStr) {
+function daysUntil(dateStr: string | null | undefined): number | null {
if (!dateStr) return null
const today = new Date(); today.setHours(0, 0, 0, 0)
const d = new Date(dateStr + 'T00:00:00'); d.setHours(0, 0, 0, 0)
- return Math.round((d - today) / 86400000)
+ return Math.round((d - today) / MS_PER_DAY)
}
-function getTripStatus(trip) {
+function getTripStatus(trip: DashboardTrip): string | null {
const today = new Date().toISOString().split('T')[0]
if (trip.start_date && trip.end_date && trip.start_date <= today && trip.end_date >= today) return 'ongoing'
const until = daysUntil(trip.start_date)
@@ -35,17 +53,17 @@ function getTripStatus(trip) {
return 'past'
}
-function formatDate(dateStr, locale = 'de-DE') {
+function formatDate(dateStr: string | null | undefined, locale: string = 'de-DE'): string | null {
if (!dateStr) return null
return new Date(dateStr + 'T00:00:00').toLocaleDateString(locale, { day: 'numeric', month: 'short', year: 'numeric' })
}
-function formatDateShort(dateStr, locale = 'de-DE') {
+function formatDateShort(dateStr: string | null | undefined, locale: string = 'de-DE'): string | null {
if (!dateStr) return null
return new Date(dateStr + 'T00:00:00').toLocaleDateString(locale, { day: 'numeric', month: 'short' })
}
-function sortTrips(trips) {
+function sortTrips(trips: DashboardTrip[]): DashboardTrip[] {
const today = new Date().toISOString().split('T')[0]
function rank(t) {
if (t.start_date && t.end_date && t.start_date <= today && t.end_date >= today) return 0 // ongoing
@@ -72,15 +90,23 @@ const GRADIENTS = [
'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)',
'linear-gradient(135deg, #96fbc4 0%, #f9f586 100%)',
]
-function tripGradient(id) { return GRADIENTS[id % GRADIENTS.length] }
+function tripGradient(id: number): string { return GRADIENTS[id % GRADIENTS.length] }
// ── Liquid Glass hover effect ────────────────────────────────────────────────
-function LiquidGlass({ children, dark, style, className = '', onClick }) {
- const ref = useRef(null)
- const glareRef = useRef(null)
- const borderRef = useRef(null)
+interface LiquidGlassProps {
+ children: React.ReactNode
+ dark: boolean
+ style?: React.CSSProperties
+ className?: string
+ onClick?: () => void
+}
+
+function LiquidGlass({ children, dark, style, className = '', onClick }: LiquidGlassProps): React.ReactElement {
+ const ref = useRef<HTMLDivElement>(null)
+ const glareRef = useRef<HTMLDivElement>(null)
+ const borderRef = useRef<HTMLDivElement>(null)
- const onMove = (e) => {
+ const onMove = (e: React.MouseEvent<HTMLDivElement>): void => {
if (!ref.current || !glareRef.current || !borderRef.current) return
const rect = ref.current.getBoundingClientRect()
const x = e.clientX - rect.left
@@ -109,7 +135,18 @@ function LiquidGlass({ children, dark, style, className = '', onClick }) {
}
// ── Spotlight Card (next upcoming trip) ─────────────────────────────────────
-function SpotlightCard({ trip, onEdit, onDelete, onArchive, onClick, t, locale, dark }) {
+interface TripCardProps {
+ trip: DashboardTrip
+ onEdit: (trip: DashboardTrip) => void
+ onDelete: (trip: DashboardTrip) => void
+ onArchive: (id: number) => void
+ onClick: (trip: DashboardTrip) => void
+ t: (key: string, params?: Record<string, string | number | null>) => string
+ locale: string
+ dark?: boolean
+}
+
+function SpotlightCard({ trip, onEdit, onDelete, onArchive, onClick, t, locale, dark }: TripCardProps): React.ReactElement {
const status = getTripStatus(trip)
const coverBg = trip.cover_image
@@ -190,7 +227,7 @@ function SpotlightCard({ trip, onEdit, onDelete, onArchive, onClick, t, locale,
}
// ── Regular Trip Card ────────────────────────────────────────────────────────
-function TripCard({ trip, onEdit, onDelete, onArchive, onClick, t, locale }) {
+function TripCard({ trip, onEdit, onDelete, onArchive, onClick, t, locale }: Omit<TripCardProps, 'dark'>): React.ReactElement {
const status = getTripStatus(trip)
const [hovered, setHovered] = useState(false)
@@ -279,7 +316,17 @@ function TripCard({ trip, onEdit, onDelete, onArchive, onClick, t, locale }) {
}
// ── Archived Trip Row ────────────────────────────────────────────────────────
-function ArchivedRow({ trip, onEdit, onUnarchive, onDelete, onClick, t, locale }) {
+interface ArchivedRowProps {
+ trip: DashboardTrip
+ onEdit: (trip: DashboardTrip) => void
+ onUnarchive: (id: number) => void
+ onDelete: (trip: DashboardTrip) => void
+ onClick: (trip: DashboardTrip) => void
+ t: (key: string, params?: Record<string, string | number | null>) => string
+ locale: string
+}
+
+function ArchivedRow({ trip, onEdit, onUnarchive, onDelete, onClick, t, locale }: ArchivedRowProps): React.ReactElement {
return (
<div onClick={() => onClick(trip)} style={{
display: 'flex', alignItems: 'center', gap: 12, padding: '10px 16px',
@@ -322,7 +369,7 @@ function ArchivedRow({ trip, onEdit, onUnarchive, onDelete, onClick, t, locale }
}
// ── Helpers ──────────────────────────────────────────────────────────────────
-function Stat({ value, label }) {
+function Stat({ value, label }: { value: number | string; label: string }): React.ReactElement {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>{value}</span>
@@ -331,7 +378,7 @@ function Stat({ value, label }) {
)
}
-function CardAction({ onClick, icon, label, danger }) {
+function CardAction({ onClick, icon, label, danger }: { onClick: () => void; icon: React.ReactNode; label: string; danger?: boolean }): React.ReactElement {
return (
<button onClick={onClick} style={{
display: 'flex', alignItems: 'center', gap: 4, padding: '4px 8px', borderRadius: 8,
@@ -345,7 +392,7 @@ function CardAction({ onClick, icon, label, danger }) {
)
}
-function IconBtn({ onClick, title, danger, loading, children }) {
+function IconBtn({ onClick, title, danger, loading, children }: { onClick: () => void; title: string; danger?: boolean; loading?: boolean; children: React.ReactNode }): React.ReactElement {
return (
<button onClick={onClick} title={title} disabled={loading} style={{
width: 32, height: 32, borderRadius: 99, border: '1px solid rgba(255,255,255,0.25)',
@@ -361,7 +408,7 @@ function IconBtn({ onClick, title, danger, loading, children }) {
}
// ── Skeleton ─────────────────────────────────────────────────────────────────
-function SkeletonCard() {
+function SkeletonCard(): React.ReactElement {
return (
<div style={{ background: 'white', borderRadius: 16, overflow: 'hidden', border: '1px solid #f3f4f6' }}>
<div style={{ height: 120, background: '#f3f4f6', animation: 'pulse 1.5s ease-in-out infinite' }} />
@@ -374,14 +421,14 @@ function SkeletonCard() {
}
// ── Main Page ────────────────────────────────────────────────────────────────
-export default function DashboardPage() {
- const [trips, setTrips] = useState([])
- const [archivedTrips, setArchivedTrips] = useState([])
- const [isLoading, setIsLoading] = useState(true)
- const [showForm, setShowForm] = useState(false)
- const [editingTrip, setEditingTrip] = useState(null)
- const [showArchived, setShowArchived] = useState(false)
- const [showWidgetSettings, setShowWidgetSettings] = useState(false)
+export default function DashboardPage(): React.ReactElement {
+ const [trips, setTrips] = useState<DashboardTrip[]>([])
+ const [archivedTrips, setArchivedTrips] = useState<DashboardTrip[]>([])
+ const [isLoading, setIsLoading] = useState<boolean>(true)
+ const [showForm, setShowForm] = useState<boolean>(false)
+ const [editingTrip, setEditingTrip] = useState<DashboardTrip | null>(null)
+ const [showArchived, setShowArchived] = useState<boolean>(false)
+ const [showWidgetSettings, setShowWidgetSettings] = useState<boolean | 'mobile'>(false)
const navigate = useNavigate()
const toast = useToast()
@@ -427,8 +474,8 @@ export default function DashboardPage() {
setTrips(prev => sortTrips([data.trip, ...prev]))
toast.success(t('dashboard.toast.created'))
return data
- } catch (err) {
- throw new Error(err.response?.data?.error || t('dashboard.toast.createError'))
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, t('dashboard.toast.createError')))
}
}
@@ -437,8 +484,8 @@ export default function DashboardPage() {
const data = await tripsApi.update(editingTrip.id, tripData)
setTrips(prev => sortTrips(prev.map(t => t.id === editingTrip.id ? data.trip : t)))
toast.success(t('dashboard.toast.updated'))
- } catch (err) {
- throw new Error(err.response?.data?.error || t('dashboard.toast.updateError'))
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, t('dashboard.toast.updateError')))
}
}
@@ -476,8 +523,8 @@ export default function DashboardPage() {
}
}
- const handleCoverUpdate = (tripId, coverImage) => {
- const update = t => t.id === tripId ? { ...t, cover_image: coverImage } : t
+ const handleCoverUpdate = (tripId: number, coverImage: string | null): void => {
+ const update = (t: DashboardTrip) => t.id === tripId ? { ...t, cover_image: coverImage } : t
setTrips(prev => prev.map(update))
setArchivedTrips(prev => prev.map(update))
}
diff --git a/client/src/pages/FilesPage.jsx b/client/src/pages/FilesPage.tsx
similarity index 76%
rename from client/src/pages/FilesPage.jsx
rename to client/src/pages/FilesPage.tsx
index 422505b58..8f5152d73 100644
--- a/client/src/pages/FilesPage.jsx
+++ b/client/src/pages/FilesPage.tsx
@@ -6,23 +6,24 @@ import Navbar from '../components/Layout/Navbar'
import FileManager from '../components/Files/FileManager'
import { ArrowLeft } from 'lucide-react'
import { useTranslation } from '../i18n'
+import type { Trip, Place, TripFile } from '../types'
-export default function FilesPage() {
+export default function FilesPage(): React.ReactElement {
const { t } = useTranslation()
- const { id: tripId } = useParams()
+ const { id: tripId } = useParams<{ id: string }>()
const navigate = useNavigate()
const tripStore = useTripStore()
- const [trip, setTrip] = useState(null)
- const [places, setPlaces] = useState([])
- const [files, setFiles] = useState([])
- const [isLoading, setIsLoading] = useState(true)
+ const [trip, setTrip] = useState<Trip | null>(null)
+ const [places, setPlaces] = useState<Place[]>([])
+ const [files, setFiles] = useState<TripFile[]>([])
+ const [isLoading, setIsLoading] = useState<boolean>(true)
useEffect(() => {
loadData()
}, [tripId])
- const loadData = async () => {
+ const loadData = async (): Promise<void> => {
setIsLoading(true)
try {
const [tripData, placesData] = await Promise.all([
@@ -32,7 +33,7 @@ export default function FilesPage() {
setTrip(tripData.trip)
setPlaces(placesData.places)
await tripStore.loadFiles(tripId)
- } catch (err) {
+ } catch (err: unknown) {
navigate('/dashboard')
} finally {
setIsLoading(false)
@@ -43,11 +44,11 @@ export default function FilesPage() {
setFiles(tripStore.files)
}, [tripStore.files])
- const handleUpload = async (formData) => {
+ const handleUpload = async (formData: FormData): Promise<void> => {
await tripStore.addFile(tripId, formData)
}
- const handleDelete = async (fileId) => {
+ const handleDelete = async (fileId: number): Promise<void> => {
await tripStore.deleteFile(tripId, fileId)
}
@@ -61,7 +62,7 @@ export default function FilesPage() {
return (
<div className="min-h-screen bg-slate-50">
- <Navbar tripTitle={trip?.title} tripId={tripId} showBack onBack={() => navigate(`/trips/${tripId}`)} />
+ <Navbar tripTitle={trip?.name} tripId={tripId} showBack onBack={() => navigate(`/trips/${tripId}`)} />
<div style={{ paddingTop: 'var(--nav-h)' }}>
<div className="max-w-5xl mx-auto px-4 py-6">
@@ -78,7 +79,7 @@ export default function FilesPage() {
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-gray-900">Dateien & Dokumente</h1>
- <p className="text-gray-500 text-sm">{files.length} Dateien für {trip?.title}</p>
+ <p className="text-gray-500 text-sm">{files.length} Dateien für {trip?.name}</p>
</div>
</div>
diff --git a/client/src/pages/LoginPage.jsx b/client/src/pages/LoginPage.tsx
similarity index 85%
rename from client/src/pages/LoginPage.jsx
rename to client/src/pages/LoginPage.tsx
index c5edb5f82..84e9d9ca6 100644
--- a/client/src/pages/LoginPage.jsx
+++ b/client/src/pages/LoginPage.tsx
@@ -6,44 +6,58 @@ import { useTranslation } from '../i18n'
import { authApi } from '../api/client'
import { Plane, Eye, EyeOff, Mail, Lock, MapPin, Calendar, Package, User, Globe, Zap, Users, Wallet, Map, CheckSquare, BookMarked, FolderOpen, Route, Shield } from 'lucide-react'
-export default function LoginPage() {
+interface AppConfig {
+ has_users: boolean
+ allow_registration: boolean
+ demo_mode: boolean
+ oidc_configured: boolean
+ oidc_display_name?: string
+}
+
+export default function LoginPage(): React.ReactElement {
const { t, language } = useTranslation()
- const [mode, setMode] = useState('login') // 'login' | 'register'
- const [username, setUsername] = useState('')
- const [email, setEmail] = useState('')
- const [password, setPassword] = useState('')
- const [showPassword, setShowPassword] = useState(false)
- const [isLoading, setIsLoading] = useState(false)
- const [error, setError] = useState('')
- const [appConfig, setAppConfig] = useState(null)
+ const [mode, setMode] = useState<'login' | 'register'>('login')
+ const [username, setUsername] = useState<string>('')
+ const [email, setEmail] = useState<string>('')
+ const [password, setPassword] = useState<string>('')
+ const [showPassword, setShowPassword] = useState<boolean>(false)
+ const [isLoading, setIsLoading] = useState<boolean>(false)
+ const [error, setError] = useState<string>('')
+ const [appConfig, setAppConfig] = useState<AppConfig | null>(null)
const { login, register, demoLogin } = useAuthStore()
const { setLanguageLocal } = useSettingsStore()
const navigate = useNavigate()
useEffect(() => {
- authApi.getAppConfig?.().catch(() => null).then(config => {
+ authApi.getAppConfig?.().catch(() => null).then((config: AppConfig | null) => {
if (config) {
setAppConfig(config)
if (!config.has_users) setMode('register')
}
})
- // Handle OIDC callback token (via URL fragment to avoid logging)
- const hash = window.location.hash.substring(1)
- const hashParams = new URLSearchParams(hash)
- const token = hashParams.get('token')
+ // Handle OIDC callback via short-lived auth code (secure exchange)
const params = new URLSearchParams(window.location.search)
+ const oidcCode = params.get('oidc_code')
const oidcError = params.get('oidc_error')
- if (token) {
- localStorage.setItem('auth_token', token)
+ if (oidcCode) {
window.history.replaceState({}, '', '/login')
- login.__fromOidc = true
- navigate('/dashboard')
- window.location.reload()
+ fetch('/api/auth/oidc/exchange?code=' + encodeURIComponent(oidcCode))
+ .then(r => r.json())
+ .then(data => {
+ if (data.token) {
+ localStorage.setItem('auth_token', data.token)
+ navigate('/dashboard')
+ window.location.reload()
+ } else {
+ setError(data.error || 'OIDC login failed')
+ }
+ })
+ .catch(() => setError('OIDC login failed'))
}
if (oidcError) {
- const errorMessages = {
+ const errorMessages: Record<string, string> = {
registration_disabled: t('login.oidc.registrationDisabled'),
no_email: t('login.oidc.noEmail'),
token_failed: t('login.oidc.tokenFailed'),
@@ -54,23 +68,23 @@ export default function LoginPage() {
}
}, [])
- const handleDemoLogin = async () => {
+ const handleDemoLogin = async (): Promise<void> => {
setError('')
setIsLoading(true)
try {
await demoLogin()
setShowTakeoff(true)
setTimeout(() => navigate('/dashboard'), 2600)
- } catch (err) {
- setError(err.message || t('login.demoFailed'))
+ } catch (err: unknown) {
+ setError(err instanceof Error ? err.message : t('login.demoFailed'))
} finally {
setIsLoading(false)
}
}
- const [showTakeoff, setShowTakeoff] = useState(false)
+ const [showTakeoff, setShowTakeoff] = useState<boolean>(false)
- const handleSubmit = async (e) => {
+ const handleSubmit = async (e: React.FormEvent<HTMLFormElement>): Promise<void> => {
e.preventDefault()
setError('')
setIsLoading(true)
@@ -84,15 +98,15 @@ export default function LoginPage() {
}
setShowTakeoff(true)
setTimeout(() => navigate('/dashboard'), 2600)
- } catch (err) {
- setError(err.message || t('login.error'))
+ } catch (err: unknown) {
+ setError(err instanceof Error ? err.message : t('login.error'))
setIsLoading(false)
}
}
const showRegisterOption = appConfig?.allow_registration || !appConfig?.has_users
- const inputBase = {
+ const inputBase: React.CSSProperties = {
width: '100%', padding: '11px 12px 11px 40px', border: '1px solid #e5e7eb',
borderRadius: 12, fontSize: 14, fontFamily: 'inherit', outline: 'none',
color: '#111827', background: 'white', boxSizing: 'border-box', transition: 'border-color 0.15s',
@@ -264,8 +278,8 @@ export default function LoginPage() {
cursor: 'pointer', fontFamily: 'inherit',
transition: 'background 0.15s',
}}
- onMouseEnter={e => e.currentTarget.style.background = 'rgba(0,0,0,0.1)'}
- onMouseLeave={e => e.currentTarget.style.background = 'rgba(0,0,0,0.06)'}
+ onMouseEnter={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.style.background = 'rgba(0,0,0,0.1)'}
+ onMouseLeave={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.style.background = 'rgba(0,0,0,0.06)'}
>
<Globe size={14} />
{language === 'en' ? 'EN' : 'DE'}
@@ -392,8 +406,8 @@ export default function LoginPage() {
{ Icon: Route, label: t('login.features.routes'), desc: t('login.features.routesDesc') },
].map(({ Icon, label, desc }) => (
<div key={label} style={{ background: 'rgba(255,255,255,0.04)', borderRadius: 14, padding: '14px 12px', border: '1px solid rgba(255,255,255,0.06)', textAlign: 'left', transition: 'all 0.2s' }}
- onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.08)'; e.currentTarget.style.borderColor = 'rgba(255,255,255,0.12)' }}
- onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.04)'; e.currentTarget.style.borderColor = 'rgba(255,255,255,0.06)' }}>
+ onMouseEnter={(e: React.MouseEvent<HTMLDivElement>) => { e.currentTarget.style.background = 'rgba(255,255,255,0.08)'; e.currentTarget.style.borderColor = 'rgba(255,255,255,0.12)' }}
+ onMouseLeave={(e: React.MouseEvent<HTMLDivElement>) => { e.currentTarget.style.background = 'rgba(255,255,255,0.04)'; e.currentTarget.style.borderColor = 'rgba(255,255,255,0.06)' }}>
<Icon size={17} style={{ color: 'rgba(255,255,255,0.7)', marginBottom: 7 }} />
<div style={{ fontSize: 12.5, color: 'white', fontWeight: 600, marginBottom: 2 }}>{label}</div>
<div style={{ fontSize: 11, color: 'rgba(255,255,255,0.35)', lineHeight: 1.4 }}>{desc}</div>
@@ -441,10 +455,10 @@ export default function LoginPage() {
<div style={{ position: 'relative' }}>
<User size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
<input
- type="text" value={username} onChange={e => setUsername(e.target.value)} required
+ type="text" value={username} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setUsername(e.target.value)} required
placeholder="admin" style={inputBase}
- onFocus={e => e.target.style.borderColor = '#111827'}
- onBlur={e => e.target.style.borderColor = '#e5e7eb'}
+ onFocus={(e: React.FocusEvent<HTMLInputElement>) => e.target.style.borderColor = '#111827'}
+ onBlur={(e: React.FocusEvent<HTMLInputElement>) => e.target.style.borderColor = '#e5e7eb'}
/>
</div>
</div>
@@ -456,10 +470,10 @@ export default function LoginPage() {
<div style={{ position: 'relative' }}>
<Mail size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
<input
- type="email" value={email} onChange={e => setEmail(e.target.value)} required
+ type="email" value={email} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)} required
placeholder={t('login.emailPlaceholder')} style={inputBase}
- onFocus={e => e.target.style.borderColor = '#111827'}
- onBlur={e => e.target.style.borderColor = '#e5e7eb'}
+ onFocus={(e: React.FocusEvent<HTMLInputElement>) => e.target.style.borderColor = '#111827'}
+ onBlur={(e: React.FocusEvent<HTMLInputElement>) => e.target.style.borderColor = '#e5e7eb'}
/>
</div>
</div>
@@ -470,10 +484,10 @@ export default function LoginPage() {
<div style={{ position: 'relative' }}>
<Lock size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
<input
- type={showPassword ? 'text' : 'password'} value={password} onChange={e => setPassword(e.target.value)} required
+ type={showPassword ? 'text' : 'password'} value={password} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)} required
placeholder="••••••••" style={{ ...inputBase, paddingRight: 44 }}
- onFocus={e => e.target.style.borderColor = '#111827'}
- onBlur={e => e.target.style.borderColor = '#e5e7eb'}
+ onFocus={(e: React.FocusEvent<HTMLInputElement>) => e.target.style.borderColor = '#111827'}
+ onBlur={(e: React.FocusEvent<HTMLInputElement>) => e.target.style.borderColor = '#e5e7eb'}
/>
<button type="button" onClick={() => setShowPassword(v => !v)} style={{
position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
@@ -490,8 +504,8 @@ export default function LoginPage() {
fontFamily: 'inherit', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
opacity: isLoading ? 0.7 : 1, transition: 'opacity 0.15s',
}}
- onMouseEnter={e => { if (!isLoading) e.currentTarget.style.background = '#1f2937' }}
- onMouseLeave={e => e.currentTarget.style.background = '#111827'}
+ onMouseEnter={(e: React.MouseEvent<HTMLButtonElement>) => { if (!isLoading) e.currentTarget.style.background = '#1f2937' }}
+ onMouseLeave={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.style.background = '#111827'}
>
{isLoading
? <><div style={{ width: 15, height: 15, border: '2px solid rgba(255,255,255,0.3)', borderTopColor: 'white', borderRadius: '50%', animation: 'spin 0.7s linear infinite' }} />{mode === 'register' ? t('login.creating') : t('login.signingIn')}</>
@@ -530,8 +544,8 @@ export default function LoginPage() {
textDecoration: 'none', transition: 'all 0.15s',
boxSizing: 'border-box',
}}
- onMouseEnter={e => { e.currentTarget.style.background = '#f9fafb'; e.currentTarget.style.borderColor = '#9ca3af' }}
- onMouseLeave={e => { e.currentTarget.style.background = 'white'; e.currentTarget.style.borderColor = '#d1d5db' }}
+ onMouseEnter={(e: React.MouseEvent<HTMLAnchorElement>) => { e.currentTarget.style.background = '#f9fafb'; e.currentTarget.style.borderColor = '#9ca3af' }}
+ onMouseLeave={(e: React.MouseEvent<HTMLAnchorElement>) => { e.currentTarget.style.background = 'white'; e.currentTarget.style.borderColor = '#d1d5db' }}
>
<Shield size={16} />
{t('login.oidcSignIn', { name: appConfig.oidc_display_name })}
@@ -551,8 +565,8 @@ export default function LoginPage() {
opacity: isLoading ? 0.7 : 1, transition: 'all 0.2s',
boxShadow: '0 2px 12px rgba(245, 158, 11, 0.3)',
}}
- onMouseEnter={e => { if (!isLoading) e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 4px 16px rgba(245, 158, 11, 0.4)' }}
- onMouseLeave={e => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 2px 12px rgba(245, 158, 11, 0.3)' }}
+ onMouseEnter={(e: React.MouseEvent<HTMLButtonElement>) => { if (!isLoading) e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 4px 16px rgba(245, 158, 11, 0.4)' }}
+ onMouseLeave={(e: React.MouseEvent<HTMLButtonElement>) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 2px 12px rgba(245, 158, 11, 0.3)' }}
>
<Plane size={18} />
{t('login.demoHint')}
diff --git a/client/src/pages/PhotosPage.jsx b/client/src/pages/PhotosPage.tsx
similarity index 74%
rename from client/src/pages/PhotosPage.jsx
rename to client/src/pages/PhotosPage.tsx
index a3e0397d5..759b18201 100644
--- a/client/src/pages/PhotosPage.jsx
+++ b/client/src/pages/PhotosPage.tsx
@@ -6,24 +6,25 @@ import Navbar from '../components/Layout/Navbar'
import PhotoGallery from '../components/Photos/PhotoGallery'
import { ArrowLeft } from 'lucide-react'
import { useTranslation } from '../i18n'
+import type { Trip, Day, Place, Photo } from '../types'
-export default function PhotosPage() {
+export default function PhotosPage(): React.ReactElement {
const { t } = useTranslation()
- const { id: tripId } = useParams()
+ const { id: tripId } = useParams<{ id: string }>()
const navigate = useNavigate()
const tripStore = useTripStore()
- const [trip, setTrip] = useState(null)
- const [days, setDays] = useState([])
- const [places, setPlaces] = useState([])
- const [photos, setPhotos] = useState([])
- const [isLoading, setIsLoading] = useState(true)
+ const [trip, setTrip] = useState<Trip | null>(null)
+ const [days, setDays] = useState<Day[]>([])
+ const [places, setPlaces] = useState<Place[]>([])
+ const [photos, setPhotos] = useState<Photo[]>([])
+ const [isLoading, setIsLoading] = useState<boolean>(true)
useEffect(() => {
loadData()
}, [tripId])
- const loadData = async () => {
+ const loadData = async (): Promise<void> => {
setIsLoading(true)
try {
const [tripData, daysData, placesData] = await Promise.all([
@@ -37,7 +38,7 @@ export default function PhotosPage() {
// Load photos
await tripStore.loadPhotos(tripId)
- } catch (err) {
+ } catch (err: unknown) {
navigate('/dashboard')
} finally {
setIsLoading(false)
@@ -49,15 +50,15 @@ export default function PhotosPage() {
setPhotos(tripStore.photos)
}, [tripStore.photos])
- const handleUpload = async (formData) => {
+ const handleUpload = async (formData: FormData): Promise<void> => {
await tripStore.addPhoto(tripId, formData)
}
- const handleDelete = async (photoId) => {
+ const handleDelete = async (photoId: number): Promise<void> => {
await tripStore.deletePhoto(tripId, photoId)
}
- const handleUpdate = async (photoId, data) => {
+ const handleUpdate = async (photoId: number, data: Record<string, string | number | null>): Promise<void> => {
await tripStore.updatePhoto(tripId, photoId, data)
}
@@ -71,7 +72,7 @@ export default function PhotosPage() {
return (
<div className="min-h-screen bg-slate-50">
- <Navbar tripTitle={trip?.title} tripId={tripId} showBack onBack={() => navigate(`/trips/${tripId}`)} />
+ <Navbar tripTitle={trip?.name} tripId={tripId} showBack onBack={() => navigate(`/trips/${tripId}`)} />
<div style={{ paddingTop: 'var(--nav-h)' }}>
<div className="max-w-7xl mx-auto px-4 py-6">
@@ -89,7 +90,7 @@ export default function PhotosPage() {
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-gray-900">Fotos</h1>
- <p className="text-gray-500 text-sm">{photos.length} Fotos für {trip?.title}</p>
+ <p className="text-gray-500 text-sm">{photos.length} Fotos für {trip?.name}</p>
</div>
</div>
diff --git a/client/src/pages/RegisterPage.jsx b/client/src/pages/RegisterPage.tsx
similarity index 87%
rename from client/src/pages/RegisterPage.jsx
rename to client/src/pages/RegisterPage.tsx
index 3089cc089..1146b64a6 100644
--- a/client/src/pages/RegisterPage.jsx
+++ b/client/src/pages/RegisterPage.tsx
@@ -4,20 +4,20 @@ import { useAuthStore } from '../store/authStore'
import { useTranslation } from '../i18n'
import { Map, Eye, EyeOff, Mail, Lock, User } from 'lucide-react'
-export default function RegisterPage() {
+export default function RegisterPage(): React.ReactElement {
const { t } = useTranslation()
- const [username, setUsername] = useState('')
- const [email, setEmail] = useState('')
- const [password, setPassword] = useState('')
- const [confirmPassword, setConfirmPassword] = useState('')
- const [showPassword, setShowPassword] = useState(false)
- const [isLoading, setIsLoading] = useState(false)
- const [error, setError] = useState('')
+ const [username, setUsername] = useState<string>('')
+ const [email, setEmail] = useState<string>('')
+ const [password, setPassword] = useState<string>('')
+ const [confirmPassword, setConfirmPassword] = useState<string>('')
+ const [showPassword, setShowPassword] = useState<boolean>(false)
+ const [isLoading, setIsLoading] = useState<boolean>(false)
+ const [error, setError] = useState<string>('')
const { register } = useAuthStore()
const navigate = useNavigate()
- const handleSubmit = async (e) => {
+ const handleSubmit = async (e: React.FormEvent<HTMLFormElement>): Promise<void> => {
e.preventDefault()
setError('')
@@ -35,8 +35,8 @@ export default function RegisterPage() {
try {
await register(username, email, password)
navigate('/dashboard')
- } catch (err) {
- setError(err.message || t('register.failed'))
+ } catch (err: unknown) {
+ setError(err instanceof Error ? err.message : t('register.failed'))
} finally {
setIsLoading(false)
}
@@ -96,7 +96,7 @@ export default function RegisterPage() {
<input
type="text"
value={username}
- onChange={e => setUsername(e.target.value)}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setUsername(e.target.value)}
required
placeholder="johndoe"
minLength={3}
@@ -112,7 +112,7 @@ export default function RegisterPage() {
<input
type="email"
value={email}
- onChange={e => setEmail(e.target.value)}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)}
required
placeholder="[email protected]"
className="w-full pl-10 pr-4 py-2.5 border border-slate-300 rounded-lg text-slate-900 placeholder-slate-400 focus:ring-2 focus:ring-slate-400 focus:border-transparent transition-all"
@@ -127,7 +127,7 @@ export default function RegisterPage() {
<input
type={showPassword ? 'text' : 'password'}
value={password}
- onChange={e => setPassword(e.target.value)}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}
required
placeholder={t('register.minChars')}
className="w-full pl-10 pr-12 py-2.5 border border-slate-300 rounded-lg text-slate-900 placeholder-slate-400 focus:ring-2 focus:ring-slate-400 focus:border-transparent transition-all"
@@ -149,7 +149,7 @@ export default function RegisterPage() {
<input
type={showPassword ? 'text' : 'password'}
value={confirmPassword}
- onChange={e => setConfirmPassword(e.target.value)}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setConfirmPassword(e.target.value)}
required
placeholder={t('register.repeatPassword')}
className="w-full pl-10 pr-4 py-2.5 border border-slate-300 rounded-lg text-slate-900 placeholder-slate-400 focus:ring-2 focus:ring-slate-400 focus:border-transparent transition-all"
diff --git a/client/src/pages/SettingsPage.jsx b/client/src/pages/SettingsPage.tsx
similarity index 82%
rename from client/src/pages/SettingsPage.jsx
rename to client/src/pages/SettingsPage.tsx
index 3eeed2d9e..bf19952dd 100644
--- a/client/src/pages/SettingsPage.jsx
+++ b/client/src/pages/SettingsPage.tsx
@@ -8,8 +8,16 @@ import CustomSelect from '../components/shared/CustomSelect'
import { useToast } from '../components/shared/Toast'
import { Save, Map, Palette, User, Moon, Sun, Monitor, Shield, Camera, Trash2, Lock } from 'lucide-react'
import { authApi, adminApi } from '../api/client'
+import type { LucideIcon } from 'lucide-react'
+import type { UserWithOidc } from '../types'
+import { getApiErrorMessage } from '../types'
-const MAP_PRESETS = [
+interface MapPreset {
+ name: string
+ url: string
+}
+
+const MAP_PRESETS: MapPreset[] = [
{ name: 'OpenStreetMap', url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' },
{ name: 'OpenStreetMap DE', url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' },
{ name: 'CartoDB Light', url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png' },
@@ -17,7 +25,13 @@ const MAP_PRESETS = [
{ name: 'Stadia Smooth', url: 'https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png' },
]
-function Section({ title, icon: Icon, children }) {
+interface SectionProps {
+ title: string
+ icon: LucideIcon
+ children: React.ReactNode
+}
+
+function Section({ title, icon: Icon, children }: SectionProps): React.ReactElement {
return (
<div className="rounded-xl border overflow-hidden" style={{ background: 'var(--bg-card)', borderColor: 'var(--border-primary)' }}>
<div className="px-6 py-4 border-b flex items-center gap-2" style={{ borderColor: 'var(--border-secondary)' }}>
@@ -31,31 +45,32 @@ function Section({ title, icon: Icon, children }) {
)
}
-export default function SettingsPage() {
+export default function SettingsPage(): React.ReactElement {
const { user, updateProfile, uploadAvatar, deleteAvatar, logout } = useAuthStore()
- const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
- const avatarInputRef = React.useRef(null)
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState<boolean | 'blocked'>(false)
+ const avatarInputRef = React.useRef<HTMLInputElement>(null)
const { settings, updateSetting, updateSettings } = useSettingsStore()
const { t, locale } = useTranslation()
const toast = useToast()
const navigate = useNavigate()
- const [saving, setSaving] = useState({})
+ const [saving, setSaving] = useState<Record<string, boolean>>({})
// Map settings
- const [mapTileUrl, setMapTileUrl] = useState(settings.map_tile_url || '')
- const [defaultLat, setDefaultLat] = useState(settings.default_lat || 48.8566)
- const [defaultLng, setDefaultLng] = useState(settings.default_lng || 2.3522)
- const [defaultZoom, setDefaultZoom] = useState(settings.default_zoom || 10)
+ const [mapTileUrl, setMapTileUrl] = useState<string>(settings.map_tile_url || '')
+ const [defaultLat, setDefaultLat] = useState<number | string>(settings.default_lat || 48.8566)
+ const [defaultLng, setDefaultLng] = useState<number | string>(settings.default_lng || 2.3522)
+ const [defaultZoom, setDefaultZoom] = useState<number | string>(settings.default_zoom || 10)
// Display
- const [tempUnit, setTempUnit] = useState(settings.temperature_unit || 'celsius')
+ const [tempUnit, setTempUnit] = useState<string>(settings.temperature_unit || 'celsius')
// Account
- const [username, setUsername] = useState(user?.username || '')
- const [email, setEmail] = useState(user?.email || '')
- const [newPassword, setNewPassword] = useState('')
- const [confirmPassword, setConfirmPassword] = useState('')
+ const [username, setUsername] = useState<string>(user?.username || '')
+ const [email, setEmail] = useState<string>(user?.email || '')
+ const [currentPassword, setCurrentPassword] = useState<string>('')
+ const [newPassword, setNewPassword] = useState<string>('')
+ const [confirmPassword, setConfirmPassword] = useState<string>('')
useEffect(() => {
setMapTileUrl(settings.map_tile_url || '')
@@ -70,36 +85,36 @@ export default function SettingsPage() {
setEmail(user?.email || '')
}, [user])
- const saveMapSettings = async () => {
+ const saveMapSettings = async (): Promise<void> => {
setSaving(s => ({ ...s, map: true }))
try {
await updateSettings({
map_tile_url: mapTileUrl,
- default_lat: parseFloat(defaultLat),
- default_lng: parseFloat(defaultLng),
- default_zoom: parseInt(defaultZoom),
+ default_lat: parseFloat(String(defaultLat)),
+ default_lng: parseFloat(String(defaultLng)),
+ default_zoom: parseInt(String(defaultZoom)),
})
toast.success(t('settings.toast.mapSaved'))
- } catch (err) {
- toast.error(err.message)
+ } catch (err: unknown) {
+ toast.error(err instanceof Error ? err.message : 'Error')
} finally {
setSaving(s => ({ ...s, map: false }))
}
}
- const saveDisplay = async () => {
+ const saveDisplay = async (): Promise<void> => {
setSaving(s => ({ ...s, display: true }))
try {
await updateSetting('temperature_unit', tempUnit)
toast.success(t('settings.toast.displaySaved'))
- } catch (err) {
- toast.error(err.message)
+ } catch (err: unknown) {
+ toast.error(err instanceof Error ? err.message : 'Error')
} finally {
setSaving(s => ({ ...s, display: false }))
}
}
- const handleAvatarUpload = async (e) => {
+ const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>): Promise<void> => {
const file = e.target.files?.[0]
if (!file) return
try {
@@ -111,7 +126,7 @@ export default function SettingsPage() {
if (avatarInputRef.current) avatarInputRef.current.value = ''
}
- const handleAvatarRemove = async () => {
+ const handleAvatarRemove = async (): Promise<void> => {
try {
await deleteAvatar()
toast.success(t('settings.avatarRemoved'))
@@ -120,13 +135,13 @@ export default function SettingsPage() {
}
}
- const saveProfile = async () => {
+ const saveProfile = async (): Promise<void> => {
setSaving(s => ({ ...s, profile: true }))
try {
await updateProfile({ username, email })
toast.success(t('settings.toast.profileSaved'))
- } catch (err) {
- toast.error(err.message)
+ } catch (err: unknown) {
+ toast.error(err instanceof Error ? err.message : 'Error')
} finally {
setSaving(s => ({ ...s, profile: false }))
}
@@ -149,7 +164,7 @@ export default function SettingsPage() {
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('settings.mapTemplate')}</label>
<CustomSelect
value=""
- onChange={value => { if (value) setMapTileUrl(value) }}
+ onChange={(value: string) => { if (value) setMapTileUrl(value) }}
placeholder={t('settings.mapTemplatePlaceholder.select')}
options={MAP_PRESETS.map(p => ({
value: p.url,
@@ -161,7 +176,7 @@ export default function SettingsPage() {
<input
type="text"
value={mapTileUrl}
- onChange={e => setMapTileUrl(e.target.value)}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMapTileUrl(e.target.value)}
placeholder="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
/>
@@ -175,7 +190,7 @@ export default function SettingsPage() {
type="number"
step="any"
value={defaultLat}
- onChange={e => setDefaultLat(e.target.value)}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setDefaultLat(e.target.value)}
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
/>
</div>
@@ -185,7 +200,7 @@ export default function SettingsPage() {
type="number"
step="any"
value={defaultLng}
- onChange={e => setDefaultLng(e.target.value)}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setDefaultLng(e.target.value)}
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
/>
</div>
@@ -220,7 +235,7 @@ export default function SettingsPage() {
onClick={async () => {
try {
await updateSetting('dark_mode', opt.value)
- } catch (e) { toast.error(e.message) }
+ } catch (e: unknown) { toast.error(e instanceof Error ? e.message : 'Error') }
}}
style={{
display: 'flex', alignItems: 'center', gap: 8,
@@ -252,7 +267,7 @@ export default function SettingsPage() {
key={opt.value}
onClick={async () => {
try { await updateSetting('language', opt.value) }
- catch (e) { toast.error(e.message) }
+ catch (e: unknown) { toast.error(e instanceof Error ? e.message : 'Error') }
}}
style={{
display: 'flex', alignItems: 'center', gap: 8,
@@ -283,7 +298,7 @@ export default function SettingsPage() {
onClick={async () => {
setTempUnit(opt.value)
try { await updateSetting('temperature_unit', opt.value) }
- catch (e) { toast.error(e.message) }
+ catch (e: unknown) { toast.error(e instanceof Error ? e.message : 'Error') }
}}
style={{
display: 'flex', alignItems: 'center', gap: 8,
@@ -313,7 +328,7 @@ export default function SettingsPage() {
key={opt.value}
onClick={async () => {
try { await updateSetting('time_format', opt.value) }
- catch (e) { toast.error(e.message) }
+ catch (e: unknown) { toast.error(e instanceof Error ? e.message : 'Error') }
}}
style={{
display: 'flex', alignItems: 'center', gap: 8,
@@ -342,7 +357,7 @@ export default function SettingsPage() {
key={String(opt.value)}
onClick={async () => {
try { await updateSetting('route_calculation', opt.value) }
- catch (e) { toast.error(e.message) }
+ catch (e: unknown) { toast.error(e instanceof Error ? e.message : 'Error') }
}}
style={{
display: 'flex', alignItems: 'center', gap: 8,
@@ -368,7 +383,7 @@ export default function SettingsPage() {
<input
type="text"
value={username}
- onChange={e => setUsername(e.target.value)}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setUsername(e.target.value)}
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
/>
</div>
@@ -377,7 +392,7 @@ export default function SettingsPage() {
<input
type="email"
value={email}
- onChange={e => setEmail(e.target.value)}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)}
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
/>
</div>
@@ -386,37 +401,45 @@ export default function SettingsPage() {
<div style={{ paddingTop: 8, marginTop: 8, borderTop: '1px solid var(--border-secondary)' }}>
<label className="block text-sm font-medium text-slate-700 mb-3">{t('settings.changePassword')}</label>
<div className="space-y-3">
+ <input
+ type="password"
+ value={currentPassword}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setCurrentPassword(e.target.value)}
+ placeholder={t('settings.currentPassword')}
+ className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
+ />
<input
type="password"
value={newPassword}
- onChange={e => setNewPassword(e.target.value)}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNewPassword(e.target.value)}
placeholder={t('settings.newPassword')}
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
/>
<input
type="password"
value={confirmPassword}
- onChange={e => setConfirmPassword(e.target.value)}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setConfirmPassword(e.target.value)}
placeholder={t('settings.confirmPassword')}
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
/>
<button
onClick={async () => {
+ if (!currentPassword) return toast.error(t('settings.currentPasswordRequired'))
if (!newPassword) return toast.error(t('settings.passwordRequired'))
if (newPassword.length < 8) return toast.error(t('settings.passwordTooShort'))
if (newPassword !== confirmPassword) return toast.error(t('settings.passwordMismatch'))
try {
- await authApi.changePassword({ new_password: newPassword })
+ await authApi.changePassword({ current_password: currentPassword, new_password: newPassword })
toast.success(t('settings.passwordChanged'))
- setNewPassword(''); setConfirmPassword('')
- } catch (err) {
- toast.error(err.response?.data?.error || t('common.error'))
+ setCurrentPassword(''); setNewPassword(''); setConfirmPassword('')
+ } catch (err: unknown) {
+ toast.error(getApiErrorMessage(err, t('common.error')))
}
}}
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors"
style={{ border: '1px solid var(--border-primary)', background: 'var(--bg-card)', color: 'var(--text-secondary)' }}
- onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
- onMouseLeave={e => e.currentTarget.style.background = 'var(--bg-card)'}
+ onMouseEnter={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.style.background = 'var(--bg-hover)'}
+ onMouseLeave={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.style.background = 'var(--bg-card)'}
>
<Lock size={14} />
{t('settings.updatePassword')}
@@ -455,8 +478,8 @@ export default function SettingsPage() {
display: 'flex', alignItems: 'center', justifyContent: 'center',
cursor: 'pointer', padding: 0, transition: 'transform 0.15s, opacity 0.15s',
}}
- onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.15)'; e.currentTarget.style.opacity = '0.85' }}
- onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.opacity = '1' }}
+ onMouseEnter={(e: React.MouseEvent<HTMLButtonElement>) => { e.currentTarget.style.transform = 'scale(1.15)'; e.currentTarget.style.opacity = '0.85' }}
+ onMouseLeave={(e: React.MouseEvent<HTMLButtonElement>) => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.opacity = '1' }}
>
<Camera size={14} />
</button>
@@ -481,7 +504,7 @@ export default function SettingsPage() {
<span className="font-medium" style={{ display: 'inline-flex', alignItems: 'center', gap: 4, color: 'var(--text-secondary)' }}>
{user?.role === 'admin' ? <><Shield size={13} /> {t('settings.roleAdmin')}</> : t('settings.roleUser')}
</span>
- {user?.oidc_issuer && (
+ {(user as UserWithOidc)?.oidc_issuer && (
<span style={{
display: 'inline-flex', alignItems: 'center', gap: 4,
fontSize: 10, fontWeight: 500, padding: '1px 8px', borderRadius: 99,
@@ -491,9 +514,9 @@ export default function SettingsPage() {
</span>
)}
</div>
- {user?.oidc_issuer && (
+ {(user as UserWithOidc)?.oidc_issuer && (
<p style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: -2 }}>
- {t('settings.oidcLinked')} {user.oidc_issuer.replace('https://', '').replace(/\/+$/, '')}
+ {t('settings.oidcLinked')} {(user as UserWithOidc).oidc_issuer!.replace('https://', '').replace(/\/+$/, '')}
</p>
)}
</div>
@@ -513,7 +536,7 @@ export default function SettingsPage() {
if (user?.role === 'admin') {
try {
const data = await adminApi.stats()
- const adminUsers = (await adminApi.users()).users.filter(u => u.role === 'admin')
+ const adminUsers = (await adminApi.users()).users.filter((u: { role: string }) => u.role === 'admin')
if (adminUsers.length <= 1) {
setShowDeleteConfirm('blocked')
return
@@ -541,7 +564,7 @@ export default function SettingsPage() {
<div style={{
background: 'var(--bg-card)', borderRadius: 16, padding: '28px 24px',
maxWidth: 400, width: '100%', boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
- }} onClick={e => e.stopPropagation()}>
+ }} onClick={(e: React.MouseEvent<HTMLDivElement>) => e.stopPropagation()}>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
<div style={{ width: 36, height: 36, borderRadius: 10, background: '#fef3c7', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<Shield size={18} style={{ color: '#d97706' }} />
@@ -576,7 +599,7 @@ export default function SettingsPage() {
<div style={{
background: 'var(--bg-card)', borderRadius: 16, padding: '28px 24px',
maxWidth: 400, width: '100%', boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
- }} onClick={e => e.stopPropagation()}>
+ }} onClick={(e: React.MouseEvent<HTMLDivElement>) => e.stopPropagation()}>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
<div style={{ width: 36, height: 36, borderRadius: 10, background: '#fef2f2', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<Trash2 size={18} style={{ color: '#ef4444' }} />
@@ -603,8 +626,8 @@ export default function SettingsPage() {
await authApi.deleteOwnAccount()
logout()
navigate('/login')
- } catch (err) {
- toast.error(err.response?.data?.error || t('common.error'))
+ } catch (err: unknown) {
+ toast.error(getApiErrorMessage(err, t('common.error')))
setShowDeleteConfirm(false)
}
}}
diff --git a/client/src/pages/TripPlannerPage.jsx b/client/src/pages/TripPlannerPage.tsx
similarity index 83%
rename from client/src/pages/TripPlannerPage.jsx
rename to client/src/pages/TripPlannerPage.tsx
index 4149d115a..baedaa973 100644
--- a/client/src/pages/TripPlannerPage.jsx
+++ b/client/src/pages/TripPlannerPage.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react'
+import React, { useState, useEffect, useCallback, useMemo } from 'react'
import ReactDOM from 'react-dom'
import { useParams, useNavigate } from 'react-router-dom'
import { useTripStore } from '../store/tripStore'
@@ -21,16 +21,16 @@ import Navbar from '../components/Layout/Navbar'
import { useToast } from '../components/shared/Toast'
import { Map, X, PanelLeftClose, PanelLeftOpen, PanelRightClose, PanelRightOpen } from 'lucide-react'
import { useTranslation } from '../i18n'
-import { joinTrip, leaveTrip, addListener, removeListener } from '../api/websocket'
import { addonsApi, accommodationsApi, authApi, tripsApi, assignmentsApi } from '../api/client'
-import { calculateRoute, calculateSegments } from '../components/Map/RouteCalculator'
import ConfirmDialog from '../components/shared/ConfirmDialog'
-
-const MIN_SIDEBAR = 200
-const MAX_SIDEBAR = 520
-
-export default function TripPlannerPage() {
- const { id: tripId } = useParams()
+import { useResizablePanels } from '../hooks/useResizablePanels'
+import { useTripWebSocket } from '../hooks/useTripWebSocket'
+import { useRouteCalculation } from '../hooks/useRouteCalculation'
+import { usePlaceSelection } from '../hooks/usePlaceSelection'
+import type { Accommodation, TripMember, Day, Place, Reservation } from '../types'
+
+export default function TripPlannerPage(): React.ReactElement | null {
+ const { id: tripId } = useParams<{ id: string }>()
const navigate = useNavigate()
const toast = useToast()
const { t } = useTranslation()
@@ -38,10 +38,10 @@ export default function TripPlannerPage() {
const tripStore = useTripStore()
const { trip, days, places, assignments, packingItems, categories, reservations, budgetItems, files, selectedDayId, isLoading } = tripStore
- const [enabledAddons, setEnabledAddons] = useState({ packing: true, budget: true, documents: true })
- const [tripAccommodations, setTripAccommodations] = useState([])
- const [allowedFileTypes, setAllowedFileTypes] = useState(null)
- const [tripMembers, setTripMembers] = useState([])
+ const [enabledAddons, setEnabledAddons] = useState<Record<string, boolean>>({ packing: true, budget: true, documents: true })
+ const [tripAccommodations, setTripAccommodations] = useState<Accommodation[]>([])
+ const [allowedFileTypes, setAllowedFileTypes] = useState<string | null>(null)
+ const [tripMembers, setTripMembers] = useState<TripMember[]>([])
const loadAccommodations = useCallback(() => {
if (tripId) accommodationsApi.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {})
@@ -67,52 +67,30 @@ export default function TripPlannerPage() {
...(enabledAddons.collab ? [{ id: 'collab', label: 'Collab' }] : []),
]
- const [activeTab, setActiveTab] = useState(() => {
+ const [activeTab, setActiveTab] = useState<string>(() => {
const saved = sessionStorage.getItem(`trip-tab-${tripId}`)
return saved || 'plan'
})
- const handleTabChange = (tabId) => {
+ const handleTabChange = (tabId: string): void => {
setActiveTab(tabId)
sessionStorage.setItem(`trip-tab-${tripId}`, tabId)
if (tabId === 'finanzplan') tripStore.loadBudgetItems?.(tripId)
if (tabId === 'dateien' && (!files || files.length === 0)) tripStore.loadFiles?.(tripId)
}
- const [leftWidth, setLeftWidth] = useState(() => parseInt(localStorage.getItem('sidebarLeftWidth')) || 340)
- const [rightWidth, setRightWidth] = useState(() => parseInt(localStorage.getItem('sidebarRightWidth')) || 300)
- const [leftCollapsed, setLeftCollapsed] = useState(false)
- const [rightCollapsed, setRightCollapsed] = useState(false)
- const [showDayDetail, setShowDayDetail] = useState(null) // day object or null
- const isResizingLeft = useRef(false)
- const isResizingRight = useRef(false)
-
- const [selectedPlaceId, _setSelectedPlaceId] = useState(null)
- const [selectedAssignmentId, setSelectedAssignmentId] = useState(null)
-
- // Set place selection - from PlacesSidebar/Map (no assignment context)
- const setSelectedPlaceId = useCallback((placeId) => {
- _setSelectedPlaceId(placeId)
- setSelectedAssignmentId(null)
- }, [])
-
- // Set assignment selection - from DayPlanSidebar (specific assignment)
- const selectAssignment = useCallback((assignmentId, placeId) => {
- setSelectedAssignmentId(assignmentId)
- _setSelectedPlaceId(placeId)
- }, [])
- const [showPlaceForm, setShowPlaceForm] = useState(false)
- const [editingPlace, setEditingPlace] = useState(null)
- const [editingAssignmentId, setEditingAssignmentId] = useState(null)
- const [showTripForm, setShowTripForm] = useState(false)
- const [showMembersModal, setShowMembersModal] = useState(false)
- const [showReservationModal, setShowReservationModal] = useState(false)
- const [editingReservation, setEditingReservation] = useState(null)
- const [route, setRoute] = useState(null)
- const [routeInfo, setRouteInfo] = useState(null) // unused legacy
- const [routeSegments, setRouteSegments] = useState([]) // { from, to, walkingText, drivingText }
- const [fitKey, setFitKey] = useState(0)
- const [mobileSidebarOpen, setMobileSidebarOpen] = useState(null) // 'left' | 'right' | null
- const [deletePlaceId, setDeletePlaceId] = useState(null)
+ const { leftWidth, rightWidth, leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed, startResizeLeft, startResizeRight } = useResizablePanels()
+ const { selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment } = usePlaceSelection()
+ const [showDayDetail, setShowDayDetail] = useState<Day | null>(null)
+ const [showPlaceForm, setShowPlaceForm] = useState<boolean>(false)
+ const [editingPlace, setEditingPlace] = useState<Place | null>(null)
+ const [editingAssignmentId, setEditingAssignmentId] = useState<number | null>(null)
+ const [showTripForm, setShowTripForm] = useState<boolean>(false)
+ const [showMembersModal, setShowMembersModal] = useState<boolean>(false)
+ const [showReservationModal, setShowReservationModal] = useState<boolean>(false)
+ const [editingReservation, setEditingReservation] = useState<Reservation | null>(null)
+ const [fitKey, setFitKey] = useState<number>(0)
+ const [mobileSidebarOpen, setMobileSidebarOpen] = useState<'left' | 'right' | null>(null)
+ const [deletePlaceId, setDeletePlaceId] = useState<number | null>(null)
// Load trip + files (needed for place inspector file section)
useEffect(() => {
@@ -132,87 +110,13 @@ export default function TripPlannerPage() {
if (tripId) tripStore.loadReservations(tripId)
}, [tripId])
- // WebSocket: join trip and listen for remote events
- useEffect(() => {
- if (!tripId) return
- const handler = useTripStore.getState().handleRemoteEvent
- joinTrip(tripId)
- addListener(handler)
- // Reload files when collab notes change (attachments sync) — from WebSocket (other users)
- const collabFileSync = (event) => {
- if (event?.type === 'collab:note:deleted' || event?.type === 'collab:note:updated') {
- tripStore.loadFiles?.(tripId)
- }
- }
- addListener(collabFileSync)
- // Reload files when local collab actions change files (own user)
- const localFileSync = () => tripStore.loadFiles?.(tripId)
- window.addEventListener('collab-files-changed', localFileSync)
- return () => {
- leaveTrip(tripId)
- removeListener(handler)
- removeListener(collabFileSync)
- window.removeEventListener('collab-files-changed', localFileSync)
- }
- }, [tripId])
-
- useEffect(() => {
- const onMove = (e) => {
- if (isResizingLeft.current) {
- const w = Math.max(MIN_SIDEBAR, Math.min(MAX_SIDEBAR, e.clientX - 10))
- setLeftWidth(w)
- localStorage.setItem('sidebarLeftWidth', w)
- }
- if (isResizingRight.current) {
- const w = Math.max(MIN_SIDEBAR, Math.min(MAX_SIDEBAR, window.innerWidth - e.clientX - 10))
- setRightWidth(w)
- localStorage.setItem('sidebarRightWidth', w)
- }
- }
- const onUp = () => {
- isResizingLeft.current = false
- isResizingRight.current = false
- document.body.style.cursor = ''
- document.body.style.userSelect = ''
- }
- document.addEventListener('mousemove', onMove)
- document.addEventListener('mouseup', onUp)
- return () => {
- document.removeEventListener('mousemove', onMove)
- document.removeEventListener('mouseup', onUp)
- }
- }, [])
+ useTripWebSocket(tripId)
const mapPlaces = useCallback(() => {
return places.filter(p => p.lat && p.lng)
}, [places])
- const routeCalcEnabled = useSettingsStore(s => s.settings.route_calculation) !== false
- const routeAbortRef = useRef(null)
-
- const updateRouteForDay = useCallback(async (dayId) => {
- // Abort any previous calculation
- if (routeAbortRef.current) routeAbortRef.current.abort()
-
- if (!dayId) { setRoute(null); setRouteSegments([]); return }
- const da = (tripStore.assignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index)
- const waypoints = da.map(a => a.place).filter(p => p?.lat && p?.lng)
- if (waypoints.length < 2) { setRoute(null); setRouteSegments([]); return }
-
- setRoute(waypoints.map(p => [p.lat, p.lng]))
- if (!routeCalcEnabled) { setRouteSegments([]); return }
-
- // Single OSRM request for all segments
- const controller = new AbortController()
- routeAbortRef.current = controller
-
- try {
- const segments = await calculateSegments(waypoints, { signal: controller.signal })
- if (!controller.signal.aborted) setRouteSegments(segments)
- } catch (err) {
- if (err.name !== 'AbortError') setRouteSegments([])
- }
- }, [tripStore, routeCalcEnabled])
+ const { route, routeSegments, routeInfo, setRoute, setRouteInfo, updateRouteForDay } = useRouteCalculation(tripStore, selectedDayId)
const handleSelectDay = useCallback((dayId, skipFit) => {
const changed = dayId !== selectedDayId
@@ -287,7 +191,7 @@ export default function TripPlannerPage() {
await tripStore.deletePlace(tripId, deletePlaceId)
if (selectedPlaceId === deletePlaceId) setSelectedPlaceId(null)
toast.success(t('trip.toast.placeDeleted'))
- } catch (err) { toast.error(err.message) }
+ } catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Unknown error') }
}, [deletePlaceId, tripId, tripStore, toast, selectedPlaceId])
const handleAssignToDay = useCallback(async (placeId, dayId, position) => {
@@ -297,14 +201,14 @@ export default function TripPlannerPage() {
await tripStore.assignPlaceToDay(tripId, target, placeId, position)
toast.success(t('trip.toast.assignedToDay'))
updateRouteForDay(target)
- } catch (err) { toast.error(err.message) }
+ } catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Unknown error') }
}, [selectedDayId, tripId, tripStore, toast, updateRouteForDay])
const handleRemoveAssignment = useCallback(async (dayId, assignmentId) => {
try {
await tripStore.removeAssignment(tripId, dayId, assignmentId)
}
- catch (err) { toast.error(err.message) }
+ catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Unknown error') }
}, [tripId, tripStore, toast, updateRouteForDay])
const handleReorder = useCallback((dayId, orderedIds) => {
@@ -323,7 +227,7 @@ export default function TripPlannerPage() {
const handleUpdateDayTitle = useCallback(async (dayId, title) => {
try { await tripStore.updateDayTitle(tripId, dayId, title) }
- catch (err) { toast.error(err.message) }
+ catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Unknown error') }
}, [tripId, tripStore, toast])
const handleSaveReservation = async (data) => {
@@ -339,12 +243,12 @@ export default function TripPlannerPage() {
setShowReservationModal(false)
return r
}
- } catch (err) { toast.error(err.message) }
+ } catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Unknown error') }
}
const handleDeleteReservation = async (id) => {
try { await tripStore.deleteReservation(tripId, id); toast.success(t('trip.toast.deleted')) }
- catch (err) { toast.error(err.message) }
+ catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Unknown error') }
}
const selectedPlace = selectedPlaceId ? places.find(p => p.id === selectedPlaceId) : null
@@ -363,12 +267,6 @@ export default function TripPlannerPage() {
return map
}, [selectedDayId, assignments])
- // Auto-update route + segments when assignments change
- useEffect(() => {
- if (!selectedDayId) { setRoute(null); setRouteSegments([]); return }
- updateRouteForDay(selectedDayId)
- }, [selectedDayId, assignments])
-
// Places assigned to selected day (with coords) — used for map fitting
const dayPlaces = useMemo(() => {
if (!selectedDayId) return []
@@ -510,7 +408,7 @@ export default function TripPlannerPage() {
/>
{!leftCollapsed && (
<div
- onMouseDown={() => { isResizingLeft.current = true; document.body.style.cursor = 'col-resize'; document.body.style.userSelect = 'none' }}
+ onMouseDown={startResizeLeft}
style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 4, cursor: 'col-resize', background: 'transparent' }}
onMouseEnter={e => e.currentTarget.style.background = 'rgba(0,0,0,0.08)'}
onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
@@ -547,7 +445,7 @@ export default function TripPlannerPage() {
}}>
{!rightCollapsed && (
<div
- onMouseDown={() => { isResizingRight.current = true; document.body.style.cursor = 'col-resize'; document.body.style.userSelect = 'none' }}
+ onMouseDown={startResizeRight}
style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 4, cursor: 'col-resize', background: 'transparent' }}
onMouseEnter={e => e.currentTarget.style.background = 'rgba(0,0,0,0.08)'}
onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
@@ -647,7 +545,7 @@ export default function TripPlannerPage() {
}))
} catch {}
}}
- onUpdatePlace={async (placeId, data) => { try { await tripStore.updatePlace(tripId, placeId, data) } catch (err) { toast.error(err.message) } }}
+ onUpdatePlace={async (placeId, data) => { try { await tripStore.updatePlace(tripId, placeId, data) } catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Unknown error') } }}
/>
)}
diff --git a/client/src/pages/VacayPage.jsx b/client/src/pages/VacayPage.tsx
similarity index 95%
rename from client/src/pages/VacayPage.jsx
rename to client/src/pages/VacayPage.tsx
index 4f37573b4..93dff4ba0 100644
--- a/client/src/pages/VacayPage.jsx
+++ b/client/src/pages/VacayPage.tsx
@@ -11,17 +11,17 @@ import VacaySettings from '../components/Vacay/VacaySettings'
import { Plus, Minus, ChevronLeft, ChevronRight, Settings, CalendarDays, AlertTriangle, Users, Eye, Pencil, Trash2, Unlink, ShieldCheck, SlidersHorizontal } from 'lucide-react'
import Modal from '../components/shared/Modal'
-export default function VacayPage() {
+export default function VacayPage(): React.ReactElement {
const { t } = useTranslation()
const { years, selectedYear, setSelectedYear, addYear, removeYear, loadAll, loadPlan, loadEntries, loadStats, loadHolidays, loading, incomingInvites, acceptInvite, declineInvite, plan } = useVacayStore()
- const [showSettings, setShowSettings] = useState(false)
- const [deleteYear, setDeleteYear] = useState(null)
- const [showMobileSidebar, setShowMobileSidebar] = useState(false)
+ const [showSettings, setShowSettings] = useState<boolean>(false)
+ const [deleteYear, setDeleteYear] = useState<number | null>(null)
+ const [showMobileSidebar, setShowMobileSidebar] = useState<boolean>(false)
useEffect(() => { loadAll() }, [])
// Live sync via WebSocket
- const handleWsMessage = useCallback((msg) => {
+ const handleWsMessage = useCallback((msg: { type: string }) => {
if (msg.type === 'vacay:update' || msg.type === 'vacay:settings') {
loadPlan()
loadEntries(selectedYear)
@@ -263,7 +263,7 @@ export default function VacayPage() {
)
}
-function InfoItem({ icon: Icon, text }) {
+function InfoItem({ icon: Icon, text }: { icon: React.ComponentType<{ size?: number; className?: string; style?: React.CSSProperties }>; text: string }): React.ReactElement {
return (
<div className="flex items-start gap-3 px-3 py-2 rounded-lg" style={{ background: 'var(--bg-secondary)' }}>
<Icon size={15} className="shrink-0 mt-0.5" style={{ color: 'var(--text-muted)' }} />
@@ -272,7 +272,7 @@ function InfoItem({ icon: Icon, text }) {
)
}
-function LegendItem({ color, label }) {
+function LegendItem({ color, label }: { color: string; label: string }): React.ReactElement {
return (
<div className="flex items-center gap-2">
<span className="w-4 h-3 rounded" style={{ background: color, border: `1px solid ${color}` }} />
diff --git a/client/src/store/authStore.js b/client/src/store/authStore.ts
similarity index 56%
rename from client/src/store/authStore.js
rename to client/src/store/authStore.ts
index 402b4b9f8..ee1f9b099 100644
--- a/client/src/store/authStore.js
+++ b/client/src/store/authStore.ts
@@ -1,8 +1,42 @@
import { create } from 'zustand'
import { authApi } from '../api/client'
import { connect, disconnect } from '../api/websocket'
+import type { User } from '../types'
+import { getApiErrorMessage } from '../types'
-export const useAuthStore = create((set, get) => ({
+interface AuthResponse {
+ user: User
+ token: string
+}
+
+interface AvatarResponse {
+ avatar_url: string
+}
+
+interface AuthState {
+ user: User | null
+ token: string | null
+ isAuthenticated: boolean
+ isLoading: boolean
+ error: string | null
+ demoMode: boolean
+ hasMapsKey: boolean
+
+ login: (email: string, password: string) => Promise<AuthResponse>
+ register: (username: string, email: string, password: string) => Promise<AuthResponse>
+ logout: () => void
+ loadUser: () => Promise<void>
+ updateMapsKey: (key: string | null) => Promise<void>
+ updateApiKeys: (keys: Record<string, string | null>) => Promise<void>
+ updateProfile: (profileData: Partial<User>) => Promise<void>
+ uploadAvatar: (file: File) => Promise<AvatarResponse>
+ deleteAvatar: () => Promise<void>
+ setDemoMode: (val: boolean) => void
+ setHasMapsKey: (val: boolean) => void
+ demoLogin: () => Promise<AuthResponse>
+}
+
+export const useAuthStore = create<AuthState>((set, get) => ({
user: null,
token: localStorage.getItem('auth_token') || null,
isAuthenticated: !!localStorage.getItem('auth_token'),
@@ -11,7 +45,7 @@ export const useAuthStore = create((set, get) => ({
demoMode: localStorage.getItem('demo_mode') === 'true',
hasMapsKey: false,
- login: async (email, password) => {
+ login: async (email: string, password: string) => {
set({ isLoading: true, error: null })
try {
const data = await authApi.login({ email, password })
@@ -25,14 +59,14 @@ export const useAuthStore = create((set, get) => ({
})
connect(data.token)
return data
- } catch (err) {
- const error = err.response?.data?.error || 'Login failed'
+ } catch (err: unknown) {
+ const error = getApiErrorMessage(err, 'Login failed')
set({ isLoading: false, error })
throw new Error(error)
}
},
- register: async (username, email, password) => {
+ register: async (username: string, email: string, password: string) => {
set({ isLoading: true, error: null })
try {
const data = await authApi.register({ username, email, password })
@@ -46,8 +80,8 @@ export const useAuthStore = create((set, get) => ({
})
connect(data.token)
return data
- } catch (err) {
- const error = err.response?.data?.error || 'Registration failed'
+ } catch (err: unknown) {
+ const error = getApiErrorMessage(err, 'Registration failed')
set({ isLoading: false, error })
throw new Error(error)
}
@@ -79,7 +113,7 @@ export const useAuthStore = create((set, get) => ({
isLoading: false,
})
connect(token)
- } catch (err) {
+ } catch (err: unknown) {
localStorage.removeItem('auth_token')
set({
user: null,
@@ -90,55 +124,55 @@ export const useAuthStore = create((set, get) => ({
}
},
- updateMapsKey: async (key) => {
+ updateMapsKey: async (key: string | null) => {
try {
await authApi.updateMapsKey(key)
- set(state => ({
- user: { ...state.user, maps_api_key: key || null }
+ set((state) => ({
+ user: state.user ? { ...state.user, maps_api_key: key || null } : null,
}))
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error saving API key')
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error saving API key'))
}
},
- updateApiKeys: async (keys) => {
+ updateApiKeys: async (keys: Record<string, string | null>) => {
try {
const data = await authApi.updateApiKeys(keys)
set({ user: data.user })
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error saving API keys')
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error saving API keys'))
}
},
- updateProfile: async (profileData) => {
+ updateProfile: async (profileData: Partial<User>) => {
try {
const data = await authApi.updateSettings(profileData)
set({ user: data.user })
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error updating profile')
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error updating profile'))
}
},
- uploadAvatar: async (file) => {
+ uploadAvatar: async (file: File) => {
const formData = new FormData()
formData.append('avatar', file)
const data = await authApi.uploadAvatar(formData)
- set(state => ({ user: { ...state.user, avatar_url: data.avatar_url } }))
+ set((state) => ({ user: state.user ? { ...state.user, avatar_url: data.avatar_url } : null }))
return data
},
deleteAvatar: async () => {
await authApi.deleteAvatar()
- set(state => ({ user: { ...state.user, avatar_url: null } }))
+ set((state) => ({ user: state.user ? { ...state.user, avatar_url: null } : null }))
},
- setDemoMode: (val) => {
+ setDemoMode: (val: boolean) => {
if (val) localStorage.setItem('demo_mode', 'true')
else localStorage.removeItem('demo_mode')
set({ demoMode: val })
},
- setHasMapsKey: (val) => set({ hasMapsKey: val }),
+ setHasMapsKey: (val: boolean) => set({ hasMapsKey: val }),
demoLogin: async () => {
set({ isLoading: true, error: null })
@@ -155,8 +189,8 @@ export const useAuthStore = create((set, get) => ({
})
connect(data.token)
return data
- } catch (err) {
- const error = err.response?.data?.error || 'Demo login failed'
+ } catch (err: unknown) {
+ const error = getApiErrorMessage(err, 'Demo login failed')
set({ isLoading: false, error })
throw new Error(error)
}
diff --git a/client/src/store/settingsStore.js b/client/src/store/settingsStore.js
deleted file mode 100644
index 5f7f4552b..000000000
--- a/client/src/store/settingsStore.js
+++ /dev/null
@@ -1,61 +0,0 @@
-import { create } from 'zustand'
-import { settingsApi } from '../api/client'
-
-export const useSettingsStore = create((set, get) => ({
- settings: {
- map_tile_url: '',
- default_lat: 48.8566,
- default_lng: 2.3522,
- default_zoom: 10,
- dark_mode: false,
- default_currency: 'USD',
- language: localStorage.getItem('app_language') || 'en',
- temperature_unit: 'fahrenheit',
- time_format: '12h',
- show_place_description: false,
- },
- isLoaded: false,
-
- loadSettings: async () => {
- try {
- const data = await settingsApi.get()
- set(state => ({
- settings: { ...state.settings, ...data.settings },
- isLoaded: true,
- }))
- } catch (err) {
- set({ isLoaded: true })
- console.error('Failed to load settings:', err)
- }
- },
-
- updateSetting: async (key, value) => {
- set(state => ({
- settings: { ...state.settings, [key]: value }
- }))
- if (key === 'language') localStorage.setItem('app_language', value)
- try {
- await settingsApi.set(key, value)
- } catch (err) {
- console.error('Failed to save setting:', err)
- throw new Error(err.response?.data?.error || 'Error saving setting')
- }
- },
-
- setLanguageLocal: (lang) => {
- localStorage.setItem('app_language', lang)
- set(state => ({ settings: { ...state.settings, language: lang } }))
- },
-
- updateSettings: async (settingsObj) => {
- set(state => ({
- settings: { ...state.settings, ...settingsObj }
- }))
- try {
- await settingsApi.setBulk(settingsObj)
- } catch (err) {
- console.error('Failed to save settings:', err)
- throw new Error(err.response?.data?.error || 'Error saving settings')
- }
- },
-}))
diff --git a/client/src/store/settingsStore.ts b/client/src/store/settingsStore.ts
new file mode 100644
index 000000000..74c14c810
--- /dev/null
+++ b/client/src/store/settingsStore.ts
@@ -0,0 +1,73 @@
+import { create } from 'zustand'
+import { settingsApi } from '../api/client'
+import type { Settings } from '../types'
+import { getApiErrorMessage } from '../types'
+
+interface SettingsState {
+ settings: Settings
+ isLoaded: boolean
+
+ loadSettings: () => Promise<void>
+ updateSetting: (key: keyof Settings, value: Settings[keyof Settings]) => Promise<void>
+ setLanguageLocal: (lang: string) => void
+ updateSettings: (settingsObj: Partial<Settings>) => Promise<void>
+}
+
+export const useSettingsStore = create<SettingsState>((set, get) => ({
+ settings: {
+ map_tile_url: '',
+ default_lat: 48.8566,
+ default_lng: 2.3522,
+ default_zoom: 10,
+ dark_mode: false,
+ default_currency: 'USD',
+ language: localStorage.getItem('app_language') || 'en',
+ temperature_unit: 'fahrenheit',
+ time_format: '12h',
+ show_place_description: false,
+ },
+ isLoaded: false,
+
+ loadSettings: async () => {
+ try {
+ const data = await settingsApi.get()
+ set((state) => ({
+ settings: { ...state.settings, ...data.settings },
+ isLoaded: true,
+ }))
+ } catch (err: unknown) {
+ set({ isLoaded: true })
+ console.error('Failed to load settings:', err)
+ }
+ },
+
+ updateSetting: async (key: keyof Settings, value: Settings[keyof Settings]) => {
+ set((state) => ({
+ settings: { ...state.settings, [key]: value },
+ }))
+ if (key === 'language') localStorage.setItem('app_language', value as string)
+ try {
+ await settingsApi.set(key, value)
+ } catch (err: unknown) {
+ console.error('Failed to save setting:', err)
+ throw new Error(getApiErrorMessage(err, 'Error saving setting'))
+ }
+ },
+
+ setLanguageLocal: (lang: string) => {
+ localStorage.setItem('app_language', lang)
+ set((state) => ({ settings: { ...state.settings, language: lang } }))
+ },
+
+ updateSettings: async (settingsObj: Partial<Settings>) => {
+ set((state) => ({
+ settings: { ...state.settings, ...settingsObj },
+ }))
+ try {
+ await settingsApi.setBulk(settingsObj)
+ } catch (err: unknown) {
+ console.error('Failed to save settings:', err)
+ throw new Error(getApiErrorMessage(err, 'Error saving settings'))
+ }
+ },
+}))
diff --git a/client/src/store/slices/assignmentsSlice.ts b/client/src/store/slices/assignmentsSlice.ts
new file mode 100644
index 000000000..8d44fb507
--- /dev/null
+++ b/client/src/store/slices/assignmentsSlice.ts
@@ -0,0 +1,168 @@
+import { assignmentsApi } from '../../api/client'
+import type { StoreApi } from 'zustand'
+import type { TripStoreState } from '../tripStore'
+import type { Assignment, AssignmentsMap } from '../../types'
+import { getApiErrorMessage } from '../../types'
+
+type SetState = StoreApi<TripStoreState>['setState']
+type GetState = StoreApi<TripStoreState>['getState']
+
+export interface AssignmentsSlice {
+ assignPlaceToDay: (tripId: number | string, dayId: number | string, placeId: number | string, position?: number | null) => Promise<Assignment | undefined>
+ removeAssignment: (tripId: number | string, dayId: number | string, assignmentId: number) => Promise<void>
+ reorderAssignments: (tripId: number | string, dayId: number | string, orderedIds: number[]) => Promise<void>
+ moveAssignment: (tripId: number | string, assignmentId: number, fromDayId: number | string, toDayId: number | string, toOrderIndex?: number | null) => Promise<void>
+ setAssignments: (assignments: AssignmentsMap) => void
+}
+
+export const createAssignmentsSlice = (set: SetState, get: GetState): AssignmentsSlice => ({
+ assignPlaceToDay: async (tripId, dayId, placeId, position) => {
+ const state = get()
+ const place = state.places.find(p => p.id === parseInt(String(placeId)))
+ if (!place) return
+
+ const tempId = Date.now() * -1
+ const current = [...(state.assignments[String(dayId)] || [])]
+ const insertIdx = position != null ? position : current.length
+ const tempAssignment: Assignment = {
+ id: tempId,
+ day_id: parseInt(String(dayId)),
+ order_index: insertIdx,
+ notes: null,
+ place,
+ }
+
+ current.splice(insertIdx, 0, tempAssignment)
+ set(state => ({
+ assignments: {
+ ...state.assignments,
+ [String(dayId)]: current,
+ }
+ }))
+
+ try {
+ const data = await assignmentsApi.create(tripId, dayId, { place_id: placeId })
+ const newAssignment: Assignment = {
+ ...data.assignment,
+ place: data.assignment.place || place,
+ order_index: position != null ? insertIdx : data.assignment.order_index,
+ }
+ set(state => ({
+ assignments: {
+ ...state.assignments,
+ [String(dayId)]: state.assignments[String(dayId)].map(
+ a => a.id === tempId ? newAssignment : a
+ ),
+ }
+ }))
+ if (position != null) {
+ const updated = get().assignments[String(dayId)] || []
+ const orderedIds = updated.map(a => a.id).filter(id => id > 0)
+ if (orderedIds.length > 0) {
+ try {
+ await assignmentsApi.reorder(tripId, dayId, orderedIds)
+ set(state => {
+ const items = state.assignments[String(dayId)] || []
+ const reordered = orderedIds.map((id, idx) => {
+ const item = items.find(a => a.id === id)
+ return item ? { ...item, order_index: idx } : null
+ }).filter((item): item is Assignment => item !== null)
+ return {
+ assignments: {
+ ...state.assignments,
+ [String(dayId)]: reordered,
+ }
+ }
+ })
+ } catch {}
+ }
+ }
+ return data.assignment
+ } catch (err: unknown) {
+ set(state => ({
+ assignments: {
+ ...state.assignments,
+ [String(dayId)]: state.assignments[String(dayId)].filter(a => a.id !== tempId),
+ }
+ }))
+ throw new Error(getApiErrorMessage(err, 'Error assigning place'))
+ }
+ },
+
+ removeAssignment: async (tripId, dayId, assignmentId) => {
+ const prevAssignments = get().assignments
+
+ set(state => ({
+ assignments: {
+ ...state.assignments,
+ [String(dayId)]: state.assignments[String(dayId)].filter(a => a.id !== assignmentId),
+ }
+ }))
+
+ try {
+ await assignmentsApi.delete(tripId, dayId, assignmentId)
+ } catch (err: unknown) {
+ set({ assignments: prevAssignments })
+ throw new Error(getApiErrorMessage(err, 'Error removing assignment'))
+ }
+ },
+
+ reorderAssignments: async (tripId, dayId, orderedIds) => {
+ const prevAssignments = get().assignments
+ const dayItems = get().assignments[String(dayId)] || []
+ const reordered = orderedIds.map((id, idx) => {
+ const item = dayItems.find(a => a.id === id)
+ return item ? { ...item, order_index: idx } : null
+ }).filter((item): item is Assignment => item !== null)
+
+ set(state => ({
+ assignments: {
+ ...state.assignments,
+ [String(dayId)]: reordered,
+ }
+ }))
+
+ try {
+ await assignmentsApi.reorder(tripId, dayId, orderedIds)
+ } catch (err: unknown) {
+ set({ assignments: prevAssignments })
+ throw new Error(getApiErrorMessage(err, 'Error reordering'))
+ }
+ },
+
+ moveAssignment: async (tripId, assignmentId, fromDayId, toDayId, toOrderIndex = null) => {
+ const state = get()
+ const prevAssignments = state.assignments
+ const assignment = (state.assignments[String(fromDayId)] || []).find(a => a.id === assignmentId)
+ if (!assignment) return
+
+ const toItems = (state.assignments[String(toDayId)] || []).slice().sort((a, b) => a.order_index - b.order_index)
+ const insertAt = toOrderIndex !== null ? toOrderIndex : toItems.length
+
+ const newToItems = [...toItems]
+ newToItems.splice(insertAt, 0, { ...assignment, day_id: parseInt(String(toDayId)) })
+ newToItems.forEach((a, i) => { a.order_index = i })
+
+ set(s => ({
+ assignments: {
+ ...s.assignments,
+ [String(fromDayId)]: s.assignments[String(fromDayId)].filter(a => a.id !== assignmentId),
+ [String(toDayId)]: newToItems,
+ }
+ }))
+
+ try {
+ await assignmentsApi.move(tripId, assignmentId, toDayId, insertAt)
+ if (newToItems.length > 1) {
+ await assignmentsApi.reorder(tripId, toDayId, newToItems.map(a => a.id))
+ }
+ } catch (err: unknown) {
+ set({ assignments: prevAssignments })
+ throw new Error(getApiErrorMessage(err, 'Error moving assignment'))
+ }
+ },
+
+ setAssignments: (assignments) => {
+ set({ assignments })
+ },
+})
diff --git a/client/src/store/slices/budgetSlice.ts b/client/src/store/slices/budgetSlice.ts
new file mode 100644
index 000000000..991949fc3
--- /dev/null
+++ b/client/src/store/slices/budgetSlice.ts
@@ -0,0 +1,82 @@
+import { budgetApi } from '../../api/client'
+import type { StoreApi } from 'zustand'
+import type { TripStoreState } from '../tripStore'
+import type { BudgetItem, BudgetMember } from '../../types'
+import { getApiErrorMessage } from '../../types'
+
+type SetState = StoreApi<TripStoreState>['setState']
+type GetState = StoreApi<TripStoreState>['getState']
+
+export interface BudgetSlice {
+ loadBudgetItems: (tripId: number | string) => Promise<void>
+ addBudgetItem: (tripId: number | string, data: Partial<BudgetItem>) => Promise<BudgetItem>
+ updateBudgetItem: (tripId: number | string, id: number, data: Partial<BudgetItem>) => Promise<BudgetItem>
+ deleteBudgetItem: (tripId: number | string, id: number) => Promise<void>
+ setBudgetItemMembers: (tripId: number | string, itemId: number, userIds: number[]) => Promise<{ members: BudgetMember[]; item: BudgetItem }>
+ toggleBudgetMemberPaid: (tripId: number | string, itemId: number, userId: number, paid: boolean) => Promise<void>
+}
+
+export const createBudgetSlice = (set: SetState, get: GetState): BudgetSlice => ({
+ loadBudgetItems: async (tripId) => {
+ try {
+ const data = await budgetApi.list(tripId)
+ set({ budgetItems: data.items })
+ } catch (err: unknown) {
+ console.error('Failed to load budget items:', err)
+ }
+ },
+
+ addBudgetItem: async (tripId, data) => {
+ try {
+ const result = await budgetApi.create(tripId, data)
+ set(state => ({ budgetItems: [...state.budgetItems, result.item] }))
+ return result.item
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error adding budget item'))
+ }
+ },
+
+ updateBudgetItem: async (tripId, id, data) => {
+ try {
+ const result = await budgetApi.update(tripId, id, data)
+ set(state => ({
+ budgetItems: state.budgetItems.map(item => item.id === id ? result.item : item)
+ }))
+ return result.item
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error updating budget item'))
+ }
+ },
+
+ deleteBudgetItem: async (tripId, id) => {
+ const prev = get().budgetItems
+ set(state => ({ budgetItems: state.budgetItems.filter(item => item.id !== id) }))
+ try {
+ await budgetApi.delete(tripId, id)
+ } catch (err: unknown) {
+ set({ budgetItems: prev })
+ throw new Error(getApiErrorMessage(err, 'Error deleting budget item'))
+ }
+ },
+
+ setBudgetItemMembers: async (tripId, itemId, userIds) => {
+ const result = await budgetApi.setMembers(tripId, itemId, userIds);
+ set(state => ({
+ budgetItems: state.budgetItems.map(item =>
+ item.id === itemId ? { ...item, members: result.members, persons: result.item.persons } : item
+ )
+ }));
+ return result;
+ },
+
+ toggleBudgetMemberPaid: async (tripId, itemId, userId, paid) => {
+ await budgetApi.togglePaid(tripId, itemId, userId, paid);
+ set(state => ({
+ budgetItems: state.budgetItems.map(item =>
+ item.id === itemId
+ ? { ...item, members: (item.members || []).map(m => m.user_id === userId ? { ...m, paid } : m) }
+ : item
+ )
+ }));
+ },
+})
diff --git a/client/src/store/slices/dayNotesSlice.ts b/client/src/store/slices/dayNotesSlice.ts
new file mode 100644
index 000000000..53ab0c6d4
--- /dev/null
+++ b/client/src/store/slices/dayNotesSlice.ts
@@ -0,0 +1,135 @@
+import { daysApi, dayNotesApi } from '../../api/client'
+import type { StoreApi } from 'zustand'
+import type { TripStoreState } from '../tripStore'
+import type { DayNote } from '../../types'
+import { getApiErrorMessage } from '../../types'
+
+type SetState = StoreApi<TripStoreState>['setState']
+type GetState = StoreApi<TripStoreState>['getState']
+
+export interface DayNotesSlice {
+ updateDayNotes: (tripId: number | string, dayId: number | string, notes: string) => Promise<void>
+ updateDayTitle: (tripId: number | string, dayId: number | string, title: string) => Promise<void>
+ addDayNote: (tripId: number | string, dayId: number | string, data: Partial<DayNote>) => Promise<DayNote>
+ updateDayNote: (tripId: number | string, dayId: number | string, id: number, data: Partial<DayNote>) => Promise<DayNote>
+ deleteDayNote: (tripId: number | string, dayId: number | string, id: number) => Promise<void>
+ moveDayNote: (tripId: number | string, fromDayId: number | string, toDayId: number | string, noteId: number, sort_order?: number) => Promise<void>
+}
+
+export const createDayNotesSlice = (set: SetState, get: GetState): DayNotesSlice => ({
+ updateDayNotes: async (tripId, dayId, notes) => {
+ try {
+ await daysApi.update(tripId, dayId, { notes })
+ set(state => ({
+ days: state.days.map(d => d.id === parseInt(String(dayId)) ? { ...d, notes } : d)
+ }))
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error updating notes'))
+ }
+ },
+
+ updateDayTitle: async (tripId, dayId, title) => {
+ try {
+ await daysApi.update(tripId, dayId, { title })
+ set(state => ({
+ days: state.days.map(d => d.id === parseInt(String(dayId)) ? { ...d, title } : d)
+ }))
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error updating day name'))
+ }
+ },
+
+ addDayNote: async (tripId, dayId, data) => {
+ const tempId = Date.now() * -1
+ const tempNote: DayNote = { id: tempId, day_id: dayId as number, ...data, created_at: new Date().toISOString() } as DayNote
+ set(state => ({
+ dayNotes: {
+ ...state.dayNotes,
+ [String(dayId)]: [...(state.dayNotes[String(dayId)] || []), tempNote],
+ }
+ }))
+ try {
+ const result = await dayNotesApi.create(tripId, dayId, data)
+ set(state => ({
+ dayNotes: {
+ ...state.dayNotes,
+ [String(dayId)]: (state.dayNotes[String(dayId)] || []).map(n => n.id === tempId ? result.note : n),
+ }
+ }))
+ return result.note
+ } catch (err: unknown) {
+ set(state => ({
+ dayNotes: {
+ ...state.dayNotes,
+ [String(dayId)]: (state.dayNotes[String(dayId)] || []).filter(n => n.id !== tempId),
+ }
+ }))
+ throw new Error(getApiErrorMessage(err, 'Error adding note'))
+ }
+ },
+
+ updateDayNote: async (tripId, dayId, id, data) => {
+ try {
+ const result = await dayNotesApi.update(tripId, dayId, id, data)
+ set(state => ({
+ dayNotes: {
+ ...state.dayNotes,
+ [String(dayId)]: (state.dayNotes[String(dayId)] || []).map(n => n.id === id ? result.note : n),
+ }
+ }))
+ return result.note
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error updating note'))
+ }
+ },
+
+ deleteDayNote: async (tripId, dayId, id) => {
+ const prev = get().dayNotes
+ set(state => ({
+ dayNotes: {
+ ...state.dayNotes,
+ [String(dayId)]: (state.dayNotes[String(dayId)] || []).filter(n => n.id !== id),
+ }
+ }))
+ try {
+ await dayNotesApi.delete(tripId, dayId, id)
+ } catch (err: unknown) {
+ set({ dayNotes: prev })
+ throw new Error(getApiErrorMessage(err, 'Error deleting note'))
+ }
+ },
+
+ moveDayNote: async (tripId, fromDayId, toDayId, noteId, sort_order = 9999) => {
+ const state = get()
+ const note = (state.dayNotes[String(fromDayId)] || []).find(n => n.id === noteId)
+ if (!note) return
+
+ set(s => ({
+ dayNotes: {
+ ...s.dayNotes,
+ [String(fromDayId)]: (s.dayNotes[String(fromDayId)] || []).filter(n => n.id !== noteId),
+ }
+ }))
+
+ try {
+ await dayNotesApi.delete(tripId, fromDayId, noteId)
+ const result = await dayNotesApi.create(tripId, toDayId, {
+ text: note.text, time: note.time, icon: note.icon, sort_order,
+ })
+ set(s => ({
+ dayNotes: {
+ ...s.dayNotes,
+ [String(toDayId)]: [...(s.dayNotes[String(toDayId)] || []), result.note],
+ }
+ }))
+ } catch (err: unknown) {
+ set(s => ({
+ dayNotes: {
+ ...s.dayNotes,
+ [String(fromDayId)]: [...(s.dayNotes[String(fromDayId)] || []), note],
+ }
+ }))
+ throw new Error(getApiErrorMessage(err, 'Error moving note'))
+ }
+ },
+})
diff --git a/client/src/store/slices/filesSlice.ts b/client/src/store/slices/filesSlice.ts
new file mode 100644
index 000000000..07ed0deb3
--- /dev/null
+++ b/client/src/store/slices/filesSlice.ts
@@ -0,0 +1,44 @@
+import { filesApi } from '../../api/client'
+import type { StoreApi } from 'zustand'
+import type { TripStoreState } from '../tripStore'
+import type { TripFile } from '../../types'
+import { getApiErrorMessage } from '../../types'
+
+type SetState = StoreApi<TripStoreState>['setState']
+type GetState = StoreApi<TripStoreState>['getState']
+
+export interface FilesSlice {
+ loadFiles: (tripId: number | string) => Promise<void>
+ addFile: (tripId: number | string, formData: FormData) => Promise<TripFile>
+ deleteFile: (tripId: number | string, id: number) => Promise<void>
+}
+
+export const createFilesSlice = (set: SetState, get: GetState): FilesSlice => ({
+ loadFiles: async (tripId) => {
+ try {
+ const data = await filesApi.list(tripId)
+ set({ files: data.files })
+ } catch (err: unknown) {
+ console.error('Failed to load files:', err)
+ }
+ },
+
+ addFile: async (tripId, formData) => {
+ try {
+ const data = await filesApi.upload(tripId, formData)
+ set(state => ({ files: [data.file, ...state.files] }))
+ return data.file
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error uploading file'))
+ }
+ },
+
+ deleteFile: async (tripId, id) => {
+ try {
+ await filesApi.delete(tripId, id)
+ set(state => ({ files: state.files.filter(f => f.id !== id) }))
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error deleting file'))
+ }
+ },
+})
diff --git a/client/src/store/slices/packingSlice.ts b/client/src/store/slices/packingSlice.ts
new file mode 100644
index 000000000..adc74d85f
--- /dev/null
+++ b/client/src/store/slices/packingSlice.ts
@@ -0,0 +1,67 @@
+import { packingApi } from '../../api/client'
+import type { StoreApi } from 'zustand'
+import type { TripStoreState } from '../tripStore'
+import type { PackingItem } from '../../types'
+import { getApiErrorMessage } from '../../types'
+
+type SetState = StoreApi<TripStoreState>['setState']
+type GetState = StoreApi<TripStoreState>['getState']
+
+export interface PackingSlice {
+ addPackingItem: (tripId: number | string, data: Partial<PackingItem>) => Promise<PackingItem>
+ updatePackingItem: (tripId: number | string, id: number, data: Partial<PackingItem>) => Promise<PackingItem>
+ deletePackingItem: (tripId: number | string, id: number) => Promise<void>
+ togglePackingItem: (tripId: number | string, id: number, checked: boolean) => Promise<void>
+}
+
+export const createPackingSlice = (set: SetState, get: GetState): PackingSlice => ({
+ addPackingItem: async (tripId, data) => {
+ try {
+ const result = await packingApi.create(tripId, data)
+ set(state => ({ packingItems: [...state.packingItems, result.item] }))
+ return result.item
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error adding item'))
+ }
+ },
+
+ updatePackingItem: async (tripId, id, data) => {
+ try {
+ const result = await packingApi.update(tripId, id, data)
+ set(state => ({
+ packingItems: state.packingItems.map(item => item.id === id ? result.item : item)
+ }))
+ return result.item
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error updating item'))
+ }
+ },
+
+ deletePackingItem: async (tripId, id) => {
+ const prev = get().packingItems
+ set(state => ({ packingItems: state.packingItems.filter(item => item.id !== id) }))
+ try {
+ await packingApi.delete(tripId, id)
+ } catch (err: unknown) {
+ set({ packingItems: prev })
+ throw new Error(getApiErrorMessage(err, 'Error deleting item'))
+ }
+ },
+
+ togglePackingItem: async (tripId, id, checked) => {
+ set(state => ({
+ packingItems: state.packingItems.map(item =>
+ item.id === id ? { ...item, checked: checked ? 1 : 0 } : item
+ )
+ }))
+ try {
+ await packingApi.update(tripId, id, { checked })
+ } catch {
+ set(state => ({
+ packingItems: state.packingItems.map(item =>
+ item.id === id ? { ...item, checked: checked ? 0 : 1 } : item
+ )
+ }))
+ }
+ },
+})
diff --git a/client/src/store/slices/placesSlice.ts b/client/src/store/slices/placesSlice.ts
new file mode 100644
index 000000000..834d0bd30
--- /dev/null
+++ b/client/src/store/slices/placesSlice.ts
@@ -0,0 +1,71 @@
+import { placesApi } from '../../api/client'
+import type { StoreApi } from 'zustand'
+import type { TripStoreState } from '../tripStore'
+import type { Place, Assignment } from '../../types'
+import { getApiErrorMessage } from '../../types'
+
+type SetState = StoreApi<TripStoreState>['setState']
+type GetState = StoreApi<TripStoreState>['getState']
+
+export interface PlacesSlice {
+ refreshPlaces: (tripId: number | string) => Promise<void>
+ addPlace: (tripId: number | string, placeData: Partial<Place>) => Promise<Place>
+ updatePlace: (tripId: number | string, placeId: number, placeData: Partial<Place>) => Promise<Place>
+ deletePlace: (tripId: number | string, placeId: number) => Promise<void>
+}
+
+export const createPlacesSlice = (set: SetState, get: GetState): PlacesSlice => ({
+ refreshPlaces: async (tripId) => {
+ try {
+ const data = await placesApi.list(tripId)
+ set({ places: data.places })
+ } catch (err: unknown) {
+ console.error('Failed to refresh places:', err)
+ }
+ },
+
+ addPlace: async (tripId, placeData) => {
+ try {
+ const data = await placesApi.create(tripId, placeData)
+ set(state => ({ places: [data.place, ...state.places] }))
+ return data.place
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error adding place'))
+ }
+ },
+
+ updatePlace: async (tripId, placeId, placeData) => {
+ try {
+ const data = await placesApi.update(tripId, placeId, placeData)
+ set(state => ({
+ places: state.places.map(p => p.id === placeId ? data.place : p),
+ assignments: Object.fromEntries(
+ Object.entries(state.assignments).map(([dayId, items]) => [
+ dayId,
+ items.map((a: Assignment) => a.place?.id === placeId ? { ...a, place: { ...data.place, place_time: a.place.place_time, end_time: a.place.end_time } } : a)
+ ])
+ ),
+ }))
+ return data.place
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error updating place'))
+ }
+ },
+
+ deletePlace: async (tripId, placeId) => {
+ try {
+ await placesApi.delete(tripId, placeId)
+ set(state => ({
+ places: state.places.filter(p => p.id !== placeId),
+ assignments: Object.fromEntries(
+ Object.entries(state.assignments).map(([dayId, items]) => [
+ dayId,
+ items.filter((a: Assignment) => a.place?.id !== placeId)
+ ])
+ ),
+ }))
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error deleting place'))
+ }
+ },
+})
diff --git a/client/src/store/slices/remoteEventHandler.ts b/client/src/store/slices/remoteEventHandler.ts
new file mode 100644
index 000000000..89e5e2770
--- /dev/null
+++ b/client/src/store/slices/remoteEventHandler.ts
@@ -0,0 +1,239 @@
+import type { StoreApi } from 'zustand'
+import type { TripStoreState } from '../tripStore'
+import type { Assignment, Place, Day, DayNote, PackingItem, BudgetItem, BudgetMember, Reservation, Trip, TripFile, WebSocketEvent } from '../../types'
+
+type SetState = StoreApi<TripStoreState>['setState']
+
+/**
+ * Applies a remote WebSocket event to the local Zustand store, keeping state in sync across collaborators.
+ * Each event type maps to an immutable state update (create/update/delete) for the relevant entity.
+ */
+export function handleRemoteEvent(set: SetState, event: WebSocketEvent): void {
+ const { type, ...payload } = event
+
+ set(state => {
+ switch (type) {
+ // Places
+ case 'place:created':
+ if (state.places.some(p => p.id === (payload.place as Place).id)) return {}
+ return { places: [payload.place as Place, ...state.places] }
+ case 'place:updated':
+ return {
+ places: state.places.map(p => p.id === (payload.place as Place).id ? payload.place as Place : p),
+ assignments: Object.fromEntries(
+ Object.entries(state.assignments).map(([dayId, items]) => [
+ dayId,
+ items.map(a => a.place?.id === (payload.place as Place).id ? { ...a, place: payload.place as Place } : a)
+ ])
+ ),
+ }
+ case 'place:deleted':
+ return {
+ places: state.places.filter(p => p.id !== payload.placeId),
+ assignments: Object.fromEntries(
+ Object.entries(state.assignments).map(([dayId, items]) => [
+ dayId,
+ items.filter(a => a.place?.id !== payload.placeId)
+ ])
+ ),
+ }
+
+ // Assignments
+ case 'assignment:created': {
+ const dayKey = String((payload.assignment as Assignment).day_id)
+ const existing = (state.assignments[dayKey] || [])
+ const placeId = (payload.assignment as Assignment).place?.id || (payload.assignment as Assignment).place_id
+ if (existing.some(a => a.id === (payload.assignment as Assignment).id || (placeId && a.place?.id === placeId))) {
+ const hasTempVersion = existing.some(a => a.id < 0 && a.place?.id === placeId)
+ if (hasTempVersion) {
+ return {
+ assignments: {
+ ...state.assignments,
+ [dayKey]: existing.map(a => (a.id < 0 && a.place?.id === placeId) ? payload.assignment as Assignment : a),
+ }
+ }
+ }
+ return {}
+ }
+ return {
+ assignments: {
+ ...state.assignments,
+ [dayKey]: [...existing, payload.assignment as Assignment],
+ }
+ }
+ }
+ case 'assignment:updated': {
+ const dayKey = String((payload.assignment as Assignment).day_id)
+ return {
+ assignments: {
+ ...state.assignments,
+ [dayKey]: (state.assignments[dayKey] || []).map(a =>
+ a.id === (payload.assignment as Assignment).id ? { ...a, ...(payload.assignment as Assignment) } : a
+ ),
+ }
+ }
+ }
+ case 'assignment:deleted': {
+ const dayKey = String(payload.dayId)
+ return {
+ assignments: {
+ ...state.assignments,
+ [dayKey]: (state.assignments[dayKey] || []).filter(a => a.id !== payload.assignmentId),
+ }
+ }
+ }
+ case 'assignment:moved': {
+ const oldKey = String(payload.oldDayId)
+ const newKey = String(payload.newDayId)
+ const movedAssignment = payload.assignment as Assignment
+ return {
+ assignments: {
+ ...state.assignments,
+ [oldKey]: (state.assignments[oldKey] || []).filter(a => a.id !== movedAssignment.id),
+ [newKey]: [...(state.assignments[newKey] || []).filter(a => a.id !== movedAssignment.id), movedAssignment],
+ }
+ }
+ }
+ case 'assignment:reordered': {
+ const dayKey = String(payload.dayId)
+ const currentItems = state.assignments[dayKey] || []
+ const orderedIds: number[] = payload.orderedIds || []
+ const reordered = orderedIds.map((id, idx) => {
+ const item = currentItems.find(a => a.id === id)
+ return item ? { ...item, order_index: idx } : null
+ }).filter((item): item is Assignment => item !== null)
+ return {
+ assignments: {
+ ...state.assignments,
+ [dayKey]: reordered,
+ }
+ }
+ }
+
+ // Days
+ case 'day:created':
+ if (state.days.some(d => d.id === (payload.day as Day).id)) return {}
+ return { days: [...state.days, payload.day as Day] }
+ case 'day:updated':
+ return {
+ days: state.days.map(d => d.id === (payload.day as Day).id ? payload.day as Day : d),
+ }
+ case 'day:deleted': {
+ const removedDayId = String(payload.dayId)
+ const newAssignments = { ...state.assignments }
+ delete newAssignments[removedDayId]
+ const newDayNotes = { ...state.dayNotes }
+ delete newDayNotes[removedDayId]
+ return {
+ days: state.days.filter(d => d.id !== payload.dayId),
+ assignments: newAssignments,
+ dayNotes: newDayNotes,
+ }
+ }
+
+ // Day Notes
+ case 'dayNote:created': {
+ const dayKey = String(payload.dayId)
+ const existingNotes = (state.dayNotes[dayKey] || [])
+ if (existingNotes.some(n => n.id === (payload.note as DayNote).id)) return {}
+ return {
+ dayNotes: {
+ ...state.dayNotes,
+ [dayKey]: [...existingNotes, payload.note as DayNote],
+ }
+ }
+ }
+ case 'dayNote:updated': {
+ const dayKey = String(payload.dayId)
+ return {
+ dayNotes: {
+ ...state.dayNotes,
+ [dayKey]: (state.dayNotes[dayKey] || []).map(n => n.id === (payload.note as DayNote).id ? payload.note as DayNote : n),
+ }
+ }
+ }
+ case 'dayNote:deleted': {
+ const dayKey = String(payload.dayId)
+ return {
+ dayNotes: {
+ ...state.dayNotes,
+ [dayKey]: (state.dayNotes[dayKey] || []).filter(n => n.id !== payload.noteId),
+ }
+ }
+ }
+
+ // Packing
+ case 'packing:created':
+ if (state.packingItems.some(i => i.id === (payload.item as PackingItem).id)) return {}
+ return { packingItems: [...state.packingItems, payload.item as PackingItem] }
+ case 'packing:updated':
+ return {
+ packingItems: state.packingItems.map(i => i.id === (payload.item as PackingItem).id ? payload.item as PackingItem : i),
+ }
+ case 'packing:deleted':
+ return {
+ packingItems: state.packingItems.filter(i => i.id !== payload.itemId),
+ }
+
+ // Budget
+ case 'budget:created':
+ if (state.budgetItems.some(i => i.id === (payload.item as BudgetItem).id)) return {}
+ return { budgetItems: [...state.budgetItems, payload.item as BudgetItem] }
+ case 'budget:updated':
+ return {
+ budgetItems: state.budgetItems.map(i => i.id === (payload.item as BudgetItem).id ? payload.item as BudgetItem : i),
+ }
+ case 'budget:deleted':
+ return {
+ budgetItems: state.budgetItems.filter(i => i.id !== payload.itemId),
+ }
+ case 'budget:members-updated':
+ return {
+ budgetItems: state.budgetItems.map(i =>
+ i.id === payload.itemId ? { ...i, members: payload.members as BudgetMember[], persons: payload.persons as number } : i
+ ),
+ }
+ case 'budget:member-paid-updated':
+ return {
+ budgetItems: state.budgetItems.map(i =>
+ i.id === payload.itemId
+ ? { ...i, members: (i.members || []).map(m => m.user_id === payload.userId ? { ...m, paid: payload.paid } : m) }
+ : i
+ ),
+ }
+
+ // Reservations
+ case 'reservation:created':
+ if (state.reservations.some(r => r.id === (payload.reservation as Reservation).id)) return {}
+ return { reservations: [payload.reservation as Reservation, ...state.reservations] }
+ case 'reservation:updated':
+ return {
+ reservations: state.reservations.map(r => r.id === (payload.reservation as Reservation).id ? payload.reservation as Reservation : r),
+ }
+ case 'reservation:deleted':
+ return {
+ reservations: state.reservations.filter(r => r.id !== payload.reservationId),
+ }
+
+ // Trip
+ case 'trip:updated':
+ return { trip: payload.trip as Trip }
+
+ // Files
+ case 'file:created':
+ if (state.files.some(f => f.id === (payload.file as TripFile).id)) return {}
+ return { files: [payload.file as TripFile, ...state.files] }
+ case 'file:updated':
+ return {
+ files: state.files.map(f => f.id === (payload.file as TripFile).id ? payload.file as TripFile : f),
+ }
+ case 'file:deleted':
+ return {
+ files: state.files.filter(f => f.id !== payload.fileId),
+ }
+
+ default:
+ return {}
+ }
+ })
+}
diff --git a/client/src/store/slices/reservationsSlice.ts b/client/src/store/slices/reservationsSlice.ts
new file mode 100644
index 000000000..536d4cb10
--- /dev/null
+++ b/client/src/store/slices/reservationsSlice.ts
@@ -0,0 +1,73 @@
+import { reservationsApi } from '../../api/client'
+import type { StoreApi } from 'zustand'
+import type { TripStoreState } from '../tripStore'
+import type { Reservation } from '../../types'
+import { getApiErrorMessage } from '../../types'
+
+type SetState = StoreApi<TripStoreState>['setState']
+type GetState = StoreApi<TripStoreState>['getState']
+
+export interface ReservationsSlice {
+ loadReservations: (tripId: number | string) => Promise<void>
+ addReservation: (tripId: number | string, data: Partial<Reservation>) => Promise<Reservation>
+ updateReservation: (tripId: number | string, id: number, data: Partial<Reservation>) => Promise<Reservation>
+ toggleReservationStatus: (tripId: number | string, id: number) => Promise<void>
+ deleteReservation: (tripId: number | string, id: number) => Promise<void>
+}
+
+export const createReservationsSlice = (set: SetState, get: GetState): ReservationsSlice => ({
+ loadReservations: async (tripId) => {
+ try {
+ const data = await reservationsApi.list(tripId)
+ set({ reservations: data.reservations })
+ } catch (err: unknown) {
+ console.error('Failed to load reservations:', err)
+ }
+ },
+
+ addReservation: async (tripId, data) => {
+ try {
+ const result = await reservationsApi.create(tripId, data)
+ set(state => ({ reservations: [result.reservation, ...state.reservations] }))
+ return result.reservation
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error creating reservation'))
+ }
+ },
+
+ updateReservation: async (tripId, id, data) => {
+ try {
+ const result = await reservationsApi.update(tripId, id, data)
+ set(state => ({
+ reservations: state.reservations.map(r => r.id === id ? result.reservation : r)
+ }))
+ return result.reservation
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error updating reservation'))
+ }
+ },
+
+ toggleReservationStatus: async (tripId, id) => {
+ const prev = get().reservations
+ const current = prev.find(r => r.id === id)
+ if (!current) return
+ const newStatus: 'pending' | 'confirmed' = current.status === 'confirmed' ? 'pending' : 'confirmed'
+ set(state => ({
+ reservations: state.reservations.map(r => r.id === id ? { ...r, status: newStatus } : r)
+ }))
+ try {
+ await reservationsApi.update(tripId, id, { status: newStatus })
+ } catch {
+ set({ reservations: prev })
+ }
+ },
+
+ deleteReservation: async (tripId, id) => {
+ try {
+ await reservationsApi.delete(tripId, id)
+ set(state => ({ reservations: state.reservations.filter(r => r.id !== id) }))
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error deleting reservation'))
+ }
+ },
+})
diff --git a/client/src/store/tripStore.js b/client/src/store/tripStore.js
deleted file mode 100644
index a287f66ac..000000000
--- a/client/src/store/tripStore.js
+++ /dev/null
@@ -1,863 +0,0 @@
-import { create } from 'zustand'
-import { tripsApi, daysApi, placesApi, assignmentsApi, packingApi, tagsApi, categoriesApi, budgetApi, filesApi, reservationsApi, dayNotesApi } from '../api/client'
-
-export const useTripStore = create((set, get) => ({
- trip: null,
- days: [],
- places: [],
- assignments: {}, // { [dayId]: [assignment objects] }
- dayNotes: {}, // { [dayId]: [note objects] }
- packingItems: [],
- tags: [],
- categories: [],
- budgetItems: [],
- files: [],
- reservations: [],
- selectedDayId: null,
- isLoading: false,
- error: null,
-
- setSelectedDay: (dayId) => set({ selectedDayId: dayId }),
-
- // Handle remote WebSocket events without making API calls
- handleRemoteEvent: (event) => {
- const { type, ...payload } = event
-
- set(state => {
- switch (type) {
- // Places
- case 'place:created':
- if (state.places.some(p => p.id === payload.place.id)) return {}
- return { places: [payload.place, ...state.places] }
- case 'place:updated':
- return {
- places: state.places.map(p => p.id === payload.place.id ? payload.place : p),
- assignments: Object.fromEntries(
- Object.entries(state.assignments).map(([dayId, items]) => [
- dayId,
- items.map(a => a.place?.id === payload.place.id ? { ...a, place: payload.place } : a)
- ])
- ),
- }
- case 'place:deleted':
- return {
- places: state.places.filter(p => p.id !== payload.placeId),
- assignments: Object.fromEntries(
- Object.entries(state.assignments).map(([dayId, items]) => [
- dayId,
- items.filter(a => a.place?.id !== payload.placeId)
- ])
- ),
- }
-
- // Assignments
- case 'assignment:created': {
- const dayKey = String(payload.assignment.day_id)
- const existing = (state.assignments[dayKey] || [])
- // Skip if already present (by id OR by place_id to handle optimistic temp ids)
- const placeId = payload.assignment.place?.id || payload.assignment.place_id
- if (existing.some(a => a.id === payload.assignment.id || (placeId && a.place?.id === placeId))) {
- // Replace temp entry with server version if needed
- const hasTempVersion = existing.some(a => a.id < 0 && a.place?.id === placeId)
- if (hasTempVersion) {
- return {
- assignments: {
- ...state.assignments,
- [dayKey]: existing.map(a => (a.id < 0 && a.place?.id === placeId) ? payload.assignment : a),
- }
- }
- }
- return {}
- }
- return {
- assignments: {
- ...state.assignments,
- [dayKey]: [...existing, payload.assignment],
- }
- }
- }
- case 'assignment:updated': {
- const dayKey = String(payload.assignment.day_id)
- return {
- assignments: {
- ...state.assignments,
- [dayKey]: (state.assignments[dayKey] || []).map(a =>
- a.id === payload.assignment.id ? { ...a, ...payload.assignment } : a
- ),
- }
- }
- }
- case 'assignment:deleted': {
- const dayKey = String(payload.dayId)
- return {
- assignments: {
- ...state.assignments,
- [dayKey]: (state.assignments[dayKey] || []).filter(a => a.id !== payload.assignmentId),
- }
- }
- }
- case 'assignment:moved': {
- const oldKey = String(payload.oldDayId)
- const newKey = String(payload.newDayId)
- const movedAssignment = payload.assignment
- return {
- assignments: {
- ...state.assignments,
- [oldKey]: (state.assignments[oldKey] || []).filter(a => a.id !== movedAssignment.id),
- [newKey]: [...(state.assignments[newKey] || []).filter(a => a.id !== movedAssignment.id), movedAssignment],
- }
- }
- }
- case 'assignment:reordered': {
- const dayKey = String(payload.dayId)
- const currentItems = state.assignments[dayKey] || []
- const orderedIds = payload.orderedIds || []
- const reordered = orderedIds.map((id, idx) => {
- const item = currentItems.find(a => a.id === id)
- return item ? { ...item, order_index: idx } : null
- }).filter(Boolean)
- return {
- assignments: {
- ...state.assignments,
- [dayKey]: reordered,
- }
- }
- }
-
- // Days
- case 'day:created':
- if (state.days.some(d => d.id === payload.day.id)) return {}
- return { days: [...state.days, payload.day] }
- case 'day:updated':
- return {
- days: state.days.map(d => d.id === payload.day.id ? payload.day : d),
- }
- case 'day:deleted': {
- const removedDayId = String(payload.dayId)
- const newAssignments = { ...state.assignments }
- delete newAssignments[removedDayId]
- const newDayNotes = { ...state.dayNotes }
- delete newDayNotes[removedDayId]
- return {
- days: state.days.filter(d => d.id !== payload.dayId),
- assignments: newAssignments,
- dayNotes: newDayNotes,
- }
- }
-
- // Day Notes
- case 'dayNote:created': {
- const dayKey = String(payload.dayId)
- const existingNotes = (state.dayNotes[dayKey] || [])
- if (existingNotes.some(n => n.id === payload.note.id)) return {}
- return {
- dayNotes: {
- ...state.dayNotes,
- [dayKey]: [...existingNotes, payload.note],
- }
- }
- }
- case 'dayNote:updated': {
- const dayKey = String(payload.dayId)
- return {
- dayNotes: {
- ...state.dayNotes,
- [dayKey]: (state.dayNotes[dayKey] || []).map(n => n.id === payload.note.id ? payload.note : n),
- }
- }
- }
- case 'dayNote:deleted': {
- const dayKey = String(payload.dayId)
- return {
- dayNotes: {
- ...state.dayNotes,
- [dayKey]: (state.dayNotes[dayKey] || []).filter(n => n.id !== payload.noteId),
- }
- }
- }
-
- // Packing
- case 'packing:created':
- if (state.packingItems.some(i => i.id === payload.item.id)) return {}
- return { packingItems: [...state.packingItems, payload.item] }
- case 'packing:updated':
- return {
- packingItems: state.packingItems.map(i => i.id === payload.item.id ? payload.item : i),
- }
- case 'packing:deleted':
- return {
- packingItems: state.packingItems.filter(i => i.id !== payload.itemId),
- }
-
- // Budget
- case 'budget:created':
- if (state.budgetItems.some(i => i.id === payload.item.id)) return {}
- return { budgetItems: [...state.budgetItems, payload.item] }
- case 'budget:updated':
- return {
- budgetItems: state.budgetItems.map(i => i.id === payload.item.id ? payload.item : i),
- }
- case 'budget:deleted':
- return {
- budgetItems: state.budgetItems.filter(i => i.id !== payload.itemId),
- }
- case 'budget:members-updated':
- return {
- budgetItems: state.budgetItems.map(i =>
- i.id === payload.itemId ? { ...i, members: payload.members, persons: payload.persons } : i
- ),
- }
- case 'budget:member-paid-updated':
- return {
- budgetItems: state.budgetItems.map(i =>
- i.id === payload.itemId
- ? { ...i, members: (i.members || []).map(m => m.user_id === payload.userId ? { ...m, paid: payload.paid } : m) }
- : i
- ),
- }
-
- // Reservations
- case 'reservation:created':
- if (state.reservations.some(r => r.id === payload.reservation.id)) return {}
- return { reservations: [payload.reservation, ...state.reservations] }
- case 'reservation:updated':
- return {
- reservations: state.reservations.map(r => r.id === payload.reservation.id ? payload.reservation : r),
- }
- case 'reservation:deleted':
- return {
- reservations: state.reservations.filter(r => r.id !== payload.reservationId),
- }
-
- // Trip
- case 'trip:updated':
- return { trip: payload.trip }
-
- // Files
- case 'file:created':
- if (state.files.some(f => f.id === payload.file.id)) return {}
- return { files: [payload.file, ...state.files] }
- case 'file:updated':
- return {
- files: state.files.map(f => f.id === payload.file.id ? payload.file : f),
- }
- case 'file:deleted':
- return {
- files: state.files.filter(f => f.id !== payload.fileId),
- }
-
- default:
- return {}
- }
- })
- },
-
- // Load everything for a trip
- loadTrip: async (tripId) => {
- set({ isLoading: true, error: null })
- try {
- const [tripData, daysData, placesData, packingData, tagsData, categoriesData] = await Promise.all([
- tripsApi.get(tripId),
- daysApi.list(tripId),
- placesApi.list(tripId),
- packingApi.list(tripId),
- tagsApi.list(),
- categoriesApi.list(),
- ])
-
- const assignmentsMap = {}
- const dayNotesMap = {}
- for (const day of daysData.days) {
- assignmentsMap[String(day.id)] = day.assignments || []
- dayNotesMap[String(day.id)] = day.notes_items || []
- }
-
- set({
- trip: tripData.trip,
- days: daysData.days,
- places: placesData.places,
- assignments: assignmentsMap,
- dayNotes: dayNotesMap,
- packingItems: packingData.items,
- tags: tagsData.tags,
- categories: categoriesData.categories,
- isLoading: false,
- })
- } catch (err) {
- set({ isLoading: false, error: err.message })
- throw err
- }
- },
-
- refreshDays: async (tripId) => {
- try {
- const daysData = await daysApi.list(tripId)
- const assignmentsMap = {}
- const dayNotesMap = {}
- for (const day of daysData.days) {
- assignmentsMap[String(day.id)] = day.assignments || []
- dayNotesMap[String(day.id)] = day.notes_items || []
- }
- set({ days: daysData.days, assignments: assignmentsMap, dayNotes: dayNotesMap })
- } catch (err) {
- console.error('Failed to refresh days:', err)
- }
- },
-
- refreshPlaces: async (tripId) => {
- try {
- const data = await placesApi.list(tripId)
- set({ places: data.places })
- } catch (err) {
- console.error('Failed to refresh places:', err)
- }
- },
-
- addPlace: async (tripId, placeData) => {
- try {
- const data = await placesApi.create(tripId, placeData)
- set(state => ({ places: [data.place, ...state.places] }))
- return data.place
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error adding place')
- }
- },
-
- updatePlace: async (tripId, placeId, placeData) => {
- try {
- const data = await placesApi.update(tripId, placeId, placeData)
- set(state => ({
- places: state.places.map(p => p.id === placeId ? data.place : p),
- assignments: Object.fromEntries(
- Object.entries(state.assignments).map(([dayId, items]) => [
- dayId,
- items.map(a => a.place?.id === placeId ? { ...a, place: { ...data.place, place_time: a.place.place_time, end_time: a.place.end_time } } : a)
- ])
- ),
- }))
- return data.place
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error updating place')
- }
- },
-
- deletePlace: async (tripId, placeId) => {
- try {
- await placesApi.delete(tripId, placeId)
- set(state => ({
- places: state.places.filter(p => p.id !== placeId),
- assignments: Object.fromEntries(
- Object.entries(state.assignments).map(([dayId, items]) => [
- dayId,
- items.filter(a => a.place?.id !== placeId)
- ])
- ),
- }))
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error deleting place')
- }
- },
-
- assignPlaceToDay: async (tripId, dayId, placeId, position) => {
- const state = get()
- const place = state.places.find(p => p.id === parseInt(placeId))
- if (!place) return
-
- const tempId = Date.now() * -1
- const current = [...(state.assignments[String(dayId)] || [])]
- const insertIdx = position != null ? position : current.length
- const tempAssignment = {
- id: tempId,
- day_id: parseInt(dayId),
- order_index: insertIdx,
- notes: null,
- place,
- }
-
- current.splice(insertIdx, 0, tempAssignment)
- set(state => ({
- assignments: {
- ...state.assignments,
- [String(dayId)]: current,
- }
- }))
-
- try {
- const data = await assignmentsApi.create(tripId, dayId, { place_id: placeId })
- const newAssignment = {
- ...data.assignment,
- place: data.assignment.place || place,
- order_index: position != null ? insertIdx : data.assignment.order_index,
- }
- set(state => ({
- assignments: {
- ...state.assignments,
- [String(dayId)]: state.assignments[String(dayId)].map(
- a => a.id === tempId ? newAssignment : a
- ),
- }
- }))
- // Reihenfolge am Server aktualisieren und lokalen State mit Server-Antwort synchronisieren
- if (position != null) {
- const updated = get().assignments[String(dayId)] || []
- const orderedIds = updated.map(a => a.id).filter(id => id > 0)
- if (orderedIds.length > 0) {
- try {
- await assignmentsApi.reorder(tripId, dayId, orderedIds)
- // Lokalen State auf die gesendete Reihenfolge setzen
- set(state => {
- const items = state.assignments[String(dayId)] || []
- const reordered = orderedIds.map((id, idx) => {
- const item = items.find(a => a.id === id)
- return item ? { ...item, order_index: idx } : null
- }).filter(Boolean)
- return {
- assignments: {
- ...state.assignments,
- [String(dayId)]: reordered,
- }
- }
- })
- } catch {}
- }
- }
- return data.assignment
- } catch (err) {
- set(state => ({
- assignments: {
- ...state.assignments,
- [String(dayId)]: state.assignments[String(dayId)].filter(a => a.id !== tempId),
- }
- }))
- throw new Error(err.response?.data?.error || 'Error assigning place')
- }
- },
-
- removeAssignment: async (tripId, dayId, assignmentId) => {
- const prevAssignments = get().assignments
-
- set(state => ({
- assignments: {
- ...state.assignments,
- [String(dayId)]: state.assignments[String(dayId)].filter(a => a.id !== assignmentId),
- }
- }))
-
- try {
- await assignmentsApi.delete(tripId, dayId, assignmentId)
- } catch (err) {
- set({ assignments: prevAssignments })
- throw new Error(err.response?.data?.error || 'Error removing assignment')
- }
- },
-
- reorderAssignments: async (tripId, dayId, orderedIds) => {
- const prevAssignments = get().assignments
- const dayItems = get().assignments[String(dayId)] || []
- const reordered = orderedIds.map((id, idx) => {
- const item = dayItems.find(a => a.id === id)
- return item ? { ...item, order_index: idx } : null
- }).filter(Boolean)
-
- set(state => ({
- assignments: {
- ...state.assignments,
- [String(dayId)]: reordered,
- }
- }))
-
- try {
- await assignmentsApi.reorder(tripId, dayId, orderedIds)
- } catch (err) {
- set({ assignments: prevAssignments })
- throw new Error(err.response?.data?.error || 'Error reordering')
- }
- },
-
- moveAssignment: async (tripId, assignmentId, fromDayId, toDayId, toOrderIndex = null) => {
- const state = get()
- const prevAssignments = state.assignments
- const assignment = (state.assignments[String(fromDayId)] || []).find(a => a.id === assignmentId)
- if (!assignment) return
-
- const toItems = (state.assignments[String(toDayId)] || []).slice().sort((a, b) => a.order_index - b.order_index)
- const insertAt = toOrderIndex !== null ? toOrderIndex : toItems.length
-
- // Build new order for target day with item inserted at correct position
- const newToItems = [...toItems]
- newToItems.splice(insertAt, 0, { ...assignment, day_id: parseInt(toDayId) })
- newToItems.forEach((a, i) => { a.order_index = i })
-
- set(s => ({
- assignments: {
- ...s.assignments,
- [String(fromDayId)]: s.assignments[String(fromDayId)].filter(a => a.id !== assignmentId),
- [String(toDayId)]: newToItems,
- }
- }))
-
- try {
- await assignmentsApi.move(tripId, assignmentId, toDayId, insertAt)
- if (newToItems.length > 1) {
- await assignmentsApi.reorder(tripId, toDayId, newToItems.map(a => a.id))
- }
- } catch (err) {
- set({ assignments: prevAssignments })
- throw new Error(err.response?.data?.error || 'Error moving assignment')
- }
- },
-
- moveDayNote: async (tripId, fromDayId, toDayId, noteId, sort_order = 9999) => {
- const state = get()
- const note = (state.dayNotes[String(fromDayId)] || []).find(n => n.id === noteId)
- if (!note) return
-
- set(s => ({
- dayNotes: {
- ...s.dayNotes,
- [String(fromDayId)]: (s.dayNotes[String(fromDayId)] || []).filter(n => n.id !== noteId),
- }
- }))
-
- try {
- await dayNotesApi.delete(tripId, fromDayId, noteId)
- const result = await dayNotesApi.create(tripId, toDayId, {
- text: note.text, time: note.time, icon: note.icon, sort_order,
- })
- set(s => ({
- dayNotes: {
- ...s.dayNotes,
- [String(toDayId)]: [...(s.dayNotes[String(toDayId)] || []), result.note],
- }
- }))
- } catch (err) {
- set(s => ({
- dayNotes: {
- ...s.dayNotes,
- [String(fromDayId)]: [...(s.dayNotes[String(fromDayId)] || []), note],
- }
- }))
- throw new Error(err.response?.data?.error || 'Error moving note')
- }
- },
-
- setAssignments: (assignments) => {
- set({ assignments })
- },
-
- addPackingItem: async (tripId, data) => {
- try {
- const result = await packingApi.create(tripId, data)
- set(state => ({ packingItems: [...state.packingItems, result.item] }))
- return result.item
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error adding item')
- }
- },
-
- updatePackingItem: async (tripId, id, data) => {
- try {
- const result = await packingApi.update(tripId, id, data)
- set(state => ({
- packingItems: state.packingItems.map(item => item.id === id ? result.item : item)
- }))
- return result.item
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error updating item')
- }
- },
-
- deletePackingItem: async (tripId, id) => {
- const prev = get().packingItems
- set(state => ({ packingItems: state.packingItems.filter(item => item.id !== id) }))
- try {
- await packingApi.delete(tripId, id)
- } catch (err) {
- set({ packingItems: prev })
- throw new Error(err.response?.data?.error || 'Error deleting item')
- }
- },
-
- togglePackingItem: async (tripId, id, checked) => {
- set(state => ({
- packingItems: state.packingItems.map(item =>
- item.id === id ? { ...item, checked: checked ? 1 : 0 } : item
- )
- }))
- try {
- await packingApi.update(tripId, id, { checked })
- } catch (err) {
- set(state => ({
- packingItems: state.packingItems.map(item =>
- item.id === id ? { ...item, checked: checked ? 0 : 1 } : item
- )
- }))
- }
- },
-
- updateDayNotes: async (tripId, dayId, notes) => {
- try {
- await daysApi.update(tripId, dayId, { notes })
- set(state => ({
- days: state.days.map(d => d.id === parseInt(dayId) ? { ...d, notes } : d)
- }))
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error updating notes')
- }
- },
-
- updateDayTitle: async (tripId, dayId, title) => {
- try {
- await daysApi.update(tripId, dayId, { title })
- set(state => ({
- days: state.days.map(d => d.id === parseInt(dayId) ? { ...d, title } : d)
- }))
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error updating day name')
- }
- },
-
- addTag: async (data) => {
- try {
- const result = await tagsApi.create(data)
- set(state => ({ tags: [...state.tags, result.tag] }))
- return result.tag
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error creating tag')
- }
- },
-
- addCategory: async (data) => {
- try {
- const result = await categoriesApi.create(data)
- set(state => ({ categories: [...state.categories, result.category] }))
- return result.category
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error creating category')
- }
- },
-
- updateTrip: async (tripId, data) => {
- try {
- const result = await tripsApi.update(tripId, data)
- set({ trip: result.trip })
- const daysData = await daysApi.list(tripId)
- const assignmentsMap = {}
- const dayNotesMap = {}
- for (const day of daysData.days) {
- assignmentsMap[String(day.id)] = day.assignments || []
- dayNotesMap[String(day.id)] = day.notes_items || []
- }
- set({ days: daysData.days, assignments: assignmentsMap, dayNotes: dayNotesMap })
- return result.trip
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error updating trip')
- }
- },
-
- loadBudgetItems: async (tripId) => {
- try {
- const data = await budgetApi.list(tripId)
- set({ budgetItems: data.items })
- } catch (err) {
- console.error('Failed to load budget items:', err)
- }
- },
-
- addBudgetItem: async (tripId, data) => {
- try {
- const result = await budgetApi.create(tripId, data)
- set(state => ({ budgetItems: [...state.budgetItems, result.item] }))
- return result.item
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error adding budget item')
- }
- },
-
- updateBudgetItem: async (tripId, id, data) => {
- try {
- const result = await budgetApi.update(tripId, id, data)
- set(state => ({
- budgetItems: state.budgetItems.map(item => item.id === id ? result.item : item)
- }))
- return result.item
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error updating budget item')
- }
- },
-
- deleteBudgetItem: async (tripId, id) => {
- const prev = get().budgetItems
- set(state => ({ budgetItems: state.budgetItems.filter(item => item.id !== id) }))
- try {
- await budgetApi.delete(tripId, id)
- } catch (err) {
- set({ budgetItems: prev })
- throw new Error(err.response?.data?.error || 'Error deleting budget item')
- }
- },
-
- setBudgetItemMembers: async (tripId, itemId, userIds) => {
- const result = await budgetApi.setMembers(tripId, itemId, userIds);
- set(state => ({
- budgetItems: state.budgetItems.map(item =>
- item.id === itemId ? { ...item, members: result.members, persons: result.item.persons } : item
- )
- }));
- return result;
- },
-
- toggleBudgetMemberPaid: async (tripId, itemId, userId, paid) => {
- await budgetApi.togglePaid(tripId, itemId, userId, paid);
- set(state => ({
- budgetItems: state.budgetItems.map(item =>
- item.id === itemId
- ? { ...item, members: (item.members || []).map(m => m.user_id === userId ? { ...m, paid } : m) }
- : item
- )
- }));
- },
-
- loadFiles: async (tripId) => {
- try {
- const data = await filesApi.list(tripId)
- set({ files: data.files })
- } catch (err) {
- console.error('Failed to load files:', err)
- }
- },
-
- addFile: async (tripId, formData) => {
- try {
- const data = await filesApi.upload(tripId, formData)
- set(state => ({ files: [data.file, ...state.files] }))
- return data.file
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error uploading file')
- }
- },
-
- deleteFile: async (tripId, id) => {
- try {
- await filesApi.delete(tripId, id)
- set(state => ({ files: state.files.filter(f => f.id !== id) }))
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error deleting file')
- }
- },
-
- loadReservations: async (tripId) => {
- try {
- const data = await reservationsApi.list(tripId)
- set({ reservations: data.reservations })
- } catch (err) {
- console.error('Failed to load reservations:', err)
- }
- },
-
- addReservation: async (tripId, data) => {
- try {
- const result = await reservationsApi.create(tripId, data)
- set(state => ({ reservations: [result.reservation, ...state.reservations] }))
- return result.reservation
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error creating reservation')
- }
- },
-
- updateReservation: async (tripId, id, data) => {
- try {
- const result = await reservationsApi.update(tripId, id, data)
- set(state => ({
- reservations: state.reservations.map(r => r.id === id ? result.reservation : r)
- }))
- return result.reservation
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error updating reservation')
- }
- },
-
- toggleReservationStatus: async (tripId, id) => {
- const prev = get().reservations
- const current = prev.find(r => r.id === id)
- if (!current) return
- const newStatus = current.status === 'confirmed' ? 'pending' : 'confirmed'
- set(state => ({
- reservations: state.reservations.map(r => r.id === id ? { ...r, status: newStatus } : r)
- }))
- try {
- await reservationsApi.update(tripId, id, { status: newStatus })
- } catch {
- set({ reservations: prev })
- }
- },
-
- deleteReservation: async (tripId, id) => {
- try {
- await reservationsApi.delete(tripId, id)
- set(state => ({ reservations: state.reservations.filter(r => r.id !== id) }))
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error deleting reservation')
- }
- },
-
- addDayNote: async (tripId, dayId, data) => {
- const tempId = Date.now() * -1
- const tempNote = { id: tempId, day_id: dayId, ...data, created_at: new Date().toISOString() }
- set(state => ({
- dayNotes: {
- ...state.dayNotes,
- [String(dayId)]: [...(state.dayNotes[String(dayId)] || []), tempNote],
- }
- }))
- try {
- const result = await dayNotesApi.create(tripId, dayId, data)
- set(state => ({
- dayNotes: {
- ...state.dayNotes,
- [String(dayId)]: (state.dayNotes[String(dayId)] || []).map(n => n.id === tempId ? result.note : n),
- }
- }))
- return result.note
- } catch (err) {
- set(state => ({
- dayNotes: {
- ...state.dayNotes,
- [String(dayId)]: (state.dayNotes[String(dayId)] || []).filter(n => n.id !== tempId),
- }
- }))
- throw new Error(err.response?.data?.error || 'Error adding note')
- }
- },
-
- updateDayNote: async (tripId, dayId, id, data) => {
- try {
- const result = await dayNotesApi.update(tripId, dayId, id, data)
- set(state => ({
- dayNotes: {
- ...state.dayNotes,
- [String(dayId)]: (state.dayNotes[String(dayId)] || []).map(n => n.id === id ? result.note : n),
- }
- }))
- return result.note
- } catch (err) {
- throw new Error(err.response?.data?.error || 'Error updating note')
- }
- },
-
- deleteDayNote: async (tripId, dayId, id) => {
- const prev = get().dayNotes
- set(state => ({
- dayNotes: {
- ...state.dayNotes,
- [String(dayId)]: (state.dayNotes[String(dayId)] || []).filter(n => n.id !== id),
- }
- }))
- try {
- await dayNotesApi.delete(tripId, dayId, id)
- } catch (err) {
- set({ dayNotes: prev })
- throw new Error(err.response?.data?.error || 'Error deleting note')
- }
- },
-}))
diff --git a/client/src/store/tripStore.ts b/client/src/store/tripStore.ts
new file mode 100644
index 000000000..fa92a360d
--- /dev/null
+++ b/client/src/store/tripStore.ts
@@ -0,0 +1,175 @@
+import { create } from 'zustand'
+import type { StoreApi } from 'zustand'
+import { tripsApi, daysApi, placesApi, packingApi, tagsApi, categoriesApi } from '../api/client'
+import { createPlacesSlice } from './slices/placesSlice'
+import { createAssignmentsSlice } from './slices/assignmentsSlice'
+import { createDayNotesSlice } from './slices/dayNotesSlice'
+import { createPackingSlice } from './slices/packingSlice'
+import { createBudgetSlice } from './slices/budgetSlice'
+import { createReservationsSlice } from './slices/reservationsSlice'
+import { createFilesSlice } from './slices/filesSlice'
+import { handleRemoteEvent } from './slices/remoteEventHandler'
+import type {
+ Trip, Day, Place, Assignment, DayNote, PackingItem,
+ Tag, Category, BudgetItem, TripFile, Reservation,
+ AssignmentsMap, DayNotesMap, WebSocketEvent,
+} from '../types'
+import { getApiErrorMessage } from '../types'
+import type { PlacesSlice } from './slices/placesSlice'
+import type { AssignmentsSlice } from './slices/assignmentsSlice'
+import type { DayNotesSlice } from './slices/dayNotesSlice'
+import type { PackingSlice } from './slices/packingSlice'
+import type { BudgetSlice } from './slices/budgetSlice'
+import type { ReservationsSlice } from './slices/reservationsSlice'
+import type { FilesSlice } from './slices/filesSlice'
+
+export interface TripStoreState
+ extends PlacesSlice,
+ AssignmentsSlice,
+ DayNotesSlice,
+ PackingSlice,
+ BudgetSlice,
+ ReservationsSlice,
+ FilesSlice {
+ trip: Trip | null
+ days: Day[]
+ places: Place[]
+ assignments: AssignmentsMap
+ dayNotes: DayNotesMap
+ packingItems: PackingItem[]
+ tags: Tag[]
+ categories: Category[]
+ budgetItems: BudgetItem[]
+ files: TripFile[]
+ reservations: Reservation[]
+ selectedDayId: number | null
+ isLoading: boolean
+ error: string | null
+
+ setSelectedDay: (dayId: number | null) => void
+ handleRemoteEvent: (event: WebSocketEvent) => void
+ loadTrip: (tripId: number | string) => Promise<void>
+ refreshDays: (tripId: number | string) => Promise<void>
+ updateTrip: (tripId: number | string, data: Partial<Trip>) => Promise<Trip>
+ addTag: (data: Partial<Tag>) => Promise<Tag>
+ addCategory: (data: Partial<Category>) => Promise<Category>
+}
+
+export const useTripStore = create<TripStoreState>((set, get) => ({
+ trip: null,
+ days: [],
+ places: [],
+ assignments: {},
+ dayNotes: {},
+ packingItems: [],
+ tags: [],
+ categories: [],
+ budgetItems: [],
+ files: [],
+ reservations: [],
+ selectedDayId: null,
+ isLoading: false,
+ error: null,
+
+ setSelectedDay: (dayId: number | null) => set({ selectedDayId: dayId }),
+
+ handleRemoteEvent: (event: WebSocketEvent) => handleRemoteEvent(set, event),
+
+ loadTrip: async (tripId: number | string) => {
+ set({ isLoading: true, error: null })
+ try {
+ const [tripData, daysData, placesData, packingData, tagsData, categoriesData] = await Promise.all([
+ tripsApi.get(tripId),
+ daysApi.list(tripId),
+ placesApi.list(tripId),
+ packingApi.list(tripId),
+ tagsApi.list(),
+ categoriesApi.list(),
+ ])
+
+ const assignmentsMap: AssignmentsMap = {}
+ const dayNotesMap: DayNotesMap = {}
+ for (const day of daysData.days) {
+ assignmentsMap[String(day.id)] = day.assignments || []
+ dayNotesMap[String(day.id)] = day.notes_items || []
+ }
+
+ set({
+ trip: tripData.trip,
+ days: daysData.days,
+ places: placesData.places,
+ assignments: assignmentsMap,
+ dayNotes: dayNotesMap,
+ packingItems: packingData.items,
+ tags: tagsData.tags,
+ categories: categoriesData.categories,
+ isLoading: false,
+ })
+ } catch (err: unknown) {
+ const message = err instanceof Error ? err.message : 'Unknown error'
+ set({ isLoading: false, error: message })
+ throw err
+ }
+ },
+
+ refreshDays: async (tripId: number | string) => {
+ try {
+ const daysData = await daysApi.list(tripId)
+ const assignmentsMap: AssignmentsMap = {}
+ const dayNotesMap: DayNotesMap = {}
+ for (const day of daysData.days) {
+ assignmentsMap[String(day.id)] = day.assignments || []
+ dayNotesMap[String(day.id)] = day.notes_items || []
+ }
+ set({ days: daysData.days, assignments: assignmentsMap, dayNotes: dayNotesMap })
+ } catch (err: unknown) {
+ console.error('Failed to refresh days:', err)
+ }
+ },
+
+ updateTrip: async (tripId: number | string, data: Partial<Trip>) => {
+ try {
+ const result = await tripsApi.update(tripId, data)
+ set({ trip: result.trip })
+ const daysData = await daysApi.list(tripId)
+ const assignmentsMap: AssignmentsMap = {}
+ const dayNotesMap: DayNotesMap = {}
+ for (const day of daysData.days) {
+ assignmentsMap[String(day.id)] = day.assignments || []
+ dayNotesMap[String(day.id)] = day.notes_items || []
+ }
+ set({ days: daysData.days, assignments: assignmentsMap, dayNotes: dayNotesMap })
+ return result.trip
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error updating trip'))
+ }
+ },
+
+ addTag: async (data: Partial<Tag>) => {
+ try {
+ const result = await tagsApi.create(data)
+ set((state) => ({ tags: [...state.tags, result.tag] }))
+ return result.tag
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error creating tag'))
+ }
+ },
+
+ addCategory: async (data: Partial<Category>) => {
+ try {
+ const result = await categoriesApi.create(data)
+ set((state) => ({ categories: [...state.categories, result.category] }))
+ return result.category
+ } catch (err: unknown) {
+ throw new Error(getApiErrorMessage(err, 'Error creating category'))
+ }
+ },
+
+ ...createPlacesSlice(set, get),
+ ...createAssignmentsSlice(set, get),
+ ...createDayNotesSlice(set, get),
+ ...createPackingSlice(set, get),
+ ...createBudgetSlice(set, get),
+ ...createReservationsSlice(set, get),
+ ...createFilesSlice(set, get),
+}))
diff --git a/client/src/store/vacayStore.js b/client/src/store/vacayStore.js
deleted file mode 100644
index dfbe227e3..000000000
--- a/client/src/store/vacayStore.js
+++ /dev/null
@@ -1,188 +0,0 @@
-import { create } from 'zustand'
-import apiClient from '../api/client'
-
-const ax = apiClient
-const api = {
- getPlan: () => ax.get('/addons/vacay/plan').then(r => r.data),
- updatePlan: (data) => ax.put('/addons/vacay/plan', data).then(r => r.data),
- updateColor: (color, targetUserId) => ax.put('/addons/vacay/color', { color, target_user_id: targetUserId }).then(r => r.data),
- invite: (userId) => ax.post('/addons/vacay/invite', { user_id: userId }).then(r => r.data),
- acceptInvite: (planId) => ax.post('/addons/vacay/invite/accept', { plan_id: planId }).then(r => r.data),
- declineInvite: (planId) => ax.post('/addons/vacay/invite/decline', { plan_id: planId }).then(r => r.data),
- cancelInvite: (userId) => ax.post('/addons/vacay/invite/cancel', { user_id: userId }).then(r => r.data),
- dissolve: () => ax.post('/addons/vacay/dissolve').then(r => r.data),
- availableUsers: () => ax.get('/addons/vacay/available-users').then(r => r.data),
- getYears: () => ax.get('/addons/vacay/years').then(r => r.data),
- addYear: (year) => ax.post('/addons/vacay/years', { year }).then(r => r.data),
- removeYear: (year) => ax.delete(`/addons/vacay/years/${year}`).then(r => r.data),
- getEntries: (year) => ax.get(`/addons/vacay/entries/${year}`).then(r => r.data),
- toggleEntry: (date, targetUserId) => ax.post('/addons/vacay/entries/toggle', { date, target_user_id: targetUserId }).then(r => r.data),
- toggleCompanyHoliday: (date) => ax.post('/addons/vacay/entries/company-holiday', { date }).then(r => r.data),
- getStats: (year) => ax.get(`/addons/vacay/stats/${year}`).then(r => r.data),
- updateStats: (year, days, targetUserId) => ax.put(`/addons/vacay/stats/${year}`, { vacation_days: days, target_user_id: targetUserId }).then(r => r.data),
- getCountries: () => ax.get('/addons/vacay/holidays/countries').then(r => r.data),
- getHolidays: (year, country) => ax.get(`/addons/vacay/holidays/${year}/${country}`).then(r => r.data),
-}
-
-export const useVacayStore = create((set, get) => ({
- plan: null,
- users: [],
- pendingInvites: [],
- incomingInvites: [],
- isOwner: true,
- isFused: false,
- years: [],
- entries: [],
- companyHolidays: [],
- stats: [],
- selectedYear: new Date().getFullYear(),
- selectedUserId: null,
- holidays: {}, // date -> { name, localName }
- loading: false,
-
- setSelectedYear: (year) => set({ selectedYear: year }),
- setSelectedUserId: (id) => set({ selectedUserId: id }),
-
- loadPlan: async () => {
- const data = await api.getPlan()
- set({
- plan: data.plan,
- users: data.users,
- pendingInvites: data.pendingInvites,
- incomingInvites: data.incomingInvites,
- isOwner: data.isOwner,
- isFused: data.isFused,
- })
- },
-
- updatePlan: async (updates) => {
- const data = await api.updatePlan(updates)
- set({ plan: data.plan })
- await get().loadEntries()
- await get().loadStats()
- await get().loadHolidays()
- },
-
- updateColor: async (color, targetUserId) => {
- await api.updateColor(color, targetUserId)
- await get().loadPlan()
- await get().loadEntries()
- },
-
- invite: async (userId) => {
- await api.invite(userId)
- await get().loadPlan()
- },
-
- acceptInvite: async (planId) => {
- await api.acceptInvite(planId)
- await get().loadAll()
- },
-
- declineInvite: async (planId) => {
- await api.declineInvite(planId)
- await get().loadPlan()
- },
-
- cancelInvite: async (userId) => {
- await api.cancelInvite(userId)
- await get().loadPlan()
- },
-
- dissolve: async () => {
- await api.dissolve()
- await get().loadAll()
- },
-
- loadYears: async () => {
- const data = await api.getYears()
- set({ years: data.years })
- if (data.years.length > 0) {
- set({ selectedYear: data.years[data.years.length - 1] })
- }
- },
-
- addYear: async (year) => {
- const data = await api.addYear(year)
- set({ years: data.years })
- await get().loadStats(year)
- },
-
- removeYear: async (year) => {
- const data = await api.removeYear(year)
- set({ years: data.years })
- },
-
- loadEntries: async (year) => {
- const y = year || get().selectedYear
- const data = await api.getEntries(y)
- set({ entries: data.entries, companyHolidays: data.companyHolidays })
- },
-
- toggleEntry: async (date, targetUserId) => {
- await api.toggleEntry(date, targetUserId)
- await get().loadEntries()
- await get().loadStats()
- },
-
- toggleCompanyHoliday: async (date) => {
- await api.toggleCompanyHoliday(date)
- await get().loadEntries()
- },
-
- loadStats: async (year) => {
- const y = year || get().selectedYear
- const data = await api.getStats(y)
- set({ stats: data.stats })
- },
-
- updateVacationDays: async (year, days, targetUserId) => {
- await api.updateStats(year, days, targetUserId)
- await get().loadStats(year)
- },
-
- loadHolidays: async (year) => {
- const y = year || get().selectedYear
- const plan = get().plan
- if (!plan?.holidays_enabled || !plan?.holidays_region) {
- set({ holidays: {} })
- return
- }
- const country = plan.holidays_region.split('-')[0]
- const region = plan.holidays_region.includes('-') ? plan.holidays_region : null
- try {
- const data = await api.getHolidays(y, country)
- // Check if this country HAS regional holidays
- const hasRegions = data.some(h => h.counties && h.counties.length > 0)
- // If country has regions but no region selected yet, only show global ones
- // Actually: don't show ANY holidays until region is selected
- if (hasRegions && !region) {
- set({ holidays: {} })
- return
- }
- const map = {}
- data.forEach(h => {
- if (h.global || !h.counties || (region && h.counties.includes(region))) {
- map[h.date] = { name: h.name, localName: h.localName }
- }
- })
- set({ holidays: map })
- } catch {
- set({ holidays: {} })
- }
- },
-
- loadAll: async () => {
- set({ loading: true })
- try {
- await get().loadPlan()
- await get().loadYears()
- const year = get().selectedYear
- await get().loadEntries(year)
- await get().loadStats(year)
- await get().loadHolidays(year)
- } finally {
- set({ loading: false })
- }
- },
-}))
diff --git a/client/src/store/vacayStore.ts b/client/src/store/vacayStore.ts
new file mode 100644
index 000000000..c58e3a3b6
--- /dev/null
+++ b/client/src/store/vacayStore.ts
@@ -0,0 +1,288 @@
+import { create } from 'zustand'
+import apiClient from '../api/client'
+import type { AxiosResponse } from 'axios'
+import type { VacayPlan, VacayUser, VacayEntry, VacayStat, HolidaysMap, HolidayInfo } from '../types'
+
+const ax = apiClient
+
+interface PendingInvite {
+ user_id: number
+ username: string
+}
+
+interface IncomingInvite {
+ plan_id: number
+ owner_username: string
+}
+
+interface VacayPlanResponse {
+ plan: VacayPlan
+ users: VacayUser[]
+ pendingInvites: PendingInvite[]
+ incomingInvites: IncomingInvite[]
+ isOwner: boolean
+ isFused: boolean
+}
+
+interface VacayYearsResponse {
+ years: number[]
+}
+
+interface VacayEntriesResponse {
+ entries: VacayEntry[]
+ companyHolidays: string[]
+}
+
+interface VacayStatsResponse {
+ stats: VacayStat[]
+}
+
+interface VacayHolidayRaw {
+ date: string
+ name: string
+ localName: string
+ global: boolean
+ counties: string[] | null
+}
+
+interface VacayApi {
+ getPlan: () => Promise<VacayPlanResponse>
+ updatePlan: (data: Partial<VacayPlan>) => Promise<{ plan: VacayPlan }>
+ updateColor: (color: string, targetUserId?: number) => Promise<unknown>
+ invite: (userId: number) => Promise<unknown>
+ acceptInvite: (planId: number) => Promise<unknown>
+ declineInvite: (planId: number) => Promise<unknown>
+ cancelInvite: (userId: number) => Promise<unknown>
+ dissolve: () => Promise<unknown>
+ availableUsers: () => Promise<{ users: VacayUser[] }>
+ getYears: () => Promise<VacayYearsResponse>
+ addYear: (year: number) => Promise<VacayYearsResponse>
+ removeYear: (year: number) => Promise<VacayYearsResponse>
+ getEntries: (year: number) => Promise<VacayEntriesResponse>
+ toggleEntry: (date: string, targetUserId?: number) => Promise<unknown>
+ toggleCompanyHoliday: (date: string) => Promise<unknown>
+ getStats: (year: number) => Promise<VacayStatsResponse>
+ updateStats: (year: number, days: number, targetUserId?: number) => Promise<unknown>
+ getCountries: () => Promise<{ countries: string[] }>
+ getHolidays: (year: number, country: string) => Promise<VacayHolidayRaw[]>
+}
+
+const api: VacayApi = {
+ getPlan: () => ax.get('/addons/vacay/plan').then((r: AxiosResponse) => r.data),
+ updatePlan: (data) => ax.put('/addons/vacay/plan', data).then((r: AxiosResponse) => r.data),
+ updateColor: (color, targetUserId) => ax.put('/addons/vacay/color', { color, target_user_id: targetUserId }).then((r: AxiosResponse) => r.data),
+ invite: (userId) => ax.post('/addons/vacay/invite', { user_id: userId }).then((r: AxiosResponse) => r.data),
+ acceptInvite: (planId) => ax.post('/addons/vacay/invite/accept', { plan_id: planId }).then((r: AxiosResponse) => r.data),
+ declineInvite: (planId) => ax.post('/addons/vacay/invite/decline', { plan_id: planId }).then((r: AxiosResponse) => r.data),
+ cancelInvite: (userId) => ax.post('/addons/vacay/invite/cancel', { user_id: userId }).then((r: AxiosResponse) => r.data),
+ dissolve: () => ax.post('/addons/vacay/dissolve').then((r: AxiosResponse) => r.data),
+ availableUsers: () => ax.get('/addons/vacay/available-users').then((r: AxiosResponse) => r.data),
+ getYears: () => ax.get('/addons/vacay/years').then((r: AxiosResponse) => r.data),
+ addYear: (year) => ax.post('/addons/vacay/years', { year }).then((r: AxiosResponse) => r.data),
+ removeYear: (year) => ax.delete(`/addons/vacay/years/${year}`).then((r: AxiosResponse) => r.data),
+ getEntries: (year) => ax.get(`/addons/vacay/entries/${year}`).then((r: AxiosResponse) => r.data),
+ toggleEntry: (date, targetUserId) => ax.post('/addons/vacay/entries/toggle', { date, target_user_id: targetUserId }).then((r: AxiosResponse) => r.data),
+ toggleCompanyHoliday: (date) => ax.post('/addons/vacay/entries/company-holiday', { date }).then((r: AxiosResponse) => r.data),
+ getStats: (year) => ax.get(`/addons/vacay/stats/${year}`).then((r: AxiosResponse) => r.data),
+ updateStats: (year, days, targetUserId) => ax.put(`/addons/vacay/stats/${year}`, { vacation_days: days, target_user_id: targetUserId }).then((r: AxiosResponse) => r.data),
+ getCountries: () => ax.get('/addons/vacay/holidays/countries').then((r: AxiosResponse) => r.data),
+ getHolidays: (year, country) => ax.get(`/addons/vacay/holidays/${year}/${country}`).then((r: AxiosResponse) => r.data),
+}
+
+interface VacayState {
+ plan: VacayPlan | null
+ users: VacayUser[]
+ pendingInvites: PendingInvite[]
+ incomingInvites: IncomingInvite[]
+ isOwner: boolean
+ isFused: boolean
+ years: number[]
+ entries: VacayEntry[]
+ companyHolidays: string[]
+ stats: VacayStat[]
+ selectedYear: number
+ selectedUserId: number | null
+ holidays: HolidaysMap
+ loading: boolean
+
+ setSelectedYear: (year: number) => void
+ setSelectedUserId: (id: number | null) => void
+ loadPlan: () => Promise<void>
+ updatePlan: (updates: Partial<VacayPlan>) => Promise<void>
+ updateColor: (color: string, targetUserId?: number) => Promise<void>
+ invite: (userId: number) => Promise<void>
+ acceptInvite: (planId: number) => Promise<void>
+ declineInvite: (planId: number) => Promise<void>
+ cancelInvite: (userId: number) => Promise<void>
+ dissolve: () => Promise<void>
+ loadYears: () => Promise<void>
+ addYear: (year: number) => Promise<void>
+ removeYear: (year: number) => Promise<void>
+ loadEntries: (year?: number) => Promise<void>
+ toggleEntry: (date: string, targetUserId?: number) => Promise<void>
+ toggleCompanyHoliday: (date: string) => Promise<void>
+ loadStats: (year?: number) => Promise<void>
+ updateVacationDays: (year: number, days: number, targetUserId?: number) => Promise<void>
+ loadHolidays: (year?: number) => Promise<void>
+ loadAll: () => Promise<void>
+}
+
+export const useVacayStore = create<VacayState>((set, get) => ({
+ plan: null,
+ users: [],
+ pendingInvites: [],
+ incomingInvites: [],
+ isOwner: true,
+ isFused: false,
+ years: [],
+ entries: [],
+ companyHolidays: [],
+ stats: [],
+ selectedYear: new Date().getFullYear(),
+ selectedUserId: null,
+ holidays: {},
+ loading: false,
+
+ setSelectedYear: (year: number) => set({ selectedYear: year }),
+ setSelectedUserId: (id: number | null) => set({ selectedUserId: id }),
+
+ loadPlan: async () => {
+ const data = await api.getPlan()
+ set({
+ plan: data.plan,
+ users: data.users,
+ pendingInvites: data.pendingInvites,
+ incomingInvites: data.incomingInvites,
+ isOwner: data.isOwner,
+ isFused: data.isFused,
+ })
+ },
+
+ updatePlan: async (updates: Partial<VacayPlan>) => {
+ const data = await api.updatePlan(updates)
+ set({ plan: data.plan })
+ await get().loadEntries()
+ await get().loadStats()
+ await get().loadHolidays()
+ },
+
+ updateColor: async (color: string, targetUserId?: number) => {
+ await api.updateColor(color, targetUserId)
+ await get().loadPlan()
+ await get().loadEntries()
+ },
+
+ invite: async (userId: number) => {
+ await api.invite(userId)
+ await get().loadPlan()
+ },
+
+ acceptInvite: async (planId: number) => {
+ await api.acceptInvite(planId)
+ await get().loadAll()
+ },
+
+ declineInvite: async (planId: number) => {
+ await api.declineInvite(planId)
+ await get().loadPlan()
+ },
+
+ cancelInvite: async (userId: number) => {
+ await api.cancelInvite(userId)
+ await get().loadPlan()
+ },
+
+ dissolve: async () => {
+ await api.dissolve()
+ await get().loadAll()
+ },
+
+ loadYears: async () => {
+ const data = await api.getYears()
+ set({ years: data.years })
+ if (data.years.length > 0) {
+ set({ selectedYear: data.years[data.years.length - 1] })
+ }
+ },
+
+ addYear: async (year: number) => {
+ const data = await api.addYear(year)
+ set({ years: data.years })
+ await get().loadStats(year)
+ },
+
+ removeYear: async (year: number) => {
+ const data = await api.removeYear(year)
+ set({ years: data.years })
+ },
+
+ loadEntries: async (year?: number) => {
+ const y = year || get().selectedYear
+ const data = await api.getEntries(y)
+ set({ entries: data.entries, companyHolidays: data.companyHolidays })
+ },
+
+ toggleEntry: async (date: string, targetUserId?: number) => {
+ await api.toggleEntry(date, targetUserId)
+ await get().loadEntries()
+ await get().loadStats()
+ },
+
+ toggleCompanyHoliday: async (date: string) => {
+ await api.toggleCompanyHoliday(date)
+ await get().loadEntries()
+ },
+
+ loadStats: async (year?: number) => {
+ const y = year || get().selectedYear
+ const data = await api.getStats(y)
+ set({ stats: data.stats })
+ },
+
+ updateVacationDays: async (year: number, days: number, targetUserId?: number) => {
+ await api.updateStats(year, days, targetUserId)
+ await get().loadStats(year)
+ },
+
+ loadHolidays: async (year?: number) => {
+ const y = year || get().selectedYear
+ const plan = get().plan
+ if (!plan?.holidays_enabled || !plan?.holidays_region) {
+ set({ holidays: {} })
+ return
+ }
+ const country = plan.holidays_region.split('-')[0]
+ const region = plan.holidays_region.includes('-') ? plan.holidays_region : null
+ try {
+ const data = await api.getHolidays(y, country)
+ const hasRegions = data.some((h: VacayHolidayRaw) => h.counties && h.counties.length > 0)
+ if (hasRegions && !region) {
+ set({ holidays: {} })
+ return
+ }
+ const map: HolidaysMap = {}
+ data.forEach((h: VacayHolidayRaw) => {
+ if (h.global || !h.counties || (region && h.counties.includes(region))) {
+ map[h.date] = { name: h.name, localName: h.localName }
+ }
+ })
+ set({ holidays: map })
+ } catch {
+ set({ holidays: {} })
+ }
+ },
+
+ loadAll: async () => {
+ set({ loading: true })
+ try {
+ await get().loadPlan()
+ await get().loadYears()
+ const year = get().selectedYear
+ await get().loadEntries(year)
+ await get().loadStats(year)
+ await get().loadHolidays(year)
+ } finally {
+ set({ loading: false })
+ }
+ },
+}))
diff --git a/client/src/types.ts b/client/src/types.ts
new file mode 100644
index 000000000..c4116373d
--- /dev/null
+++ b/client/src/types.ts
@@ -0,0 +1,332 @@
+// Shared types for the NOMAD travel planner
+
+export interface User {
+ id: number
+ username: string
+ email: string
+ role: 'admin' | 'user'
+ avatar_url: string | null
+ maps_api_key: string | null
+ created_at: string
+}
+
+export interface Trip {
+ id: number
+ name: string
+ description: string | null
+ start_date: string
+ end_date: string
+ cover_url: string | null
+ is_archived: boolean
+ owner_id: number
+ created_at: string
+ updated_at: string
+}
+
+export interface Day {
+ id: number
+ trip_id: number
+ date: string
+ title: string | null
+ notes: string | null
+ assignments: Assignment[]
+ notes_items: DayNote[]
+}
+
+export interface Place {
+ id: number
+ trip_id: number
+ name: string
+ description: string | null
+ lat: number | null
+ lng: number | null
+ address: string | null
+ category_id: number | null
+ icon: string | null
+ price: string | null
+ image_url: string | null
+ google_place_id: string | null
+ place_time: string | null
+ end_time: string | null
+ created_at: string
+}
+
+export interface Assignment {
+ id: number
+ day_id: number
+ place_id?: number
+ order_index: number
+ notes: string | null
+ place: Place
+}
+
+export interface DayNote {
+ id: number
+ day_id: number
+ text: string
+ time: string | null
+ icon: string | null
+ sort_order?: number
+ created_at: string
+}
+
+export interface PackingItem {
+ id: number
+ trip_id: number
+ name: string
+ category: string | null
+ checked: number
+ quantity: number
+}
+
+export interface Tag {
+ id: number
+ name: string
+ color: string | null
+ user_id: number
+}
+
+export interface Category {
+ id: number
+ name: string
+ icon: string | null
+ user_id: number
+}
+
+export interface BudgetItem {
+ id: number
+ trip_id: number
+ name: string
+ amount: number
+ currency: string
+ category: string | null
+ paid_by: number | null
+ persons: number
+ members: BudgetMember[]
+}
+
+export interface BudgetMember {
+ user_id: number
+ paid: boolean
+}
+
+export interface Reservation {
+ id: number
+ trip_id: number
+ name: string
+ type: string | null
+ status: 'pending' | 'confirmed'
+ date: string | null
+ time: string | null
+ confirmation_number: string | null
+ notes: string | null
+ url: string | null
+ created_at: string
+}
+
+export interface TripFile {
+ id: number
+ trip_id: number
+ filename: string
+ original_name: string
+ mime_type: string
+ size: number
+ created_at: string
+}
+
+export interface Settings {
+ map_tile_url: string
+ default_lat: number
+ default_lng: number
+ default_zoom: number
+ dark_mode: boolean | string
+ default_currency: string
+ language: string
+ temperature_unit: string
+ time_format: string
+ show_place_description: boolean
+ route_calculation?: boolean
+}
+
+export interface AssignmentsMap {
+ [dayId: string]: Assignment[]
+}
+
+export interface DayNotesMap {
+ [dayId: string]: DayNote[]
+}
+
+export interface RouteSegment {
+ mid: [number, number]
+ from: [number, number]
+ to: [number, number]
+ walkingText: string
+ drivingText: string
+}
+
+export interface RouteResult {
+ coordinates: [number, number][]
+ distance: number
+ duration: number
+ distanceText: string
+ durationText: string
+ walkingText: string
+ drivingText: string
+}
+
+export interface Waypoint {
+ lat: number
+ lng: number
+}
+
+// User with optional OIDC fields
+export interface UserWithOidc extends User {
+ oidc_issuer?: string | null
+}
+
+// Accommodation type
+export interface Accommodation {
+ id: number
+ trip_id: number
+ name: string
+ address: string | null
+ check_in: string | null
+ check_out: string | null
+ confirmation_number: string | null
+ notes: string | null
+ url: string | null
+ created_at: string
+}
+
+// Trip member (owner or collaborator)
+export interface TripMember {
+ id: number
+ username: string
+ email?: string
+ avatar_url?: string | null
+ role?: string
+}
+
+// Photo type
+export interface Photo {
+ id: number
+ trip_id: number
+ filename: string
+ original_name: string
+ mime_type: string
+ size: number
+ caption: string | null
+ place_id: number | null
+ day_id: number | null
+ created_at: string
+}
+
+// Atlas place detail
+export interface AtlasPlace {
+ id: number
+ name: string
+ lat: number | null
+ lng: number | null
+}
+
+// GeoJSON types (simplified for atlas map)
+export interface GeoJsonFeature {
+ type: 'Feature'
+ properties: Record<string, string | number | null | undefined>
+ geometry: {
+ type: string
+ coordinates: unknown
+ }
+ id?: string
+}
+
+export interface GeoJsonFeatureCollection {
+ type: 'FeatureCollection'
+ features: GeoJsonFeature[]
+}
+
+// App config from /auth/app-config
+export interface AppConfig {
+ has_users: boolean
+ allow_registration: boolean
+ demo_mode: boolean
+ oidc_configured: boolean
+ oidc_display_name?: string
+ has_maps_key?: boolean
+ allowed_file_types?: string
+}
+
+// Translation function type
+export type TranslationFn = (key: string, params?: Record<string, string | number | null>) => string
+
+// WebSocket event type
+export interface WebSocketEvent {
+ type: string
+ [key: string]: unknown
+}
+
+// Vacay types
+export interface VacayPlan {
+ id: number
+ holidays_enabled: boolean
+ holidays_region: string | null
+ name?: string
+ year?: number
+ owner_id?: number
+ created_at?: string
+ updated_at?: string
+}
+
+export interface VacayUser {
+ id: number
+ username: string
+ color: string | null
+}
+
+export interface VacayEntry {
+ date: string
+ user_id: number
+}
+
+export interface VacayStat {
+ user_id: number
+ vacation_days: number
+ used: number
+}
+
+export interface HolidayInfo {
+ name: string
+ localName: string
+}
+
+export interface HolidaysMap {
+ [date: string]: HolidayInfo
+}
+
+// API error shape from axios
+export interface ApiError {
+ response?: {
+ data?: {
+ error?: string
+ }
+ status?: number
+ }
+ message: string
+}
+
+/** Safely extract an error message from an unknown catch value */
+export function getApiErrorMessage(err: unknown, fallback: string): string {
+ if (typeof err === 'object' && err !== null && 'response' in err) {
+ const apiErr = err as ApiError
+ if (apiErr.response?.data?.error) return apiErr.response.data.error
+ }
+ if (err instanceof Error) return err.message
+ return fallback
+}
+
+// MergedItem used in day notes hook
+export interface MergedItem {
+ type: 'assignment' | 'note'
+ sortKey: number
+ data: Assignment | DayNote
+}
diff --git a/client/src/utils/formatters.ts b/client/src/utils/formatters.ts
new file mode 100644
index 000000000..e2e47c3b2
--- /dev/null
+++ b/client/src/utils/formatters.ts
@@ -0,0 +1,31 @@
+import type { AssignmentsMap } from '../types'
+
+export function formatDate(dateStr: string | null | undefined, locale: string): string | null {
+ if (!dateStr) return null
+ return new Date(dateStr + 'T00:00:00').toLocaleDateString(locale, {
+ weekday: 'short', day: 'numeric', month: 'short',
+ })
+}
+
+export function formatTime(timeStr: string | null | undefined, locale: string, timeFormat: string): string {
+ if (!timeStr) return ''
+ try {
+ const parts = timeStr.split(':')
+ const h = Number(parts[0]) || 0
+ const m = Number(parts[1]) || 0
+ if (isNaN(h)) return timeStr
+ if (timeFormat === '12h') {
+ const period = h >= 12 ? 'PM' : 'AM'
+ const h12 = h === 0 ? 12 : h > 12 ? h - 12 : h
+ return `${h12}:${String(m).padStart(2, '0')} ${period}`
+ }
+ const str = `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`
+ return locale?.startsWith('de') ? `${str} Uhr` : str
+ } catch { return timeStr }
+}
+
+export function dayTotalCost(dayId: number, assignments: AssignmentsMap, currency: string): string | null {
+ const da = assignments[String(dayId)] || []
+ const total = da.reduce((s, a) => s + (parseFloat(a.place?.price || '') || 0), 0)
+ return total > 0 ? `${total.toFixed(0)} ${currency}` : null
+}
diff --git a/client/src/utils/reorder.ts b/client/src/utils/reorder.ts
new file mode 100644
index 000000000..232697f2b
--- /dev/null
+++ b/client/src/utils/reorder.ts
@@ -0,0 +1,12 @@
+interface ItemWithId {
+ id: number
+ [key: string]: unknown
+}
+
+export function swapItems(items: ItemWithId[], index: number, direction: 'up' | 'down'): number[] | null {
+ const target = direction === 'up' ? index - 1 : index + 1
+ if (target < 0 || target >= items.length) return null
+ const ids = items.map((a) => a.id)
+ ;[ids[index], ids[target]] = [ids[target], ids[index]]
+ return ids
+}
diff --git a/client/tsconfig.json b/client/tsconfig.json
new file mode 100644
index 000000000..81cc7b93d
--- /dev/null
+++ b/client/tsconfig.json
@@ -0,0 +1,24 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "useDefineForClassFields": true,
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "skipLibCheck": true,
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "isolatedModules": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "jsx": "react-jsx",
+ "strict": false,
+ "noUnusedLocals": false,
+ "noUnusedParameters": false,
+ "noFallthroughCasesInSwitch": true,
+ "allowJs": true,
+ "esModuleInterop": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true
+ },
+ "include": ["src"]
+}
diff --git a/server/package-lock.json b/server/package-lock.json
index a1818acfb..6be8c5fc9 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -19,14 +19,651 @@
"multer": "^1.4.5-lts.1",
"node-cron": "^4.2.1",
"node-fetch": "^2.7.0",
+ "tsx": "^4.21.0",
+ "typescript": "^6.0.2",
"unzipper": "^0.12.3",
"uuid": "^9.0.0",
"ws": "^8.19.0"
},
"devDependencies": {
+ "@types/archiver": "^7.0.0",
+ "@types/bcryptjs": "^2.4.6",
+ "@types/better-sqlite3": "^7.6.13",
+ "@types/cors": "^2.8.19",
+ "@types/express": "^5.0.6",
+ "@types/jsonwebtoken": "^9.0.10",
+ "@types/multer": "^2.1.0",
+ "@types/node": "^25.5.0",
+ "@types/node-cron": "^3.0.11",
+ "@types/unzipper": "^0.10.11",
+ "@types/uuid": "^10.0.0",
+ "@types/ws": "^8.18.1",
"nodemon": "^3.1.0"
}
},
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz",
+ "integrity": "sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.4.tgz",
+ "integrity": "sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.4.tgz",
+ "integrity": "sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.4.tgz",
+ "integrity": "sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.4.tgz",
+ "integrity": "sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.4.tgz",
+ "integrity": "sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.4.tgz",
+ "integrity": "sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.4.tgz",
+ "integrity": "sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.4.tgz",
+ "integrity": "sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.4.tgz",
+ "integrity": "sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.4.tgz",
+ "integrity": "sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.4.tgz",
+ "integrity": "sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==",
+ "cpu": [
+ "loong64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.4.tgz",
+ "integrity": "sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.4.tgz",
+ "integrity": "sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.4.tgz",
+ "integrity": "sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.4.tgz",
+ "integrity": "sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==",
+ "cpu": [
+ "s390x"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.4.tgz",
+ "integrity": "sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.4.tgz",
+ "integrity": "sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.4.tgz",
+ "integrity": "sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.4.tgz",
+ "integrity": "sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.4.tgz",
+ "integrity": "sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.4.tgz",
+ "integrity": "sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.4.tgz",
+ "integrity": "sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.4.tgz",
+ "integrity": "sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.4.tgz",
+ "integrity": "sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.4.tgz",
+ "integrity": "sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@types/archiver": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/@types/archiver/-/archiver-7.0.0.tgz",
+ "integrity": "sha512-/3vwGwx9n+mCQdYZ2IKGGHEFL30I96UgBlk8EtRDDFQ9uxM1l4O5Ci6r00EMAkiDaTqD9DQ6nVrWRICnBPtzzg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/readdir-glob": "*"
+ }
+ },
+ "node_modules/@types/bcryptjs": {
+ "version": "2.4.6",
+ "resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz",
+ "integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/better-sqlite3": {
+ "version": "7.6.13",
+ "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz",
+ "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/body-parser": {
+ "version": "1.19.6",
+ "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
+ "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/connect": "*",
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/connect": {
+ "version": "3.4.38",
+ "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",
+ "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/cors": {
+ "version": "2.8.19",
+ "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz",
+ "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/express": {
+ "version": "5.0.6",
+ "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",
+ "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/body-parser": "*",
+ "@types/express-serve-static-core": "^5.0.0",
+ "@types/serve-static": "^2"
+ }
+ },
+ "node_modules/@types/express-serve-static-core": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.1.tgz",
+ "integrity": "sha512-v4zIMr/cX7/d2BpAEX3KNKL/JrT1s43s96lLvvdTmza1oEvDudCqK9aF/djc/SWgy8Yh0h30TZx5VpzqFCxk5A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*",
+ "@types/qs": "*",
+ "@types/range-parser": "*",
+ "@types/send": "*"
+ }
+ },
+ "node_modules/@types/http-errors": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz",
+ "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/jsonwebtoken": {
+ "version": "9.0.10",
+ "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz",
+ "integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/ms": "*",
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/ms": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/multer": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@types/multer/-/multer-2.1.0.tgz",
+ "integrity": "sha512-zYZb0+nJhOHtPpGDb3vqPjwpdeGlGC157VpkqNQL+UU2qwoacoQ7MpsAmUptI/0Oa127X32JzWDqQVEXp2RcIA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/express": "*"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "25.5.0",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-25.5.0.tgz",
+ "integrity": "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~7.18.0"
+ }
+ },
+ "node_modules/@types/node-cron": {
+ "version": "3.0.11",
+ "resolved": "https://registry.npmjs.org/@types/node-cron/-/node-cron-3.0.11.tgz",
+ "integrity": "sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/qs": {
+ "version": "6.15.0",
+ "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.0.tgz",
+ "integrity": "sha512-JawvT8iBVWpzTrz3EGw9BTQFg3BQNmwERdKE22vlTxawwtbyUSlMppvZYKLZzB5zgACXdXxbD3m1bXaMqP/9ow==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/range-parser": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",
+ "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/readdir-glob": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@types/readdir-glob/-/readdir-glob-1.1.5.tgz",
+ "integrity": "sha512-raiuEPUYqXu+nvtY2Pe8s8FEmZ3x5yAH4VkLdihcPdalvsHltomrRC9BzuStrJ9yk06470hS0Crw0f1pXqD+Hg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/send": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",
+ "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/serve-static": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz",
+ "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/http-errors": "*",
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/unzipper": {
+ "version": "0.10.11",
+ "resolved": "https://registry.npmjs.org/@types/unzipper/-/unzipper-0.10.11.tgz",
+ "integrity": "sha512-D25im2zjyMCcgL9ag6N46+wbtJBnXIr7SI4zHf9eJD2Dw2tEB5e+p5MYkrxKIVRscs5QV0EhtU9rgXSPx90oJg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/uuid": {
+ "version": "10.0.0",
+ "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",
+ "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/ws": {
+ "version": "8.18.1",
+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
@@ -805,6 +1442,47 @@
"node": ">= 0.4"
}
},
+ "node_modules/esbuild": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.4.tgz",
+ "integrity": "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.27.4",
+ "@esbuild/android-arm": "0.27.4",
+ "@esbuild/android-arm64": "0.27.4",
+ "@esbuild/android-x64": "0.27.4",
+ "@esbuild/darwin-arm64": "0.27.4",
+ "@esbuild/darwin-x64": "0.27.4",
+ "@esbuild/freebsd-arm64": "0.27.4",
+ "@esbuild/freebsd-x64": "0.27.4",
+ "@esbuild/linux-arm": "0.27.4",
+ "@esbuild/linux-arm64": "0.27.4",
+ "@esbuild/linux-ia32": "0.27.4",
+ "@esbuild/linux-loong64": "0.27.4",
+ "@esbuild/linux-mips64el": "0.27.4",
+ "@esbuild/linux-ppc64": "0.27.4",
+ "@esbuild/linux-riscv64": "0.27.4",
+ "@esbuild/linux-s390x": "0.27.4",
+ "@esbuild/linux-x64": "0.27.4",
+ "@esbuild/netbsd-arm64": "0.27.4",
+ "@esbuild/netbsd-x64": "0.27.4",
+ "@esbuild/openbsd-arm64": "0.27.4",
+ "@esbuild/openbsd-x64": "0.27.4",
+ "@esbuild/openharmony-arm64": "0.27.4",
+ "@esbuild/sunos-x64": "0.27.4",
+ "@esbuild/win32-arm64": "0.27.4",
+ "@esbuild/win32-ia32": "0.27.4",
+ "@esbuild/win32-x64": "0.27.4"
+ }
+ },
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
@@ -975,7 +1653,6 @@
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
- "dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
@@ -1032,6 +1709,18 @@
"node": ">= 0.4"
}
},
+ "node_modules/get-tsconfig": {
+ "version": "4.13.7",
+ "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.7.tgz",
+ "integrity": "sha512-7tN6rFgBlMgpBML5j8typ92BKFi2sFQvIdpAqLA2beia5avZDrMs0FLZiM5etShWq5irVyGcGMEA1jcDaK7A/Q==",
+ "license": "MIT",
+ "dependencies": {
+ "resolve-pkg-maps": "^1.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
+ }
+ },
"node_modules/github-from-package": {
"version": "0.0.0",
"resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
@@ -1977,6 +2666,15 @@
"node": ">=8.10.0"
}
},
+ "node_modules/resolve-pkg-maps": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
+ "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
+ }
+ },
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
@@ -2351,6 +3049,25 @@
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"license": "MIT"
},
+ "node_modules/tsx": {
+ "version": "4.21.0",
+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
+ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "~0.27.0",
+ "get-tsconfig": "^4.7.5"
+ },
+ "bin": {
+ "tsx": "dist/cli.mjs"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ }
+ },
"node_modules/tunnel-agent": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
@@ -2382,6 +3099,19 @@
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
"license": "MIT"
},
+ "node_modules/typescript": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.2.tgz",
+ "integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==",
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
"node_modules/undefsafe": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz",
@@ -2389,6 +3119,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/undici-types": {
+ "version": "7.18.2",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
+ "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/universalify": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
diff --git a/server/package.json b/server/package.json
index db8bddcc2..a8f78aa22 100644
--- a/server/package.json
+++ b/server/package.json
@@ -1,10 +1,10 @@
{
"name": "nomad-server",
- "version": "2.6.0",
- "main": "src/index.js",
+ "version": "2.6.1",
+ "main": "src/index.ts",
"scripts": {
- "start": "node src/index.js",
- "dev": "nodemon src/index.js"
+ "start": "node --import tsx src/index.ts",
+ "dev": "tsx watch src/index.ts"
},
"dependencies": {
"archiver": "^6.0.1",
@@ -18,11 +18,25 @@
"multer": "^1.4.5-lts.1",
"node-cron": "^4.2.1",
"node-fetch": "^2.7.0",
+ "tsx": "^4.21.0",
+ "typescript": "^6.0.2",
"unzipper": "^0.12.3",
"uuid": "^9.0.0",
"ws": "^8.19.0"
},
"devDependencies": {
+ "@types/archiver": "^7.0.0",
+ "@types/bcryptjs": "^2.4.6",
+ "@types/better-sqlite3": "^7.6.13",
+ "@types/cors": "^2.8.19",
+ "@types/express": "^5.0.6",
+ "@types/jsonwebtoken": "^9.0.10",
+ "@types/multer": "^2.1.0",
+ "@types/node": "^25.5.0",
+ "@types/node-cron": "^3.0.11",
+ "@types/unzipper": "^0.10.11",
+ "@types/uuid": "^10.0.0",
+ "@types/ws": "^8.18.1",
"nodemon": "^3.1.0"
}
}
diff --git a/server/src/config.js b/server/src/config.ts
similarity index 67%
rename from server/src/config.js
rename to server/src/config.ts
index 2a8f4bc74..e7ac9ed15 100644
--- a/server/src/config.js
+++ b/server/src/config.ts
@@ -1,28 +1,26 @@
-const crypto = require('crypto');
-const fs = require('fs');
-const path = require('path');
+import crypto from 'crypto';
+import fs from 'fs';
+import path from 'path';
-let JWT_SECRET = process.env.JWT_SECRET;
+let JWT_SECRET: string = process.env.JWT_SECRET || '';
if (!JWT_SECRET) {
- // Try to read a persisted secret from disk
const dataDir = path.resolve(__dirname, '../data');
const secretFile = path.join(dataDir, '.jwt_secret');
try {
JWT_SECRET = fs.readFileSync(secretFile, 'utf8').trim();
} catch {
- // File doesn't exist yet — generate and persist a new secret
JWT_SECRET = crypto.randomBytes(32).toString('hex');
try {
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
fs.writeFileSync(secretFile, JWT_SECRET, { mode: 0o600 });
console.log('Generated and saved JWT secret to', secretFile);
- } catch (writeErr) {
- console.warn('WARNING: Could not persist JWT secret to disk:', writeErr.message);
+ } catch (writeErr: unknown) {
+ console.warn('WARNING: Could not persist JWT secret to disk:', writeErr instanceof Error ? writeErr.message : writeErr);
console.warn('Sessions will reset on server restart. Set JWT_SECRET env var for persistent sessions.');
}
}
}
-module.exports = { JWT_SECRET };
+export { JWT_SECRET };
diff --git a/server/src/db/database.js b/server/src/db/database.js
deleted file mode 100644
index ad25e449a..000000000
--- a/server/src/db/database.js
+++ /dev/null
@@ -1,754 +0,0 @@
-const Database = require('better-sqlite3');
-const path = require('path');
-const fs = require('fs');
-const bcrypt = require('bcryptjs');
-
-const dataDir = path.join(__dirname, '../../data');
-if (!fs.existsSync(dataDir)) {
- fs.mkdirSync(dataDir, { recursive: true });
-}
-
-const dbPath = path.join(dataDir, 'travel.db');
-
-let _db = null;
-
-function initDb() {
- if (_db) {
- try { _db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
- try { _db.close(); } catch (e) {}
- _db = null;
- }
-
- _db = new Database(dbPath);
- _db.exec('PRAGMA journal_mode = WAL');
- _db.exec('PRAGMA busy_timeout = 5000');
- _db.exec('PRAGMA foreign_keys = ON');
-
- // Create all tables
- _db.exec(`
- CREATE TABLE IF NOT EXISTS users (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- username TEXT UNIQUE NOT NULL,
- email TEXT UNIQUE NOT NULL,
- password_hash TEXT NOT NULL,
- role TEXT NOT NULL DEFAULT 'user',
- maps_api_key TEXT,
- unsplash_api_key TEXT,
- openweather_api_key TEXT,
- avatar TEXT,
- oidc_sub TEXT,
- oidc_issuer TEXT,
- last_login DATETIME,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS settings (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- key TEXT NOT NULL,
- value TEXT,
- UNIQUE(user_id, key)
- );
-
- CREATE TABLE IF NOT EXISTS trips (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- title TEXT NOT NULL,
- description TEXT,
- start_date TEXT,
- end_date TEXT,
- currency TEXT DEFAULT 'EUR',
- cover_image TEXT,
- is_archived INTEGER DEFAULT 0,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS days (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- day_number INTEGER NOT NULL,
- date TEXT,
- notes TEXT,
- title TEXT,
- UNIQUE(trip_id, day_number)
- );
-
- CREATE TABLE IF NOT EXISTS categories (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- name TEXT NOT NULL,
- color TEXT DEFAULT '#6366f1',
- icon TEXT DEFAULT '📍',
- user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS tags (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- name TEXT NOT NULL,
- color TEXT DEFAULT '#10b981',
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS places (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- name TEXT NOT NULL,
- description TEXT,
- lat REAL,
- lng REAL,
- address TEXT,
- category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL,
- price REAL,
- currency TEXT,
- reservation_status TEXT DEFAULT 'none',
- reservation_notes TEXT,
- reservation_datetime TEXT,
- place_time TEXT,
- end_time TEXT,
- duration_minutes INTEGER DEFAULT 60,
- notes TEXT,
- image_url TEXT,
- google_place_id TEXT,
- website TEXT,
- phone TEXT,
- transport_mode TEXT DEFAULT 'walking',
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS place_tags (
- place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
- tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
- PRIMARY KEY (place_id, tag_id)
- );
-
- CREATE TABLE IF NOT EXISTS day_assignments (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
- place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
- order_index INTEGER DEFAULT 0,
- notes TEXT,
- reservation_status TEXT DEFAULT 'none',
- reservation_notes TEXT,
- reservation_datetime TEXT,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS packing_items (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- name TEXT NOT NULL,
- checked INTEGER DEFAULT 0,
- category TEXT,
- sort_order INTEGER DEFAULT 0,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS photos (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- day_id INTEGER REFERENCES days(id) ON DELETE SET NULL,
- place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
- filename TEXT NOT NULL,
- original_name TEXT NOT NULL,
- file_size INTEGER,
- mime_type TEXT,
- caption TEXT,
- taken_at TEXT,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS trip_files (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
- reservation_id INTEGER REFERENCES reservations(id) ON DELETE SET NULL,
- filename TEXT NOT NULL,
- original_name TEXT NOT NULL,
- file_size INTEGER,
- mime_type TEXT,
- description TEXT,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS reservations (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- day_id INTEGER REFERENCES days(id) ON DELETE SET NULL,
- place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
- assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE SET NULL,
- title TEXT NOT NULL,
- reservation_time TEXT,
- reservation_end_time TEXT,
- location TEXT,
- confirmation_number TEXT,
- notes TEXT,
- status TEXT DEFAULT 'pending',
- type TEXT DEFAULT 'other',
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS trip_members (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- invited_by INTEGER REFERENCES users(id),
- added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(trip_id, user_id)
- );
-
- CREATE TABLE IF NOT EXISTS day_notes (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- text TEXT NOT NULL,
- time TEXT,
- icon TEXT DEFAULT '📝',
- sort_order REAL DEFAULT 0,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS app_settings (
- key TEXT PRIMARY KEY,
- value TEXT
- );
-
- CREATE TABLE IF NOT EXISTS budget_items (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- category TEXT NOT NULL DEFAULT 'Other',
- name TEXT NOT NULL,
- total_price REAL NOT NULL DEFAULT 0,
- persons INTEGER DEFAULT NULL,
- days INTEGER DEFAULT NULL,
- note TEXT,
- sort_order INTEGER DEFAULT 0,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- -- Addon system
- CREATE TABLE IF NOT EXISTS addons (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- description TEXT,
- type TEXT NOT NULL DEFAULT 'global',
- icon TEXT DEFAULT 'Puzzle',
- enabled INTEGER DEFAULT 0,
- config TEXT DEFAULT '{}',
- sort_order INTEGER DEFAULT 0
- );
-
- -- Vacay addon tables
- CREATE TABLE IF NOT EXISTS vacay_plans (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- block_weekends INTEGER DEFAULT 1,
- holidays_enabled INTEGER DEFAULT 0,
- holidays_region TEXT DEFAULT '',
- company_holidays_enabled INTEGER DEFAULT 1,
- carry_over_enabled INTEGER DEFAULT 1,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(owner_id)
- );
-
- CREATE TABLE IF NOT EXISTS vacay_plan_members (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- status TEXT DEFAULT 'pending',
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(plan_id, user_id)
- );
-
- CREATE TABLE IF NOT EXISTS vacay_user_colors (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
- color TEXT DEFAULT '#6366f1',
- UNIQUE(user_id, plan_id)
- );
-
- CREATE TABLE IF NOT EXISTS vacay_years (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
- year INTEGER NOT NULL,
- UNIQUE(plan_id, year)
- );
-
- CREATE TABLE IF NOT EXISTS vacay_user_years (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
- year INTEGER NOT NULL,
- vacation_days INTEGER DEFAULT 30,
- carried_over INTEGER DEFAULT 0,
- UNIQUE(user_id, plan_id, year)
- );
-
- CREATE TABLE IF NOT EXISTS vacay_entries (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- date TEXT NOT NULL,
- note TEXT DEFAULT '',
- UNIQUE(user_id, plan_id, date)
- );
-
- CREATE TABLE IF NOT EXISTS vacay_company_holidays (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
- date TEXT NOT NULL,
- note TEXT DEFAULT '',
- UNIQUE(plan_id, date)
- );
-
- CREATE TABLE IF NOT EXISTS day_accommodations (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
- start_day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
- end_day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
- check_in TEXT,
- check_out TEXT,
- confirmation TEXT,
- notes TEXT,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- -- Collab addon tables
- CREATE TABLE IF NOT EXISTS collab_notes (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- category TEXT DEFAULT 'General',
- title TEXT NOT NULL,
- content TEXT,
- color TEXT DEFAULT '#6366f1',
- pinned INTEGER DEFAULT 0,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS collab_polls (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- question TEXT NOT NULL,
- options TEXT NOT NULL,
- multiple INTEGER DEFAULT 0,
- closed INTEGER DEFAULT 0,
- deadline TEXT,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE TABLE IF NOT EXISTS collab_poll_votes (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- poll_id INTEGER NOT NULL REFERENCES collab_polls(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- option_index INTEGER NOT NULL,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(poll_id, user_id, option_index)
- );
-
- CREATE TABLE IF NOT EXISTS collab_messages (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- text TEXT NOT NULL,
- reply_to INTEGER REFERENCES collab_messages(id) ON DELETE SET NULL,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
-
- CREATE INDEX IF NOT EXISTS idx_collab_notes_trip ON collab_notes(trip_id);
- CREATE INDEX IF NOT EXISTS idx_collab_polls_trip ON collab_polls(trip_id);
- CREATE INDEX IF NOT EXISTS idx_collab_messages_trip ON collab_messages(trip_id);
- `);
-
- // Create indexes for performance
- _db.exec(`
- CREATE INDEX IF NOT EXISTS idx_places_trip_id ON places(trip_id);
- CREATE INDEX IF NOT EXISTS idx_places_category_id ON places(category_id);
- CREATE INDEX IF NOT EXISTS idx_days_trip_id ON days(trip_id);
- CREATE INDEX IF NOT EXISTS idx_day_assignments_day_id ON day_assignments(day_id);
- CREATE INDEX IF NOT EXISTS idx_day_assignments_place_id ON day_assignments(place_id);
- CREATE INDEX IF NOT EXISTS idx_place_tags_place_id ON place_tags(place_id);
- CREATE INDEX IF NOT EXISTS idx_place_tags_tag_id ON place_tags(tag_id);
- CREATE INDEX IF NOT EXISTS idx_trip_members_trip_id ON trip_members(trip_id);
- CREATE INDEX IF NOT EXISTS idx_trip_members_user_id ON trip_members(user_id);
- CREATE INDEX IF NOT EXISTS idx_packing_items_trip_id ON packing_items(trip_id);
- CREATE INDEX IF NOT EXISTS idx_budget_items_trip_id ON budget_items(trip_id);
- CREATE INDEX IF NOT EXISTS idx_reservations_trip_id ON reservations(trip_id);
- CREATE INDEX IF NOT EXISTS idx_trip_files_trip_id ON trip_files(trip_id);
- CREATE INDEX IF NOT EXISTS idx_day_notes_day_id ON day_notes(day_id);
- CREATE INDEX IF NOT EXISTS idx_photos_trip_id ON photos(trip_id);
- CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
- CREATE INDEX IF NOT EXISTS idx_day_accommodations_trip_id ON day_accommodations(trip_id);
-
- CREATE TABLE IF NOT EXISTS assignment_participants (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- assignment_id INTEGER NOT NULL REFERENCES day_assignments(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- UNIQUE(assignment_id, user_id)
- );
- CREATE INDEX IF NOT EXISTS idx_assignment_participants_assignment ON assignment_participants(assignment_id);
- `);
-
- // Versioned migrations — each runs exactly once
- _db.exec('CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)');
- const versionRow = _db.prepare('SELECT version FROM schema_version').get();
- let currentVersion = versionRow?.version ?? 0;
-
- // Existing or fresh DBs may already have columns the migrations add.
- // Detect by checking for a column from migration 1 (unsplash_api_key).
- if (currentVersion === 0) {
- const hasUnsplash = _db.prepare(
- "SELECT 1 FROM pragma_table_info('users') WHERE name = 'unsplash_api_key'"
- ).get();
- if (hasUnsplash) {
- // All columns from CREATE TABLE already exist — skip ALTER migrations
- currentVersion = 19;
- _db.prepare('INSERT INTO schema_version (version) VALUES (?)').run(currentVersion);
- console.log('[DB] Schema already up-to-date, setting version to', currentVersion);
- } else {
- _db.prepare('INSERT INTO schema_version (version) VALUES (?)').run(0);
- }
- }
-
- const migrations = [
- // 1–18: ALTER TABLE additions
- () => _db.exec('ALTER TABLE users ADD COLUMN unsplash_api_key TEXT'),
- () => _db.exec('ALTER TABLE users ADD COLUMN openweather_api_key TEXT'),
- () => _db.exec('ALTER TABLE places ADD COLUMN duration_minutes INTEGER DEFAULT 60'),
- () => _db.exec('ALTER TABLE places ADD COLUMN notes TEXT'),
- () => _db.exec('ALTER TABLE places ADD COLUMN image_url TEXT'),
- () => _db.exec("ALTER TABLE places ADD COLUMN transport_mode TEXT DEFAULT 'walking'"),
- () => _db.exec('ALTER TABLE days ADD COLUMN title TEXT'),
- () => _db.exec("ALTER TABLE reservations ADD COLUMN status TEXT DEFAULT 'pending'"),
- () => _db.exec('ALTER TABLE trip_files ADD COLUMN reservation_id INTEGER REFERENCES reservations(id) ON DELETE SET NULL'),
- () => _db.exec("ALTER TABLE reservations ADD COLUMN type TEXT DEFAULT 'other'"),
- () => _db.exec('ALTER TABLE trips ADD COLUMN cover_image TEXT'),
- () => _db.exec("ALTER TABLE day_notes ADD COLUMN icon TEXT DEFAULT '📝'"),
- () => _db.exec('ALTER TABLE trips ADD COLUMN is_archived INTEGER DEFAULT 0'),
- () => _db.exec('ALTER TABLE categories ADD COLUMN user_id INTEGER REFERENCES users(id) ON DELETE SET NULL'),
- () => _db.exec('ALTER TABLE users ADD COLUMN avatar TEXT'),
- () => _db.exec('ALTER TABLE users ADD COLUMN oidc_sub TEXT'),
- () => _db.exec('ALTER TABLE users ADD COLUMN oidc_issuer TEXT'),
- () => _db.exec('ALTER TABLE users ADD COLUMN last_login DATETIME'),
- // 19: budget_items table rebuild (NOT NULL → nullable persons)
- () => {
- const schema = _db.prepare("SELECT sql FROM sqlite_master WHERE name = 'budget_items'").get();
- if (schema?.sql?.includes('NOT NULL DEFAULT 1')) {
- _db.exec(`
- CREATE TABLE budget_items_new (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- category TEXT NOT NULL DEFAULT 'Other',
- name TEXT NOT NULL,
- total_price REAL NOT NULL DEFAULT 0,
- persons INTEGER DEFAULT NULL,
- days INTEGER DEFAULT NULL,
- note TEXT,
- sort_order INTEGER DEFAULT 0,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
- INSERT INTO budget_items_new SELECT * FROM budget_items;
- DROP TABLE budget_items;
- ALTER TABLE budget_items_new RENAME TO budget_items;
- `);
- }
- },
- // 20: accommodation check-in/check-out/confirmation fields
- () => {
- try { _db.exec('ALTER TABLE day_accommodations ADD COLUMN check_in TEXT'); } catch {}
- try { _db.exec('ALTER TABLE day_accommodations ADD COLUMN check_out TEXT'); } catch {}
- try { _db.exec('ALTER TABLE day_accommodations ADD COLUMN confirmation TEXT'); } catch {}
- },
- // 21: places end_time field (place_time becomes start_time conceptually, end_time is new)
- () => {
- try { _db.exec('ALTER TABLE places ADD COLUMN end_time TEXT'); } catch {}
- },
- // 22: Move reservation fields from places to day_assignments
- () => {
- // Add new columns to day_assignments
- try { _db.exec('ALTER TABLE day_assignments ADD COLUMN reservation_status TEXT DEFAULT \'none\''); } catch {}
- try { _db.exec('ALTER TABLE day_assignments ADD COLUMN reservation_notes TEXT'); } catch {}
- try { _db.exec('ALTER TABLE day_assignments ADD COLUMN reservation_datetime TEXT'); } catch {}
-
- // Migrate existing data: copy reservation info from places to all their assignments
- try {
- _db.exec(`
- UPDATE day_assignments SET
- reservation_status = (SELECT reservation_status FROM places WHERE places.id = day_assignments.place_id),
- reservation_notes = (SELECT reservation_notes FROM places WHERE places.id = day_assignments.place_id),
- reservation_datetime = (SELECT reservation_datetime FROM places WHERE places.id = day_assignments.place_id)
- WHERE place_id IN (SELECT id FROM places WHERE reservation_status IS NOT NULL AND reservation_status != 'none')
- `);
- console.log('[DB] Migrated reservation data from places to day_assignments');
- } catch (e) {
- console.error('[DB] Migration 22 data copy error:', e.message);
- }
- },
- // 23: Add assignment_id to reservations table
- () => {
- try { _db.exec('ALTER TABLE reservations ADD COLUMN assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE SET NULL'); } catch {}
- },
- // 24: Assignment participants (who's joining which activity)
- () => {
- _db.exec(`
- CREATE TABLE IF NOT EXISTS assignment_participants (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- assignment_id INTEGER NOT NULL REFERENCES day_assignments(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- UNIQUE(assignment_id, user_id)
- )
- `);
- },
- // 25: Collab addon tables
- () => {
- _db.exec(`
- CREATE TABLE IF NOT EXISTS collab_notes (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- category TEXT DEFAULT 'General',
- title TEXT NOT NULL,
- content TEXT,
- color TEXT DEFAULT '#6366f1',
- pinned INTEGER DEFAULT 0,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
- CREATE TABLE IF NOT EXISTS collab_polls (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- question TEXT NOT NULL,
- options TEXT NOT NULL,
- multiple INTEGER DEFAULT 0,
- closed INTEGER DEFAULT 0,
- deadline TEXT,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
- CREATE TABLE IF NOT EXISTS collab_poll_votes (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- poll_id INTEGER NOT NULL REFERENCES collab_polls(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- option_index INTEGER NOT NULL,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(poll_id, user_id, option_index)
- );
- CREATE TABLE IF NOT EXISTS collab_messages (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- text TEXT NOT NULL,
- reply_to INTEGER REFERENCES collab_messages(id) ON DELETE SET NULL,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
- CREATE INDEX IF NOT EXISTS idx_collab_notes_trip ON collab_notes(trip_id);
- CREATE INDEX IF NOT EXISTS idx_collab_polls_trip ON collab_polls(trip_id);
- CREATE INDEX IF NOT EXISTS idx_collab_messages_trip ON collab_messages(trip_id);
- `);
- // Ensure collab addon exists for existing installations
- try {
- _db.prepare("INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES ('collab', 'Collab', 'Notes, polls, and live chat for trip collaboration', 'trip', 'Users', 1, 6)").run();
- } catch {}
- },
- // 26: Per-assignment times (instead of shared place times)
- () => {
- try { _db.exec('ALTER TABLE day_assignments ADD COLUMN assignment_time TEXT'); } catch {}
- try { _db.exec('ALTER TABLE day_assignments ADD COLUMN assignment_end_time TEXT'); } catch {}
- // Copy existing place times to assignments as initial values
- try {
- _db.exec(`
- UPDATE day_assignments SET
- assignment_time = (SELECT place_time FROM places WHERE places.id = day_assignments.place_id),
- assignment_end_time = (SELECT end_time FROM places WHERE places.id = day_assignments.place_id)
- `);
- } catch {}
- },
- // 27: Budget item members (per-person expense tracking)
- () => {
- _db.exec(`
- CREATE TABLE IF NOT EXISTS budget_item_members (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- budget_item_id INTEGER NOT NULL REFERENCES budget_items(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- paid INTEGER NOT NULL DEFAULT 0,
- UNIQUE(budget_item_id, user_id)
- );
- CREATE INDEX IF NOT EXISTS idx_budget_item_members_item ON budget_item_members(budget_item_id);
- CREATE INDEX IF NOT EXISTS idx_budget_item_members_user ON budget_item_members(user_id);
- `);
- },
- // 28: Message reactions
- () => {
- _db.exec(`
- CREATE TABLE IF NOT EXISTS collab_message_reactions (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- message_id INTEGER NOT NULL REFERENCES collab_messages(id) ON DELETE CASCADE,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- emoji TEXT NOT NULL,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(message_id, user_id, emoji)
- );
- CREATE INDEX IF NOT EXISTS idx_collab_reactions_msg ON collab_message_reactions(message_id);
- `);
- },
- // 29: Soft-delete for chat messages
- () => {
- try { _db.exec('ALTER TABLE collab_messages ADD COLUMN deleted INTEGER DEFAULT 0'); } catch {}
- },
- // 30: Note attachments + website field
- () => {
- try { _db.exec('ALTER TABLE trip_files ADD COLUMN note_id INTEGER REFERENCES collab_notes(id) ON DELETE SET NULL'); } catch {}
- try { _db.exec('ALTER TABLE collab_notes ADD COLUMN website TEXT'); } catch {}
- },
- // 28: Add end_time to reservations
- () => {
- try { _db.exec('ALTER TABLE reservations ADD COLUMN reservation_end_time TEXT'); } catch {}
- },
- // Future migrations go here (append only, never reorder)
- ];
-
- if (currentVersion < migrations.length) {
- for (let i = currentVersion; i < migrations.length; i++) {
- console.log(`[DB] Running migration ${i + 1}/${migrations.length}`);
- migrations[i]();
- }
- _db.prepare('UPDATE schema_version SET version = ?').run(migrations.length);
- console.log(`[DB] Migrations complete — schema version ${migrations.length}`);
- }
-
- // First registered user becomes admin — no default admin seed needed
-
- // Seed: default categories
- try {
- const existingCats = _db.prepare('SELECT COUNT(*) as count FROM categories').get();
- if (existingCats.count === 0) {
- const defaultCategories = [
- { name: 'Hotel', color: '#3b82f6', icon: '🏨' },
- { name: 'Restaurant', color: '#ef4444', icon: '🍽️' },
- { name: 'Attraction', color: '#8b5cf6', icon: '🏛️' },
- { name: 'Shopping', color: '#f59e0b', icon: '🛍️' },
- { name: 'Transport', color: '#6b7280', icon: '🚌' },
- { name: 'Activity', color: '#10b981', icon: '🎯' },
- { name: 'Bar/Cafe', color: '#f97316', icon: '☕' },
- { name: 'Beach', color: '#06b6d4', icon: '🏖️' },
- { name: 'Nature', color: '#84cc16', icon: '🌿' },
- { name: 'Other', color: '#6366f1', icon: '📍' },
- ];
- const insertCat = _db.prepare('INSERT INTO categories (name, color, icon) VALUES (?, ?, ?)');
- for (const cat of defaultCategories) insertCat.run(cat.name, cat.color, cat.icon);
- console.log('Default categories seeded');
- }
- } catch (err) {
- console.error('Error seeding categories:', err.message);
- }
-
- // Seed: default addons (INSERT OR IGNORE so migration-inserted rows don't block seeding)
- try {
- const defaultAddons = [
- { id: 'packing', name: 'Packing List', description: 'Pack your bags with checklists per trip', type: 'trip', icon: 'ListChecks', enabled: 1, sort_order: 0 },
- { id: 'budget', name: 'Budget Planner', description: 'Track expenses and plan your travel budget', type: 'trip', icon: 'Wallet', enabled: 1, sort_order: 1 },
- { id: 'documents', name: 'Documents', description: 'Store and manage travel documents', type: 'trip', icon: 'FileText', enabled: 1, sort_order: 2 },
- { id: 'vacay', name: 'Vacay', description: 'Personal vacation day planner with calendar view', type: 'global', icon: 'CalendarDays', enabled: 1, sort_order: 10 },
- { id: 'atlas', name: 'Atlas', description: 'World map of your visited countries with travel stats', type: 'global', icon: 'Globe', enabled: 1, sort_order: 11 },
- { id: 'collab', name: 'Collab', description: 'Notes, polls, and live chat for trip collaboration', type: 'trip', icon: 'Users', enabled: 1, sort_order: 6 },
- ];
- const insertAddon = _db.prepare('INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)');
- for (const a of defaultAddons) insertAddon.run(a.id, a.name, a.description, a.type, a.icon, a.enabled, a.sort_order);
- console.log('Default addons seeded');
- } catch (err) {
- console.error('Error seeding addons:', err.message);
- }
-}
-
-// Initialize on module load
-initDb();
-
-// Demo mode: seed admin + demo user + example trips
-if (process.env.DEMO_MODE === 'true') {
- try {
- const { seedDemoData } = require('../demo/demo-seed');
- seedDemoData(_db);
- } catch (err) {
- console.error('[Demo] Seed error:', err.message);
- }
-}
-
-// Proxy so all route modules always use the current _db instance
-// without needing a server restart after reinitialize()
-const db = new Proxy({}, {
- get(_, prop) {
- if (!_db) throw new Error('Database connection is not available (restore in progress?)');
- const val = _db[prop];
- return typeof val === 'function' ? val.bind(_db) : val;
- },
- set(_, prop, val) {
- _db[prop] = val;
- return true;
- },
-});
-
-function closeDb() {
- if (_db) {
- try { _db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
- try { _db.close(); } catch (e) {}
- _db = null;
- console.log('[DB] Database connection closed');
- }
-}
-
-function reinitialize() {
- console.log('[DB] Reinitializing database connection after restore...');
- // initDb handles close + reopen, but if closeDb was already called, _db is null
- if (_db) closeDb();
- initDb();
- console.log('[DB] Database reinitialized successfully');
-}
-
-function getPlaceWithTags(placeId) {
- const place = _db.prepare(`
- SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
- FROM places p
- LEFT JOIN categories c ON p.category_id = c.id
- WHERE p.id = ?
- `).get(placeId);
-
- if (!place) return null;
-
- const tags = _db.prepare(`
- SELECT t.* FROM tags t
- JOIN place_tags pt ON t.id = pt.tag_id
- WHERE pt.place_id = ?
- `).all(placeId);
-
- return {
- ...place,
- category: place.category_id ? {
- id: place.category_id,
- name: place.category_name,
- color: place.category_color,
- icon: place.category_icon,
- } : null,
- tags,
- };
-}
-
-function canAccessTrip(tripId, userId) {
- return _db.prepare(`
- SELECT t.id, t.user_id FROM trips t
- LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
- WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
- `).get(userId, tripId, userId);
-}
-
-function isOwner(tripId, userId) {
- return !!_db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId);
-}
-
-module.exports = { db, closeDb, reinitialize, getPlaceWithTags, canAccessTrip, isOwner };
diff --git a/server/src/db/database.ts b/server/src/db/database.ts
new file mode 100644
index 000000000..0b59233db
--- /dev/null
+++ b/server/src/db/database.ts
@@ -0,0 +1,131 @@
+import Database from 'better-sqlite3';
+import path from 'path';
+import fs from 'fs';
+import { createTables } from './schema';
+import { runMigrations } from './migrations';
+import { runSeeds } from './seeds';
+import { Place, Tag } from '../types';
+
+const dataDir = path.join(__dirname, '../../data');
+if (!fs.existsSync(dataDir)) {
+ fs.mkdirSync(dataDir, { recursive: true });
+}
+
+const dbPath = path.join(dataDir, 'travel.db');
+
+let _db: Database.Database | null = null;
+
+function initDb(): void {
+ if (_db) {
+ try { _db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
+ try { _db.close(); } catch (e) {}
+ _db = null;
+ }
+
+ _db = new Database(dbPath);
+ _db.exec('PRAGMA journal_mode = WAL');
+ _db.exec('PRAGMA busy_timeout = 5000');
+ _db.exec('PRAGMA foreign_keys = ON');
+
+ createTables(_db);
+ runMigrations(_db);
+
+ runSeeds(_db);
+}
+
+initDb();
+
+if (process.env.DEMO_MODE === 'true') {
+ try {
+ const { seedDemoData } = require('../demo/demo-seed');
+ seedDemoData(_db);
+ } catch (err: unknown) {
+ console.error('[Demo] Seed error:', err instanceof Error ? err.message : err);
+ }
+}
+
+const db = new Proxy({} as Database.Database, {
+ get(_, prop: string | symbol) {
+ if (!_db) throw new Error('Database connection is not available (restore in progress?)');
+ const val = (_db as unknown as Record<string | symbol, unknown>)[prop];
+ return typeof val === 'function' ? val.bind(_db) : val;
+ },
+ set(_, prop: string | symbol, val: unknown) {
+ (_db as unknown as Record<string | symbol, unknown>)[prop] = val;
+ return true;
+ },
+});
+
+function closeDb(): void {
+ if (_db) {
+ try { _db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
+ try { _db.close(); } catch (e) {}
+ _db = null;
+ console.log('[DB] Database connection closed');
+ }
+}
+
+function reinitialize(): void {
+ console.log('[DB] Reinitializing database connection after restore...');
+ if (_db) closeDb();
+ initDb();
+ console.log('[DB] Database reinitialized successfully');
+}
+
+interface PlaceWithCategory extends Place {
+ category_name: string | null;
+ category_color: string | null;
+ category_icon: string | null;
+}
+
+interface PlaceWithTags extends Place {
+ category: { id: number; name: string; color: string; icon: string } | null;
+ tags: Tag[];
+}
+
+function getPlaceWithTags(placeId: number | string): PlaceWithTags | null {
+ const place = _db!.prepare(`
+ SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
+ FROM places p
+ LEFT JOIN categories c ON p.category_id = c.id
+ WHERE p.id = ?
+ `).get(placeId) as PlaceWithCategory | undefined;
+
+ if (!place) return null;
+
+ const tags = _db!.prepare(`
+ SELECT t.* FROM tags t
+ JOIN place_tags pt ON t.id = pt.tag_id
+ WHERE pt.place_id = ?
+ `).all(placeId) as Tag[];
+
+ return {
+ ...place,
+ category: place.category_id ? {
+ id: place.category_id,
+ name: place.category_name!,
+ color: place.category_color!,
+ icon: place.category_icon!,
+ } : null,
+ tags,
+ };
+}
+
+interface TripAccess {
+ id: number;
+ user_id: number;
+}
+
+function canAccessTrip(tripId: number | string, userId: number): TripAccess | undefined {
+ return _db!.prepare(`
+ SELECT t.id, t.user_id FROM trips t
+ LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
+ WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
+ `).get(userId, tripId, userId) as TripAccess | undefined;
+}
+
+function isOwner(tripId: number | string, userId: number): boolean {
+ return !!_db!.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId);
+}
+
+export { db, closeDb, reinitialize, getPlaceWithTags, canAccessTrip, isOwner };
diff --git a/server/src/db/migrations.ts b/server/src/db/migrations.ts
new file mode 100644
index 000000000..dfcdf9e31
--- /dev/null
+++ b/server/src/db/migrations.ts
@@ -0,0 +1,208 @@
+import Database from 'better-sqlite3';
+
+function runMigrations(db: Database.Database): void {
+ db.exec('CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)');
+ const versionRow = db.prepare('SELECT version FROM schema_version').get() as { version: number } | undefined;
+ let currentVersion = versionRow?.version ?? 0;
+
+ if (currentVersion === 0) {
+ const hasUnsplash = db.prepare(
+ "SELECT 1 FROM pragma_table_info('users') WHERE name = 'unsplash_api_key'"
+ ).get();
+ if (hasUnsplash) {
+ currentVersion = 19;
+ db.prepare('INSERT INTO schema_version (version) VALUES (?)').run(currentVersion);
+ console.log('[DB] Schema already up-to-date, setting version to', currentVersion);
+ } else {
+ db.prepare('INSERT INTO schema_version (version) VALUES (?)').run(0);
+ }
+ }
+
+ const migrations: Array<() => void> = [
+ () => db.exec('ALTER TABLE users ADD COLUMN unsplash_api_key TEXT'),
+ () => db.exec('ALTER TABLE users ADD COLUMN openweather_api_key TEXT'),
+ () => db.exec('ALTER TABLE places ADD COLUMN duration_minutes INTEGER DEFAULT 60'),
+ () => db.exec('ALTER TABLE places ADD COLUMN notes TEXT'),
+ () => db.exec('ALTER TABLE places ADD COLUMN image_url TEXT'),
+ () => db.exec("ALTER TABLE places ADD COLUMN transport_mode TEXT DEFAULT 'walking'"),
+ () => db.exec('ALTER TABLE days ADD COLUMN title TEXT'),
+ () => db.exec("ALTER TABLE reservations ADD COLUMN status TEXT DEFAULT 'pending'"),
+ () => db.exec('ALTER TABLE trip_files ADD COLUMN reservation_id INTEGER REFERENCES reservations(id) ON DELETE SET NULL'),
+ () => db.exec("ALTER TABLE reservations ADD COLUMN type TEXT DEFAULT 'other'"),
+ () => db.exec('ALTER TABLE trips ADD COLUMN cover_image TEXT'),
+ () => db.exec("ALTER TABLE day_notes ADD COLUMN icon TEXT DEFAULT '📝'"),
+ () => db.exec('ALTER TABLE trips ADD COLUMN is_archived INTEGER DEFAULT 0'),
+ () => db.exec('ALTER TABLE categories ADD COLUMN user_id INTEGER REFERENCES users(id) ON DELETE SET NULL'),
+ () => db.exec('ALTER TABLE users ADD COLUMN avatar TEXT'),
+ () => db.exec('ALTER TABLE users ADD COLUMN oidc_sub TEXT'),
+ () => db.exec('ALTER TABLE users ADD COLUMN oidc_issuer TEXT'),
+ () => db.exec('ALTER TABLE users ADD COLUMN last_login DATETIME'),
+ () => {
+ const schema = db.prepare("SELECT sql FROM sqlite_master WHERE name = 'budget_items'").get() as { sql: string } | undefined;
+ if (schema?.sql?.includes('NOT NULL DEFAULT 1')) {
+ db.exec(`
+ CREATE TABLE budget_items_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ category TEXT NOT NULL DEFAULT 'Other',
+ name TEXT NOT NULL,
+ total_price REAL NOT NULL DEFAULT 0,
+ persons INTEGER DEFAULT NULL,
+ days INTEGER DEFAULT NULL,
+ note TEXT,
+ sort_order INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ INSERT INTO budget_items_new SELECT * FROM budget_items;
+ DROP TABLE budget_items;
+ ALTER TABLE budget_items_new RENAME TO budget_items;
+ `);
+ }
+ },
+ () => {
+ try { db.exec('ALTER TABLE day_accommodations ADD COLUMN check_in TEXT'); } catch {}
+ try { db.exec('ALTER TABLE day_accommodations ADD COLUMN check_out TEXT'); } catch {}
+ try { db.exec('ALTER TABLE day_accommodations ADD COLUMN confirmation TEXT'); } catch {}
+ },
+ () => {
+ try { db.exec('ALTER TABLE places ADD COLUMN end_time TEXT'); } catch {}
+ },
+ () => {
+ try { db.exec('ALTER TABLE day_assignments ADD COLUMN reservation_status TEXT DEFAULT \'none\''); } catch {}
+ try { db.exec('ALTER TABLE day_assignments ADD COLUMN reservation_notes TEXT'); } catch {}
+ try { db.exec('ALTER TABLE day_assignments ADD COLUMN reservation_datetime TEXT'); } catch {}
+ try {
+ db.exec(`
+ UPDATE day_assignments SET
+ reservation_status = (SELECT reservation_status FROM places WHERE places.id = day_assignments.place_id),
+ reservation_notes = (SELECT reservation_notes FROM places WHERE places.id = day_assignments.place_id),
+ reservation_datetime = (SELECT reservation_datetime FROM places WHERE places.id = day_assignments.place_id)
+ WHERE place_id IN (SELECT id FROM places WHERE reservation_status IS NOT NULL AND reservation_status != 'none')
+ `);
+ console.log('[DB] Migrated reservation data from places to day_assignments');
+ } catch (e: unknown) {
+ console.error('[DB] Migration 22 data copy error:', e instanceof Error ? e.message : e);
+ }
+ },
+ () => {
+ try { db.exec('ALTER TABLE reservations ADD COLUMN assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE SET NULL'); } catch {}
+ },
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS assignment_participants (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ assignment_id INTEGER NOT NULL REFERENCES day_assignments(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ UNIQUE(assignment_id, user_id)
+ )
+ `);
+ },
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS collab_notes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ category TEXT DEFAULT 'General',
+ title TEXT NOT NULL,
+ content TEXT,
+ color TEXT DEFAULT '#6366f1',
+ pinned INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE TABLE IF NOT EXISTS collab_polls (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ question TEXT NOT NULL,
+ options TEXT NOT NULL,
+ multiple INTEGER DEFAULT 0,
+ closed INTEGER DEFAULT 0,
+ deadline TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE TABLE IF NOT EXISTS collab_poll_votes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ poll_id INTEGER NOT NULL REFERENCES collab_polls(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ option_index INTEGER NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(poll_id, user_id, option_index)
+ );
+ CREATE TABLE IF NOT EXISTS collab_messages (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ text TEXT NOT NULL,
+ reply_to INTEGER REFERENCES collab_messages(id) ON DELETE SET NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE INDEX IF NOT EXISTS idx_collab_notes_trip ON collab_notes(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_collab_polls_trip ON collab_polls(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_collab_messages_trip ON collab_messages(trip_id);
+ `);
+ try {
+ db.prepare("INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES ('collab', 'Collab', 'Notes, polls, and live chat for trip collaboration', 'trip', 'Users', 1, 6)").run();
+ } catch {}
+ },
+ () => {
+ try { db.exec('ALTER TABLE day_assignments ADD COLUMN assignment_time TEXT'); } catch {}
+ try { db.exec('ALTER TABLE day_assignments ADD COLUMN assignment_end_time TEXT'); } catch {}
+ try {
+ db.exec(`
+ UPDATE day_assignments SET
+ assignment_time = (SELECT place_time FROM places WHERE places.id = day_assignments.place_id),
+ assignment_end_time = (SELECT end_time FROM places WHERE places.id = day_assignments.place_id)
+ `);
+ } catch {}
+ },
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS budget_item_members (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ budget_item_id INTEGER NOT NULL REFERENCES budget_items(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ paid INTEGER NOT NULL DEFAULT 0,
+ UNIQUE(budget_item_id, user_id)
+ );
+ CREATE INDEX IF NOT EXISTS idx_budget_item_members_item ON budget_item_members(budget_item_id);
+ CREATE INDEX IF NOT EXISTS idx_budget_item_members_user ON budget_item_members(user_id);
+ `);
+ },
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS collab_message_reactions (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ message_id INTEGER NOT NULL REFERENCES collab_messages(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ emoji TEXT NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(message_id, user_id, emoji)
+ );
+ CREATE INDEX IF NOT EXISTS idx_collab_reactions_msg ON collab_message_reactions(message_id);
+ `);
+ },
+ () => {
+ try { db.exec('ALTER TABLE collab_messages ADD COLUMN deleted INTEGER DEFAULT 0'); } catch {}
+ },
+ () => {
+ try { db.exec('ALTER TABLE trip_files ADD COLUMN note_id INTEGER REFERENCES collab_notes(id) ON DELETE SET NULL'); } catch {}
+ try { db.exec('ALTER TABLE collab_notes ADD COLUMN website TEXT'); } catch {}
+ },
+ () => {
+ try { db.exec('ALTER TABLE reservations ADD COLUMN reservation_end_time TEXT'); } catch {}
+ },
+ ];
+
+ if (currentVersion < migrations.length) {
+ for (let i = currentVersion; i < migrations.length; i++) {
+ console.log(`[DB] Running migration ${i + 1}/${migrations.length}`);
+ migrations[i]();
+ }
+ db.prepare('UPDATE schema_version SET version = ?').run(migrations.length);
+ console.log(`[DB] Migrations complete — schema version ${migrations.length}`);
+ }
+}
+
+export { runMigrations };
diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts
new file mode 100644
index 000000000..40f3d44b6
--- /dev/null
+++ b/server/src/db/schema.ts
@@ -0,0 +1,375 @@
+import Database from 'better-sqlite3';
+
+function createTables(db: Database.Database): void {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS users (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ username TEXT UNIQUE NOT NULL,
+ email TEXT UNIQUE NOT NULL,
+ password_hash TEXT NOT NULL,
+ role TEXT NOT NULL DEFAULT 'user',
+ maps_api_key TEXT,
+ unsplash_api_key TEXT,
+ openweather_api_key TEXT,
+ avatar TEXT,
+ oidc_sub TEXT,
+ oidc_issuer TEXT,
+ last_login DATETIME,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS settings (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ key TEXT NOT NULL,
+ value TEXT,
+ UNIQUE(user_id, key)
+ );
+
+ CREATE TABLE IF NOT EXISTS trips (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ title TEXT NOT NULL,
+ description TEXT,
+ start_date TEXT,
+ end_date TEXT,
+ currency TEXT DEFAULT 'EUR',
+ cover_image TEXT,
+ is_archived INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS days (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ day_number INTEGER NOT NULL,
+ date TEXT,
+ notes TEXT,
+ title TEXT,
+ UNIQUE(trip_id, day_number)
+ );
+
+ CREATE TABLE IF NOT EXISTS categories (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ color TEXT DEFAULT '#6366f1',
+ icon TEXT DEFAULT '📍',
+ user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS tags (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ color TEXT DEFAULT '#10b981',
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS places (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ description TEXT,
+ lat REAL,
+ lng REAL,
+ address TEXT,
+ category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL,
+ price REAL,
+ currency TEXT,
+ reservation_status TEXT DEFAULT 'none',
+ reservation_notes TEXT,
+ reservation_datetime TEXT,
+ place_time TEXT,
+ end_time TEXT,
+ duration_minutes INTEGER DEFAULT 60,
+ notes TEXT,
+ image_url TEXT,
+ google_place_id TEXT,
+ website TEXT,
+ phone TEXT,
+ transport_mode TEXT DEFAULT 'walking',
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS place_tags (
+ place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
+ tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
+ PRIMARY KEY (place_id, tag_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS day_assignments (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
+ place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
+ order_index INTEGER DEFAULT 0,
+ notes TEXT,
+ reservation_status TEXT DEFAULT 'none',
+ reservation_notes TEXT,
+ reservation_datetime TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS packing_items (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ checked INTEGER DEFAULT 0,
+ category TEXT,
+ sort_order INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS photos (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ day_id INTEGER REFERENCES days(id) ON DELETE SET NULL,
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
+ filename TEXT NOT NULL,
+ original_name TEXT NOT NULL,
+ file_size INTEGER,
+ mime_type TEXT,
+ caption TEXT,
+ taken_at TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS trip_files (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
+ reservation_id INTEGER REFERENCES reservations(id) ON DELETE SET NULL,
+ filename TEXT NOT NULL,
+ original_name TEXT NOT NULL,
+ file_size INTEGER,
+ mime_type TEXT,
+ description TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS reservations (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ day_id INTEGER REFERENCES days(id) ON DELETE SET NULL,
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
+ assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE SET NULL,
+ title TEXT NOT NULL,
+ reservation_time TEXT,
+ reservation_end_time TEXT,
+ location TEXT,
+ confirmation_number TEXT,
+ notes TEXT,
+ status TEXT DEFAULT 'pending',
+ type TEXT DEFAULT 'other',
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS trip_members (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ invited_by INTEGER REFERENCES users(id),
+ added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(trip_id, user_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS day_notes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ text TEXT NOT NULL,
+ time TEXT,
+ icon TEXT DEFAULT '📝',
+ sort_order REAL DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS app_settings (
+ key TEXT PRIMARY KEY,
+ value TEXT
+ );
+
+ CREATE TABLE IF NOT EXISTS budget_items (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ category TEXT NOT NULL DEFAULT 'Other',
+ name TEXT NOT NULL,
+ total_price REAL NOT NULL DEFAULT 0,
+ persons INTEGER DEFAULT NULL,
+ days INTEGER DEFAULT NULL,
+ note TEXT,
+ sort_order INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ -- Addon system
+ CREATE TABLE IF NOT EXISTS addons (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ description TEXT,
+ type TEXT NOT NULL DEFAULT 'global',
+ icon TEXT DEFAULT 'Puzzle',
+ enabled INTEGER DEFAULT 0,
+ config TEXT DEFAULT '{}',
+ sort_order INTEGER DEFAULT 0
+ );
+
+ -- Vacay addon tables
+ CREATE TABLE IF NOT EXISTS vacay_plans (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ block_weekends INTEGER DEFAULT 1,
+ holidays_enabled INTEGER DEFAULT 0,
+ holidays_region TEXT DEFAULT '',
+ company_holidays_enabled INTEGER DEFAULT 1,
+ carry_over_enabled INTEGER DEFAULT 1,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(owner_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_plan_members (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ status TEXT DEFAULT 'pending',
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(plan_id, user_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_user_colors (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ color TEXT DEFAULT '#6366f1',
+ UNIQUE(user_id, plan_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_years (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ year INTEGER NOT NULL,
+ UNIQUE(plan_id, year)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_user_years (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ year INTEGER NOT NULL,
+ vacation_days INTEGER DEFAULT 30,
+ carried_over INTEGER DEFAULT 0,
+ UNIQUE(user_id, plan_id, year)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_entries (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ date TEXT NOT NULL,
+ note TEXT DEFAULT '',
+ UNIQUE(user_id, plan_id, date)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_company_holidays (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ date TEXT NOT NULL,
+ note TEXT DEFAULT '',
+ UNIQUE(plan_id, date)
+ );
+
+ CREATE TABLE IF NOT EXISTS day_accommodations (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
+ start_day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
+ end_day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
+ check_in TEXT,
+ check_out TEXT,
+ confirmation TEXT,
+ notes TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ -- Collab addon tables
+ CREATE TABLE IF NOT EXISTS collab_notes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ category TEXT DEFAULT 'General',
+ title TEXT NOT NULL,
+ content TEXT,
+ color TEXT DEFAULT '#6366f1',
+ pinned INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS collab_polls (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ question TEXT NOT NULL,
+ options TEXT NOT NULL,
+ multiple INTEGER DEFAULT 0,
+ closed INTEGER DEFAULT 0,
+ deadline TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS collab_poll_votes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ poll_id INTEGER NOT NULL REFERENCES collab_polls(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ option_index INTEGER NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(poll_id, user_id, option_index)
+ );
+
+ CREATE TABLE IF NOT EXISTS collab_messages (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ text TEXT NOT NULL,
+ reply_to INTEGER REFERENCES collab_messages(id) ON DELETE SET NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_collab_notes_trip ON collab_notes(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_collab_polls_trip ON collab_polls(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_collab_messages_trip ON collab_messages(trip_id);
+ `);
+
+ db.exec(`
+ CREATE INDEX IF NOT EXISTS idx_places_trip_id ON places(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_places_category_id ON places(category_id);
+ CREATE INDEX IF NOT EXISTS idx_days_trip_id ON days(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_day_assignments_day_id ON day_assignments(day_id);
+ CREATE INDEX IF NOT EXISTS idx_day_assignments_place_id ON day_assignments(place_id);
+ CREATE INDEX IF NOT EXISTS idx_place_tags_place_id ON place_tags(place_id);
+ CREATE INDEX IF NOT EXISTS idx_place_tags_tag_id ON place_tags(tag_id);
+ CREATE INDEX IF NOT EXISTS idx_trip_members_trip_id ON trip_members(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_trip_members_user_id ON trip_members(user_id);
+ CREATE INDEX IF NOT EXISTS idx_packing_items_trip_id ON packing_items(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_budget_items_trip_id ON budget_items(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_reservations_trip_id ON reservations(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_trip_files_trip_id ON trip_files(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_day_notes_day_id ON day_notes(day_id);
+ CREATE INDEX IF NOT EXISTS idx_photos_trip_id ON photos(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
+ CREATE INDEX IF NOT EXISTS idx_day_accommodations_trip_id ON day_accommodations(trip_id);
+
+ CREATE TABLE IF NOT EXISTS assignment_participants (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ assignment_id INTEGER NOT NULL REFERENCES day_assignments(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ UNIQUE(assignment_id, user_id)
+ );
+ CREATE INDEX IF NOT EXISTS idx_assignment_participants_assignment ON assignment_participants(assignment_id);
+ `);
+}
+
+export { createTables };
diff --git a/server/src/db/seeds.ts b/server/src/db/seeds.ts
new file mode 100644
index 000000000..e98b2f3fc
--- /dev/null
+++ b/server/src/db/seeds.ts
@@ -0,0 +1,51 @@
+import Database from 'better-sqlite3';
+
+function seedCategories(db: Database.Database): void {
+ try {
+ const existingCats = db.prepare('SELECT COUNT(*) as count FROM categories').get() as { count: number };
+ if (existingCats.count === 0) {
+ const defaultCategories = [
+ { name: 'Hotel', color: '#3b82f6', icon: '🏨' },
+ { name: 'Restaurant', color: '#ef4444', icon: '🍽️' },
+ { name: 'Attraction', color: '#8b5cf6', icon: '🏛️' },
+ { name: 'Shopping', color: '#f59e0b', icon: '🛍️' },
+ { name: 'Transport', color: '#6b7280', icon: '🚌' },
+ { name: 'Activity', color: '#10b981', icon: '🎯' },
+ { name: 'Bar/Cafe', color: '#f97316', icon: '☕' },
+ { name: 'Beach', color: '#06b6d4', icon: '🏖️' },
+ { name: 'Nature', color: '#84cc16', icon: '🌿' },
+ { name: 'Other', color: '#6366f1', icon: '📍' },
+ ];
+ const insertCat = db.prepare('INSERT INTO categories (name, color, icon) VALUES (?, ?, ?)');
+ for (const cat of defaultCategories) insertCat.run(cat.name, cat.color, cat.icon);
+ console.log('Default categories seeded');
+ }
+ } catch (err: unknown) {
+ console.error('Error seeding categories:', err instanceof Error ? err.message : err);
+ }
+}
+
+function seedAddons(db: Database.Database): void {
+ try {
+ const defaultAddons = [
+ { id: 'packing', name: 'Packing List', description: 'Pack your bags with checklists per trip', type: 'trip', icon: 'ListChecks', enabled: 1, sort_order: 0 },
+ { id: 'budget', name: 'Budget Planner', description: 'Track expenses and plan your travel budget', type: 'trip', icon: 'Wallet', enabled: 1, sort_order: 1 },
+ { id: 'documents', name: 'Documents', description: 'Store and manage travel documents', type: 'trip', icon: 'FileText', enabled: 1, sort_order: 2 },
+ { id: 'vacay', name: 'Vacay', description: 'Personal vacation day planner with calendar view', type: 'global', icon: 'CalendarDays', enabled: 1, sort_order: 10 },
+ { id: 'atlas', name: 'Atlas', description: 'World map of your visited countries with travel stats', type: 'global', icon: 'Globe', enabled: 1, sort_order: 11 },
+ { id: 'collab', name: 'Collab', description: 'Notes, polls, and live chat for trip collaboration', type: 'trip', icon: 'Users', enabled: 1, sort_order: 6 },
+ ];
+ const insertAddon = db.prepare('INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)');
+ for (const a of defaultAddons) insertAddon.run(a.id, a.name, a.description, a.type, a.icon, a.enabled, a.sort_order);
+ console.log('Default addons seeded');
+ } catch (err: unknown) {
+ console.error('Error seeding addons:', err instanceof Error ? err.message : err);
+ }
+}
+
+function runSeeds(db: Database.Database): void {
+ seedCategories(db);
+ seedAddons(db);
+}
+
+export { runSeeds };
diff --git a/server/src/demo/demo-reset.js b/server/src/demo/demo-reset.ts
similarity index 73%
rename from server/src/demo/demo-reset.js
rename to server/src/demo/demo-reset.ts
index eca69d309..bcd04983a 100644
--- a/server/src/demo/demo-reset.js
+++ b/server/src/demo/demo-reset.ts
@@ -1,11 +1,11 @@
-const fs = require('fs');
-const path = require('path');
+import fs from 'fs';
+import path from 'path';
const dataDir = path.join(__dirname, '../../data');
const dbPath = path.join(dataDir, 'travel.db');
const baselinePath = path.join(dataDir, 'travel-baseline.db');
-function resetDemoUser() {
+function resetDemoUser(): void {
if (!fs.existsSync(baselinePath)) {
console.log('[Demo Reset] No baseline found, skipping. Admin must save baseline first.');
return;
@@ -15,13 +15,14 @@ function resetDemoUser() {
// Save admin's current credentials and API keys (these should survive the reset)
const adminEmail = process.env.DEMO_ADMIN_EMAIL || '[email protected]';
- let adminData = null;
+ interface AdminData { password_hash: string; maps_api_key: string | null; openweather_api_key: string | null; unsplash_api_key: string | null; avatar: string | null; }
+ let adminData: AdminData | undefined = undefined;
try {
adminData = db.prepare(
'SELECT password_hash, maps_api_key, openweather_api_key, unsplash_api_key, avatar FROM users WHERE email = ?'
- ).get(adminEmail);
- } catch (e) {
- console.error('[Demo Reset] Failed to read admin data:', e.message);
+ ).get(adminEmail) as AdminData | undefined;
+ } catch (e: unknown) {
+ console.error('[Demo Reset] Failed to read admin data:', e instanceof Error ? e.message : e);
}
// Flush WAL to main DB file
@@ -36,8 +37,8 @@ function resetDemoUser() {
// Remove WAL/SHM files if they exist (stale from old connection)
try { fs.unlinkSync(dbPath + '-wal'); } catch (e) {}
try { fs.unlinkSync(dbPath + '-shm'); } catch (e) {}
- } catch (e) {
- console.error('[Demo Reset] Failed to restore baseline:', e.message);
+ } catch (e: unknown) {
+ console.error('[Demo Reset] Failed to restore baseline:', e instanceof Error ? e.message : e);
reinitialize();
return;
}
@@ -59,15 +60,15 @@ function resetDemoUser() {
adminData.avatar,
adminEmail
);
- } catch (e) {
- console.error('[Demo Reset] Failed to restore admin credentials:', e.message);
+ } catch (e: unknown) {
+ console.error('[Demo Reset] Failed to restore admin credentials:', e instanceof Error ? e.message : e);
}
}
console.log('[Demo Reset] Database restored from baseline');
}
-function saveBaseline() {
+function saveBaseline(): void {
const { db } = require('../db/database');
// Flush WAL so baseline file is self-contained
@@ -77,8 +78,8 @@ function saveBaseline() {
console.log('[Demo] Baseline saved');
}
-function hasBaseline() {
+function hasBaseline(): boolean {
return fs.existsSync(baselinePath);
}
-module.exports = { resetDemoUser, saveBaseline, hasBaseline };
+export { resetDemoUser, saveBaseline, hasBaseline };
diff --git a/server/src/demo/demo-seed.js b/server/src/demo/demo-seed.ts
similarity index 93%
rename from server/src/demo/demo-seed.js
rename to server/src/demo/demo-seed.ts
index 26b7b0df0..1ef6734da 100644
--- a/server/src/demo/demo-seed.js
+++ b/server/src/demo/demo-seed.ts
@@ -1,6 +1,7 @@
-const bcrypt = require('bcryptjs');
+import bcrypt from 'bcryptjs';
+import Database from 'better-sqlite3';
-function seedDemoData(db) {
+function seedDemoData(db: Database.Database): { adminId: number; demoId: number } {
const ADMIN_USER = process.env.DEMO_ADMIN_USER || 'admin';
const ADMIN_EMAIL = process.env.DEMO_ADMIN_EMAIL || '[email protected]';
const ADMIN_PASS = process.env.DEMO_ADMIN_PASS || 'admin12345';
@@ -8,7 +9,7 @@ function seedDemoData(db) {
const DEMO_PASS = 'demo12345';
// Create admin user if not exists
- let admin = db.prepare('SELECT id FROM users WHERE email = ?').get(ADMIN_EMAIL);
+ let admin = db.prepare('SELECT id FROM users WHERE email = ?').get(ADMIN_EMAIL) as { id: number } | undefined;
if (!admin) {
const hash = bcrypt.hashSync(ADMIN_PASS, 10);
const r = db.prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)').run(ADMIN_USER, ADMIN_EMAIL, hash, 'admin');
@@ -19,7 +20,7 @@ function seedDemoData(db) {
}
// Create demo user if not exists
- let demo = db.prepare('SELECT id FROM users WHERE email = ?').get(DEMO_EMAIL);
+ let demo = db.prepare('SELECT id FROM users WHERE email = ?').get(DEMO_EMAIL) as { id: number } | undefined;
if (!demo) {
const hash = bcrypt.hashSync(DEMO_PASS, 10);
const r = db.prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)').run('demo', DEMO_EMAIL, hash, 'user');
@@ -33,7 +34,7 @@ function seedDemoData(db) {
db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'false')").run();
// Check if admin already has example trips
- const adminTrips = db.prepare('SELECT COUNT(*) as count FROM trips WHERE user_id = ?').get(admin.id);
+ const adminTrips = db.prepare('SELECT COUNT(*) as count FROM trips WHERE user_id = ?').get(admin.id) as { count: number };
if (adminTrips.count > 0) {
console.log('[Demo] Example trips already exist, ensuring demo membership');
ensureDemoMembership(db, admin.id, demo.id);
@@ -52,15 +53,15 @@ function seedDemoData(db) {
return { adminId: admin.id, demoId: demo.id };
}
-function ensureDemoMembership(db, adminId, demoId) {
- const trips = db.prepare('SELECT id FROM trips WHERE user_id = ?').all(adminId);
+function ensureDemoMembership(db: Database.Database, adminId: number, demoId: number): void {
+ const trips = db.prepare('SELECT id FROM trips WHERE user_id = ?').all(adminId) as { id: number }[];
const insertMember = db.prepare('INSERT OR IGNORE INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)');
for (const trip of trips) {
insertMember.run(trip.id, demoId, adminId);
}
}
-function seedExampleTrips(db, adminId, demoId) {
+function seedExampleTrips(db: Database.Database, adminId: number, demoId: number): void {
const insertTrip = db.prepare('INSERT INTO trips (user_id, title, description, start_date, end_date, currency) VALUES (?, ?, ?, ?, ?, ?)');
const insertDay = db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, ?)');
const insertPlace = db.prepare('INSERT INTO places (trip_id, name, lat, lng, address, category_id, place_time, duration_minutes, notes, image_url, google_place_id, website, phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
@@ -73,17 +74,17 @@ function seedExampleTrips(db, adminId, demoId) {
// Category IDs: 1=Hotel, 2=Restaurant, 3=Attraction, 5=Transport, 7=Bar/Cafe, 8=Beach, 9=Nature, 6=Entertainment
- // ─── Trip 1: Tokyo & Kyoto ─────────────────────────────────────────────────
+ // --- Trip 1: Tokyo & Kyoto ---
const trip1 = insertTrip.run(adminId, 'Tokyo & Kyoto', 'Two weeks in Japan — from the neon-lit streets of Tokyo to the serene temples of Kyoto.', '2026-04-15', '2026-04-21', 'JPY');
const t1 = Number(trip1.lastInsertRowid);
- const t1days = [];
+ const t1days: number[] = [];
for (let i = 0; i < 7; i++) {
const d = insertDay.run(t1, i + 1, `2026-04-${15 + i}`);
t1days.push(Number(d.lastInsertRowid));
}
- const t1places = [
+ const t1places: [number, string, number, number, string, number, string, number, string, string | null, string | null, string | null, string | null][] = [
[t1, 'Hotel Shinjuku Granbell', 35.6938, 139.7035, '2-14-5 Kabukicho, Shinjuku City, Tokyo 160-0021, Japan', 1, '15:00', 60, 'Check-in from 3 PM. Steps from Shinjuku Station.', null, 'ChIJdaGEJBeMGGARYgt8sLBv6lM', 'https://www.grfranbellhotel.jp/shinjuku/', '+81 3-5155-2666'],
[t1, 'Senso-ji Temple', 35.7148, 139.7967, '2 Chome-3-1 Asakusa, Taito City, Tokyo 111-0032, Japan', 3, '09:00', 90, 'Oldest temple in Tokyo. Fewer tourists in the early morning.', null, 'ChIJ8T1GpMGOGGARDYGSgpoOdfg', 'https://www.senso-ji.jp/', '+81 3-3842-0181'],
[t1, 'Shibuya Crossing', 35.6595, 139.7004, '2 Chome-2-1 Dogenzaka, Shibuya City, Tokyo 150-0043, Japan', 3, '18:00', 45, 'World\'s busiest pedestrian crossing. Most impressive at night.', null, 'ChIJLyzOhmyLGGARMKWbl5z6wGg', null, null],
@@ -127,7 +128,7 @@ function seedExampleTrips(db, adminId, demoId) {
insertNote.run(t1days[6], t1, 'Last evening — farewell dinner at Pontocho Alley', '19:00', 'Star', 1);
// Packing
- const t1packing = [
+ const t1packing: [string, number, string, number][] = [
['Passport', 1, 'Documents', 0], ['Japan Rail Pass', 1, 'Documents', 1],
['Power adapter Type A/B', 0, 'Electronics', 2], ['Camera + charger', 0, 'Electronics', 3],
['Comfortable walking shoes', 0, 'Clothing', 4], ['Rain jacket', 0, 'Clothing', 5],
@@ -150,17 +151,17 @@ function seedExampleTrips(db, adminId, demoId) {
insertMember.run(t1, demoId, adminId);
- // ─── Trip 2: Barcelona Long Weekend ────────────────────────────────────────
+ // --- Trip 2: Barcelona Long Weekend ---
const trip2 = insertTrip.run(adminId, 'Barcelona Long Weekend', 'Gaudi, tapas, and Mediterranean vibes — a long weekend in the Catalan capital.', '2026-05-21', '2026-05-24', 'EUR');
const t2 = Number(trip2.lastInsertRowid);
- const t2days = [];
+ const t2days: number[] = [];
for (let i = 0; i < 4; i++) {
const d = insertDay.run(t2, i + 1, `2026-05-${21 + i}`);
t2days.push(Number(d.lastInsertRowid));
}
- const t2places = [
+ const t2places: [number, string, number, number, string, number, string, number, string, string | null, string | null, string | null, string | null][] = [
[t2, 'W Barcelona', 41.3686, 2.1920, 'Placa de la Rosa dels Vents 1, 08039 Barcelona, Spain', 1, '14:00', 60, 'Right on the beach. Rooftop bar with panoramic views!', null, 'ChIJKfj5C8yjpBIRCPC3RPI0JO4', 'https://www.marriott.com/hotels/travel/bcnwh-w-barcelona/', '+34 932 95 28 00'],
[t2, 'Sagrada Familia', 41.4036, 2.1744, 'C/ de Mallorca, 401, 08013 Barcelona, Spain', 3, '10:00', 120, 'Gaudi\'s masterpiece. Book tickets online in advance — sells out fast!', null, 'ChIJk_s92NyipBIRUMnDG8Kq2Js', 'https://sagradafamilia.org/', '+34 932 08 04 14'],
[t2, 'Park Guell', 41.4145, 2.1527, '08024 Barcelona, Spain', 3, '09:00', 90, 'Mosaic terrace with city views. Book early for the Monumental Zone.', null, 'ChIJ4eQMeOmipBIRb65JRUzGE8k', 'https://parkguell.barcelona/', '+34 934 09 18 31'],
@@ -204,17 +205,17 @@ function seedExampleTrips(db, adminId, demoId) {
insertMember.run(t2, demoId, adminId);
- // ─── Trip 3: New York City ─────────────────────────────────────────────────
+ // --- Trip 3: New York City ---
const trip3 = insertTrip.run(adminId, 'New York City', 'The city that never sleeps — iconic landmarks, world-class food, and Broadway lights.', '2026-09-18', '2026-09-22', 'USD');
const t3 = Number(trip3.lastInsertRowid);
- const t3days = [];
+ const t3days: number[] = [];
for (let i = 0; i < 5; i++) {
const d = insertDay.run(t3, i + 1, `2026-09-${18 + i}`);
t3days.push(Number(d.lastInsertRowid));
}
- const t3places = [
+ const t3places: [number, string, number, number, string, number, string, number, string, string | null, string | null, string | null, string | null][] = [
[t3, 'The Plaza Hotel', 40.7645, -73.9744, '768 5th Ave, New York, NY 10019, USA', 1, '15:00', 60, 'Iconic luxury hotel on Central Park. The lobby alone is worth a visit.', null, 'ChIJYbISlAVYwokRn6ORbSPV0xk', 'https://www.theplazany.com/', '+1 212-759-3000'],
[t3, 'Statue of Liberty', 40.6892, -74.0445, 'Liberty Island, New York, NY 10004, USA', 3, '09:00', 180, 'Book crown access tickets months in advance. Ferry from Battery Park.', null, 'ChIJPTacEpBQwokRKwIlDXelxkA', 'https://www.nps.gov/stli/', '+1 212-363-3200'],
[t3, 'Central Park', 40.7829, -73.9654, 'Central Park, New York, NY 10024, USA', 9, '10:00', 120, 'Bethesda Fountain, Bow Bridge, and Strawberry Fields. Rent bikes!', null, 'ChIJ4zGFAZpYwokRGUGph3Mf37k', 'https://www.centralparknyc.org/', null],
@@ -251,7 +252,7 @@ function seedExampleTrips(db, adminId, demoId) {
insertNote.run(t3days[4], t3, 'Flight departs JFK at 17:00 — last bagel at Russ & Daughters!', '10:00', 'Plane', 0);
// Packing
- const t3packing = [
+ const t3packing: [string, number, string, number][] = [
['Passport', 1, 'Documents', 0], ['ESTA confirmation', 1, 'Documents', 1],
['Travel insurance', 0, 'Documents', 2], ['Comfortable sneakers', 0, 'Clothing', 3],
['Light jacket', 0, 'Clothing', 4], ['Portable charger', 0, 'Electronics', 5],
@@ -275,4 +276,4 @@ function seedExampleTrips(db, adminId, demoId) {
console.log('[Demo] 3 example trips seeded and shared with demo user');
}
-module.exports = { seedDemoData };
+export { seedDemoData };
diff --git a/server/src/index.js b/server/src/index.js
deleted file mode 100644
index 5a1751ab8..000000000
--- a/server/src/index.js
+++ /dev/null
@@ -1,164 +0,0 @@
-require('dotenv').config();
-const express = require('express');
-const cors = require('cors');
-const helmet = require('helmet');
-const path = require('path');
-const fs = require('fs');
-
-const app = express();
-
-// Create upload directories on startup
-const uploadsDir = path.join(__dirname, '../uploads');
-const photosDir = path.join(uploadsDir, 'photos');
-const filesDir = path.join(uploadsDir, 'files');
-const coversDir = path.join(uploadsDir, 'covers');
-const backupsDir = path.join(__dirname, '../data/backups');
-const tmpDir = path.join(__dirname, '../data/tmp');
-
-[uploadsDir, photosDir, filesDir, coversDir, backupsDir, tmpDir].forEach(dir => {
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
-});
-
-// Middleware
-const allowedOrigins = process.env.ALLOWED_ORIGINS
- ? process.env.ALLOWED_ORIGINS.split(',')
- : null;
-
-let corsOrigin;
-if (allowedOrigins) {
- // Explicit whitelist from env var
- corsOrigin = (origin, callback) => {
- if (!origin || allowedOrigins.includes(origin)) callback(null, true);
- else callback(new Error('Not allowed by CORS'));
- };
-} else if (process.env.NODE_ENV === 'production') {
- // Production: same-origin only (Express serves the static client)
- corsOrigin = false;
-} else {
- // Development: allow all origins (needed for Vite dev server)
- corsOrigin = true;
-}
-
-app.use(cors({
- origin: corsOrigin,
- credentials: true
-}));
-app.use(helmet({
- contentSecurityPolicy: false, // managed by frontend meta tag or reverse proxy
- crossOriginEmbedderPolicy: false, // allows loading external images (maps, etc.)
-}));
-app.use(express.json({ limit: '100kb' }));
-app.use(express.urlencoded({ extended: true }));
-
-// Serve uploaded files
-app.use('/uploads', express.static(path.join(__dirname, '../uploads')));
-
-// Routes
-const authRoutes = require('./routes/auth');
-const tripsRoutes = require('./routes/trips');
-const daysRoutes = require('./routes/days');
-const accommodationsRoutes = require('./routes/days').accommodationsRouter;
-const placesRoutes = require('./routes/places');
-const assignmentsRoutes = require('./routes/assignments');
-const packingRoutes = require('./routes/packing');
-const tagsRoutes = require('./routes/tags');
-const categoriesRoutes = require('./routes/categories');
-const adminRoutes = require('./routes/admin');
-const mapsRoutes = require('./routes/maps');
-const filesRoutes = require('./routes/files');
-const reservationsRoutes = require('./routes/reservations');
-const dayNotesRoutes = require('./routes/dayNotes');
-const weatherRoutes = require('./routes/weather');
-const settingsRoutes = require('./routes/settings');
-const budgetRoutes = require('./routes/budget');
-const collabRoutes = require('./routes/collab');
-const backupRoutes = require('./routes/backup');
-
-const oidcRoutes = require('./routes/oidc');
-app.use('/api/auth', authRoutes);
-app.use('/api/auth/oidc', oidcRoutes);
-app.use('/api/trips', tripsRoutes);
-app.use('/api/trips/:tripId/days', daysRoutes);
-app.use('/api/trips/:tripId/accommodations', accommodationsRoutes);
-app.use('/api/trips/:tripId/places', placesRoutes);
-app.use('/api/trips/:tripId/packing', packingRoutes);
-app.use('/api/trips/:tripId/files', filesRoutes);
-app.use('/api/trips/:tripId/budget', budgetRoutes);
-app.use('/api/trips/:tripId/collab', collabRoutes);
-app.use('/api/trips/:tripId/reservations', reservationsRoutes);
-app.use('/api/trips/:tripId/days/:dayId/notes', dayNotesRoutes);
-app.get('/api/health', (req, res) => res.json({ status: 'ok' }));
-app.use('/api', assignmentsRoutes);
-app.use('/api/tags', tagsRoutes);
-app.use('/api/categories', categoriesRoutes);
-app.use('/api/admin', adminRoutes);
-
-// Public addons endpoint (authenticated but not admin-only)
-const { authenticate: addonAuth } = require('./middleware/auth');
-const { db: addonDb } = require('./db/database');
-app.get('/api/addons', addonAuth, (req, res) => {
- const addons = addonDb.prepare('SELECT id, name, type, icon, enabled FROM addons WHERE enabled = 1 ORDER BY sort_order').all();
- res.json({ addons: addons.map(a => ({ ...a, enabled: !!a.enabled })) });
-});
-
-// Addon routes
-const vacayRoutes = require('./routes/vacay');
-app.use('/api/addons/vacay', vacayRoutes);
-const atlasRoutes = require('./routes/atlas');
-app.use('/api/addons/atlas', atlasRoutes);
-
-app.use('/api/maps', mapsRoutes);
-app.use('/api/weather', weatherRoutes);
-app.use('/api/settings', settingsRoutes);
-app.use('/api/backup', backupRoutes);
-
-// Serve static files in production
-if (process.env.NODE_ENV === 'production') {
- const publicPath = path.join(__dirname, '../public');
- app.use(express.static(publicPath));
- app.get('*', (req, res) => {
- res.sendFile(path.join(publicPath, 'index.html'));
- });
-}
-
-// Global error handler
-app.use((err, req, res, next) => {
- console.error('Unhandled error:', err);
- res.status(500).json({ error: 'Internal server error' });
-});
-
-const scheduler = require('./scheduler');
-
-const PORT = process.env.PORT || 3001;
-const server = app.listen(PORT, () => {
- console.log(`NOMAD API running on port ${PORT}`);
- console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
- if (process.env.DEMO_MODE === 'true') console.log('Demo mode: ENABLED');
- scheduler.start();
- scheduler.startDemoReset();
- const { setupWebSocket } = require('./websocket');
- setupWebSocket(server);
-});
-
-// Graceful shutdown
-function shutdown(signal) {
- console.log(`\n${signal} received — shutting down gracefully...`);
- scheduler.stop();
- server.close(() => {
- console.log('HTTP server closed');
- const { closeDb } = require('./db/database');
- closeDb();
- console.log('Shutdown complete');
- process.exit(0);
- });
- // Force exit after 10s if connections don't close
- setTimeout(() => {
- console.error('Forced shutdown after timeout');
- process.exit(1);
- }, 10000);
-}
-
-process.on('SIGTERM', () => shutdown('SIGTERM'));
-process.on('SIGINT', () => shutdown('SIGINT'));
-
-module.exports = app;
diff --git a/server/src/index.ts b/server/src/index.ts
new file mode 100644
index 000000000..1317fa2af
--- /dev/null
+++ b/server/src/index.ts
@@ -0,0 +1,208 @@
+import 'dotenv/config';
+import express, { Request, Response, NextFunction } from 'express';
+import cors from 'cors';
+import helmet from 'helmet';
+import path from 'path';
+import fs from 'fs';
+
+const app = express();
+
+// Trust first proxy (nginx/Docker) for correct req.ip
+if (process.env.NODE_ENV === 'production' || process.env.TRUST_PROXY) {
+ app.set('trust proxy', parseInt(process.env.TRUST_PROXY as string) || 1);
+}
+
+// Create upload directories on startup
+const uploadsDir = path.join(__dirname, '../uploads');
+const photosDir = path.join(uploadsDir, 'photos');
+const filesDir = path.join(uploadsDir, 'files');
+const coversDir = path.join(uploadsDir, 'covers');
+const backupsDir = path.join(__dirname, '../data/backups');
+const tmpDir = path.join(__dirname, '../data/tmp');
+
+[uploadsDir, photosDir, filesDir, coversDir, backupsDir, tmpDir].forEach(dir => {
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
+});
+
+// Middleware
+const allowedOrigins = process.env.ALLOWED_ORIGINS
+ ? process.env.ALLOWED_ORIGINS.split(',')
+ : null;
+
+let corsOrigin: cors.CorsOptions['origin'];
+if (allowedOrigins) {
+ // Explicit whitelist from env var
+ corsOrigin = (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {
+ if (!origin || allowedOrigins.includes(origin)) callback(null, true);
+ else callback(new Error('Not allowed by CORS'));
+ };
+} else if (process.env.NODE_ENV === 'production') {
+ // Production: same-origin only (Express serves the static client)
+ corsOrigin = false;
+} else {
+ // Development: allow all origins (needed for Vite dev server)
+ corsOrigin = true;
+}
+
+app.use(cors({
+ origin: corsOrigin,
+ credentials: true
+}));
+app.use(helmet({
+ contentSecurityPolicy: {
+ directives: {
+ defaultSrc: ["'self'"],
+ scriptSrc: ["'self'", "'unsafe-inline'"],
+ styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://unpkg.com"],
+ imgSrc: ["'self'", "data:", "blob:", "https:", "http:"],
+ connectSrc: ["'self'", "ws:", "wss:", "https:", "http:"],
+ fontSrc: ["'self'", "https://fonts.gstatic.com", "data:"],
+ objectSrc: ["'self'"],
+ frameAncestors: ["'none'"],
+ }
+ },
+ crossOriginEmbedderPolicy: false,
+}));
+// Redirect HTTP to HTTPS in production
+if (process.env.NODE_ENV === 'production' && process.env.FORCE_HTTPS !== 'false') {
+ app.use((req: Request, res: Response, next: NextFunction) => {
+ if (req.secure || req.headers['x-forwarded-proto'] === 'https') return next();
+ res.redirect(301, 'https://' + req.headers.host + req.url);
+ });
+}
+app.use(express.json({ limit: '100kb' }));
+app.use(express.urlencoded({ extended: true }));
+
+// Avatars are public (shown on login, sharing screens)
+app.use('/uploads/avatars', express.static(path.join(__dirname, '../uploads/avatars')));
+
+// All other uploads require authentication
+app.get('/uploads/:type/:filename', (req: Request, res: Response) => {
+ const { type, filename } = req.params;
+ const allowedTypes = ['covers', 'files', 'photos'];
+ if (!allowedTypes.includes(type)) return res.status(404).send('Not found');
+
+ // Prevent path traversal
+ const safeName = path.basename(filename);
+ const filePath = path.join(__dirname, '../uploads', type, safeName);
+ const resolved = path.resolve(filePath);
+ if (!resolved.startsWith(path.resolve(__dirname, '../uploads', type))) {
+ return res.status(403).send('Forbidden');
+ }
+
+ if (!fs.existsSync(resolved)) return res.status(404).send('Not found');
+ res.sendFile(resolved);
+});
+
+// Routes
+import authRoutes from './routes/auth';
+import tripsRoutes from './routes/trips';
+import daysRoutes, { accommodationsRouter as accommodationsRoutes } from './routes/days';
+import placesRoutes from './routes/places';
+import assignmentsRoutes from './routes/assignments';
+import packingRoutes from './routes/packing';
+import tagsRoutes from './routes/tags';
+import categoriesRoutes from './routes/categories';
+import adminRoutes from './routes/admin';
+import mapsRoutes from './routes/maps';
+import filesRoutes from './routes/files';
+import reservationsRoutes from './routes/reservations';
+import dayNotesRoutes from './routes/dayNotes';
+import weatherRoutes from './routes/weather';
+import settingsRoutes from './routes/settings';
+import budgetRoutes from './routes/budget';
+import collabRoutes from './routes/collab';
+import backupRoutes from './routes/backup';
+import oidcRoutes from './routes/oidc';
+app.use('/api/auth', authRoutes);
+app.use('/api/auth/oidc', oidcRoutes);
+app.use('/api/trips', tripsRoutes);
+app.use('/api/trips/:tripId/days', daysRoutes);
+app.use('/api/trips/:tripId/accommodations', accommodationsRoutes);
+app.use('/api/trips/:tripId/places', placesRoutes);
+app.use('/api/trips/:tripId/packing', packingRoutes);
+app.use('/api/trips/:tripId/files', filesRoutes);
+app.use('/api/trips/:tripId/budget', budgetRoutes);
+app.use('/api/trips/:tripId/collab', collabRoutes);
+app.use('/api/trips/:tripId/reservations', reservationsRoutes);
+app.use('/api/trips/:tripId/days/:dayId/notes', dayNotesRoutes);
+app.get('/api/health', (req: Request, res: Response) => res.json({ status: 'ok' }));
+app.use('/api', assignmentsRoutes);
+app.use('/api/tags', tagsRoutes);
+app.use('/api/categories', categoriesRoutes);
+app.use('/api/admin', adminRoutes);
+
+// Public addons endpoint (authenticated but not admin-only)
+import { authenticate as addonAuth } from './middleware/auth';
+import { db as addonDb } from './db/database';
+import { Addon } from './types';
+app.get('/api/addons', addonAuth, (req: Request, res: Response) => {
+ const addons = addonDb.prepare('SELECT id, name, type, icon, enabled FROM addons WHERE enabled = 1 ORDER BY sort_order').all() as Pick<Addon, 'id' | 'name' | 'type' | 'icon' | 'enabled'>[];
+ res.json({ addons: addons.map(a => ({ ...a, enabled: !!a.enabled })) });
+});
+
+// Addon routes
+import vacayRoutes from './routes/vacay';
+app.use('/api/addons/vacay', vacayRoutes);
+import atlasRoutes from './routes/atlas';
+app.use('/api/addons/atlas', atlasRoutes);
+
+app.use('/api/maps', mapsRoutes);
+app.use('/api/weather', weatherRoutes);
+app.use('/api/settings', settingsRoutes);
+app.use('/api/backup', backupRoutes);
+
+// Serve static files in production
+if (process.env.NODE_ENV === 'production') {
+ const publicPath = path.join(__dirname, '../public');
+ app.use(express.static(publicPath));
+ app.get('*', (req: Request, res: Response) => {
+ res.sendFile(path.join(publicPath, 'index.html'));
+ });
+}
+
+// Global error handler
+app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
+ console.error('Unhandled error:', err);
+ res.status(500).json({ error: 'Internal server error' });
+});
+
+import * as scheduler from './scheduler';
+
+const PORT = process.env.PORT || 3001;
+const server = app.listen(PORT, () => {
+ console.log(`NOMAD API running on port ${PORT}`);
+ console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
+ if (process.env.DEMO_MODE === 'true') console.log('Demo mode: ENABLED');
+ if (process.env.DEMO_MODE === 'true' && process.env.NODE_ENV === 'production') {
+ console.warn('[SECURITY WARNING] DEMO_MODE is enabled in production! Demo credentials are publicly exposed.');
+ }
+ scheduler.start();
+ scheduler.startDemoReset();
+ import('./websocket').then(({ setupWebSocket }) => {
+ setupWebSocket(server);
+ });
+});
+
+// Graceful shutdown
+function shutdown(signal: string): void {
+ console.log(`\n${signal} received — shutting down gracefully...`);
+ scheduler.stop();
+ server.close(() => {
+ console.log('HTTP server closed');
+ const { closeDb } = require('./db/database');
+ closeDb();
+ console.log('Shutdown complete');
+ process.exit(0);
+ });
+ // Force exit after 10s if connections don't close
+ setTimeout(() => {
+ console.error('Forced shutdown after timeout');
+ process.exit(1);
+ }, 10000);
+}
+
+process.on('SIGTERM', () => shutdown('SIGTERM'));
+process.on('SIGINT', () => shutdown('SIGINT'));
+
+export default app;
diff --git a/server/src/middleware/auth.js b/server/src/middleware/auth.js
deleted file mode 100644
index 2dd4b85aa..000000000
--- a/server/src/middleware/auth.js
+++ /dev/null
@@ -1,63 +0,0 @@
-const jwt = require('jsonwebtoken');
-const { db } = require('../db/database');
-const { JWT_SECRET } = require('../config');
-
-const authenticate = (req, res, next) => {
- const authHeader = req.headers['authorization'];
- const token = authHeader && authHeader.split(' ')[1];
-
- if (!token) {
- return res.status(401).json({ error: 'Access token required' });
- }
-
- try {
- const decoded = jwt.verify(token, JWT_SECRET);
- const user = db.prepare(
- 'SELECT id, username, email, role, maps_api_key, unsplash_api_key, openweather_api_key FROM users WHERE id = ?'
- ).get(decoded.id);
- if (!user) {
- return res.status(401).json({ error: 'User not found' });
- }
- req.user = user;
- next();
- } catch (err) {
- return res.status(401).json({ error: 'Invalid or expired token' });
- }
-};
-
-const optionalAuth = (req, res, next) => {
- const authHeader = req.headers['authorization'];
- const token = authHeader && authHeader.split(' ')[1];
-
- if (!token) {
- req.user = null;
- return next();
- }
-
- try {
- const decoded = jwt.verify(token, JWT_SECRET);
- const user = db.prepare(
- 'SELECT id, username, email, role, maps_api_key, unsplash_api_key, openweather_api_key FROM users WHERE id = ?'
- ).get(decoded.id);
- req.user = user || null;
- } catch (err) {
- req.user = null;
- }
- next();
-};
-
-const adminOnly = (req, res, next) => {
- if (!req.user || req.user.role !== 'admin') {
- return res.status(403).json({ error: 'Admin access required' });
- }
- next();
-};
-
-const demoUploadBlock = (req, res, next) => {
- if (process.env.DEMO_MODE === 'true' && req.user?.email === '[email protected]') {
- return res.status(403).json({ error: 'Uploads are disabled in demo mode. Self-host NOMAD for full functionality.' });
- }
- next();
-};
-
-module.exports = { authenticate, optionalAuth, adminOnly, demoUploadBlock };
diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts
new file mode 100644
index 000000000..e0844df20
--- /dev/null
+++ b/server/src/middleware/auth.ts
@@ -0,0 +1,71 @@
+import { Request, Response, NextFunction } from 'express';
+import jwt from 'jsonwebtoken';
+import { db } from '../db/database';
+import { JWT_SECRET } from '../config';
+import { AuthRequest, OptionalAuthRequest, User } from '../types';
+
+const authenticate = (req: Request, res: Response, next: NextFunction): void => {
+ const authHeader = req.headers['authorization'];
+ const token = authHeader && authHeader.split(' ')[1];
+
+ if (!token) {
+ res.status(401).json({ error: 'Access token required' });
+ return;
+ }
+
+ try {
+ const decoded = jwt.verify(token, JWT_SECRET) as { id: number };
+ const user = db.prepare(
+ 'SELECT id, username, email, role FROM users WHERE id = ?'
+ ).get(decoded.id) as User | undefined;
+ if (!user) {
+ res.status(401).json({ error: 'User not found' });
+ return;
+ }
+ (req as AuthRequest).user = user;
+ next();
+ } catch (err: unknown) {
+ res.status(401).json({ error: 'Invalid or expired token' });
+ }
+};
+
+const optionalAuth = (req: Request, res: Response, next: NextFunction): void => {
+ const authHeader = req.headers['authorization'];
+ const token = authHeader && authHeader.split(' ')[1];
+
+ if (!token) {
+ (req as OptionalAuthRequest).user = null;
+ return next();
+ }
+
+ try {
+ const decoded = jwt.verify(token, JWT_SECRET) as { id: number };
+ const user = db.prepare(
+ 'SELECT id, username, email, role FROM users WHERE id = ?'
+ ).get(decoded.id) as User | undefined;
+ (req as OptionalAuthRequest).user = user || null;
+ } catch (err: unknown) {
+ (req as OptionalAuthRequest).user = null;
+ }
+ next();
+};
+
+const adminOnly = (req: Request, res: Response, next: NextFunction): void => {
+ const authReq = req as AuthRequest;
+ if (!authReq.user || authReq.user.role !== 'admin') {
+ res.status(403).json({ error: 'Admin access required' });
+ return;
+ }
+ next();
+};
+
+const demoUploadBlock = (req: Request, res: Response, next: NextFunction): void => {
+ const authReq = req as AuthRequest;
+ if (process.env.DEMO_MODE === 'true' && authReq.user?.email === '[email protected]') {
+ res.status(403).json({ error: 'Uploads are disabled in demo mode. Self-host NOMAD for full functionality.' });
+ return;
+ }
+ next();
+};
+
+export { authenticate, optionalAuth, adminOnly, demoUploadBlock };
diff --git a/server/src/middleware/tripAccess.ts b/server/src/middleware/tripAccess.ts
new file mode 100644
index 000000000..2c973f50d
--- /dev/null
+++ b/server/src/middleware/tripAccess.ts
@@ -0,0 +1,37 @@
+import { Request, Response, NextFunction } from 'express';
+import { canAccessTrip, isOwner } from '../db/database';
+import { AuthRequest } from '../types';
+
+/** Middleware: verifies the authenticated user is an owner or member of the trip, then attaches trip to req. */
+function requireTripAccess(req: Request, res: Response, next: NextFunction): void {
+ const authReq = req as AuthRequest;
+ const tripId = req.params.tripId || req.params.id;
+ if (!tripId) {
+ res.status(400).json({ error: 'Trip ID required' });
+ return;
+ }
+ const trip = canAccessTrip(Number(tripId), authReq.user.id);
+ if (!trip) {
+ res.status(404).json({ error: 'Trip not found' });
+ return;
+ }
+ authReq.trip = trip;
+ next();
+}
+
+/** Middleware: verifies the authenticated user is the trip owner (not just a member). */
+function requireTripOwner(req: Request, res: Response, next: NextFunction): void {
+ const authReq = req as AuthRequest;
+ const tripId = req.params.tripId || req.params.id;
+ if (!tripId) {
+ res.status(400).json({ error: 'Trip ID required' });
+ return;
+ }
+ if (!isOwner(Number(tripId), authReq.user.id)) {
+ res.status(403).json({ error: 'Only the trip owner can do this' });
+ return;
+ }
+ next();
+}
+
+export { requireTripAccess, requireTripOwner };
diff --git a/server/src/middleware/validate.ts b/server/src/middleware/validate.ts
new file mode 100644
index 000000000..90101e7b3
--- /dev/null
+++ b/server/src/middleware/validate.ts
@@ -0,0 +1,26 @@
+import { Request, Response, NextFunction } from 'express';
+
+function maxLength(field: string, max: number) {
+ return (req: Request, res: Response, next: NextFunction): void => {
+ if (req.body[field] && typeof req.body[field] === 'string' && req.body[field].length > max) {
+ res.status(400).json({ error: `${field} must be ${max} characters or less` });
+ return;
+ }
+ next();
+ };
+}
+
+function validateStringLengths(maxLengths: Record<string, number>) {
+ return (req: Request, res: Response, next: NextFunction): void => {
+ for (const [field, max] of Object.entries(maxLengths)) {
+ const value = req.body[field];
+ if (value && typeof value === 'string' && value.length > max) {
+ res.status(400).json({ error: `${field} must be ${max} characters or less` });
+ return;
+ }
+ }
+ next();
+ };
+}
+
+export { maxLength, validateStringLengths };
diff --git a/server/src/routes/admin.js b/server/src/routes/admin.ts
similarity index 68%
rename from server/src/routes/admin.js
rename to server/src/routes/admin.ts
index 5c2774501..e4928e177 100644
--- a/server/src/routes/admin.js
+++ b/server/src/routes/admin.ts
@@ -1,22 +1,21 @@
-const express = require('express');
-const bcrypt = require('bcryptjs');
-const { execSync } = require('child_process');
-const path = require('path');
-const { db } = require('../db/database');
-const { authenticate, adminOnly } = require('../middleware/auth');
+import express, { Request, Response } from 'express';
+import bcrypt from 'bcryptjs';
+import { execSync } from 'child_process';
+import path from 'path';
+import fs from 'fs';
+import { db } from '../db/database';
+import { authenticate, adminOnly } from '../middleware/auth';
+import { AuthRequest, User, Addon } from '../types';
const router = express.Router();
-// All admin routes require authentication and admin role
router.use(authenticate, adminOnly);
-// GET /api/admin/users
-router.get('/users', (req, res) => {
+router.get('/users', (req: Request, res: Response) => {
const users = db.prepare(
'SELECT id, username, email, role, created_at, updated_at, last_login FROM users ORDER BY created_at DESC'
- ).all();
- // Add online status from WebSocket connections
- let onlineUserIds = new Set();
+ ).all() as Pick<User, 'id' | 'username' | 'email' | 'role' | 'created_at' | 'updated_at' | 'last_login'>[];
+ let onlineUserIds = new Set<number>();
try {
const { getOnlineUserIds } = require('../websocket');
onlineUserIds = getOnlineUserIds();
@@ -25,8 +24,7 @@ router.get('/users', (req, res) => {
res.json({ users: usersWithStatus });
});
-// POST /api/admin/users
-router.post('/users', (req, res) => {
+router.post('/users', (req: Request, res: Response) => {
const { username, email, password, role } = req.body;
if (!username?.trim() || !email?.trim() || !password?.trim()) {
@@ -43,7 +41,7 @@ router.post('/users', (req, res) => {
const existingEmail = db.prepare('SELECT id FROM users WHERE email = ?').get(email.trim());
if (existingEmail) return res.status(409).json({ error: 'Email already taken' });
- const passwordHash = bcrypt.hashSync(password.trim(), 10);
+ const passwordHash = bcrypt.hashSync(password.trim(), 12);
const result = db.prepare(
'INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)'
@@ -56,10 +54,9 @@ router.post('/users', (req, res) => {
res.status(201).json({ user });
});
-// PUT /api/admin/users/:id
-router.put('/users/:id', (req, res) => {
+router.put('/users/:id', (req: Request, res: Response) => {
const { username, email, role, password } = req.body;
- const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
+ const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id) as User | undefined;
if (!user) return res.status(404).json({ error: 'User not found' });
@@ -76,7 +73,7 @@ router.put('/users/:id', (req, res) => {
if (conflict) return res.status(409).json({ error: 'Email already taken' });
}
- const passwordHash = password ? bcrypt.hashSync(password, 10) : null;
+ const passwordHash = password ? bcrypt.hashSync(password, 12) : null;
db.prepare(`
UPDATE users SET
@@ -95,9 +92,9 @@ router.put('/users/:id', (req, res) => {
res.json({ user: updated });
});
-// DELETE /api/admin/users/:id
-router.delete('/users/:id', (req, res) => {
- if (parseInt(req.params.id) === req.user.id) {
+router.delete('/users/:id', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ if (parseInt(req.params.id) === authReq.user.id) {
return res.status(400).json({ error: 'Cannot delete own account' });
}
@@ -108,40 +105,37 @@ router.delete('/users/:id', (req, res) => {
res.json({ success: true });
});
-// GET /api/admin/stats
-router.get('/stats', (req, res) => {
- const totalUsers = db.prepare('SELECT COUNT(*) as count FROM users').get().count;
- const totalTrips = db.prepare('SELECT COUNT(*) as count FROM trips').get().count;
- const totalPlaces = db.prepare('SELECT COUNT(*) as count FROM places').get().count;
- const totalFiles = db.prepare('SELECT COUNT(*) as count FROM trip_files').get().count;
+router.get('/stats', (_req: Request, res: Response) => {
+ const totalUsers = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
+ const totalTrips = (db.prepare('SELECT COUNT(*) as count FROM trips').get() as { count: number }).count;
+ const totalPlaces = (db.prepare('SELECT COUNT(*) as count FROM places').get() as { count: number }).count;
+ const totalFiles = (db.prepare('SELECT COUNT(*) as count FROM trip_files').get() as { count: number }).count;
res.json({ totalUsers, totalTrips, totalPlaces, totalFiles });
});
-// GET /api/admin/oidc — get OIDC config
-router.get('/oidc', (req, res) => {
- const get = (key) => db.prepare("SELECT value FROM app_settings WHERE key = ?").get(key)?.value || '';
+router.get('/oidc', (_req: Request, res: Response) => {
+ const get = (key: string) => (db.prepare("SELECT value FROM app_settings WHERE key = ?").get(key) as { value: string } | undefined)?.value || '';
+ const secret = get('oidc_client_secret');
res.json({
issuer: get('oidc_issuer'),
client_id: get('oidc_client_id'),
- client_secret: get('oidc_client_secret'),
+ client_secret_set: !!secret,
display_name: get('oidc_display_name'),
});
});
-// PUT /api/admin/oidc — update OIDC config
-router.put('/oidc', (req, res) => {
+router.put('/oidc', (req: Request, res: Response) => {
const { issuer, client_id, client_secret, display_name } = req.body;
- const set = (key, val) => db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)").run(key, val || '');
+ const set = (key: string, val: string) => db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)").run(key, val || '');
set('oidc_issuer', issuer);
set('oidc_client_id', client_id);
- set('oidc_client_secret', client_secret);
+ if (client_secret !== undefined) set('oidc_client_secret', client_secret);
set('oidc_display_name', display_name);
res.json({ success: true });
});
-// POST /api/admin/save-demo-baseline (demo mode only)
-router.post('/save-demo-baseline', (req, res) => {
+router.post('/save-demo-baseline', (_req: Request, res: Response) => {
if (process.env.DEMO_MODE !== 'true') {
return res.status(404).json({ error: 'Not found' });
}
@@ -149,22 +143,30 @@ router.post('/save-demo-baseline', (req, res) => {
const { saveBaseline } = require('../demo/demo-reset');
saveBaseline();
res.json({ success: true, message: 'Demo baseline saved. Hourly resets will restore to this state.' });
- } catch (err) {
- res.status(500).json({ error: 'Failed to save baseline: ' + err.message });
+ } catch (err: unknown) {
+ console.error(err);
+ res.status(500).json({ error: 'Failed to save baseline' });
}
});
-// ── Version check ──────────────────────────────────────────
-
-// Detect if running inside Docker
const isDocker = (() => {
try {
- const fs = require('fs');
return fs.existsSync('/.dockerenv') || (fs.existsSync('/proc/1/cgroup') && fs.readFileSync('/proc/1/cgroup', 'utf8').includes('docker'));
} catch { return false }
})();
-router.get('/version-check', async (req, res) => {
+function compareVersions(a: string, b: string): number {
+ const pa = a.split('.').map(Number);
+ const pb = b.split('.').map(Number);
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
+ const na = pa[i] || 0, nb = pb[i] || 0;
+ if (na > nb) return 1;
+ if (na < nb) return -1;
+ }
+ return 0;
+}
+
+router.get('/version-check', async (_req: Request, res: Response) => {
const { version: currentVersion } = require('../../package.json');
try {
const resp = await fetch(
@@ -172,7 +174,7 @@ router.get('/version-check', async (req, res) => {
{ headers: { 'Accept': 'application/vnd.github.v3+json', 'User-Agent': 'NOMAD-Server' } }
);
if (!resp.ok) return res.json({ current: currentVersion, latest: currentVersion, update_available: false });
- const data = await resp.json();
+ const data = await resp.json() as { tag_name?: string; html_url?: string };
const latest = (data.tag_name || '').replace(/^v/, '');
const update_available = latest && latest !== currentVersion && compareVersions(latest, currentVersion) > 0;
res.json({ current: currentVersion, latest, update_available, release_url: data.html_url || '', is_docker: isDocker });
@@ -181,74 +183,55 @@ router.get('/version-check', async (req, res) => {
}
});
-function compareVersions(a, b) {
- const pa = a.split('.').map(Number);
- const pb = b.split('.').map(Number);
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
- const na = pa[i] || 0, nb = pb[i] || 0;
- if (na > nb) return 1;
- if (na < nb) return -1;
- }
- return 0;
-}
-
-// POST /api/admin/update — pull latest code, install deps, restart
-router.post('/update', async (req, res) => {
+router.post('/update', async (_req: Request, res: Response) => {
const rootDir = path.resolve(__dirname, '../../..');
const serverDir = path.resolve(__dirname, '../..');
const clientDir = path.join(rootDir, 'client');
- const steps = [];
+ const steps: { step: string; success?: boolean; output?: string; version?: string }[] = [];
try {
- // 1. git pull
const pullOutput = execSync('git pull origin main', { cwd: rootDir, timeout: 60000, encoding: 'utf8' });
steps.push({ step: 'git pull', success: true, output: pullOutput.trim() });
- // 2. npm install server
- execSync('npm install --production', { cwd: serverDir, timeout: 120000, encoding: 'utf8' });
+ execSync('npm install --production --ignore-scripts', { cwd: serverDir, timeout: 120000, encoding: 'utf8' });
steps.push({ step: 'npm install (server)', success: true });
- // 3. npm install + build client (production only)
if (process.env.NODE_ENV === 'production') {
- execSync('npm install', { cwd: clientDir, timeout: 120000, encoding: 'utf8' });
+ execSync('npm install --ignore-scripts', { cwd: clientDir, timeout: 120000, encoding: 'utf8' });
execSync('npm run build', { cwd: clientDir, timeout: 120000, encoding: 'utf8' });
steps.push({ step: 'npm install + build (client)', success: true });
}
- // Read new version
delete require.cache[require.resolve('../../package.json')];
const { version: newVersion } = require('../../package.json');
steps.push({ step: 'version', version: newVersion });
- // 4. Send response before restart
res.json({ success: true, steps, restarting: true });
- // 5. Graceful restart — exit and let process manager (Docker/systemd/pm2) restart
setTimeout(() => {
console.log('[Update] Restarting after update...');
process.exit(0);
}, 1000);
- } catch (err) {
- steps.push({ step: 'error', success: false, output: err.message });
+ } catch (err: unknown) {
+ console.error(err);
+ steps.push({ step: 'error', success: false, output: 'Internal error' });
res.status(500).json({ success: false, steps });
}
});
-// ── Addons ─────────────────────────────────────────────────
-
-router.get('/addons', (req, res) => {
- const addons = db.prepare('SELECT * FROM addons ORDER BY sort_order, id').all();
+router.get('/addons', (_req: Request, res: Response) => {
+ const addons = db.prepare('SELECT * FROM addons ORDER BY sort_order, id').all() as Addon[];
res.json({ addons: addons.map(a => ({ ...a, enabled: !!a.enabled, config: JSON.parse(a.config || '{}') })) });
});
-router.put('/addons/:id', (req, res) => {
+router.put('/addons/:id', (req: Request, res: Response) => {
const addon = db.prepare('SELECT * FROM addons WHERE id = ?').get(req.params.id);
if (!addon) return res.status(404).json({ error: 'Addon not found' });
const { enabled, config } = req.body;
if (enabled !== undefined) db.prepare('UPDATE addons SET enabled = ? WHERE id = ?').run(enabled ? 1 : 0, req.params.id);
if (config !== undefined) db.prepare('UPDATE addons SET config = ? WHERE id = ?').run(JSON.stringify(config), req.params.id);
- const updated = db.prepare('SELECT * FROM addons WHERE id = ?').get(req.params.id);
+ const updated = db.prepare('SELECT * FROM addons WHERE id = ?').get(req.params.id) as Addon;
res.json({ addon: { ...updated, enabled: !!updated.enabled, config: JSON.parse(updated.config || '{}') } });
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/assignments.js b/server/src/routes/assignments.ts
similarity index 62%
rename from server/src/routes/assignments.js
rename to server/src/routes/assignments.ts
index dfa669ff8..cb2d9a9fc 100644
--- a/server/src/routes/assignments.js
+++ b/server/src/routes/assignments.ts
@@ -1,15 +1,14 @@
-const express = require('express');
-const { db, canAccessTrip } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
-const { broadcast } = require('../websocket');
+import express, { Request, Response } from 'express';
+import { db } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { requireTripAccess } from '../middleware/tripAccess';
+import { broadcast } from '../websocket';
+import { loadTagsByPlaceIds, loadParticipantsByAssignmentIds, formatAssignmentWithPlace } from '../services/queryHelpers';
+import { AuthRequest, AssignmentRow, DayAssignment, Tag, Participant } from '../types';
const router = express.Router({ mergeParams: true });
-function verifyTripOwnership(tripId, userId) {
- return canAccessTrip(tripId, userId);
-}
-
-function getAssignmentWithPlace(assignmentId) {
+function getAssignmentWithPlace(assignmentId: number | bigint) {
const a = db.prepare(`
SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description,
p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency,
@@ -22,7 +21,7 @@ function getAssignmentWithPlace(assignmentId) {
JOIN places p ON da.place_id = p.id
LEFT JOIN categories c ON p.category_id = c.id
WHERE da.id = ?
- `).get(assignmentId);
+ `).get(assignmentId) as AssignmentRow | undefined;
if (!a) return null;
@@ -76,13 +75,9 @@ function getAssignmentWithPlace(assignmentId) {
};
}
-// GET /api/trips/:tripId/days/:dayId/assignments
-router.get('/trips/:tripId/days/:dayId/assignments', authenticate, (req, res) => {
+router.get('/trips/:tripId/days/:dayId/assignments', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, dayId } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) return res.status(404).json({ error: 'Trip not found' });
-
const day = db.prepare('SELECT id FROM days WHERE id = ? AND trip_id = ?').get(dayId, tripId);
if (!day) return res.status(404).json({ error: 'Day not found' });
@@ -99,91 +94,32 @@ router.get('/trips/:tripId/days/:dayId/assignments', authenticate, (req, res) =>
LEFT JOIN categories c ON p.category_id = c.id
WHERE da.day_id = ?
ORDER BY da.order_index ASC, da.created_at ASC
- `).all(dayId);
+ `).all(dayId) as AssignmentRow[];
- // Batch-load all tags for all places in one query to avoid N+1
const placeIds = [...new Set(assignments.map(a => a.place_id))];
- const tagsByPlaceId = {};
- if (placeIds.length > 0) {
- const placeholders = placeIds.map(() => '?').join(',');
- const allTags = db.prepare(`
- SELECT t.*, pt.place_id FROM tags t
- JOIN place_tags pt ON t.id = pt.tag_id
- WHERE pt.place_id IN (${placeholders})
- `).all(...placeIds);
- for (const tag of allTags) {
- if (!tagsByPlaceId[tag.place_id]) tagsByPlaceId[tag.place_id] = [];
- tagsByPlaceId[tag.place_id].push({ id: tag.id, name: tag.name, color: tag.color, created_at: tag.created_at });
- }
- }
+ const tagsByPlaceId = loadTagsByPlaceIds(placeIds, { compact: true });
- // Load all participants for this day's assignments in one query
- const assignmentIds = assignments.map(a => a.id)
- const allParticipants = assignmentIds.length > 0
- ? db.prepare(`SELECT ap.assignment_id, ap.user_id, u.username, u.avatar FROM assignment_participants ap JOIN users u ON ap.user_id = u.id WHERE ap.assignment_id IN (${assignmentIds.map(() => '?').join(',')})`)
- .all(...assignmentIds)
- : []
- const participantsByAssignment = {}
- for (const p of allParticipants) {
- if (!participantsByAssignment[p.assignment_id]) participantsByAssignment[p.assignment_id] = []
- participantsByAssignment[p.assignment_id].push({ user_id: p.user_id, username: p.username, avatar: p.avatar })
- }
+ const assignmentIds = assignments.map(a => a.id);
+ const participantsByAssignment = loadParticipantsByAssignmentIds(assignmentIds);
const result = assignments.map(a => {
- return {
- id: a.id,
- day_id: a.day_id,
- order_index: a.order_index,
- notes: a.notes,
- participants: participantsByAssignment[a.id] || [],
- created_at: a.created_at,
- place: {
- id: a.place_id,
- name: a.place_name,
- description: a.place_description,
- lat: a.lat,
- lng: a.lng,
- address: a.address,
- category_id: a.category_id,
- price: a.price,
- currency: a.place_currency,
- place_time: a.place_time,
- duration_minutes: a.duration_minutes,
- notes: a.place_notes,
- image_url: a.image_url,
- transport_mode: a.transport_mode,
- google_place_id: a.google_place_id,
- website: a.website,
- phone: a.phone,
- category: a.category_id ? {
- id: a.category_id,
- name: a.category_name,
- color: a.category_color,
- icon: a.category_icon,
- } : null,
- tags: tagsByPlaceId[a.place_id] || [],
- }
- };
+ return formatAssignmentWithPlace(a, tagsByPlaceId[a.place_id] || [], participantsByAssignment[a.id] || []);
});
res.json({ assignments: result });
});
-// POST /api/trips/:tripId/days/:dayId/assignments
-router.post('/trips/:tripId/days/:dayId/assignments', authenticate, (req, res) => {
+router.post('/trips/:tripId/days/:dayId/assignments', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, dayId } = req.params;
const { place_id, notes } = req.body;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) return res.status(404).json({ error: 'Trip not found' });
-
const day = db.prepare('SELECT id FROM days WHERE id = ? AND trip_id = ?').get(dayId, tripId);
if (!day) return res.status(404).json({ error: 'Day not found' });
const place = db.prepare('SELECT id FROM places WHERE id = ? AND trip_id = ?').get(place_id, tripId);
if (!place) return res.status(404).json({ error: 'Place not found' });
- const maxOrder = db.prepare('SELECT MAX(order_index) as max FROM day_assignments WHERE day_id = ?').get(dayId);
+ const maxOrder = db.prepare('SELECT MAX(order_index) as max FROM day_assignments WHERE day_id = ?').get(dayId) as { max: number | null };
const orderIndex = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
const result = db.prepare(
@@ -192,16 +128,12 @@ router.post('/trips/:tripId/days/:dayId/assignments', authenticate, (req, res) =
const assignment = getAssignmentWithPlace(result.lastInsertRowid);
res.status(201).json({ assignment });
- broadcast(tripId, 'assignment:created', { assignment }, req.headers['x-socket-id']);
+ broadcast(tripId, 'assignment:created', { assignment }, req.headers['x-socket-id'] as string);
});
-// DELETE /api/trips/:tripId/days/:dayId/assignments/:id
-router.delete('/trips/:tripId/days/:dayId/assignments/:id', authenticate, (req, res) => {
+router.delete('/trips/:tripId/days/:dayId/assignments/:id', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, dayId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) return res.status(404).json({ error: 'Trip not found' });
-
const assignment = db.prepare(
'SELECT da.id FROM day_assignments da JOIN days d ON da.day_id = d.id WHERE da.id = ? AND da.day_id = ? AND d.trip_id = ?'
).get(id, dayId, tripId);
@@ -210,24 +142,20 @@ router.delete('/trips/:tripId/days/:dayId/assignments/:id', authenticate, (req,
db.prepare('DELETE FROM day_assignments WHERE id = ?').run(id);
res.json({ success: true });
- broadcast(tripId, 'assignment:deleted', { assignmentId: Number(id), dayId: Number(dayId) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'assignment:deleted', { assignmentId: Number(id), dayId: Number(dayId) }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/days/:dayId/assignments/reorder
-router.put('/trips/:tripId/days/:dayId/assignments/reorder', authenticate, (req, res) => {
+router.put('/trips/:tripId/days/:dayId/assignments/reorder', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, dayId } = req.params;
const { orderedIds } = req.body;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) return res.status(404).json({ error: 'Trip not found' });
-
const day = db.prepare('SELECT id FROM days WHERE id = ? AND trip_id = ?').get(dayId, tripId);
if (!day) return res.status(404).json({ error: 'Day not found' });
const update = db.prepare('UPDATE day_assignments SET order_index = ? WHERE id = ? AND day_id = ?');
db.exec('BEGIN');
try {
- orderedIds.forEach((id, index) => {
+ orderedIds.forEach((id: number, index: number) => {
update.run(index, id, dayId);
});
db.exec('COMMIT');
@@ -236,22 +164,18 @@ router.put('/trips/:tripId/days/:dayId/assignments/reorder', authenticate, (req,
throw e;
}
res.json({ success: true });
- broadcast(tripId, 'assignment:reordered', { dayId: Number(dayId), orderedIds }, req.headers['x-socket-id']);
+ broadcast(tripId, 'assignment:reordered', { dayId: Number(dayId), orderedIds }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/assignments/:id/move
-router.put('/trips/:tripId/assignments/:id/move', authenticate, (req, res) => {
+router.put('/trips/:tripId/assignments/:id/move', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, id } = req.params;
const { new_day_id, order_index } = req.body;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) return res.status(404).json({ error: 'Trip not found' });
-
const assignment = db.prepare(`
SELECT da.* FROM day_assignments da
JOIN days d ON da.day_id = d.id
WHERE da.id = ? AND d.trip_id = ?
- `).get(id, tripId);
+ `).get(id, tripId) as DayAssignment | undefined;
if (!assignment) return res.status(404).json({ error: 'Assignment not found' });
@@ -261,15 +185,13 @@ router.put('/trips/:tripId/assignments/:id/move', authenticate, (req, res) => {
const oldDayId = assignment.day_id;
db.prepare('UPDATE day_assignments SET day_id = ?, order_index = ? WHERE id = ?').run(new_day_id, order_index || 0, id);
- const updated = getAssignmentWithPlace(id);
+ const updated = getAssignmentWithPlace(Number(id));
res.json({ assignment: updated });
- broadcast(tripId, 'assignment:moved', { assignment: updated, oldDayId: Number(oldDayId), newDayId: Number(new_day_id) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'assignment:moved', { assignment: updated, oldDayId: Number(oldDayId), newDayId: Number(new_day_id) }, req.headers['x-socket-id'] as string);
});
-// GET /api/trips/:tripId/assignments/:id/participants
-router.get('/trips/:tripId/assignments/:id/participants', authenticate, (req, res) => {
+router.get('/trips/:tripId/assignments/:id/participants', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, id } = req.params;
- if (!canAccessTrip(Number(tripId), req.user.id)) return res.status(404).json({ error: 'Trip not found' });
const participants = db.prepare(`
SELECT ap.user_id, u.username, u.avatar
@@ -281,10 +203,8 @@ router.get('/trips/:tripId/assignments/:id/participants', authenticate, (req, re
res.json({ participants });
});
-// PUT /api/trips/:tripId/assignments/:id/time — update per-assignment time
-router.put('/trips/:tripId/assignments/:id/time', authenticate, (req, res) => {
+router.put('/trips/:tripId/assignments/:id/time', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, id } = req.params;
- if (!canAccessTrip(Number(tripId), req.user.id)) return res.status(404).json({ error: 'Trip not found' });
const assignment = db.prepare(`
SELECT da.* FROM day_assignments da
@@ -297,20 +217,17 @@ router.put('/trips/:tripId/assignments/:id/time', authenticate, (req, res) => {
db.prepare('UPDATE day_assignments SET assignment_time = ?, assignment_end_time = ? WHERE id = ?')
.run(place_time ?? null, end_time ?? null, id);
- const updated = getAssignmentWithPlace(id);
+ const updated = getAssignmentWithPlace(Number(id));
res.json({ assignment: updated });
- broadcast(Number(tripId), 'assignment:updated', { assignment: updated }, req.headers['x-socket-id']);
+ broadcast(Number(tripId), 'assignment:updated', { assignment: updated }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/assignments/:id/participants — set participants (replace all)
-router.put('/trips/:tripId/assignments/:id/participants', authenticate, (req, res) => {
+router.put('/trips/:tripId/assignments/:id/participants', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, id } = req.params;
- if (!canAccessTrip(Number(tripId), req.user.id)) return res.status(404).json({ error: 'Trip not found' });
- const { user_ids } = req.body; // array of user IDs, empty array = everyone
+ const { user_ids } = req.body;
if (!Array.isArray(user_ids)) return res.status(400).json({ error: 'user_ids must be an array' });
- // Delete existing and insert new
db.prepare('DELETE FROM assignment_participants WHERE assignment_id = ?').run(id);
if (user_ids.length > 0) {
const insert = db.prepare('INSERT OR IGNORE INTO assignment_participants (assignment_id, user_id) VALUES (?, ?)');
@@ -325,7 +242,7 @@ router.put('/trips/:tripId/assignments/:id/participants', authenticate, (req, re
`).all(id);
res.json({ participants });
- broadcast(Number(tripId), 'assignment:participants', { assignmentId: Number(id), participants }, req.headers['x-socket-id']);
+ broadcast(Number(tripId), 'assignment:participants', { assignmentId: Number(id), participants }, req.headers['x-socket-id'] as string);
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/atlas.js b/server/src/routes/atlas.ts
similarity index 56%
rename from server/src/routes/atlas.js
rename to server/src/routes/atlas.ts
index aa40f856a..c6e2f11c5 100644
--- a/server/src/routes/atlas.js
+++ b/server/src/routes/atlas.ts
@@ -1,13 +1,12 @@
-const express = require('express');
-const { db } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
+import express, { Request, Response } from 'express';
+import { db } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { AuthRequest, Trip, Place } from '../types';
const router = express.Router();
router.use(authenticate);
-// Country code lookup from coordinates (bounding box approach)
-// Covers most countries — not pixel-perfect but good enough for visited-country tracking
-const COUNTRY_BOXES = {
+const COUNTRY_BOXES: Record<string, [number, number, number, number]> = {
AF:[60.5,29.4,75,38.5],AL:[19,39.6,21.1,42.7],DZ:[-8.7,19,12,37.1],AD:[1.4,42.4,1.8,42.7],AO:[11.7,-18.1,24.1,-4.4],
AR:[-73.6,-55.1,-53.6,-21.8],AM:[43.4,38.8,46.6,41.3],AU:[112.9,-43.6,153.6,-10.7],AT:[9.5,46.4,17.2,49],AZ:[44.8,38.4,50.4,41.9],
BR:[-73.9,-33.8,-34.8,5.3],BE:[2.5,49.5,6.4,51.5],BG:[22.4,41.2,28.6,44.2],CA:[-141,41.7,-52.6,83.1],CL:[-75.6,-55.9,-66.9,-17.5],
@@ -24,7 +23,7 @@ const COUNTRY_BOXES = {
AE:[51.6,22.6,56.4,26.1],GB:[-8,49.9,2,60.9],US:[-125,24.5,-66.9,49.4],VN:[102.1,8.6,109.5,23.4],
};
-function getCountryFromCoords(lat, lng) {
+function getCountryFromCoords(lat: number, lng: number): string | null {
for (const [code, [minLng, minLat, maxLng, maxLat]] of Object.entries(COUNTRY_BOXES)) {
if (lat >= minLat && lat <= maxLat && lng >= minLng && lng <= maxLng) {
return code;
@@ -33,68 +32,72 @@ function getCountryFromCoords(lat, lng) {
return null;
}
-function getCountryFromAddress(address) {
+const NAME_TO_CODE: Record<string, string> = {
+ 'germany':'DE','deutschland':'DE','france':'FR','frankreich':'FR','spain':'ES','spanien':'ES',
+ 'italy':'IT','italien':'IT','united kingdom':'GB','uk':'GB','england':'GB','united states':'US',
+ 'usa':'US','netherlands':'NL','niederlande':'NL','austria':'AT','osterreich':'AT','switzerland':'CH',
+ 'schweiz':'CH','portugal':'PT','greece':'GR','griechenland':'GR','turkey':'TR','turkei':'TR',
+ 'croatia':'HR','kroatien':'HR','czech republic':'CZ','tschechien':'CZ','czechia':'CZ',
+ 'poland':'PL','polen':'PL','sweden':'SE','schweden':'SE','norway':'NO','norwegen':'NO',
+ 'denmark':'DK','danemark':'DK','finland':'FI','finnland':'FI','belgium':'BE','belgien':'BE',
+ 'ireland':'IE','irland':'IE','hungary':'HU','ungarn':'HU','romania':'RO','rumanien':'RO',
+ 'bulgaria':'BG','bulgarien':'BG','japan':'JP','china':'CN','australia':'AU','australien':'AU',
+ 'canada':'CA','kanada':'CA','mexico':'MX','mexiko':'MX','brazil':'BR','brasilien':'BR',
+ 'argentina':'AR','argentinien':'AR','thailand':'TH','indonesia':'ID','indonesien':'ID',
+ 'india':'IN','indien':'IN','egypt':'EG','agypten':'EG','morocco':'MA','marokko':'MA',
+ 'south africa':'ZA','sudafrika':'ZA','new zealand':'NZ','neuseeland':'NZ','iceland':'IS','island':'IS',
+ 'luxembourg':'LU','luxemburg':'LU','slovenia':'SI','slowenien':'SI','slovakia':'SK','slowakei':'SK',
+ 'estonia':'EE','estland':'EE','latvia':'LV','lettland':'LV','lithuania':'LT','litauen':'LT',
+ 'serbia':'RS','serbien':'RS','israel':'IL','russia':'RU','russland':'RU','ukraine':'UA',
+ 'vietnam':'VN','south korea':'KR','sudkorea':'KR','philippines':'PH','philippinen':'PH',
+ 'malaysia':'MY','colombia':'CO','kolumbien':'CO','peru':'PE','chile':'CL','iran':'IR',
+ 'iraq':'IQ','irak':'IQ','pakistan':'PK','kenya':'KE','kenia':'KE','nigeria':'NG',
+ 'saudi arabia':'SA','saudi-arabien':'SA','albania':'AL','albanien':'AL',
+};
+
+function getCountryFromAddress(address: string | null): string | null {
if (!address) return null;
- // Take last segment after comma, trim
const parts = address.split(',').map(s => s.trim()).filter(Boolean);
if (parts.length === 0) return null;
const last = parts[parts.length - 1];
- // Try to match known country names to codes
- const NAME_TO_CODE = {
- 'germany':'DE','deutschland':'DE','france':'FR','frankreich':'FR','spain':'ES','spanien':'ES',
- 'italy':'IT','italien':'IT','united kingdom':'GB','uk':'GB','england':'GB','united states':'US',
- 'usa':'US','netherlands':'NL','niederlande':'NL','austria':'AT','österreich':'AT','switzerland':'CH',
- 'schweiz':'CH','portugal':'PT','greece':'GR','griechenland':'GR','turkey':'TR','türkei':'TR',
- 'croatia':'HR','kroatien':'HR','czech republic':'CZ','tschechien':'CZ','czechia':'CZ',
- 'poland':'PL','polen':'PL','sweden':'SE','schweden':'SE','norway':'NO','norwegen':'NO',
- 'denmark':'DK','dänemark':'DK','finland':'FI','finnland':'FI','belgium':'BE','belgien':'BE',
- 'ireland':'IE','irland':'IE','hungary':'HU','ungarn':'HU','romania':'RO','rumänien':'RO',
- 'bulgaria':'BG','bulgarien':'BG','japan':'JP','china':'CN','australia':'AU','australien':'AU',
- 'canada':'CA','kanada':'CA','mexico':'MX','mexiko':'MX','brazil':'BR','brasilien':'BR',
- 'argentina':'AR','argentinien':'AR','thailand':'TH','indonesia':'ID','indonesien':'ID',
- 'india':'IN','indien':'IN','egypt':'EG','ägypten':'EG','morocco':'MA','marokko':'MA',
- 'south africa':'ZA','südafrika':'ZA','new zealand':'NZ','neuseeland':'NZ','iceland':'IS','island':'IS',
- 'luxembourg':'LU','luxemburg':'LU','slovenia':'SI','slowenien':'SI','slovakia':'SK','slowakei':'SK',
- 'estonia':'EE','estland':'EE','latvia':'LV','lettland':'LV','lithuania':'LT','litauen':'LT',
- 'serbia':'RS','serbien':'RS','israel':'IL','russia':'RU','russland':'RU','ukraine':'UA',
- 'vietnam':'VN','south korea':'KR','südkorea':'KR','philippines':'PH','philippinen':'PH',
- 'malaysia':'MY','colombia':'CO','kolumbien':'CO','peru':'PE','chile':'CL','iran':'IR',
- 'iraq':'IQ','irak':'IQ','pakistan':'PK','kenya':'KE','kenia':'KE','nigeria':'NG',
- 'saudi arabia':'SA','saudi-arabien':'SA','albania':'AL','albanien':'AL',
- '日本':'JP','中国':'CN','한국':'KR','대한민국':'KR','ไทย':'TH',
- };
const normalized = last.toLowerCase();
if (NAME_TO_CODE[normalized]) return NAME_TO_CODE[normalized];
- // Try original case (for non-Latin scripts like 日本)
if (NAME_TO_CODE[last]) return NAME_TO_CODE[last];
- // Try 2-letter code directly
if (last.length === 2 && last === last.toUpperCase()) return last;
return null;
}
-// GET /api/addons/atlas/stats
-router.get('/stats', (req, res) => {
- const userId = req.user.id;
+const CONTINENT_MAP: Record<string, string> = {
+ AF:'Africa',AL:'Europe',DZ:'Africa',AD:'Europe',AO:'Africa',AR:'South America',AM:'Asia',AU:'Oceania',AT:'Europe',AZ:'Asia',
+ BR:'South America',BE:'Europe',BG:'Europe',CA:'North America',CL:'South America',CN:'Asia',CO:'South America',HR:'Europe',CZ:'Europe',DK:'Europe',
+ EG:'Africa',EE:'Europe',FI:'Europe',FR:'Europe',DE:'Europe',GR:'Europe',HU:'Europe',IS:'Europe',IN:'Asia',ID:'Asia',
+ IR:'Asia',IQ:'Asia',IE:'Europe',IL:'Asia',IT:'Europe',JP:'Asia',KE:'Africa',KR:'Asia',LV:'Europe',LT:'Europe',
+ LU:'Europe',MY:'Asia',MX:'North America',MA:'Africa',NL:'Europe',NZ:'Oceania',NO:'Europe',PK:'Asia',PE:'South America',PH:'Asia',
+ PL:'Europe',PT:'Europe',RO:'Europe',RU:'Europe',SA:'Asia',RS:'Europe',SK:'Europe',SI:'Europe',ZA:'Africa',ES:'Europe',
+ SE:'Europe',CH:'Europe',TH:'Asia',TR:'Europe',UA:'Europe',AE:'Asia',GB:'Europe',US:'North America',VN:'Asia',NG:'Africa',
+};
+
+router.get('/stats', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const userId = authReq.user.id;
- // Get all trips (own + shared)
const trips = db.prepare(`
SELECT DISTINCT t.* FROM trips t
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
WHERE t.user_id = ? OR m.user_id = ?
ORDER BY t.start_date DESC
- `).all(userId, userId, userId);
+ `).all(userId, userId, userId) as Trip[];
- // Get all places from those trips
const tripIds = trips.map(t => t.id);
if (tripIds.length === 0) {
return res.json({ countries: [], trips: [], stats: { totalTrips: 0, totalPlaces: 0, totalCountries: 0, totalDays: 0 } });
}
const placeholders = tripIds.map(() => '?').join(',');
- const places = db.prepare(`SELECT * FROM places WHERE trip_id IN (${placeholders})`).all(...tripIds);
+ const places = db.prepare(`SELECT * FROM places WHERE trip_id IN (${placeholders})`).all(...tripIds) as Place[];
- // Extract countries
- const countrySet = new Map(); // code -> { code, places: [], trips: Set }
+ interface CountryEntry { code: string; places: { id: number; name: string; lat: number | null; lng: number | null }[]; tripIds: Set<number> }
+ const countrySet = new Map<string, CountryEntry>();
for (const place of places) {
let code = getCountryFromAddress(place.address);
if (!code && place.lat && place.lng) {
@@ -104,18 +107,17 @@ router.get('/stats', (req, res) => {
if (!countrySet.has(code)) {
countrySet.set(code, { code, places: [], tripIds: new Set() });
}
- countrySet.get(code).places.push({ id: place.id, name: place.name, lat: place.lat, lng: place.lng });
- countrySet.get(code).tripIds.add(place.trip_id);
+ countrySet.get(code)!.places.push({ id: place.id, name: place.name, lat: place.lat, lng: place.lng });
+ countrySet.get(code)!.tripIds.add(place.trip_id);
}
}
- // Calculate total days across all trips
let totalDays = 0;
for (const trip of trips) {
if (trip.start_date && trip.end_date) {
const start = new Date(trip.start_date);
const end = new Date(trip.end_date);
- const diff = Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1;
+ const diff = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
if (diff > 0) totalDays += diff;
}
}
@@ -132,45 +134,30 @@ router.get('/stats', (req, res) => {
};
});
- // Unique cities (extract city from address — second to last comma segment)
- // Strip postal codes and normalize to avoid duplicates like "Tokyo" vs "Tokyo 131-0045"
- const citySet = new Set();
+ const citySet = new Set<string>();
for (const place of places) {
if (place.address) {
- const parts = place.address.split(',').map(s => s.trim()).filter(Boolean);
+ const parts = place.address.split(',').map((s: string) => s.trim()).filter(Boolean);
let raw = parts.length >= 2 ? parts[parts.length - 2] : parts[0];
if (raw) {
- const city = raw.replace(/[\d\-−〒]+/g, '').trim().toLowerCase();
+ const city = raw.replace(/[\d\-\u2212\u3012]+/g, '').trim().toLowerCase();
if (city) citySet.add(city);
}
}
}
const totalCities = citySet.size;
- // Most visited country
const mostVisited = countries.length > 0 ? countries.reduce((a, b) => a.placeCount > b.placeCount ? a : b) : null;
- // Continent breakdown
- const CONTINENT_MAP = {
- AF:'Africa',AL:'Europe',DZ:'Africa',AD:'Europe',AO:'Africa',AR:'South America',AM:'Asia',AU:'Oceania',AT:'Europe',AZ:'Asia',
- BR:'South America',BE:'Europe',BG:'Europe',CA:'North America',CL:'South America',CN:'Asia',CO:'South America',HR:'Europe',CZ:'Europe',DK:'Europe',
- EG:'Africa',EE:'Europe',FI:'Europe',FR:'Europe',DE:'Europe',GR:'Europe',HU:'Europe',IS:'Europe',IN:'Asia',ID:'Asia',
- IR:'Asia',IQ:'Asia',IE:'Europe',IL:'Asia',IT:'Europe',JP:'Asia',KE:'Africa',KR:'Asia',LV:'Europe',LT:'Europe',
- LU:'Europe',MY:'Asia',MX:'North America',MA:'Africa',NL:'Europe',NZ:'Oceania',NO:'Europe',PK:'Asia',PE:'South America',PH:'Asia',
- PL:'Europe',PT:'Europe',RO:'Europe',RU:'Europe',SA:'Asia',RS:'Europe',SK:'Europe',SI:'Europe',ZA:'Africa',ES:'Europe',
- SE:'Europe',CH:'Europe',TH:'Asia',TR:'Europe',UA:'Europe',AE:'Asia',GB:'Europe',US:'North America',VN:'Asia',NG:'Africa',
- };
- const continents = {};
+ const continents: Record<string, number> = {};
countries.forEach(c => {
const cont = CONTINENT_MAP[c.code] || 'Other';
continents[cont] = (continents[cont] || 0) + 1;
});
- // Last trip (most recent past trip)
const now = new Date().toISOString().split('T')[0];
const pastTrips = trips.filter(t => t.end_date && t.end_date <= now).sort((a, b) => b.end_date.localeCompare(a.end_date));
- const lastTrip = pastTrips[0] ? { id: pastTrips[0].id, title: pastTrips[0].title, start_date: pastTrips[0].start_date, end_date: pastTrips[0].end_date } : null;
- // Find country for last trip
+ const lastTrip: { id: number; title: string; start_date?: string | null; end_date?: string | null; countryCode?: string } | null = pastTrips[0] ? { id: pastTrips[0].id, title: pastTrips[0].title, start_date: pastTrips[0].start_date, end_date: pastTrips[0].end_date } : null;
if (lastTrip) {
const lastTripPlaces = places.filter(p => p.trip_id === lastTrip.id);
for (const p of lastTripPlaces) {
@@ -180,15 +167,13 @@ router.get('/stats', (req, res) => {
}
}
- // Next trip (earliest future trip)
const futureTrips = trips.filter(t => t.start_date && t.start_date > now).sort((a, b) => a.start_date.localeCompare(b.start_date));
- const nextTrip = futureTrips[0] ? { id: futureTrips[0].id, title: futureTrips[0].title, start_date: futureTrips[0].start_date } : null;
+ const nextTrip: { id: number; title: string; start_date?: string | null; daysUntil?: number } | null = futureTrips[0] ? { id: futureTrips[0].id, title: futureTrips[0].title, start_date: futureTrips[0].start_date } : null;
if (nextTrip) {
- const diff = Math.ceil((new Date(nextTrip.start_date) - new Date()) / (1000 * 60 * 60 * 24));
+ const diff = Math.ceil((new Date(nextTrip.start_date).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24));
nextTrip.daysUntil = Math.max(0, diff);
}
- // Travel streak (consecutive years with at least one trip)
const tripYears = new Set(trips.filter(t => t.start_date).map(t => parseInt(t.start_date.split('-')[0])));
let streak = 0;
const currentYear = new Date().getFullYear();
@@ -217,25 +202,25 @@ router.get('/stats', (req, res) => {
});
});
-// GET /api/addons/atlas/country/:code — details for a country
-router.get('/country/:code', (req, res) => {
- const userId = req.user.id;
+router.get('/country/:code', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const userId = authReq.user.id;
const code = req.params.code.toUpperCase();
const trips = db.prepare(`
SELECT DISTINCT t.* FROM trips t
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
WHERE t.user_id = ? OR m.user_id = ?
- `).all(userId, userId, userId);
+ `).all(userId, userId, userId) as Trip[];
const tripIds = trips.map(t => t.id);
if (tripIds.length === 0) return res.json({ places: [], trips: [] });
const placeholders = tripIds.map(() => '?').join(',');
- const places = db.prepare(`SELECT * FROM places WHERE trip_id IN (${placeholders})`).all(...tripIds);
+ const places = db.prepare(`SELECT * FROM places WHERE trip_id IN (${placeholders})`).all(...tripIds) as Place[];
- const matchingPlaces = [];
- const matchingTripIds = new Set();
+ const matchingPlaces: { id: number; name: string; address: string | null; lat: number | null; lng: number | null; trip_id: number }[] = [];
+ const matchingTripIds = new Set<number>();
for (const place of places) {
let pCode = getCountryFromAddress(place.address);
@@ -251,4 +236,4 @@ router.get('/country/:code', (req, res) => {
res.json({ places: matchingPlaces, trips: matchingTrips });
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/auth.js b/server/src/routes/auth.ts
similarity index 55%
rename from server/src/routes/auth.js
rename to server/src/routes/auth.ts
index 9f088cbe1..e64eb8eee 100644
--- a/server/src/routes/auth.js
+++ b/server/src/routes/auth.ts
@@ -1,26 +1,28 @@
-const express = require('express');
-const bcrypt = require('bcryptjs');
-const jwt = require('jsonwebtoken');
-const multer = require('multer');
-const path = require('path');
-const fs = require('fs');
-const { v4: uuid } = require('uuid');
-const fetch = require('node-fetch');
-const { db } = require('../db/database');
-const { authenticate, demoUploadBlock } = require('../middleware/auth');
+import express, { Request, Response, NextFunction } from 'express';
+import bcrypt from 'bcryptjs';
+import jwt from 'jsonwebtoken';
+import multer from 'multer';
+import path from 'path';
+import fs from 'fs';
+import { v4 as uuid } from 'uuid';
+import fetch from 'node-fetch';
+import { db } from '../db/database';
+import { authenticate, demoUploadBlock } from '../middleware/auth';
+import { JWT_SECRET } from '../config';
+import { AuthRequest, User } from '../types';
const router = express.Router();
-const { JWT_SECRET } = require('../config');
const avatarDir = path.join(__dirname, '../../uploads/avatars');
if (!fs.existsSync(avatarDir)) fs.mkdirSync(avatarDir, { recursive: true });
const avatarStorage = multer.diskStorage({
- destination: (req, file, cb) => cb(null, avatarDir),
- filename: (req, file, cb) => cb(null, uuid() + path.extname(file.originalname))
+ destination: (_req, _file, cb) => cb(null, avatarDir),
+ filename: (_req, file, cb) => cb(null, uuid() + path.extname(file.originalname))
});
const ALLOWED_AVATAR_EXTS = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
-const avatarUpload = multer({ storage: avatarStorage, limits: { fileSize: 5 * 1024 * 1024 }, fileFilter: (req, file, cb) => {
+const MAX_AVATAR_SIZE = 5 * 1024 * 1024; // 5 MB
+const avatarUpload = multer({ storage: avatarStorage, limits: { fileSize: MAX_AVATAR_SIZE }, fileFilter: (_req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase();
if (!file.mimetype.startsWith('image/') || !ALLOWED_AVATAR_EXTS.includes(ext)) {
return cb(new Error('Only .jpg, .jpeg, .png, .gif, .webp images are allowed'));
@@ -28,11 +30,20 @@ const avatarUpload = multer({ storage: avatarStorage, limits: { fileSize: 5 * 10
cb(null, true);
}});
-// Simple rate limiter
-const loginAttempts = new Map();
-function rateLimiter(maxAttempts, windowMs) {
- return (req, res, next) => {
- const key = req.ip;
+const RATE_LIMIT_WINDOW = 15 * 60 * 1000; // 15 minutes
+const RATE_LIMIT_CLEANUP = 5 * 60 * 1000; // 5 minutes
+
+const loginAttempts = new Map<string, { count: number; first: number }>();
+setInterval(() => {
+ const now = Date.now();
+ for (const [key, record] of loginAttempts) {
+ if (now - record.first >= RATE_LIMIT_WINDOW) loginAttempts.delete(key);
+ }
+}, RATE_LIMIT_CLEANUP);
+
+function rateLimiter(maxAttempts: number, windowMs: number) {
+ return (req: Request, res: Response, next: NextFunction) => {
+ const key = req.ip || 'unknown';
const now = Date.now();
const record = loginAttempts.get(key);
if (record && record.count >= maxAttempts && now - record.first < windowMs) {
@@ -46,32 +57,37 @@ function rateLimiter(maxAttempts, windowMs) {
next();
};
}
-const authLimiter = rateLimiter(10, 15 * 60 * 1000); // 10 attempts per 15 minutes
+const authLimiter = rateLimiter(10, RATE_LIMIT_WINDOW);
+
+function maskKey(key: string | null | undefined): string | null {
+ if (!key) return null;
+ if (key.length <= 8) return '--------';
+ return '----' + key.slice(-4);
+}
-function avatarUrl(user) {
+function avatarUrl(user: { avatar?: string | null }): string | null {
return user.avatar ? `/uploads/avatars/${user.avatar}` : null;
}
-function generateToken(user) {
+function generateToken(user: { id: number | bigint }) {
return jwt.sign(
- { id: user.id, username: user.username, email: user.email, role: user.role },
+ { id: user.id },
JWT_SECRET,
{ expiresIn: '24h' }
);
}
-// GET /api/auth/app-config (public — no auth needed)
-router.get('/app-config', (req, res) => {
- const userCount = db.prepare('SELECT COUNT(*) as count FROM users').get().count;
- const setting = db.prepare("SELECT value FROM app_settings WHERE key = 'allow_registration'").get();
+router.get('/app-config', (_req: Request, res: Response) => {
+ const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
+ const setting = db.prepare("SELECT value FROM app_settings WHERE key = 'allow_registration'").get() as { value: string } | undefined;
const allowRegistration = userCount === 0 || (setting?.value ?? 'true') === 'true';
const isDemo = process.env.DEMO_MODE === 'true';
const { version } = require('../../package.json');
const hasGoogleKey = !!db.prepare("SELECT maps_api_key FROM users WHERE role = 'admin' AND maps_api_key IS NOT NULL AND maps_api_key != '' LIMIT 1").get();
- const oidcDisplayName = db.prepare("SELECT value FROM app_settings WHERE key = 'oidc_display_name'").get()?.value || null;
+ const oidcDisplayName = (db.prepare("SELECT value FROM app_settings WHERE key = 'oidc_display_name'").get() as { value: string } | undefined)?.value || null;
const oidcConfigured = !!(
- db.prepare("SELECT value FROM app_settings WHERE key = 'oidc_issuer'").get()?.value &&
- db.prepare("SELECT value FROM app_settings WHERE key = 'oidc_client_id'").get()?.value
+ (db.prepare("SELECT value FROM app_settings WHERE key = 'oidc_issuer'").get() as { value: string } | undefined)?.value &&
+ (db.prepare("SELECT value FROM app_settings WHERE key = 'oidc_client_id'").get() as { value: string } | undefined)?.value
);
res.json({
allow_registration: isDemo ? false : allowRegistration,
@@ -80,33 +96,30 @@ router.get('/app-config', (req, res) => {
has_maps_key: hasGoogleKey,
oidc_configured: oidcConfigured,
oidc_display_name: oidcConfigured ? (oidcDisplayName || 'SSO') : undefined,
- allowed_file_types: db.prepare("SELECT value FROM app_settings WHERE key = 'allowed_file_types'").get()?.value || 'jpg,jpeg,png,gif,webp,heic,pdf,doc,docx,xls,xlsx,txt,csv',
+ allowed_file_types: (db.prepare("SELECT value FROM app_settings WHERE key = 'allowed_file_types'").get() as { value: string } | undefined)?.value || 'jpg,jpeg,png,gif,webp,heic,pdf,doc,docx,xls,xlsx,txt,csv',
demo_mode: isDemo,
demo_email: isDemo ? '[email protected]' : undefined,
demo_password: isDemo ? 'demo12345' : undefined,
});
});
-// POST /api/auth/demo-login (demo mode only)
-router.post('/demo-login', (req, res) => {
+router.post('/demo-login', (_req: Request, res: Response) => {
if (process.env.DEMO_MODE !== 'true') {
return res.status(404).json({ error: 'Not found' });
}
- const user = db.prepare('SELECT * FROM users WHERE email = ?').get('[email protected]');
+ const user = db.prepare('SELECT * FROM users WHERE email = ?').get('[email protected]') as User | undefined;
if (!user) return res.status(500).json({ error: 'Demo user not found' });
const token = generateToken(user);
const { password_hash, maps_api_key, openweather_api_key, unsplash_api_key, ...safe } = user;
res.json({ token, user: { ...safe, avatar_url: avatarUrl(user) } });
});
-// POST /api/auth/register
-router.post('/register', authLimiter, (req, res) => {
+router.post('/register', authLimiter, (req: Request, res: Response) => {
const { username, email, password } = req.body;
- // Check if registration is allowed
- const userCount = db.prepare('SELECT COUNT(*) as count FROM users').get().count;
+ const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
if (userCount > 0) {
- const setting = db.prepare("SELECT value FROM app_settings WHERE key = 'allow_registration'").get();
+ const setting = db.prepare("SELECT value FROM app_settings WHERE key = 'allow_registration'").get() as { value: string } | undefined;
if (setting?.value === 'false') {
return res.status(403).json({ error: 'Registration is disabled. Contact your administrator.' });
}
@@ -120,6 +133,10 @@ router.post('/register', authLimiter, (req, res) => {
return res.status(400).json({ error: 'Password must be at least 8 characters' });
}
+ if (!/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password)) {
+ return res.status(400).json({ error: 'Password must contain at least one uppercase letter, one lowercase letter, and one number' });
+ }
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return res.status(400).json({ error: 'Invalid email format' });
@@ -127,12 +144,11 @@ router.post('/register', authLimiter, (req, res) => {
const existingUser = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?) OR LOWER(username) = LOWER(?)').get(email, username);
if (existingUser) {
- return res.status(409).json({ error: 'A user with this email or username already exists' });
+ return res.status(409).json({ error: 'Registration failed. Please try different credentials.' });
}
- const password_hash = bcrypt.hashSync(password, 10);
+ const password_hash = bcrypt.hashSync(password, 12);
- // First user becomes admin
const isFirstUser = userCount === 0;
const role = isFirstUser ? 'admin' : 'user';
@@ -145,25 +161,24 @@ router.post('/register', authLimiter, (req, res) => {
const token = generateToken(user);
res.status(201).json({ token, user: { ...user, avatar_url: null } });
- } catch (err) {
+ } catch (err: unknown) {
res.status(500).json({ error: 'Error creating user' });
}
});
-// POST /api/auth/login
-router.post('/login', authLimiter, (req, res) => {
+router.post('/login', authLimiter, (req: Request, res: Response) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Email and password are required' });
}
- const user = db.prepare('SELECT * FROM users WHERE LOWER(email) = LOWER(?)').get(email);
+ const user = db.prepare('SELECT * FROM users WHERE LOWER(email) = LOWER(?)').get(email) as User | undefined;
if (!user) {
return res.status(401).json({ error: 'Invalid email or password' });
}
- const validPassword = bcrypt.compareSync(password, user.password_hash);
+ const validPassword = bcrypt.compareSync(password, user.password_hash!);
if (!validPassword) {
return res.status(401).json({ error: 'Invalid email or password' });
}
@@ -175,11 +190,11 @@ router.post('/login', authLimiter, (req, res) => {
res.json({ token, user: { ...userWithoutSensitive, avatar_url: avatarUrl(user) } });
});
-// GET /api/auth/me
-router.get('/me', authenticate, (req, res) => {
+router.get('/me', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const user = db.prepare(
'SELECT id, username, email, role, avatar, oidc_issuer, created_at FROM users WHERE id = ?'
- ).get(req.user.id);
+ ).get(authReq.user.id) as User | undefined;
if (!user) {
return res.status(404).json({ error: 'User not found' });
@@ -188,147 +203,177 @@ router.get('/me', authenticate, (req, res) => {
res.json({ user: { ...user, avatar_url: avatarUrl(user) } });
});
-// PUT /api/auth/me/password
-router.put('/me/password', authenticate, (req, res) => {
- if (process.env.DEMO_MODE === 'true' && req.user.email === '[email protected]') {
+router.put('/me/password', authenticate, rateLimiter(5, RATE_LIMIT_WINDOW), (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ if (process.env.DEMO_MODE === 'true' && authReq.user.email === '[email protected]') {
return res.status(403).json({ error: 'Password change is disabled in demo mode.' });
}
- const { new_password } = req.body;
+ const { current_password, new_password } = req.body;
+ if (!current_password) return res.status(400).json({ error: 'Current password is required' });
if (!new_password) return res.status(400).json({ error: 'New password is required' });
if (new_password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters' });
- const hash = bcrypt.hashSync(new_password, 10);
- db.prepare('UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(hash, req.user.id);
+ if (!/[A-Z]/.test(new_password) || !/[a-z]/.test(new_password) || !/[0-9]/.test(new_password)) {
+ return res.status(400).json({ error: 'Password must contain at least one uppercase letter, one lowercase letter, and one number' });
+ }
+
+ const user = db.prepare('SELECT password_hash FROM users WHERE id = ?').get(authReq.user.id) as { password_hash: string } | undefined;
+ if (!user || !bcrypt.compareSync(current_password, user.password_hash)) {
+ return res.status(401).json({ error: 'Current password is incorrect' });
+ }
+
+ const hash = bcrypt.hashSync(new_password, 12);
+ db.prepare('UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(hash, authReq.user.id);
res.json({ success: true });
});
-// DELETE /api/auth/me — delete own account
-router.delete('/me', authenticate, (req, res) => {
- // Block demo user
- if (process.env.DEMO_MODE === 'true' && req.user.email === '[email protected]') {
+router.delete('/me', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ if (process.env.DEMO_MODE === 'true' && authReq.user.email === '[email protected]') {
return res.status(403).json({ error: 'Account deletion is disabled in demo mode.' });
}
- // Prevent deleting last admin
- if (req.user.role === 'admin') {
- const adminCount = db.prepare("SELECT COUNT(*) as count FROM users WHERE role = 'admin'").get().count;
+ if (authReq.user.role === 'admin') {
+ const adminCount = (db.prepare("SELECT COUNT(*) as count FROM users WHERE role = 'admin'").get() as { count: number }).count;
if (adminCount <= 1) {
return res.status(400).json({ error: 'Cannot delete the last admin account' });
}
}
- db.prepare('DELETE FROM users WHERE id = ?').run(req.user.id);
+ db.prepare('DELETE FROM users WHERE id = ?').run(authReq.user.id);
res.json({ success: true });
});
-// PUT /api/auth/me/maps-key
-router.put('/me/maps-key', authenticate, (req, res) => {
+router.put('/me/maps-key', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { maps_api_key } = req.body;
db.prepare(
'UPDATE users SET maps_api_key = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?'
- ).run(maps_api_key || null, req.user.id);
+ ).run(maps_api_key || null, authReq.user.id);
res.json({ success: true, maps_api_key: maps_api_key || null });
});
-// PUT /api/auth/me/api-keys
-router.put('/me/api-keys', authenticate, (req, res) => {
+router.put('/me/api-keys', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { maps_api_key, openweather_api_key } = req.body;
+ const current = db.prepare('SELECT maps_api_key, openweather_api_key FROM users WHERE id = ?').get(authReq.user.id) as Pick<User, 'maps_api_key' | 'openweather_api_key'> | undefined;
db.prepare(
'UPDATE users SET maps_api_key = ?, openweather_api_key = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?'
).run(
- maps_api_key !== undefined ? (maps_api_key || null) : req.user.maps_api_key,
- openweather_api_key !== undefined ? (openweather_api_key || null) : req.user.openweather_api_key,
- req.user.id
+ maps_api_key !== undefined ? (maps_api_key || null) : current.maps_api_key,
+ openweather_api_key !== undefined ? (openweather_api_key || null) : current.openweather_api_key,
+ authReq.user.id
);
const updated = db.prepare(
'SELECT id, username, email, role, maps_api_key, openweather_api_key, avatar FROM users WHERE id = ?'
- ).get(req.user.id);
+ ).get(authReq.user.id) as Pick<User, 'id' | 'username' | 'email' | 'role' | 'maps_api_key' | 'openweather_api_key' | 'avatar'> | undefined;
- res.json({ success: true, user: { ...updated, avatar_url: avatarUrl(updated) } });
+ res.json({ success: true, user: { ...updated, maps_api_key: maskKey(updated?.maps_api_key), openweather_api_key: maskKey(updated?.openweather_api_key), avatar_url: avatarUrl(updated || {}) } });
});
-// PUT /api/auth/me/settings
-router.put('/me/settings', authenticate, (req, res) => {
+router.put('/me/settings', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { maps_api_key, openweather_api_key, username, email } = req.body;
- const updates = [];
- const params = [];
+ if (username !== undefined) {
+ const trimmed = username.trim();
+ if (!trimmed || trimmed.length < 2 || trimmed.length > 50) {
+ return res.status(400).json({ error: 'Username must be between 2 and 50 characters' });
+ }
+ if (!/^[a-zA-Z0-9_.-]+$/.test(trimmed)) {
+ return res.status(400).json({ error: 'Username can only contain letters, numbers, underscores, dots and hyphens' });
+ }
+ const conflict = db.prepare('SELECT id FROM users WHERE LOWER(username) = LOWER(?) AND id != ?').get(trimmed, authReq.user.id);
+ if (conflict) return res.status(409).json({ error: 'Username already taken' });
+ }
+
+ if (email !== undefined) {
+ const trimmed = email.trim();
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+ if (!trimmed || !emailRegex.test(trimmed)) {
+ return res.status(400).json({ error: 'Invalid email format' });
+ }
+ const conflict = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?) AND id != ?').get(trimmed, authReq.user.id);
+ if (conflict) return res.status(409).json({ error: 'Email already taken' });
+ }
+
+ const updates: string[] = [];
+ const params: (string | number | null)[] = [];
if (maps_api_key !== undefined) { updates.push('maps_api_key = ?'); params.push(maps_api_key || null); }
if (openweather_api_key !== undefined) { updates.push('openweather_api_key = ?'); params.push(openweather_api_key || null); }
- if (username !== undefined) { updates.push('username = ?'); params.push(username); }
- if (email !== undefined) { updates.push('email = ?'); params.push(email); }
+ if (username !== undefined) { updates.push('username = ?'); params.push(username.trim()); }
+ if (email !== undefined) { updates.push('email = ?'); params.push(email.trim()); }
if (updates.length > 0) {
updates.push('updated_at = CURRENT_TIMESTAMP');
- params.push(req.user.id);
+ params.push(authReq.user.id);
db.prepare(`UPDATE users SET ${updates.join(', ')} WHERE id = ?`).run(...params);
}
const updated = db.prepare(
'SELECT id, username, email, role, maps_api_key, openweather_api_key, avatar FROM users WHERE id = ?'
- ).get(req.user.id);
+ ).get(authReq.user.id) as Pick<User, 'id' | 'username' | 'email' | 'role' | 'maps_api_key' | 'openweather_api_key' | 'avatar'> | undefined;
- res.json({ success: true, user: { ...updated, avatar_url: avatarUrl(updated) } });
+ res.json({ success: true, user: { ...updated, maps_api_key: maskKey(updated?.maps_api_key), openweather_api_key: maskKey(updated?.openweather_api_key), avatar_url: avatarUrl(updated || {}) } });
});
-// GET /api/auth/me/settings (admin only — returns API keys)
-router.get('/me/settings', authenticate, (req, res) => {
+router.get('/me/settings', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const user = db.prepare(
'SELECT role, maps_api_key, openweather_api_key FROM users WHERE id = ?'
- ).get(req.user.id);
+ ).get(authReq.user.id) as Pick<User, 'role' | 'maps_api_key' | 'openweather_api_key'> | undefined;
if (user?.role !== 'admin') return res.status(403).json({ error: 'Admin access required' });
res.json({ settings: { maps_api_key: user.maps_api_key, openweather_api_key: user.openweather_api_key } });
});
-// POST /api/auth/avatar — upload avatar
-router.post('/avatar', authenticate, demoUploadBlock, avatarUpload.single('avatar'), (req, res) => {
+router.post('/avatar', authenticate, demoUploadBlock, avatarUpload.single('avatar'), (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
if (!req.file) return res.status(400).json({ error: 'No image uploaded' });
- const current = db.prepare('SELECT avatar FROM users WHERE id = ?').get(req.user.id);
+ const current = db.prepare('SELECT avatar FROM users WHERE id = ?').get(authReq.user.id) as { avatar: string | null } | undefined;
if (current && current.avatar) {
const oldPath = path.join(avatarDir, current.avatar);
if (fs.existsSync(oldPath)) fs.unlinkSync(oldPath);
}
const filename = req.file.filename;
- db.prepare('UPDATE users SET avatar = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(filename, req.user.id);
+ db.prepare('UPDATE users SET avatar = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(filename, authReq.user.id);
- const updated = db.prepare('SELECT id, username, email, role, avatar FROM users WHERE id = ?').get(req.user.id);
- res.json({ success: true, avatar_url: avatarUrl(updated) });
+ const updated = db.prepare('SELECT id, username, email, role, avatar FROM users WHERE id = ?').get(authReq.user.id) as Pick<User, 'id' | 'username' | 'email' | 'role' | 'avatar'> | undefined;
+ res.json({ success: true, avatar_url: avatarUrl(updated || {}) });
});
-// DELETE /api/auth/avatar — remove avatar
-router.delete('/avatar', authenticate, (req, res) => {
- const current = db.prepare('SELECT avatar FROM users WHERE id = ?').get(req.user.id);
+router.delete('/avatar', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const current = db.prepare('SELECT avatar FROM users WHERE id = ?').get(authReq.user.id) as { avatar: string | null } | undefined;
if (current && current.avatar) {
const filePath = path.join(avatarDir, current.avatar);
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
}
- db.prepare('UPDATE users SET avatar = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(req.user.id);
+ db.prepare('UPDATE users SET avatar = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(authReq.user.id);
res.json({ success: true });
});
-// GET /api/auth/users — list all users (for sharing/inviting)
-router.get('/users', authenticate, (req, res) => {
+router.get('/users', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const users = db.prepare(
'SELECT id, username, avatar FROM users WHERE id != ? ORDER BY username ASC'
- ).all(req.user.id);
+ ).all(authReq.user.id) as Pick<User, 'id' | 'username' | 'avatar'>[];
res.json({ users: users.map(u => ({ ...u, avatar_url: avatarUrl(u) })) });
});
-// GET /api/auth/validate-keys (admin only)
-router.get('/validate-keys', authenticate, async (req, res) => {
- const user = db.prepare('SELECT role, maps_api_key, openweather_api_key FROM users WHERE id = ?').get(req.user.id);
+router.get('/validate-keys', authenticate, async (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const user = db.prepare('SELECT role, maps_api_key, openweather_api_key FROM users WHERE id = ?').get(authReq.user.id) as Pick<User, 'role' | 'maps_api_key' | 'openweather_api_key'> | undefined;
if (user?.role !== 'admin') return res.status(403).json({ error: 'Admin access required' });
const result = { maps: false, weather: false };
- // Test Google Maps Places API
if (user.maps_api_key) {
try {
const mapsRes = await fetch(
@@ -344,19 +389,18 @@ router.get('/validate-keys', authenticate, async (req, res) => {
}
);
result.maps = mapsRes.status === 200;
- } catch (err) {
+ } catch (err: unknown) {
result.maps = false;
}
}
- // Test OpenWeatherMap API
if (user.openweather_api_key) {
try {
const weatherRes = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=London&appid=${user.openweather_api_key}`
);
result.weather = weatherRes.status === 200;
- } catch (err) {
+ } catch (err: unknown) {
result.weather = false;
}
}
@@ -364,9 +408,9 @@ router.get('/validate-keys', authenticate, async (req, res) => {
res.json(result);
});
-// PUT /api/auth/app-settings (admin only)
-router.put('/app-settings', authenticate, (req, res) => {
- const user = db.prepare('SELECT role FROM users WHERE id = ?').get(req.user.id);
+router.put('/app-settings', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const user = db.prepare('SELECT role FROM users WHERE id = ?').get(authReq.user.id) as { role: string } | undefined;
if (user?.role !== 'admin') return res.status(403).json({ error: 'Admin access required' });
const { allow_registration, allowed_file_types } = req.body;
@@ -379,20 +423,18 @@ router.put('/app-settings', authenticate, (req, res) => {
res.json({ success: true });
});
-// GET /api/auth/travel-stats — aggregated travel statistics for current user
-router.get('/travel-stats', authenticate, (req, res) => {
- const userId = req.user.id;
+router.get('/travel-stats', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const userId = authReq.user.id;
- // Get all places from user's trips (owned + shared)
const places = db.prepare(`
SELECT DISTINCT p.address, p.lat, p.lng
FROM places p
JOIN trips t ON p.trip_id = t.id
LEFT JOIN trip_members tm ON t.id = tm.trip_id
WHERE t.user_id = ? OR tm.user_id = ?
- `).all(userId, userId);
+ `).all(userId, userId) as { address: string | null; lat: number | null; lng: number | null }[];
- // Get trip count + total days
const tripStats = db.prepare(`
SELECT COUNT(DISTINCT t.id) as trips,
COUNT(DISTINCT d.id) as days
@@ -400,21 +442,20 @@ router.get('/travel-stats', authenticate, (req, res) => {
LEFT JOIN days d ON d.trip_id = t.id
LEFT JOIN trip_members tm ON t.id = tm.trip_id
WHERE (t.user_id = ? OR tm.user_id = ?) AND t.is_archived = 0
- `).get(userId, userId);
+ `).get(userId, userId) as { trips: number; days: number } | undefined;
- // Known country names (EN + DE)
const KNOWN_COUNTRIES = new Set([
'Japan', 'Germany', 'Deutschland', 'France', 'Frankreich', 'Italy', 'Italien', 'Spain', 'Spanien',
'United States', 'USA', 'United Kingdom', 'UK', 'Thailand', 'Australia', 'Australien',
'Canada', 'Kanada', 'Mexico', 'Mexiko', 'Brazil', 'Brasilien', 'China', 'India', 'Indien',
- 'South Korea', 'Südkorea', 'Indonesia', 'Indonesien', 'Turkey', 'Türkei', 'Türkiye',
+ 'South Korea', 'Sudkorea', 'Indonesia', 'Indonesien', 'Turkey', 'Turkei', 'Turkiye',
'Greece', 'Griechenland', 'Portugal', 'Netherlands', 'Niederlande', 'Belgium', 'Belgien',
- 'Switzerland', 'Schweiz', 'Austria', 'Österreich', 'Sweden', 'Schweden', 'Norway', 'Norwegen',
- 'Denmark', 'Dänemark', 'Finland', 'Finnland', 'Poland', 'Polen', 'Czech Republic', 'Tschechien',
- 'Czechia', 'Hungary', 'Ungarn', 'Croatia', 'Kroatien', 'Romania', 'Rumänien',
+ 'Switzerland', 'Schweiz', 'Austria', 'Osterreich', 'Sweden', 'Schweden', 'Norway', 'Norwegen',
+ 'Denmark', 'Danemark', 'Finland', 'Finnland', 'Poland', 'Polen', 'Czech Republic', 'Tschechien',
+ 'Czechia', 'Hungary', 'Ungarn', 'Croatia', 'Kroatien', 'Romania', 'Rumanien',
'Ireland', 'Irland', 'Iceland', 'Island', 'New Zealand', 'Neuseeland',
'Singapore', 'Singapur', 'Malaysia', 'Vietnam', 'Philippines', 'Philippinen',
- 'Egypt', 'Ägypten', 'Morocco', 'Marokko', 'South Africa', 'Südafrika', 'Kenya', 'Kenia',
+ 'Egypt', 'Agypten', 'Morocco', 'Marokko', 'South Africa', 'Sudafrika', 'Kenya', 'Kenia',
'Argentina', 'Argentinien', 'Chile', 'Colombia', 'Kolumbien', 'Peru',
'Russia', 'Russland', 'United Arab Emirates', 'UAE', 'Vereinigte Arabische Emirate',
'Israel', 'Jordan', 'Jordanien', 'Taiwan', 'Hong Kong', 'Hongkong',
@@ -424,16 +465,15 @@ router.get('/travel-stats', authenticate, (req, res) => {
'Bulgaria', 'Bulgarien', 'Serbia', 'Serbien', 'Montenegro', 'Albania', 'Albanien',
'Sri Lanka', 'Nepal', 'Cambodia', 'Kambodscha', 'Laos', 'Myanmar', 'Mongolia', 'Mongolei',
'Saudi Arabia', 'Saudi-Arabien', 'Qatar', 'Katar', 'Oman', 'Bahrain', 'Kuwait',
- 'Tanzania', 'Tansania', 'Ethiopia', 'Äthiopien', 'Nigeria', 'Ghana', 'Tunisia', 'Tunesien',
+ 'Tanzania', 'Tansania', 'Ethiopia', 'Athiopien', 'Nigeria', 'Ghana', 'Tunisia', 'Tunesien',
'Dominican Republic', 'Dominikanische Republik', 'Jamaica', 'Jamaika',
'Ukraine', 'Georgia', 'Georgien', 'Armenia', 'Armenien', 'Pakistan', 'Bangladesh', 'Bangladesch',
- 'Senegal', 'Mozambique', 'Mosambik', 'Moldova', 'Moldawien', 'Belarus', 'Weißrussland',
+ 'Senegal', 'Mozambique', 'Mosambik', 'Moldova', 'Moldawien', 'Belarus', 'Weissrussland',
]);
- // Extract countries from addresses — only accept known country names
- const countries = new Set();
- const cities = new Set();
- const coords = [];
+ const countries = new Set<string>();
+ const cities = new Set<string>();
+ const coords: { lat: number; lng: number }[] = [];
places.forEach(p => {
if (p.lat && p.lng) coords.push({ lat: p.lat, lng: p.lng });
@@ -442,8 +482,7 @@ router.get('/travel-stats', authenticate, (req, res) => {
for (const part of parts) {
if (KNOWN_COUNTRIES.has(part)) { countries.add(part); break; }
}
- // City: first part that's not the country and looks like a name (Latin chars, > 2 chars)
- const cityPart = parts.find(s => !KNOWN_COUNTRIES.has(s) && /^[A-Za-zÀ-ÿ\s-]{2,}$/.test(s));
+ const cityPart = parts.find(s => !KNOWN_COUNTRIES.has(s) && /^[A-Za-z\u00C0-\u00FF\s-]{2,}$/.test(s));
if (cityPart) cities.add(cityPart);
}
});
@@ -458,4 +497,4 @@ router.get('/travel-stats', authenticate, (req, res) => {
});
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/backup.js b/server/src/routes/backup.ts
similarity index 71%
rename from server/src/routes/backup.js
rename to server/src/routes/backup.ts
index f96f1c62d..f1c4883c6 100644
--- a/server/src/routes/backup.js
+++ b/server/src/routes/backup.ts
@@ -1,18 +1,38 @@
-const express = require('express');
-const archiver = require('archiver');
-const unzipper = require('unzipper');
-const multer = require('multer');
-const path = require('path');
-const fs = require('fs');
-const { authenticate, adminOnly } = require('../middleware/auth');
-const scheduler = require('../scheduler');
-const { db, closeDb, reinitialize } = require('../db/database');
+import express, { Request, Response, NextFunction } from 'express';
+import archiver from 'archiver';
+import unzipper from 'unzipper';
+import multer from 'multer';
+import path from 'path';
+import fs from 'fs';
+import { authenticate, adminOnly } from '../middleware/auth';
+import scheduler from '../scheduler';
+import { db, closeDb, reinitialize } from '../db/database';
const router = express.Router();
-// All backup routes require admin
router.use(authenticate, adminOnly);
+const BACKUP_RATE_WINDOW = 60 * 60 * 1000; // 1 hour
+const MAX_BACKUP_UPLOAD_SIZE = 500 * 1024 * 1024; // 500 MB
+
+const backupAttempts = new Map<string, { count: number; first: number }>();
+function backupRateLimiter(maxAttempts: number, windowMs: number) {
+ return (req: Request, res: Response, next: NextFunction) => {
+ const key = req.ip || 'unknown';
+ const now = Date.now();
+ const record = backupAttempts.get(key);
+ if (record && record.count >= maxAttempts && now - record.first < windowMs) {
+ return res.status(429).json({ error: 'Too many backup requests. Please try again later.' });
+ }
+ if (!record || now - record.first >= windowMs) {
+ backupAttempts.set(key, { count: 1, first: now });
+ } else {
+ record.count++;
+ }
+ next();
+ };
+}
+
const dataDir = path.join(__dirname, '../../data');
const backupsDir = path.join(dataDir, 'backups');
const uploadsDir = path.join(__dirname, '../../uploads');
@@ -21,14 +41,13 @@ function ensureBackupsDir() {
if (!fs.existsSync(backupsDir)) fs.mkdirSync(backupsDir, { recursive: true });
}
-function formatSize(bytes) {
+function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}
-// GET /api/backup/list
-router.get('/list', (req, res) => {
+router.get('/list', (_req: Request, res: Response) => {
ensureBackupsDir();
try {
@@ -44,16 +63,15 @@ router.get('/list', (req, res) => {
created_at: stat.birthtime.toISOString(),
};
})
- .sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
+ .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
res.json({ backups: files });
- } catch (err) {
+ } catch (err: unknown) {
res.status(500).json({ error: 'Error loading backups' });
}
});
-// POST /api/backup/create
-router.post('/create', async (req, res) => {
+router.post('/create', backupRateLimiter(3, BACKUP_RATE_WINDOW), async (_req: Request, res: Response) => {
ensureBackupsDir();
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
@@ -61,10 +79,9 @@ router.post('/create', async (req, res) => {
const outputPath = path.join(backupsDir, filename);
try {
- // Flush WAL to main DB file before archiving so all data is captured
try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
- await new Promise((resolve, reject) => {
+ await new Promise<void>((resolve, reject) => {
const output = fs.createWriteStream(outputPath);
const archive = archiver('zip', { zlib: { level: 9 } });
@@ -73,13 +90,11 @@ router.post('/create', async (req, res) => {
archive.pipe(output);
- // Add database
const dbPath = path.join(dataDir, 'travel.db');
if (fs.existsSync(dbPath)) {
archive.file(dbPath, { name: 'travel.db' });
}
- // Add uploads directory
if (fs.existsSync(uploadsDir)) {
archive.directory(uploadsDir, 'uploads');
}
@@ -97,18 +112,16 @@ router.post('/create', async (req, res) => {
created_at: stat.birthtime.toISOString(),
}
});
- } catch (err) {
+ } catch (err: unknown) {
console.error('Backup error:', err);
if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath);
res.status(500).json({ error: 'Error creating backup' });
}
});
-// GET /api/backup/download/:filename
-router.get('/download/:filename', (req, res) => {
+router.get('/download/:filename', (req: Request, res: Response) => {
const { filename } = req.params;
- // Security: prevent path traversal
if (!/^backup-[\w\-]+\.zip$/.test(filename)) {
return res.status(400).json({ error: 'Invalid filename' });
}
@@ -121,8 +134,7 @@ router.get('/download/:filename', (req, res) => {
res.download(filePath, filename);
});
-// Helper: restore from a zip file path
-async function restoreFromZip(zipPath, res) {
+async function restoreFromZip(zipPath: string, res: Response) {
const extractDir = path.join(dataDir, `restore-${Date.now()}`);
try {
await fs.createReadStream(zipPath)
@@ -135,22 +147,17 @@ async function restoreFromZip(zipPath, res) {
return res.status(400).json({ error: 'Invalid backup: travel.db not found' });
}
- // Step 1: close DB connection BEFORE touching the file (required on Windows)
closeDb();
try {
- // Step 2: remove WAL/SHM and overwrite DB file
const dbDest = path.join(dataDir, 'travel.db');
for (const ext of ['', '-wal', '-shm']) {
try { fs.unlinkSync(dbDest + ext); } catch (e) {}
}
fs.copyFileSync(extractedDb, dbDest);
- // Step 3: restore uploads — overwrite in-place instead of rmSync
- // (rmSync fails with EBUSY because express.static holds the directory)
const extractedUploads = path.join(extractDir, 'uploads');
if (fs.existsSync(extractedUploads)) {
- // Clear contents of each subdirectory without removing the root uploads dir
for (const sub of fs.readdirSync(uploadsDir)) {
const subPath = path.join(uploadsDir, sub);
if (fs.statSync(subPath).isDirectory()) {
@@ -159,26 +166,23 @@ async function restoreFromZip(zipPath, res) {
}
}
}
- // Copy restored files over
fs.cpSync(extractedUploads, uploadsDir, { recursive: true, force: true });
}
} finally {
- // Step 4: ALWAYS reopen DB — even if file copy failed, so the server stays functional
reinitialize();
}
fs.rmSync(extractDir, { recursive: true, force: true });
res.json({ success: true });
- } catch (err) {
+ } catch (err: unknown) {
console.error('Restore error:', err);
if (fs.existsSync(extractDir)) fs.rmSync(extractDir, { recursive: true, force: true });
- if (!res.headersSent) res.status(500).json({ error: err.message || 'Error restoring backup' });
+ if (!res.headersSent) res.status(500).json({ error: 'Error restoring backup' });
}
}
-// POST /api/backup/restore/:filename - restore from stored backup
-router.post('/restore/:filename', async (req, res) => {
+router.post('/restore/:filename', async (req: Request, res: Response) => {
const { filename } = req.params;
if (!/^backup-[\w\-]+\.zip$/.test(filename)) {
return res.status(400).json({ error: 'Invalid filename' });
@@ -190,30 +194,27 @@ router.post('/restore/:filename', async (req, res) => {
await restoreFromZip(zipPath, res);
});
-// POST /api/backup/upload-restore - upload a zip and restore
const uploadTmp = multer({
dest: path.join(dataDir, 'tmp/'),
- fileFilter: (req, file, cb) => {
+ fileFilter: (_req, file, cb) => {
if (file.originalname.endsWith('.zip')) cb(null, true);
else cb(new Error('Only ZIP files allowed'));
},
- limits: { fileSize: 500 * 1024 * 1024 },
+ limits: { fileSize: MAX_BACKUP_UPLOAD_SIZE },
});
-router.post('/upload-restore', uploadTmp.single('backup'), async (req, res) => {
+router.post('/upload-restore', uploadTmp.single('backup'), async (req: Request, res: Response) => {
if (!req.file) return res.status(400).json({ error: 'No file uploaded' });
const zipPath = req.file.path;
await restoreFromZip(zipPath, res);
if (fs.existsSync(zipPath)) fs.unlinkSync(zipPath);
});
-// GET /api/backup/auto-settings
-router.get('/auto-settings', (req, res) => {
+router.get('/auto-settings', (_req: Request, res: Response) => {
res.json({ settings: scheduler.loadSettings() });
});
-// PUT /api/backup/auto-settings
-router.put('/auto-settings', (req, res) => {
+router.put('/auto-settings', (req: Request, res: Response) => {
const { enabled, interval, keep_days } = req.body;
const settings = {
enabled: !!enabled,
@@ -225,8 +226,7 @@ router.put('/auto-settings', (req, res) => {
res.json({ settings });
});
-// DELETE /api/backup/:filename
-router.delete('/:filename', (req, res) => {
+router.delete('/:filename', (req: Request, res: Response) => {
const { filename } = req.params;
if (!/^backup-[\w\-]+\.zip$/.test(filename)) {
@@ -242,4 +242,4 @@ router.delete('/:filename', (req, res) => {
res.json({ success: true });
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/budget.js b/server/src/routes/budget.ts
similarity index 69%
rename from server/src/routes/budget.js
rename to server/src/routes/budget.ts
index ec2bbb66d..c1b925801 100644
--- a/server/src/routes/budget.js
+++ b/server/src/routes/budget.ts
@@ -1,48 +1,48 @@
-const express = require('express');
-const { db, canAccessTrip } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
-const { broadcast } = require('../websocket');
+import express, { Request, Response } from 'express';
+import { db, canAccessTrip } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { broadcast } from '../websocket';
+import { AuthRequest, BudgetItem, BudgetItemMember } from '../types';
const router = express.Router({ mergeParams: true });
-function verifyTripOwnership(tripId, userId) {
+function verifyTripOwnership(tripId: string | number, userId: number) {
return canAccessTrip(tripId, userId);
}
-function loadItemMembers(itemId) {
+function loadItemMembers(itemId: number | string) {
return db.prepare(`
SELECT bm.user_id, bm.paid, u.username, u.avatar
FROM budget_item_members bm
JOIN users u ON bm.user_id = u.id
WHERE bm.budget_item_id = ?
- `).all(itemId);
+ `).all(itemId) as BudgetItemMember[];
}
-function avatarUrl(user) {
+function avatarUrl(user: { avatar?: string | null }): string | null {
return user.avatar ? `/uploads/avatars/${user.avatar}` : null;
}
-// GET /api/trips/:tripId/budget
-router.get('/', authenticate, (req, res) => {
+router.get('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
const items = db.prepare(
'SELECT * FROM budget_items WHERE trip_id = ? ORDER BY category ASC, created_at ASC'
- ).all(tripId);
+ ).all(tripId) as BudgetItem[];
- // Batch-load all members
const itemIds = items.map(i => i.id);
- const membersByItem = {};
+ const membersByItem: Record<number, (BudgetItemMember & { avatar_url: string | null })[]> = {};
if (itemIds.length > 0) {
const allMembers = db.prepare(`
SELECT bm.budget_item_id, bm.user_id, bm.paid, u.username, u.avatar
FROM budget_item_members bm
JOIN users u ON bm.user_id = u.id
WHERE bm.budget_item_id IN (${itemIds.map(() => '?').join(',')})
- `).all(...itemIds);
+ `).all(...itemIds) as (BudgetItemMember & { budget_item_id: number })[];
for (const m of allMembers) {
if (!membersByItem[m.budget_item_id]) membersByItem[m.budget_item_id] = [];
membersByItem[m.budget_item_id].push({
@@ -55,10 +55,10 @@ router.get('/', authenticate, (req, res) => {
res.json({ items });
});
-// GET /api/trips/:tripId/budget/summary/per-person (must be before /:id routes)
-router.get('/summary/per-person', authenticate, (req, res) => {
+router.get('/summary/per-person', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
- if (!canAccessTrip(Number(tripId), req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!canAccessTrip(Number(tripId), authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const summary = db.prepare(`
SELECT bm.user_id, u.username, u.avatar,
@@ -70,22 +70,22 @@ router.get('/summary/per-person', authenticate, (req, res) => {
JOIN users u ON bm.user_id = u.id
WHERE bi.trip_id = ?
GROUP BY bm.user_id
- `).all(tripId);
+ `).all(tripId) as { user_id: number; username: string; avatar: string | null; total_assigned: number; total_paid: number; items_count: number }[];
res.json({ summary: summary.map(s => ({ ...s, avatar_url: avatarUrl(s) })) });
});
-// POST /api/trips/:tripId/budget
-router.post('/', authenticate, (req, res) => {
+router.post('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
const { category, name, total_price, persons, days, note } = req.body;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
if (!name) return res.status(400).json({ error: 'Name is required' });
- const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM budget_items WHERE trip_id = ?').get(tripId);
+ const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM budget_items WHERE trip_id = ?').get(tripId) as { max: number | null };
const sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
const result = db.prepare(
@@ -101,18 +101,18 @@ router.post('/', authenticate, (req, res) => {
sortOrder
);
- const item = db.prepare('SELECT * FROM budget_items WHERE id = ?').get(result.lastInsertRowid);
+ const item = db.prepare('SELECT * FROM budget_items WHERE id = ?').get(result.lastInsertRowid) as BudgetItem & { members?: BudgetItemMember[] };
item.members = [];
res.status(201).json({ item });
- broadcast(tripId, 'budget:created', { item }, req.headers['x-socket-id']);
+ broadcast(tripId, 'budget:created', { item }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/budget/:id
-router.put('/:id', authenticate, (req, res) => {
+router.put('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
const { category, name, total_price, persons, days, note, sort_order } = req.body;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
const item = db.prepare('SELECT * FROM budget_items WHERE id = ? AND trip_id = ?').get(id, tripId);
@@ -139,16 +139,16 @@ router.put('/:id', authenticate, (req, res) => {
id
);
- const updated = db.prepare('SELECT * FROM budget_items WHERE id = ?').get(id);
+ const updated = db.prepare('SELECT * FROM budget_items WHERE id = ?').get(id) as BudgetItem & { members?: BudgetItemMember[] };
updated.members = loadItemMembers(id);
res.json({ item: updated });
- broadcast(tripId, 'budget:updated', { item: updated }, req.headers['x-socket-id']);
+ broadcast(tripId, 'budget:updated', { item: updated }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/budget/:id/members
-router.put('/:id/members', authenticate, (req, res) => {
+router.put('/:id/members', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
- if (!canAccessTrip(Number(tripId), req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!canAccessTrip(Number(tripId), authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const item = db.prepare('SELECT * FROM budget_items WHERE id = ? AND trip_id = ?').get(id, tripId);
if (!item) return res.status(404).json({ error: 'Budget item not found' });
@@ -156,16 +156,14 @@ router.put('/:id/members', authenticate, (req, res) => {
const { user_ids } = req.body;
if (!Array.isArray(user_ids)) return res.status(400).json({ error: 'user_ids must be an array' });
- // Preserve paid status for existing members
- const existingPaid = {};
- const existing = db.prepare('SELECT user_id, paid FROM budget_item_members WHERE budget_item_id = ?').all(id);
+ const existingPaid: Record<number, number> = {};
+ const existing = db.prepare('SELECT user_id, paid FROM budget_item_members WHERE budget_item_id = ?').all(id) as { user_id: number; paid: number }[];
for (const e of existing) existingPaid[e.user_id] = e.paid;
db.prepare('DELETE FROM budget_item_members WHERE budget_item_id = ?').run(id);
if (user_ids.length > 0) {
const insert = db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid) VALUES (?, ?, ?)');
for (const userId of user_ids) insert.run(id, userId, existingPaid[userId] || 0);
- // Auto-update persons count
db.prepare('UPDATE budget_items SET persons = ? WHERE id = ?').run(user_ids.length, id);
} else {
db.prepare('UPDATE budget_items SET persons = NULL WHERE id = ?').run(id);
@@ -174,13 +172,13 @@ router.put('/:id/members', authenticate, (req, res) => {
const members = loadItemMembers(id).map(m => ({ ...m, avatar_url: avatarUrl(m) }));
const updated = db.prepare('SELECT * FROM budget_items WHERE id = ?').get(id);
res.json({ members, item: updated });
- broadcast(Number(tripId), 'budget:members-updated', { itemId: Number(id), members, persons: updated.persons }, req.headers['x-socket-id']);
+ broadcast(Number(tripId), 'budget:members-updated', { itemId: Number(id), members, persons: (updated as BudgetItem).persons }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/budget/:id/members/:userId/paid
-router.put('/:id/members/:userId/paid', authenticate, (req, res) => {
+router.put('/:id/members/:userId/paid', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id, userId } = req.params;
- if (!canAccessTrip(Number(tripId), req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!canAccessTrip(Number(tripId), authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const { paid } = req.body;
db.prepare('UPDATE budget_item_members SET paid = ? WHERE budget_item_id = ? AND user_id = ?')
@@ -190,18 +188,18 @@ router.put('/:id/members/:userId/paid', authenticate, (req, res) => {
SELECT bm.user_id, bm.paid, u.username, u.avatar
FROM budget_item_members bm JOIN users u ON bm.user_id = u.id
WHERE bm.budget_item_id = ? AND bm.user_id = ?
- `).get(id, userId);
+ `).get(id, userId) as BudgetItemMember | undefined;
const result = member ? { ...member, avatar_url: avatarUrl(member) } : null;
res.json({ member: result });
- broadcast(Number(tripId), 'budget:member-paid-updated', { itemId: Number(id), userId: Number(userId), paid: paid ? 1 : 0 }, req.headers['x-socket-id']);
+ broadcast(Number(tripId), 'budget:member-paid-updated', { itemId: Number(id), userId: Number(userId), paid: paid ? 1 : 0 }, req.headers['x-socket-id'] as string);
});
-// DELETE /api/trips/:tripId/budget/:id
-router.delete('/:id', authenticate, (req, res) => {
+router.delete('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
const item = db.prepare('SELECT id FROM budget_items WHERE id = ? AND trip_id = ?').get(id, tripId);
@@ -209,7 +207,7 @@ router.delete('/:id', authenticate, (req, res) => {
db.prepare('DELETE FROM budget_items WHERE id = ?').run(id);
res.json({ success: true });
- broadcast(tripId, 'budget:deleted', { itemId: Number(id) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'budget:deleted', { itemId: Number(id) }, req.headers['x-socket-id'] as string);
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/categories.js b/server/src/routes/categories.ts
similarity index 68%
rename from server/src/routes/categories.js
rename to server/src/routes/categories.ts
index dccffdf3b..f7dc99379 100644
--- a/server/src/routes/categories.js
+++ b/server/src/routes/categories.ts
@@ -1,33 +1,32 @@
-const express = require('express');
-const { db } = require('../db/database');
-const { authenticate, adminOnly } = require('../middleware/auth');
+import express, { Request, Response } from 'express';
+import { db } from '../db/database';
+import { authenticate, adminOnly } from '../middleware/auth';
+import { AuthRequest } from '../types';
const router = express.Router();
-// GET /api/categories - public to all authenticated users
-router.get('/', authenticate, (req, res) => {
+router.get('/', authenticate, (_req: Request, res: Response) => {
const categories = db.prepare(
'SELECT * FROM categories ORDER BY name ASC'
).all();
res.json({ categories });
});
-// POST /api/categories - admin only
-router.post('/', authenticate, adminOnly, (req, res) => {
+router.post('/', authenticate, adminOnly, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { name, color, icon } = req.body;
if (!name) return res.status(400).json({ error: 'Category name is required' });
const result = db.prepare(
'INSERT INTO categories (name, color, icon, user_id) VALUES (?, ?, ?, ?)'
- ).run(name, color || '#6366f1', icon || '📍', req.user.id);
+ ).run(name, color || '#6366f1', icon || '\uD83D\uDCCD', authReq.user.id);
const category = db.prepare('SELECT * FROM categories WHERE id = ?').get(result.lastInsertRowid);
res.status(201).json({ category });
});
-// PUT /api/categories/:id - admin only
-router.put('/:id', authenticate, adminOnly, (req, res) => {
+router.put('/:id', authenticate, adminOnly, (req: Request, res: Response) => {
const { name, color, icon } = req.body;
const category = db.prepare('SELECT * FROM categories WHERE id = ?').get(req.params.id);
@@ -45,8 +44,7 @@ router.put('/:id', authenticate, adminOnly, (req, res) => {
res.json({ category: updated });
});
-// DELETE /api/categories/:id - admin only
-router.delete('/:id', authenticate, adminOnly, (req, res) => {
+router.delete('/:id', authenticate, adminOnly, (req: Request, res: Response) => {
const category = db.prepare('SELECT * FROM categories WHERE id = ?').get(req.params.id);
if (!category) return res.status(404).json({ error: 'Category not found' });
@@ -55,4 +53,4 @@ router.delete('/:id', authenticate, adminOnly, (req, res) => {
res.json({ success: true });
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/collab.js b/server/src/routes/collab.ts
similarity index 58%
rename from server/src/routes/collab.js
rename to server/src/routes/collab.ts
index 242f10f52..3c5d6b252 100644
--- a/server/src/routes/collab.js
+++ b/server/src/routes/collab.ts
@@ -1,33 +1,66 @@
-const express = require('express');
-const multer = require('multer');
-const path = require('path');
-const fs = require('fs');
-const { v4: uuidv4 } = require('uuid');
-const { db, canAccessTrip } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
-const { broadcast } = require('../websocket');
+import express, { Request, Response } from 'express';
+import multer from 'multer';
+import path from 'path';
+import fs from 'fs';
+import { v4 as uuidv4 } from 'uuid';
+import { db, canAccessTrip } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { broadcast } from '../websocket';
+import { validateStringLengths } from '../middleware/validate';
+import { AuthRequest, CollabNote, CollabPoll, CollabMessage, TripFile } from '../types';
+
+interface ReactionRow {
+ emoji: string;
+ user_id: number;
+ username: string;
+ message_id?: number;
+}
+
+interface PollVoteRow {
+ option_index: number;
+ user_id: number;
+ username: string;
+ avatar: string | null;
+}
+
+interface NoteFileRow {
+ id: number;
+ filename: string;
+ original_name?: string;
+ file_size?: number;
+ mime_type?: string;
+}
+const MAX_NOTE_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
const filesDir = path.join(__dirname, '../../uploads/files');
const noteUpload = multer({
storage: multer.diskStorage({
- destination: (req, file, cb) => { if (!fs.existsSync(filesDir)) fs.mkdirSync(filesDir, { recursive: true }); cb(null, filesDir) },
- filename: (req, file, cb) => { cb(null, `${uuidv4()}${path.extname(file.originalname)}`) },
+ destination: (_req, _file, cb) => { if (!fs.existsSync(filesDir)) fs.mkdirSync(filesDir, { recursive: true }); cb(null, filesDir) },
+ filename: (_req, file, cb) => { cb(null, `${uuidv4()}${path.extname(file.originalname)}`) },
}),
- limits: { fileSize: 50 * 1024 * 1024 },
+ limits: { fileSize: MAX_NOTE_FILE_SIZE },
+ fileFilter: (_req, file, cb) => {
+ const ext = path.extname(file.originalname).toLowerCase();
+ const BLOCKED = ['.svg', '.html', '.htm', '.xml', '.xhtml', '.js', '.jsx', '.ts', '.exe', '.bat', '.sh', '.cmd', '.msi', '.dll', '.com', '.vbs', '.ps1', '.php'];
+ if (BLOCKED.includes(ext) || file.mimetype.includes('svg') || file.mimetype.includes('html') || file.mimetype.includes('javascript')) {
+ return cb(new Error('File type not allowed'));
+ }
+ cb(null, true);
+ },
});
const router = express.Router({ mergeParams: true });
-function verifyTripAccess(tripId, userId) {
+function verifyTripAccess(tripId: string | number, userId: number) {
return canAccessTrip(tripId, userId);
}
-function avatarUrl(user) {
+function avatarUrl(user: { avatar?: string | null }): string | null {
return user.avatar ? `/uploads/avatars/${user.avatar}` : null;
}
-function formatNote(note) {
- const attachments = db.prepare('SELECT id, filename, original_name, file_size, mime_type FROM trip_files WHERE note_id = ?').all(note.id);
+function formatNote(note: CollabNote) {
+ const attachments = db.prepare('SELECT id, filename, original_name, file_size, mime_type FROM trip_files WHERE note_id = ?').all(note.id) as NoteFileRow[];
return {
...note,
avatar_url: avatarUrl(note),
@@ -35,17 +68,17 @@ function formatNote(note) {
};
}
-function loadReactions(messageId) {
+function loadReactions(messageId: number | string) {
return db.prepare(`
SELECT r.emoji, r.user_id, u.username
FROM collab_message_reactions r
JOIN users u ON r.user_id = u.id
WHERE r.message_id = ?
- `).all(messageId);
+ `).all(messageId) as ReactionRow[];
}
-function groupReactions(reactions) {
- const map = {};
+function groupReactions(reactions: ReactionRow[]) {
+ const map: Record<string, { user_id: number; username: string }[]> = {};
for (const r of reactions) {
if (!map[r.emoji]) map[r.emoji] = [];
map[r.emoji].push({ user_id: r.user_id, username: r.username });
@@ -53,16 +86,14 @@ function groupReactions(reactions) {
return Object.entries(map).map(([emoji, users]) => ({ emoji, users, count: users.length }));
}
-function formatMessage(msg, reactions) {
+function formatMessage(msg: CollabMessage, reactions?: { emoji: string; users: { user_id: number; username: string }[]; count: number }[]) {
return { ...msg, user_avatar: avatarUrl(msg), avatar_url: avatarUrl(msg), reactions: reactions || [] };
}
-// ─── NOTES ───────────────────────────────────────────────────────────────────
-
-// GET /notes
-router.get('/notes', authenticate, (req, res) => {
+router.get('/notes', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
- if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const notes = db.prepare(`
SELECT n.*, u.username, u.avatar
@@ -70,37 +101,37 @@ router.get('/notes', authenticate, (req, res) => {
JOIN users u ON n.user_id = u.id
WHERE n.trip_id = ?
ORDER BY n.pinned DESC, n.updated_at DESC
- `).all(tripId);
+ `).all(tripId) as CollabNote[];
res.json({ notes: notes.map(formatNote) });
});
-// POST /notes
-router.post('/notes', authenticate, (req, res) => {
+router.post('/notes', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
const { title, content, category, color, website } = req.body;
- if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
if (!title) return res.status(400).json({ error: 'Title is required' });
const result = db.prepare(`
INSERT INTO collab_notes (trip_id, user_id, title, content, category, color, website)
VALUES (?, ?, ?, ?, ?, ?, ?)
- `).run(tripId, req.user.id, title, content || null, category || 'General', color || '#6366f1', website || null);
+ `).run(tripId, authReq.user.id, title, content || null, category || 'General', color || '#6366f1', website || null);
const note = db.prepare(`
SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ?
- `).get(result.lastInsertRowid);
+ `).get(result.lastInsertRowid) as CollabNote;
const formatted = formatNote(note);
res.status(201).json({ note: formatted });
- broadcast(tripId, 'collab:note:created', { note: formatted }, req.headers['x-socket-id']);
+ broadcast(tripId, 'collab:note:created', { note: formatted }, req.headers['x-socket-id'] as string);
});
-// PUT /notes/:id
-router.put('/notes/:id', authenticate, (req, res) => {
+router.put('/notes/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
const { title, content, category, color, pinned, website } = req.body;
- if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const existing = db.prepare('SELECT * FROM collab_notes WHERE id = ? AND trip_id = ?').get(id, tripId);
if (!existing) return res.status(404).json({ error: 'Note not found' });
@@ -127,23 +158,22 @@ router.put('/notes/:id', authenticate, (req, res) => {
const note = db.prepare(`
SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ?
- `).get(id);
+ `).get(id) as CollabNote;
const formatted = formatNote(note);
res.json({ note: formatted });
- broadcast(tripId, 'collab:note:updated', { note: formatted }, req.headers['x-socket-id']);
+ broadcast(tripId, 'collab:note:updated', { note: formatted }, req.headers['x-socket-id'] as string);
});
-// DELETE /notes/:id
-router.delete('/notes/:id', authenticate, (req, res) => {
+router.delete('/notes/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
- if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const existing = db.prepare('SELECT id FROM collab_notes WHERE id = ? AND trip_id = ?').get(id, tripId);
if (!existing) return res.status(404).json({ error: 'Note not found' });
- // Delete attached files (physical + DB)
- const noteFiles = db.prepare('SELECT id, filename FROM trip_files WHERE note_id = ?').all(id);
+ const noteFiles = db.prepare('SELECT id, filename FROM trip_files WHERE note_id = ?').all(id) as NoteFileRow[];
for (const f of noteFiles) {
const filePath = path.join(__dirname, '../../uploads', f.filename);
try { fs.unlinkSync(filePath) } catch {}
@@ -152,13 +182,13 @@ router.delete('/notes/:id', authenticate, (req, res) => {
db.prepare('DELETE FROM collab_notes WHERE id = ?').run(id);
res.json({ success: true });
- broadcast(tripId, 'collab:note:deleted', { noteId: Number(id) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'collab:note:deleted', { noteId: Number(id) }, req.headers['x-socket-id'] as string);
});
-// POST /notes/:id/files — upload attachment to note
-router.post('/notes/:id/files', authenticate, noteUpload.single('file'), (req, res) => {
+router.post('/notes/:id/files', authenticate, noteUpload.single('file'), (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
- if (!verifyTripAccess(Number(tripId), req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(Number(tripId), authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
if (!req.file) return res.status(400).json({ error: 'No file uploaded' });
const note = db.prepare('SELECT id FROM collab_notes WHERE id = ? AND trip_id = ?').get(id, tripId);
@@ -168,51 +198,47 @@ router.post('/notes/:id/files', authenticate, noteUpload.single('file'), (req, r
'INSERT INTO trip_files (trip_id, note_id, filename, original_name, file_size, mime_type) VALUES (?, ?, ?, ?, ?, ?)'
).run(tripId, id, `files/${req.file.filename}`, req.file.originalname, req.file.size, req.file.mimetype);
- const file = db.prepare('SELECT * FROM trip_files WHERE id = ?').get(result.lastInsertRowid);
+ const file = db.prepare('SELECT * FROM trip_files WHERE id = ?').get(result.lastInsertRowid) as TripFile;
res.status(201).json({ file: { ...file, url: `/uploads/${file.filename}` } });
- broadcast(Number(tripId), 'collab:note:updated', { note: formatNote(db.prepare('SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ?').get(id)) }, req.headers['x-socket-id']);
+ broadcast(Number(tripId), 'collab:note:updated', { note: formatNote(db.prepare('SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ?').get(id) as CollabNote) }, req.headers['x-socket-id'] as string);
});
-// DELETE /notes/:id/files/:fileId — remove attachment
-router.delete('/notes/:id/files/:fileId', authenticate, (req, res) => {
+router.delete('/notes/:id/files/:fileId', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id, fileId } = req.params;
- if (!verifyTripAccess(Number(tripId), req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(Number(tripId), authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
- const file = db.prepare('SELECT * FROM trip_files WHERE id = ? AND note_id = ?').get(fileId, id);
+ const file = db.prepare('SELECT * FROM trip_files WHERE id = ? AND note_id = ?').get(fileId, id) as TripFile | undefined;
if (!file) return res.status(404).json({ error: 'File not found' });
- // Delete physical file
const filePath = path.join(__dirname, '../../uploads', file.filename);
try { fs.unlinkSync(filePath) } catch {}
db.prepare('DELETE FROM trip_files WHERE id = ?').run(fileId);
res.json({ success: true });
- broadcast(Number(tripId), 'collab:note:updated', { note: formatNote(db.prepare('SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ?').get(id)) }, req.headers['x-socket-id']);
+ broadcast(Number(tripId), 'collab:note:updated', { note: formatNote(db.prepare('SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ?').get(id) as CollabNote) }, req.headers['x-socket-id'] as string);
});
-// ─── POLLS ───────────────────────────────────────────────────────────────────
-
-function getPollWithVotes(pollId) {
+function getPollWithVotes(pollId: number | bigint | string) {
const poll = db.prepare(`
SELECT p.*, u.username, u.avatar
FROM collab_polls p
JOIN users u ON p.user_id = u.id
WHERE p.id = ?
- `).get(pollId);
+ `).get(pollId) as CollabPoll | undefined;
if (!poll) return null;
- const options = JSON.parse(poll.options);
+ const options: (string | { label: string })[] = JSON.parse(poll.options);
const votes = db.prepare(`
SELECT v.option_index, v.user_id, u.username, u.avatar
FROM collab_poll_votes v
JOIN users u ON v.user_id = u.id
WHERE v.poll_id = ?
- `).all(pollId);
+ `).all(pollId) as PollVoteRow[];
- // Transform: nest voters into each option (frontend expects options[i].voters)
- const formattedOptions = options.map((label, idx) => ({
+ const formattedOptions = options.map((label: string | { label: string }, idx: number) => ({
label: typeof label === 'string' ? label : label.label || label,
voters: votes
.filter(v => v.option_index === idx)
@@ -228,49 +254,48 @@ function getPollWithVotes(pollId) {
};
}
-// GET /polls
-router.get('/polls', authenticate, (req, res) => {
+router.get('/polls', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
- if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const rows = db.prepare(`
SELECT id FROM collab_polls WHERE trip_id = ? ORDER BY created_at DESC
- `).all(tripId);
+ `).all(tripId) as { id: number }[];
const polls = rows.map(row => getPollWithVotes(row.id)).filter(Boolean);
res.json({ polls });
});
-// POST /polls
-router.post('/polls', authenticate, (req, res) => {
+router.post('/polls', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
const { question, options, multiple, multiple_choice, deadline } = req.body;
- if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
if (!question) return res.status(400).json({ error: 'Question is required' });
if (!Array.isArray(options) || options.length < 2) {
return res.status(400).json({ error: 'At least 2 options are required' });
}
- // Accept both 'multiple' and 'multiple_choice' from frontend
const isMultiple = multiple || multiple_choice;
const result = db.prepare(`
INSERT INTO collab_polls (trip_id, user_id, question, options, multiple, deadline)
VALUES (?, ?, ?, ?, ?, ?)
- `).run(tripId, req.user.id, question, JSON.stringify(options), isMultiple ? 1 : 0, deadline || null);
+ `).run(tripId, authReq.user.id, question, JSON.stringify(options), isMultiple ? 1 : 0, deadline || null);
const poll = getPollWithVotes(result.lastInsertRowid);
res.status(201).json({ poll });
- broadcast(tripId, 'collab:poll:created', { poll }, req.headers['x-socket-id']);
+ broadcast(tripId, 'collab:poll:created', { poll }, req.headers['x-socket-id'] as string);
});
-// POST /polls/:id/vote
-router.post('/polls/:id/vote', authenticate, (req, res) => {
+router.post('/polls/:id/vote', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
const { option_index } = req.body;
- if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
- const poll = db.prepare('SELECT * FROM collab_polls WHERE id = ? AND trip_id = ?').get(id, tripId);
+ const poll = db.prepare('SELECT * FROM collab_polls WHERE id = ? AND trip_id = ?').get(id, tripId) as CollabPoll | undefined;
if (!poll) return res.status(404).json({ error: 'Poll not found' });
if (poll.closed) return res.status(400).json({ error: 'Poll is closed' });
@@ -279,29 +304,28 @@ router.post('/polls/:id/vote', authenticate, (req, res) => {
return res.status(400).json({ error: 'Invalid option index' });
}
- // Toggle: if vote exists, remove it; otherwise add it
const existingVote = db.prepare(
'SELECT id FROM collab_poll_votes WHERE poll_id = ? AND user_id = ? AND option_index = ?'
- ).get(id, req.user.id, option_index);
+ ).get(id, authReq.user.id, option_index) as { id: number } | undefined;
if (existingVote) {
db.prepare('DELETE FROM collab_poll_votes WHERE id = ?').run(existingVote.id);
} else {
if (!poll.multiple) {
- db.prepare('DELETE FROM collab_poll_votes WHERE poll_id = ? AND user_id = ?').run(id, req.user.id);
+ db.prepare('DELETE FROM collab_poll_votes WHERE poll_id = ? AND user_id = ?').run(id, authReq.user.id);
}
- db.prepare('INSERT INTO collab_poll_votes (poll_id, user_id, option_index) VALUES (?, ?, ?)').run(id, req.user.id, option_index);
+ db.prepare('INSERT INTO collab_poll_votes (poll_id, user_id, option_index) VALUES (?, ?, ?)').run(id, authReq.user.id, option_index);
}
const updatedPoll = getPollWithVotes(id);
res.json({ poll: updatedPoll });
- broadcast(tripId, 'collab:poll:voted', { poll: updatedPoll }, req.headers['x-socket-id']);
+ broadcast(tripId, 'collab:poll:voted', { poll: updatedPoll }, req.headers['x-socket-id'] as string);
});
-// PUT /polls/:id/close
-router.put('/polls/:id/close', authenticate, (req, res) => {
+router.put('/polls/:id/close', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
- if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const poll = db.prepare('SELECT * FROM collab_polls WHERE id = ? AND trip_id = ?').get(id, tripId);
if (!poll) return res.status(404).json({ error: 'Poll not found' });
@@ -310,29 +334,27 @@ router.put('/polls/:id/close', authenticate, (req, res) => {
const updatedPoll = getPollWithVotes(id);
res.json({ poll: updatedPoll });
- broadcast(tripId, 'collab:poll:closed', { poll: updatedPoll }, req.headers['x-socket-id']);
+ broadcast(tripId, 'collab:poll:closed', { poll: updatedPoll }, req.headers['x-socket-id'] as string);
});
-// DELETE /polls/:id
-router.delete('/polls/:id', authenticate, (req, res) => {
+router.delete('/polls/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
- if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const poll = db.prepare('SELECT id FROM collab_polls WHERE id = ? AND trip_id = ?').get(id, tripId);
if (!poll) return res.status(404).json({ error: 'Poll not found' });
db.prepare('DELETE FROM collab_polls WHERE id = ?').run(id);
res.json({ success: true });
- broadcast(tripId, 'collab:poll:deleted', { pollId: Number(id) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'collab:poll:deleted', { pollId: Number(id) }, req.headers['x-socket-id'] as string);
});
-// ─── MESSAGES (CHAT) ────────────────────────────────────────────────────────
-
-// GET /messages
-router.get('/messages', authenticate, (req, res) => {
+router.get('/messages', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
const { before } = req.query;
- if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const query = `
SELECT m.*, u.username, u.avatar,
@@ -347,20 +369,19 @@ router.get('/messages', authenticate, (req, res) => {
`;
const messages = before
- ? db.prepare(query).all(tripId, before)
- : db.prepare(query).all(tripId);
+ ? db.prepare(query).all(tripId, before) as CollabMessage[]
+ : db.prepare(query).all(tripId) as CollabMessage[];
messages.reverse();
- // Batch-load reactions
const msgIds = messages.map(m => m.id);
- const reactionsByMsg = {};
+ const reactionsByMsg: Record<number, ReactionRow[]> = {};
if (msgIds.length > 0) {
const allReactions = db.prepare(`
SELECT r.message_id, r.emoji, r.user_id, u.username
FROM collab_message_reactions r
JOIN users u ON r.user_id = u.id
WHERE r.message_id IN (${msgIds.map(() => '?').join(',')})
- `).all(...msgIds);
+ `).all(...msgIds) as (ReactionRow & { message_id: number })[];
for (const r of allReactions) {
if (!reactionsByMsg[r.message_id]) reactionsByMsg[r.message_id] = [];
reactionsByMsg[r.message_id].push(r);
@@ -369,11 +390,11 @@ router.get('/messages', authenticate, (req, res) => {
res.json({ messages: messages.map(m => formatMessage(m, groupReactions(reactionsByMsg[m.id] || []))) });
});
-// POST /messages
-router.post('/messages', authenticate, (req, res) => {
+router.post('/messages', authenticate, validateStringLengths({ text: 5000 }), (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
const { text, reply_to } = req.body;
- if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
if (!text || !text.trim()) return res.status(400).json({ error: 'Message text is required' });
if (reply_to) {
@@ -383,7 +404,7 @@ router.post('/messages', authenticate, (req, res) => {
const result = db.prepare(`
INSERT INTO collab_messages (trip_id, user_id, text, reply_to) VALUES (?, ?, ?, ?)
- `).run(tripId, req.user.id, text.trim(), reply_to || null);
+ `).run(tripId, authReq.user.id, text.trim(), reply_to || null);
const message = db.prepare(`
SELECT m.*, u.username, u.avatar,
@@ -393,71 +414,93 @@ router.post('/messages', authenticate, (req, res) => {
LEFT JOIN collab_messages rm ON m.reply_to = rm.id
LEFT JOIN users ru ON rm.user_id = ru.id
WHERE m.id = ?
- `).get(result.lastInsertRowid);
+ `).get(result.lastInsertRowid) as CollabMessage;
const formatted = formatMessage(message);
res.status(201).json({ message: formatted });
- broadcast(tripId, 'collab:message:created', { message: formatted }, req.headers['x-socket-id']);
+ broadcast(tripId, 'collab:message:created', { message: formatted }, req.headers['x-socket-id'] as string);
});
-// POST /messages/:id/react — toggle emoji reaction
-router.post('/messages/:id/react', authenticate, (req, res) => {
+router.post('/messages/:id/react', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
const { emoji } = req.body;
- if (!verifyTripAccess(Number(tripId), req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(Number(tripId), authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
if (!emoji) return res.status(400).json({ error: 'Emoji is required' });
const msg = db.prepare('SELECT id FROM collab_messages WHERE id = ? AND trip_id = ?').get(id, tripId);
if (!msg) return res.status(404).json({ error: 'Message not found' });
- const existing = db.prepare('SELECT id FROM collab_message_reactions WHERE message_id = ? AND user_id = ? AND emoji = ?').get(id, req.user.id, emoji);
+ const existing = db.prepare('SELECT id FROM collab_message_reactions WHERE message_id = ? AND user_id = ? AND emoji = ?').get(id, authReq.user.id, emoji) as { id: number } | undefined;
if (existing) {
db.prepare('DELETE FROM collab_message_reactions WHERE id = ?').run(existing.id);
} else {
- db.prepare('INSERT INTO collab_message_reactions (message_id, user_id, emoji) VALUES (?, ?, ?)').run(id, req.user.id, emoji);
+ db.prepare('INSERT INTO collab_message_reactions (message_id, user_id, emoji) VALUES (?, ?, ?)').run(id, authReq.user.id, emoji);
}
const reactions = groupReactions(loadReactions(id));
res.json({ reactions });
- broadcast(Number(tripId), 'collab:message:reacted', { messageId: Number(id), reactions }, req.headers['x-socket-id']);
+ broadcast(Number(tripId), 'collab:message:reacted', { messageId: Number(id), reactions }, req.headers['x-socket-id'] as string);
});
-// DELETE /messages/:id (soft-delete)
-router.delete('/messages/:id', authenticate, (req, res) => {
+router.delete('/messages/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
- if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyTripAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
- const message = db.prepare('SELECT * FROM collab_messages WHERE id = ? AND trip_id = ?').get(id, tripId);
+ const message = db.prepare('SELECT * FROM collab_messages WHERE id = ? AND trip_id = ?').get(id, tripId) as CollabMessage | undefined;
if (!message) return res.status(404).json({ error: 'Message not found' });
- if (Number(message.user_id) !== Number(req.user.id)) return res.status(403).json({ error: 'You can only delete your own messages' });
+ if (Number(message.user_id) !== Number(authReq.user.id)) return res.status(403).json({ error: 'You can only delete your own messages' });
db.prepare('UPDATE collab_messages SET deleted = 1 WHERE id = ?').run(id);
res.json({ success: true });
- broadcast(tripId, 'collab:message:deleted', { messageId: Number(id), username: message.username || req.user.username }, req.headers['x-socket-id']);
+ broadcast(tripId, 'collab:message:deleted', { messageId: Number(id), username: message.username || authReq.user.username }, req.headers['x-socket-id'] as string);
});
-// ─── LINK PREVIEW ────────────────────────────────────────────────────────────
-
-router.get('/link-preview', authenticate, (req, res) => {
- const { url } = req.query;
+router.get('/link-preview', authenticate, async (req: Request, res: Response) => {
+ const { url } = req.query as { url?: string };
if (!url) return res.status(400).json({ error: 'URL is required' });
try {
- const fetch = require('node-fetch');
+ const parsed = new URL(url);
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
+ return res.status(400).json({ error: 'Only HTTP(S) URLs are allowed' });
+ }
+ const hostname = parsed.hostname.toLowerCase();
+ if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' ||
+ hostname === '0.0.0.0' || hostname.endsWith('.local') || hostname.endsWith('.internal') ||
+ /^10\./.test(hostname) || /^172\.(1[6-9]|2\d|3[01])\./.test(hostname) || /^192\.168\./.test(hostname) ||
+ /^169\.254\./.test(hostname) || hostname === '[::1]' || hostname.startsWith('fc') || hostname.startsWith('fd') || hostname.startsWith('fe80')) {
+ return res.status(400).json({ error: 'Private/internal URLs are not allowed' });
+ }
+
+ const dns = require('dns').promises;
+ let resolved: { address: string };
+ try {
+ resolved = await dns.lookup(parsed.hostname);
+ } catch {
+ return res.status(400).json({ error: 'Could not resolve hostname' });
+ }
+ const ip = resolved.address;
+ if (/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|0\.|169\.254\.|::1|::ffff:(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.))/.test(ip)) {
+ return res.status(400).json({ error: 'Private/internal URLs are not allowed' });
+ }
+
+ const nodeFetch = require('node-fetch');
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
- fetch(url, {
+ nodeFetch(url, { redirect: 'error',
signal: controller.signal,
headers: { 'User-Agent': 'Mozilla/5.0 (compatible; NOMAD/1.0; +https://github.com/mauriceboe/NOMAD)' },
})
- .then(r => {
+ .then((r: { ok: boolean; text: () => Promise<string> }) => {
clearTimeout(timeout);
if (!r.ok) throw new Error('Fetch failed');
return r.text();
})
- .then(html => {
- const get = (prop) => {
+ .then((html: string) => {
+ const get = (prop: string) => {
const m = html.match(new RegExp(`<meta[^>]*property=["']og:${prop}["'][^>]*content=["']([^"']*)["']`, 'i'))
|| html.match(new RegExp(`<meta[^>]*content=["']([^"']*)["'][^>]*property=["']og:${prop}["']`, 'i'));
return m ? m[1] : null;
@@ -483,4 +526,4 @@ router.get('/link-preview', authenticate, (req, res) => {
}
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/dayNotes.js b/server/src/routes/dayNotes.ts
similarity index 55%
rename from server/src/routes/dayNotes.js
rename to server/src/routes/dayNotes.ts
index 0bee4a615..1605c8eb7 100644
--- a/server/src/routes/dayNotes.js
+++ b/server/src/routes/dayNotes.ts
@@ -1,18 +1,20 @@
-const express = require('express');
-const { db, canAccessTrip } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
-const { broadcast } = require('../websocket');
+import express, { Request, Response } from 'express';
+import { db, canAccessTrip } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { broadcast } from '../websocket';
+import { validateStringLengths } from '../middleware/validate';
+import { AuthRequest, DayNote } from '../types';
const router = express.Router({ mergeParams: true });
-function verifyAccess(tripId, userId) {
+function verifyAccess(tripId: string | number, userId: number) {
return canAccessTrip(tripId, userId);
}
-// GET /api/trips/:tripId/days/:dayId/notes
-router.get('/', authenticate, (req, res) => {
+router.get('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, dayId } = req.params;
- if (!verifyAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const notes = db.prepare(
'SELECT * FROM day_notes WHERE day_id = ? AND trip_id = ? ORDER BY sort_order ASC, created_at ASC'
@@ -21,10 +23,10 @@ router.get('/', authenticate, (req, res) => {
res.json({ notes });
});
-// POST /api/trips/:tripId/days/:dayId/notes
-router.post('/', authenticate, (req, res) => {
+router.post('/', authenticate, validateStringLengths({ text: 500, time: 150 }), (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, dayId } = req.params;
- if (!verifyAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const day = db.prepare('SELECT id FROM days WHERE id = ? AND trip_id = ?').get(dayId, tripId);
if (!day) return res.status(404).json({ error: 'Day not found' });
@@ -34,19 +36,19 @@ router.post('/', authenticate, (req, res) => {
const result = db.prepare(
'INSERT INTO day_notes (day_id, trip_id, text, time, icon, sort_order) VALUES (?, ?, ?, ?, ?, ?)'
- ).run(dayId, tripId, text.trim(), time || null, icon || '📝', sort_order ?? 9999);
+ ).run(dayId, tripId, text.trim(), time || null, icon || '\uD83D\uDCDD', sort_order ?? 9999);
const note = db.prepare('SELECT * FROM day_notes WHERE id = ?').get(result.lastInsertRowid);
res.status(201).json({ note });
- broadcast(tripId, 'dayNote:created', { dayId: Number(dayId), note }, req.headers['x-socket-id']);
+ broadcast(tripId, 'dayNote:created', { dayId: Number(dayId), note }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/days/:dayId/notes/:id
-router.put('/:id', authenticate, (req, res) => {
+router.put('/:id', authenticate, validateStringLengths({ text: 500, time: 150 }), (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, dayId, id } = req.params;
- if (!verifyAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
- const note = db.prepare('SELECT * FROM day_notes WHERE id = ? AND day_id = ? AND trip_id = ?').get(id, dayId, tripId);
+ const note = db.prepare('SELECT * FROM day_notes WHERE id = ? AND day_id = ? AND trip_id = ?').get(id, dayId, tripId) as DayNote | undefined;
if (!note) return res.status(404).json({ error: 'Note not found' });
const { text, time, icon, sort_order } = req.body;
@@ -62,20 +64,20 @@ router.put('/:id', authenticate, (req, res) => {
const updated = db.prepare('SELECT * FROM day_notes WHERE id = ?').get(id);
res.json({ note: updated });
- broadcast(tripId, 'dayNote:updated', { dayId: Number(dayId), note: updated }, req.headers['x-socket-id']);
+ broadcast(tripId, 'dayNote:updated', { dayId: Number(dayId), note: updated }, req.headers['x-socket-id'] as string);
});
-// DELETE /api/trips/:tripId/days/:dayId/notes/:id
-router.delete('/:id', authenticate, (req, res) => {
+router.delete('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, dayId, id } = req.params;
- if (!verifyAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });
+ if (!verifyAccess(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' });
const note = db.prepare('SELECT id FROM day_notes WHERE id = ? AND day_id = ? AND trip_id = ?').get(id, dayId, tripId);
if (!note) return res.status(404).json({ error: 'Note not found' });
db.prepare('DELETE FROM day_notes WHERE id = ?').run(id);
res.json({ success: true });
- broadcast(tripId, 'dayNote:deleted', { noteId: Number(id), dayId: Number(dayId) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'dayNote:deleted', { noteId: Number(id), dayId: Number(dayId) }, req.headers['x-socket-id'] as string);
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/days.js b/server/src/routes/days.ts
similarity index 59%
rename from server/src/routes/days.js
rename to server/src/routes/days.ts
index 58d2a269e..b739b395b 100644
--- a/server/src/routes/days.js
+++ b/server/src/routes/days.ts
@@ -1,15 +1,14 @@
-const express = require('express');
-const { db, canAccessTrip } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
-const { broadcast } = require('../websocket');
+import express, { Request, Response } from 'express';
+import { db } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { requireTripAccess } from '../middleware/tripAccess';
+import { broadcast } from '../websocket';
+import { loadTagsByPlaceIds, loadParticipantsByAssignmentIds, formatAssignmentWithPlace } from '../services/queryHelpers';
+import { AuthRequest, AssignmentRow, Day, DayNote } from '../types';
const router = express.Router({ mergeParams: true });
-function verifyTripOwnership(tripId, userId) {
- return canAccessTrip(tripId, userId);
-}
-
-function getAssignmentsForDay(dayId) {
+function getAssignmentsForDay(dayId: number | string) {
const assignments = db.prepare(`
SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description,
p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency,
@@ -23,7 +22,7 @@ function getAssignmentsForDay(dayId) {
LEFT JOIN categories c ON p.category_id = c.id
WHERE da.day_id = ?
ORDER BY da.order_index ASC, da.created_at ASC
- `).all(dayId);
+ `).all(dayId) as AssignmentRow[];
return assignments.map(a => {
const tags = db.prepare(`
@@ -69,16 +68,10 @@ function getAssignmentsForDay(dayId) {
});
}
-// GET /api/trips/:tripId/days
-router.get('/', authenticate, (req, res) => {
+router.get('/', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
- const days = db.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number ASC').all(tripId);
+ const days = db.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number ASC').all(tripId) as Day[];
if (days.length === 0) {
return res.json({ days: [] });
@@ -87,7 +80,6 @@ router.get('/', authenticate, (req, res) => {
const dayIds = days.map(d => d.id);
const dayPlaceholders = dayIds.map(() => '?').join(',');
- // Load ALL assignments for all days in one query
const allAssignments = db.prepare(`
SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description,
p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency,
@@ -101,82 +93,24 @@ router.get('/', authenticate, (req, res) => {
LEFT JOIN categories c ON p.category_id = c.id
WHERE da.day_id IN (${dayPlaceholders})
ORDER BY da.order_index ASC, da.created_at ASC
- `).all(...dayIds);
+ `).all(...dayIds) as AssignmentRow[];
- // Batch-load ALL tags for all places across all assignments
const placeIds = [...new Set(allAssignments.map(a => a.place_id))];
- const tagsByPlaceId = {};
- if (placeIds.length > 0) {
- const placePlaceholders = placeIds.map(() => '?').join(',');
- const allTags = db.prepare(`
- SELECT t.*, pt.place_id FROM tags t
- JOIN place_tags pt ON t.id = pt.tag_id
- WHERE pt.place_id IN (${placePlaceholders})
- `).all(...placeIds);
- for (const tag of allTags) {
- if (!tagsByPlaceId[tag.place_id]) tagsByPlaceId[tag.place_id] = [];
- tagsByPlaceId[tag.place_id].push({ id: tag.id, name: tag.name, color: tag.color, created_at: tag.created_at });
- }
- }
+ const tagsByPlaceId = loadTagsByPlaceIds(placeIds, { compact: true });
- // Group assignments by day_id
- const assignmentsByDayId = {};
- // Load all participants for all assignments
- const allAssignmentIds = allAssignments.map(a => a.id)
- const allParticipants = allAssignmentIds.length > 0
- ? db.prepare(`SELECT ap.assignment_id, ap.user_id, u.username, u.avatar FROM assignment_participants ap JOIN users u ON ap.user_id = u.id WHERE ap.assignment_id IN (${allAssignmentIds.map(() => '?').join(',')})`)
- .all(...allAssignmentIds)
- : []
- const participantsByAssignment = {}
- for (const p of allParticipants) {
- if (!participantsByAssignment[p.assignment_id]) participantsByAssignment[p.assignment_id] = []
- participantsByAssignment[p.assignment_id].push({ user_id: p.user_id, username: p.username, avatar: p.avatar })
- }
+ const allAssignmentIds = allAssignments.map(a => a.id);
+ const participantsByAssignment = loadParticipantsByAssignmentIds(allAssignmentIds);
+ const assignmentsByDayId: Record<number, ReturnType<typeof formatAssignmentWithPlace>[]> = {};
for (const a of allAssignments) {
if (!assignmentsByDayId[a.day_id]) assignmentsByDayId[a.day_id] = [];
- assignmentsByDayId[a.day_id].push({
- id: a.id,
- day_id: a.day_id,
- order_index: a.order_index,
- notes: a.notes,
- participants: participantsByAssignment[a.id] || [],
- created_at: a.created_at,
- place: {
- id: a.place_id,
- name: a.place_name,
- description: a.place_description,
- lat: a.lat,
- lng: a.lng,
- address: a.address,
- category_id: a.category_id,
- price: a.price,
- currency: a.place_currency,
- place_time: a.place_time,
- end_time: a.end_time,
- duration_minutes: a.duration_minutes,
- notes: a.place_notes,
- image_url: a.image_url,
- transport_mode: a.transport_mode,
- google_place_id: a.google_place_id,
- website: a.website,
- phone: a.phone,
- category: a.category_id ? {
- id: a.category_id,
- name: a.category_name,
- color: a.category_color,
- icon: a.category_icon,
- } : null,
- tags: tagsByPlaceId[a.place_id] || [],
- }
- });
+ assignmentsByDayId[a.day_id].push(formatAssignmentWithPlace(a, tagsByPlaceId[a.place_id] || [], participantsByAssignment[a.id] || []));
}
- // Load ALL day_notes for all days in one query
const allNotes = db.prepare(
`SELECT * FROM day_notes WHERE day_id IN (${dayPlaceholders}) ORDER BY sort_order ASC, created_at ASC`
- ).all(...dayIds);
- const notesByDayId = {};
+ ).all(...dayIds) as DayNote[];
+ const notesByDayId: Record<number, DayNote[]> = {};
for (const note of allNotes) {
if (!notesByDayId[note.day_id]) notesByDayId[note.day_id] = [];
notesByDayId[note.day_id].push(note);
@@ -191,41 +125,28 @@ router.get('/', authenticate, (req, res) => {
res.json({ days: daysWithAssignments });
});
-// POST /api/trips/:tripId/days
-router.post('/', authenticate, (req, res) => {
+router.post('/', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId } = req.params;
-
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
const { date, notes } = req.body;
- const maxDay = db.prepare('SELECT MAX(day_number) as max FROM days WHERE trip_id = ?').get(tripId);
+ const maxDay = db.prepare('SELECT MAX(day_number) as max FROM days WHERE trip_id = ?').get(tripId) as { max: number | null };
const dayNumber = (maxDay.max || 0) + 1;
const result = db.prepare(
'INSERT INTO days (trip_id, day_number, date, notes) VALUES (?, ?, ?, ?)'
).run(tripId, dayNumber, date || null, notes || null);
- const day = db.prepare('SELECT * FROM days WHERE id = ?').get(result.lastInsertRowid);
+ const day = db.prepare('SELECT * FROM days WHERE id = ?').get(result.lastInsertRowid) as Day;
const dayResult = { ...day, assignments: [] };
res.status(201).json({ day: dayResult });
- broadcast(tripId, 'day:created', { day: dayResult }, req.headers['x-socket-id']);
+ broadcast(tripId, 'day:created', { day: dayResult }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/days/:id
-router.put('/:id', authenticate, (req, res) => {
+router.put('/:id', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
- const day = db.prepare('SELECT * FROM days WHERE id = ? AND trip_id = ?').get(id, tripId);
+ const day = db.prepare('SELECT * FROM days WHERE id = ? AND trip_id = ?').get(id, tripId) as Day | undefined;
if (!day) {
return res.status(404).json({ error: 'Day not found' });
}
@@ -233,21 +154,15 @@ router.put('/:id', authenticate, (req, res) => {
const { notes, title } = req.body;
db.prepare('UPDATE days SET notes = ?, title = ? WHERE id = ?').run(notes || null, title !== undefined ? title : day.title, id);
- const updatedDay = db.prepare('SELECT * FROM days WHERE id = ?').get(id);
+ const updatedDay = db.prepare('SELECT * FROM days WHERE id = ?').get(id) as Day;
const dayWithAssignments = { ...updatedDay, assignments: getAssignmentsForDay(id) };
res.json({ day: dayWithAssignments });
- broadcast(tripId, 'day:updated', { day: dayWithAssignments }, req.headers['x-socket-id']);
+ broadcast(tripId, 'day:updated', { day: dayWithAssignments }, req.headers['x-socket-id'] as string);
});
-// DELETE /api/trips/:tripId/days/:id
-router.delete('/:id', authenticate, (req, res) => {
+router.delete('/:id', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
const day = db.prepare('SELECT * FROM days WHERE id = ? AND trip_id = ?').get(id, tripId);
if (!day) {
return res.status(404).json({ error: 'Day not found' });
@@ -255,13 +170,12 @@ router.delete('/:id', authenticate, (req, res) => {
db.prepare('DELETE FROM days WHERE id = ?').run(id);
res.json({ success: true });
- broadcast(tripId, 'day:deleted', { dayId: Number(id) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'day:deleted', { dayId: Number(id) }, req.headers['x-socket-id'] as string);
});
-// === Accommodation routes ===
const accommodationsRouter = express.Router({ mergeParams: true });
-function getAccommodationWithPlace(id) {
+function getAccommodationWithPlace(id: number | bigint) {
return db.prepare(`
SELECT a.*, p.name as place_name, p.address as place_address, p.image_url as place_image, p.lat as place_lat, p.lng as place_lng
FROM day_accommodations a
@@ -270,15 +184,9 @@ function getAccommodationWithPlace(id) {
`).get(id);
}
-// GET /api/trips/:tripId/accommodations
-accommodationsRouter.get('/', authenticate, (req, res) => {
+accommodationsRouter.get('/', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
const accommodations = db.prepare(`
SELECT a.*, p.name as place_name, p.address as place_address, p.image_url as place_image, p.lat as place_lat, p.lng as place_lng
FROM day_accommodations a
@@ -290,15 +198,8 @@ accommodationsRouter.get('/', authenticate, (req, res) => {
res.json({ accommodations });
});
-// POST /api/trips/:tripId/accommodations
-accommodationsRouter.post('/', authenticate, (req, res) => {
+accommodationsRouter.post('/', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId } = req.params;
-
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
const { place_id, start_day_id, end_day_id, check_in, check_out, confirmation, notes } = req.body;
if (!place_id || !start_day_id || !end_day_id) {
@@ -306,19 +207,13 @@ accommodationsRouter.post('/', authenticate, (req, res) => {
}
const place = db.prepare('SELECT id FROM places WHERE id = ? AND trip_id = ?').get(place_id, tripId);
- if (!place) {
- return res.status(404).json({ error: 'Place not found' });
- }
+ if (!place) return res.status(404).json({ error: 'Place not found' });
const startDay = db.prepare('SELECT id FROM days WHERE id = ? AND trip_id = ?').get(start_day_id, tripId);
- if (!startDay) {
- return res.status(404).json({ error: 'Start day not found' });
- }
+ if (!startDay) return res.status(404).json({ error: 'Start day not found' });
const endDay = db.prepare('SELECT id FROM days WHERE id = ? AND trip_id = ?').get(end_day_id, tripId);
- if (!endDay) {
- return res.status(404).json({ error: 'End day not found' });
- }
+ if (!endDay) return res.status(404).json({ error: 'End day not found' });
const result = db.prepare(
'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_out, confirmation, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
@@ -326,22 +221,15 @@ accommodationsRouter.post('/', authenticate, (req, res) => {
const accommodation = getAccommodationWithPlace(result.lastInsertRowid);
res.status(201).json({ accommodation });
- broadcast(tripId, 'accommodation:created', { accommodation }, req.headers['x-socket-id']);
+ broadcast(tripId, 'accommodation:created', { accommodation }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/accommodations/:id
-accommodationsRouter.put('/:id', authenticate, (req, res) => {
+accommodationsRouter.put('/:id', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
- const existing = db.prepare('SELECT * FROM day_accommodations WHERE id = ? AND trip_id = ?').get(id, tripId);
- if (!existing) {
- return res.status(404).json({ error: 'Accommodation not found' });
- }
+ interface DayAccommodation { id: number; trip_id: number; place_id: number; start_day_id: number; end_day_id: number; check_in: string | null; check_out: string | null; confirmation: string | null; notes: string | null; }
+ const existing = db.prepare('SELECT * FROM day_accommodations WHERE id = ? AND trip_id = ?').get(id, tripId) as DayAccommodation | undefined;
+ if (!existing) return res.status(404).json({ error: 'Accommodation not found' });
const { place_id, start_day_id, end_day_id, check_in, check_out, confirmation, notes } = req.body;
@@ -355,52 +243,38 @@ accommodationsRouter.put('/:id', authenticate, (req, res) => {
if (place_id !== undefined) {
const place = db.prepare('SELECT id FROM places WHERE id = ? AND trip_id = ?').get(place_id, tripId);
- if (!place) {
- return res.status(404).json({ error: 'Place not found' });
- }
+ if (!place) return res.status(404).json({ error: 'Place not found' });
}
if (start_day_id !== undefined) {
const startDay = db.prepare('SELECT id FROM days WHERE id = ? AND trip_id = ?').get(start_day_id, tripId);
- if (!startDay) {
- return res.status(404).json({ error: 'Start day not found' });
- }
+ if (!startDay) return res.status(404).json({ error: 'Start day not found' });
}
if (end_day_id !== undefined) {
const endDay = db.prepare('SELECT id FROM days WHERE id = ? AND trip_id = ?').get(end_day_id, tripId);
- if (!endDay) {
- return res.status(404).json({ error: 'End day not found' });
- }
+ if (!endDay) return res.status(404).json({ error: 'End day not found' });
}
db.prepare(
'UPDATE day_accommodations SET place_id = ?, start_day_id = ?, end_day_id = ?, check_in = ?, check_out = ?, confirmation = ?, notes = ? WHERE id = ?'
).run(newPlaceId, newStartDayId, newEndDayId, newCheckIn, newCheckOut, newConfirmation, newNotes, id);
- const accommodation = getAccommodationWithPlace(id);
+ const accommodation = getAccommodationWithPlace(Number(id));
res.json({ accommodation });
- broadcast(tripId, 'accommodation:updated', { accommodation }, req.headers['x-socket-id']);
+ broadcast(tripId, 'accommodation:updated', { accommodation }, req.headers['x-socket-id'] as string);
});
-// DELETE /api/trips/:tripId/accommodations/:id
-accommodationsRouter.delete('/:id', authenticate, (req, res) => {
+accommodationsRouter.delete('/:id', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
const existing = db.prepare('SELECT * FROM day_accommodations WHERE id = ? AND trip_id = ?').get(id, tripId);
- if (!existing) {
- return res.status(404).json({ error: 'Accommodation not found' });
- }
+ if (!existing) return res.status(404).json({ error: 'Accommodation not found' });
db.prepare('DELETE FROM day_accommodations WHERE id = ?').run(id);
res.json({ success: true });
- broadcast(tripId, 'accommodation:deleted', { accommodationId: Number(id) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'accommodation:deleted', { accommodationId: Number(id) }, req.headers['x-socket-id'] as string);
});
-module.exports = router;
-module.exports.accommodationsRouter = accommodationsRouter;
+export default router;
+export { accommodationsRouter };
diff --git a/server/src/routes/files.js b/server/src/routes/files.ts
similarity index 69%
rename from server/src/routes/files.js
rename to server/src/routes/files.ts
index 3df2c8d8d..aac21dc2b 100644
--- a/server/src/routes/files.js
+++ b/server/src/routes/files.ts
@@ -1,22 +1,25 @@
-const express = require('express');
-const multer = require('multer');
-const path = require('path');
-const fs = require('fs');
-const { v4: uuidv4 } = require('uuid');
-const { db, canAccessTrip } = require('../db/database');
-const { authenticate, demoUploadBlock } = require('../middleware/auth');
-const { broadcast } = require('../websocket');
+import express, { Request, Response } from 'express';
+import multer from 'multer';
+import path from 'path';
+import fs from 'fs';
+import { v4 as uuidv4 } from 'uuid';
+import { db, canAccessTrip } from '../db/database';
+import { authenticate, demoUploadBlock } from '../middleware/auth';
+import { requireTripAccess } from '../middleware/tripAccess';
+import { broadcast } from '../websocket';
+import { AuthRequest, TripFile } from '../types';
const router = express.Router({ mergeParams: true });
+const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
const filesDir = path.join(__dirname, '../../uploads/files');
const storage = multer.diskStorage({
- destination: (req, file, cb) => {
+ destination: (_req, _file, cb) => {
if (!fs.existsSync(filesDir)) fs.mkdirSync(filesDir, { recursive: true });
cb(null, filesDir);
},
- filename: (req, file, cb) => {
+ filename: (_req, file, cb) => {
const ext = path.extname(file.originalname);
cb(null, `${uuidv4()}${ext}`);
},
@@ -25,17 +28,17 @@ const storage = multer.diskStorage({
const DEFAULT_ALLOWED_EXTENSIONS = 'jpg,jpeg,png,gif,webp,heic,pdf,doc,docx,xls,xlsx,txt,csv';
const BLOCKED_EXTENSIONS = ['.svg', '.html', '.htm', '.xml'];
-function getAllowedExtensions() {
+function getAllowedExtensions(): string {
try {
- const row = db.prepare("SELECT value FROM app_settings WHERE key = 'allowed_file_types'").get();
+ const row = db.prepare("SELECT value FROM app_settings WHERE key = 'allowed_file_types'").get() as { value: string } | undefined;
return row?.value || DEFAULT_ALLOWED_EXTENSIONS;
} catch { return DEFAULT_ALLOWED_EXTENSIONS; }
}
const upload = multer({
storage,
- limits: { fileSize: 50 * 1024 * 1024 }, // 50MB
- fileFilter: (req, file, cb) => {
+ limits: { fileSize: MAX_FILE_SIZE },
+ fileFilter: (_req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase();
if (BLOCKED_EXTENSIONS.includes(ext) || file.mimetype.includes('svg')) {
return cb(new Error('File type not allowed'));
@@ -50,22 +53,22 @@ const upload = multer({
},
});
-function verifyTripOwnership(tripId, userId) {
+function verifyTripOwnership(tripId: string | number, userId: number) {
return canAccessTrip(tripId, userId);
}
-function formatFile(file) {
+function formatFile(file: TripFile) {
return {
...file,
url: file.filename?.startsWith('files/') ? `/uploads/${file.filename}` : `/uploads/files/${file.filename}`,
};
}
-// GET /api/trips/:tripId/files
-router.get('/', authenticate, (req, res) => {
+router.get('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
const files = db.prepare(`
@@ -74,21 +77,14 @@ router.get('/', authenticate, (req, res) => {
LEFT JOIN reservations r ON f.reservation_id = r.id
WHERE f.trip_id = ?
ORDER BY f.created_at DESC
- `).all(tripId);
+ `).all(tripId) as TripFile[];
res.json({ files: files.map(formatFile) });
});
-// POST /api/trips/:tripId/files
-router.post('/', authenticate, demoUploadBlock, upload.single('file'), (req, res) => {
+router.post('/', authenticate, requireTripAccess, demoUploadBlock, upload.single('file'), (req: Request, res: Response) => {
const { tripId } = req.params;
const { place_id, description, reservation_id } = req.body;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- if (req.file) fs.unlinkSync(req.file.path);
- return res.status(404).json({ error: 'Trip not found' });
- }
-
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
@@ -112,20 +108,20 @@ router.post('/', authenticate, demoUploadBlock, upload.single('file'), (req, res
FROM trip_files f
LEFT JOIN reservations r ON f.reservation_id = r.id
WHERE f.id = ?
- `).get(result.lastInsertRowid);
+ `).get(result.lastInsertRowid) as TripFile;
res.status(201).json({ file: formatFile(file) });
- broadcast(tripId, 'file:created', { file: formatFile(file) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'file:created', { file: formatFile(file) }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/files/:id
-router.put('/:id', authenticate, (req, res) => {
+router.put('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
const { description, place_id, reservation_id } = req.body;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
- const file = db.prepare('SELECT * FROM trip_files WHERE id = ? AND trip_id = ?').get(id, tripId);
+ const file = db.prepare('SELECT * FROM trip_files WHERE id = ? AND trip_id = ?').get(id, tripId) as TripFile | undefined;
if (!file) return res.status(404).json({ error: 'File not found' });
db.prepare(`
@@ -146,19 +142,19 @@ router.put('/:id', authenticate, (req, res) => {
FROM trip_files f
LEFT JOIN reservations r ON f.reservation_id = r.id
WHERE f.id = ?
- `).get(id);
+ `).get(id) as TripFile;
res.json({ file: formatFile(updated) });
- broadcast(tripId, 'file:updated', { file: formatFile(updated) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'file:updated', { file: formatFile(updated) }, req.headers['x-socket-id'] as string);
});
-// DELETE /api/trips/:tripId/files/:id
-router.delete('/:id', authenticate, (req, res) => {
+router.delete('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
- const file = db.prepare('SELECT * FROM trip_files WHERE id = ? AND trip_id = ?').get(id, tripId);
+ const file = db.prepare('SELECT * FROM trip_files WHERE id = ? AND trip_id = ?').get(id, tripId) as TripFile | undefined;
if (!file) return res.status(404).json({ error: 'File not found' });
const filePath = path.join(filesDir, file.filename);
@@ -168,7 +164,7 @@ router.delete('/:id', authenticate, (req, res) => {
db.prepare('DELETE FROM trip_files WHERE id = ?').run(id);
res.json({ success: true });
- broadcast(tripId, 'file:deleted', { fileId: Number(id) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'file:deleted', { fileId: Number(id) }, req.headers['x-socket-id'] as string);
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/maps.js b/server/src/routes/maps.ts
similarity index 64%
rename from server/src/routes/maps.js
rename to server/src/routes/maps.ts
index 4477fd1f2..0cd18e921 100644
--- a/server/src/routes/maps.js
+++ b/server/src/routes/maps.ts
@@ -1,24 +1,66 @@
-const express = require('express');
-const fetch = require('node-fetch');
-const { db } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
+import express, { Request, Response } from 'express';
+import fetch from 'node-fetch';
+import { db } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { AuthRequest } from '../types';
+
+interface NominatimResult {
+ osm_type: string;
+ osm_id: string;
+ name?: string;
+ display_name?: string;
+ lat: string;
+ lon: string;
+}
+
+interface GooglePlaceResult {
+ id: string;
+ displayName?: { text: string };
+ formattedAddress?: string;
+ location?: { latitude: number; longitude: number };
+ rating?: number;
+ websiteUri?: string;
+ nationalPhoneNumber?: string;
+ types?: string[];
+}
+
+interface GooglePlaceDetails extends GooglePlaceResult {
+ userRatingCount?: number;
+ regularOpeningHours?: { weekdayDescriptions?: string[]; openNow?: boolean };
+ googleMapsUri?: string;
+ editorialSummary?: { text: string };
+ reviews?: { authorAttribution?: { displayName?: string; photoUri?: string }; rating?: number; text?: { text?: string }; relativePublishTimeDescription?: string }[];
+ photos?: { name: string; authorAttributions?: { displayName?: string }[] }[];
+}
const router = express.Router();
-// Get API key: user's own key, or fall back to any admin's key
-function getMapsKey(userId) {
- const user = db.prepare('SELECT maps_api_key FROM users WHERE id = ?').get(userId);
+function getMapsKey(userId: number): string | null {
+ const user = db.prepare('SELECT maps_api_key FROM users WHERE id = ?').get(userId) as { maps_api_key: string | null } | undefined;
if (user?.maps_api_key) return user.maps_api_key;
- const admin = db.prepare("SELECT maps_api_key FROM users WHERE role = 'admin' AND maps_api_key IS NOT NULL AND maps_api_key != '' LIMIT 1").get();
+ const admin = db.prepare("SELECT maps_api_key FROM users WHERE role = 'admin' AND maps_api_key IS NOT NULL AND maps_api_key != '' LIMIT 1").get() as { maps_api_key: string } | undefined;
return admin?.maps_api_key || null;
}
-// In-memory photo cache: placeId → { photoUrl, attribution, fetchedAt }
-const photoCache = new Map();
+const photoCache = new Map<string, { photoUrl: string; attribution: string | null; fetchedAt: number }>();
const PHOTO_TTL = 12 * 60 * 60 * 1000; // 12 hours
+const CACHE_MAX_ENTRIES = 1000;
+const CACHE_PRUNE_TARGET = 500;
+const CACHE_CLEANUP_INTERVAL = 5 * 60 * 1000; // 5 minutes
+
+setInterval(() => {
+ const now = Date.now();
+ for (const [key, entry] of photoCache) {
+ if (now - entry.fetchedAt > PHOTO_TTL) photoCache.delete(key);
+ }
+ if (photoCache.size > CACHE_MAX_ENTRIES) {
+ const entries = [...photoCache.entries()].sort((a, b) => a[1].fetchedAt - b[1].fetchedAt);
+ const toDelete = entries.slice(0, entries.length - CACHE_PRUNE_TARGET);
+ toDelete.forEach(([key]) => photoCache.delete(key));
+ }
+}, CACHE_CLEANUP_INTERVAL);
-// Nominatim search (OpenStreetMap) — free fallback when no Google API key
-async function searchNominatim(query, lang) {
+async function searchNominatim(query: string, lang?: string) {
const params = new URLSearchParams({
q: query,
format: 'json',
@@ -30,7 +72,7 @@ async function searchNominatim(query, lang) {
headers: { 'User-Agent': 'NOMAD Travel Planner (https://github.com/mauriceboe/NOMAD)' },
});
if (!response.ok) throw new Error('Nominatim API error');
- const data = await response.json();
+ const data = await response.json() as NominatimResult[];
return data.map(item => ({
google_place_id: null,
osm_id: `${item.osm_type}/${item.osm_id}`,
@@ -45,20 +87,19 @@ async function searchNominatim(query, lang) {
}));
}
-// POST /api/maps/search
-router.post('/search', authenticate, async (req, res) => {
+router.post('/search', authenticate, async (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { query } = req.body;
if (!query) return res.status(400).json({ error: 'Search query is required' });
- const apiKey = getMapsKey(req.user.id);
+ const apiKey = getMapsKey(authReq.user.id);
- // No Google API key → use Nominatim (OpenStreetMap)
if (!apiKey) {
try {
- const places = await searchNominatim(query, req.query.lang);
+ const places = await searchNominatim(query, req.query.lang as string);
return res.json({ places, source: 'openstreetmap' });
- } catch (err) {
+ } catch (err: unknown) {
console.error('Nominatim search error:', err);
return res.status(500).json({ error: 'OpenStreetMap search error' });
}
@@ -72,16 +113,16 @@ router.post('/search', authenticate, async (req, res) => {
'X-Goog-Api-Key': apiKey,
'X-Goog-FieldMask': 'places.id,places.displayName,places.formattedAddress,places.location,places.rating,places.websiteUri,places.nationalPhoneNumber,places.types',
},
- body: JSON.stringify({ textQuery: query, languageCode: req.query.lang || 'en' }),
+ body: JSON.stringify({ textQuery: query, languageCode: (req.query.lang as string) || 'en' }),
});
- const data = await response.json();
+ const data = await response.json() as { places?: GooglePlaceResult[]; error?: { message?: string } };
if (!response.ok) {
return res.status(response.status).json({ error: data.error?.message || 'Google Places API error' });
}
- const places = (data.places || []).map(p => ({
+ const places = (data.places || []).map((p: GooglePlaceResult) => ({
google_place_id: p.id,
name: p.displayName?.text || '',
address: p.formattedAddress || '',
@@ -94,23 +135,23 @@ router.post('/search', authenticate, async (req, res) => {
}));
res.json({ places, source: 'google' });
- } catch (err) {
+ } catch (err: unknown) {
console.error('Maps search error:', err);
res.status(500).json({ error: 'Google Places search error' });
}
});
-// GET /api/maps/details/:placeId
-router.get('/details/:placeId', authenticate, async (req, res) => {
+router.get('/details/:placeId', authenticate, async (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { placeId } = req.params;
- const apiKey = getMapsKey(req.user.id);
+ const apiKey = getMapsKey(authReq.user.id);
if (!apiKey) {
return res.status(400).json({ error: 'Google Maps API key not configured' });
}
try {
- const lang = req.query.lang || 'de'
+ const lang = (req.query.lang as string) || 'de';
const response = await fetch(`https://places.googleapis.com/v1/places/${placeId}?languageCode=${lang}`, {
method: 'GET',
headers: {
@@ -119,7 +160,7 @@ router.get('/details/:placeId', authenticate, async (req, res) => {
},
});
- const data = await response.json();
+ const data = await response.json() as GooglePlaceDetails & { error?: { message?: string } };
if (!response.ok) {
return res.status(response.status).json({ error: data.error?.message || 'Google Places API error' });
@@ -139,7 +180,7 @@ router.get('/details/:placeId', authenticate, async (req, res) => {
open_now: data.regularOpeningHours?.openNow ?? null,
google_maps_url: data.googleMapsUri || null,
summary: data.editorialSummary?.text || null,
- reviews: (data.reviews || []).slice(0, 5).map(r => ({
+ reviews: (data.reviews || []).slice(0, 5).map((r: NonNullable<GooglePlaceDetails['reviews']>[number]) => ({
author: r.authorAttribution?.displayName || null,
rating: r.rating || null,
text: r.text?.text || null,
@@ -149,37 +190,34 @@ router.get('/details/:placeId', authenticate, async (req, res) => {
};
res.json({ place });
- } catch (err) {
+ } catch (err: unknown) {
console.error('Maps details error:', err);
res.status(500).json({ error: 'Error fetching place details' });
}
});
-// GET /api/maps/place-photo/:placeId
-// Proxies a Google Places photo (hides API key from client). Returns { photoUrl, attribution }.
-router.get('/place-photo/:placeId', authenticate, async (req, res) => {
+router.get('/place-photo/:placeId', authenticate, async (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { placeId } = req.params;
- // Check TTL cache
const cached = photoCache.get(placeId);
if (cached && Date.now() - cached.fetchedAt < PHOTO_TTL) {
return res.json({ photoUrl: cached.photoUrl, attribution: cached.attribution });
}
- const apiKey = getMapsKey(req.user.id);
+ const apiKey = getMapsKey(authReq.user.id);
if (!apiKey) {
return res.status(400).json({ error: 'Google Maps API key not configured' });
}
try {
- // Fetch place details to get photo reference
const detailsRes = await fetch(`https://places.googleapis.com/v1/places/${placeId}`, {
headers: {
'X-Goog-Api-Key': apiKey,
'X-Goog-FieldMask': 'photos',
},
});
- const details = await detailsRes.json();
+ const details = await detailsRes.json() as GooglePlaceDetails & { error?: { message?: string } };
if (!detailsRes.ok) {
console.error('Google Places photo details error:', details.error?.message || detailsRes.status);
@@ -194,11 +232,10 @@ router.get('/place-photo/:placeId', authenticate, async (req, res) => {
const photoName = photo.name;
const attribution = photo.authorAttributions?.[0]?.displayName || null;
- // Fetch the media URL (skipHttpRedirect returns JSON with photoUri)
const mediaRes = await fetch(
`https://places.googleapis.com/v1/${photoName}/media?maxHeightPx=600&key=${apiKey}&skipHttpRedirect=true`
);
- const mediaData = await mediaRes.json();
+ const mediaData = await mediaRes.json() as { photoUri?: string };
const photoUrl = mediaData.photoUri;
if (!photoUrl) {
@@ -207,8 +244,6 @@ router.get('/place-photo/:placeId', authenticate, async (req, res) => {
photoCache.set(placeId, { photoUrl, attribution, fetchedAt: Date.now() });
- // Persist the photo URL to all places with this google_place_id so future
- // loads serve image_url directly without hitting the Google API again.
try {
db.prepare(
'UPDATE places SET image_url = ?, updated_at = CURRENT_TIMESTAMP WHERE google_place_id = ? AND (image_url IS NULL OR image_url = ?)'
@@ -218,10 +253,10 @@ router.get('/place-photo/:placeId', authenticate, async (req, res) => {
}
res.json({ photoUrl, attribution });
- } catch (err) {
+ } catch (err: unknown) {
console.error('Place photo error:', err);
res.status(500).json({ error: 'Error fetching photo' });
}
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/oidc.js b/server/src/routes/oidc.ts
similarity index 58%
rename from server/src/routes/oidc.js
rename to server/src/routes/oidc.ts
index e9ad34085..405ea8adf 100644
--- a/server/src/routes/oidc.js
+++ b/server/src/routes/oidc.ts
@@ -1,27 +1,57 @@
-const express = require('express');
-const crypto = require('crypto');
-const fetch = require('node-fetch');
-const jwt = require('jsonwebtoken');
-const { db } = require('../db/database');
-const { JWT_SECRET } = require('../config');
+import express, { Request, Response } from 'express';
+import crypto from 'crypto';
+import fetch from 'node-fetch';
+import jwt from 'jsonwebtoken';
+import { db } from '../db/database';
+import { JWT_SECRET } from '../config';
+import { User } from '../types';
+
+interface OidcDiscoveryDoc {
+ authorization_endpoint: string;
+ token_endpoint: string;
+ userinfo_endpoint: string;
+ _issuer?: string;
+}
+
+interface OidcTokenResponse {
+ access_token?: string;
+ id_token?: string;
+ token_type?: string;
+}
+
+interface OidcUserInfo {
+ sub: string;
+ email?: string;
+ name?: string;
+ preferred_username?: string;
+}
const router = express.Router();
-// In-memory state store for CSRF protection (state → { createdAt, redirectUri })
-const pendingStates = new Map();
-const STATE_TTL = 5 * 60 * 1000; // 5 minutes
+const AUTH_CODE_TTL = 60000; // 1 minute
+const AUTH_CODE_CLEANUP = 30000; // 30 seconds
+const STATE_TTL = 5 * 60 * 1000; // 5 minutes
+const STATE_CLEANUP = 60 * 1000; // 1 minute
+
+const authCodes = new Map<string, { token: string; created: number }>();
+setInterval(() => {
+ const now = Date.now();
+ for (const [code, entry] of authCodes) {
+ if (now - entry.created > AUTH_CODE_TTL) authCodes.delete(code);
+ }
+}, AUTH_CODE_CLEANUP);
+
+const pendingStates = new Map<string, { createdAt: number; redirectUri: string }>();
-// Cleanup expired states periodically
setInterval(() => {
const now = Date.now();
for (const [state, data] of pendingStates) {
if (now - data.createdAt > STATE_TTL) pendingStates.delete(state);
}
-}, 60 * 1000);
+}, STATE_CLEANUP);
-// Read OIDC config from app_settings
function getOidcConfig() {
- const get = (key) => db.prepare("SELECT value FROM app_settings WHERE key = ?").get(key)?.value || null;
+ const get = (key: string) => (db.prepare("SELECT value FROM app_settings WHERE key = ?").get(key) as { value: string } | undefined)?.value || null;
const issuer = get('oidc_issuer');
const clientId = get('oidc_client_id');
const clientSecret = get('oidc_client_secret');
@@ -30,25 +60,24 @@ function getOidcConfig() {
return { issuer: issuer.replace(/\/+$/, ''), clientId, clientSecret, displayName };
}
-// Cache discovery document
-let discoveryCache = null;
+let discoveryCache: OidcDiscoveryDoc | null = null;
let discoveryCacheTime = 0;
const DISCOVERY_TTL = 60 * 60 * 1000; // 1 hour
-async function discover(issuer) {
+async function discover(issuer: string) {
if (discoveryCache && Date.now() - discoveryCacheTime < DISCOVERY_TTL && discoveryCache._issuer === issuer) {
return discoveryCache;
}
const res = await fetch(`${issuer}/.well-known/openid-configuration`);
if (!res.ok) throw new Error('Failed to fetch OIDC discovery document');
- const doc = await res.json();
+ const doc = await res.json() as OidcDiscoveryDoc;
doc._issuer = issuer;
discoveryCache = doc;
discoveryCacheTime = Date.now();
return doc;
}
-function generateToken(user) {
+function generateToken(user: { id: number; username: string; email: string; role: string }) {
return jwt.sign(
{ id: user.id, username: user.username, email: user.email, role: user.role },
JWT_SECRET,
@@ -56,21 +85,24 @@ function generateToken(user) {
);
}
-function frontendUrl(path) {
+function frontendUrl(path: string): string {
const base = process.env.NODE_ENV === 'production' ? '' : 'http://localhost:5173';
return base + path;
}
-// GET /api/auth/oidc/login — redirect to OIDC provider
-router.get('/login', async (req, res) => {
+router.get('/login', async (req: Request, res: Response) => {
const config = getOidcConfig();
if (!config) return res.status(400).json({ error: 'OIDC not configured' });
+ if (config.issuer && !config.issuer.startsWith('https://') && process.env.NODE_ENV === 'production') {
+ return res.status(400).json({ error: 'OIDC issuer must use HTTPS in production' });
+ }
+
try {
const doc = await discover(config.issuer);
const state = crypto.randomBytes(32).toString('hex');
- const proto = req.headers['x-forwarded-proto'] || req.protocol;
- const host = req.headers['x-forwarded-host'] || req.headers.host;
+ const proto = (req.headers['x-forwarded-proto'] as string) || req.protocol;
+ const host = (req.headers['x-forwarded-host'] as string) || req.headers.host;
const redirectUri = `${proto}://${host}/api/auth/oidc/callback`;
pendingStates.set(state, { createdAt: Date.now(), redirectUri });
@@ -84,15 +116,14 @@ router.get('/login', async (req, res) => {
});
res.redirect(`${doc.authorization_endpoint}?${params}`);
- } catch (err) {
- console.error('[OIDC] Login error:', err.message);
+ } catch (err: unknown) {
+ console.error('[OIDC] Login error:', err instanceof Error ? err.message : err);
res.status(500).json({ error: 'OIDC login failed' });
}
});
-// GET /api/auth/oidc/callback — handle provider callback
-router.get('/callback', async (req, res) => {
- const { code, state, error: oidcError } = req.query;
+router.get('/callback', async (req: Request, res: Response) => {
+ const { code, state, error: oidcError } = req.query as { code?: string; state?: string; error?: string };
if (oidcError) {
console.error('[OIDC] Provider error:', oidcError);
@@ -112,10 +143,13 @@ router.get('/callback', async (req, res) => {
const config = getOidcConfig();
if (!config) return res.redirect(frontendUrl('/login?oidc_error=not_configured'));
+ if (config.issuer && !config.issuer.startsWith('https://') && process.env.NODE_ENV === 'production') {
+ return res.redirect(frontendUrl('/login?oidc_error=issuer_not_https'));
+ }
+
try {
const doc = await discover(config.issuer);
- // Exchange code for tokens
const tokenRes = await fetch(doc.token_endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
@@ -128,17 +162,16 @@ router.get('/callback', async (req, res) => {
}),
});
- const tokenData = await tokenRes.json();
+ const tokenData = await tokenRes.json() as OidcTokenResponse;
if (!tokenRes.ok || !tokenData.access_token) {
console.error('[OIDC] Token exchange failed:', tokenData);
return res.redirect(frontendUrl('/login?oidc_error=token_failed'));
}
- // Get user info
const userInfoRes = await fetch(doc.userinfo_endpoint, {
headers: { Authorization: `Bearer ${tokenData.access_token}` },
});
- const userInfo = await userInfoRes.json();
+ const userInfo = await userInfoRes.json() as OidcUserInfo;
if (!userInfo.email) {
return res.redirect(frontendUrl('/login?oidc_error=no_email'));
@@ -148,37 +181,31 @@ router.get('/callback', async (req, res) => {
const name = userInfo.name || userInfo.preferred_username || email.split('@')[0];
const sub = userInfo.sub;
- // Find existing user by OIDC sub or email
- let user = db.prepare('SELECT * FROM users WHERE oidc_sub = ? AND oidc_issuer = ?').get(sub, config.issuer);
+ let user = db.prepare('SELECT * FROM users WHERE oidc_sub = ? AND oidc_issuer = ?').get(sub, config.issuer) as User | undefined;
if (!user) {
- user = db.prepare('SELECT * FROM users WHERE LOWER(email) = ?').get(email);
+ user = db.prepare('SELECT * FROM users WHERE LOWER(email) = ?').get(email) as User | undefined;
}
if (user) {
- // Existing user — link OIDC if not already linked
if (!user.oidc_sub) {
db.prepare('UPDATE users SET oidc_sub = ?, oidc_issuer = ? WHERE id = ?').run(sub, config.issuer, user.id);
}
} else {
- // New user — check if registration is allowed
- const userCount = db.prepare('SELECT COUNT(*) as count FROM users').get().count;
+ const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
const isFirstUser = userCount === 0;
if (!isFirstUser) {
- const setting = db.prepare("SELECT value FROM app_settings WHERE key = 'allow_registration'").get();
+ const setting = db.prepare("SELECT value FROM app_settings WHERE key = 'allow_registration'").get() as { value: string } | undefined;
if (setting?.value === 'false') {
return res.redirect(frontendUrl('/login?oidc_error=registration_disabled'));
}
}
- // Create user (first user = admin)
const role = isFirstUser ? 'admin' : 'user';
- // Generate a random password hash (user won't use password login)
const randomPass = crypto.randomBytes(32).toString('hex');
const bcrypt = require('bcryptjs');
const hash = bcrypt.hashSync(randomPass, 10);
- // Ensure unique username
let username = name.replace(/[^a-zA-Z0-9_-]/g, '').substring(0, 30) || 'user';
const existing = db.prepare('SELECT id FROM users WHERE LOWER(username) = LOWER(?)').get(username);
if (existing) username = `${username}_${Date.now() % 10000}`;
@@ -187,20 +214,30 @@ router.get('/callback', async (req, res) => {
'INSERT INTO users (username, email, password_hash, role, oidc_sub, oidc_issuer) VALUES (?, ?, ?, ?, ?, ?)'
).run(username, email, hash, role, sub, config.issuer);
- user = { id: Number(result.lastInsertRowid), username, email, role };
+ user = { id: Number(result.lastInsertRowid), username, email, role } as User;
}
- // Update last login
db.prepare('UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?').run(user.id);
- // Generate JWT and redirect to frontend
const token = generateToken(user);
- // In dev mode, frontend runs on a different port
- res.redirect(frontendUrl(`/login#token=${token}`));
- } catch (err) {
+ const { v4: uuidv4 } = require('uuid');
+ const authCode = uuidv4();
+ authCodes.set(authCode, { token, created: Date.now() });
+ res.redirect(frontendUrl('/login?oidc_code=' + authCode));
+ } catch (err: unknown) {
console.error('[OIDC] Callback error:', err);
res.redirect(frontendUrl('/login?oidc_error=server_error'));
}
});
-module.exports = router;
+router.get('/exchange', (req: Request, res: Response) => {
+ const { code } = req.query as { code?: string };
+ if (!code) return res.status(400).json({ error: 'Code required' });
+ const entry = authCodes.get(code);
+ if (!entry) return res.status(400).json({ error: 'Invalid or expired code' });
+ authCodes.delete(code);
+ if (Date.now() - entry.created > AUTH_CODE_TTL) return res.status(400).json({ error: 'Code expired' });
+ res.json({ token: entry.token });
+});
+
+export default router;
diff --git a/server/src/routes/packing.js b/server/src/routes/packing.ts
similarity index 66%
rename from server/src/routes/packing.js
rename to server/src/routes/packing.ts
index 20af44c91..22cb7b787 100644
--- a/server/src/routes/packing.js
+++ b/server/src/routes/packing.ts
@@ -1,19 +1,20 @@
-const express = require('express');
-const { db, canAccessTrip } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
-const { broadcast } = require('../websocket');
+import express, { Request, Response } from 'express';
+import { db, canAccessTrip } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { broadcast } from '../websocket';
+import { AuthRequest } from '../types';
const router = express.Router({ mergeParams: true });
-function verifyTripOwnership(tripId, userId) {
+function verifyTripOwnership(tripId: string | number, userId: number) {
return canAccessTrip(tripId, userId);
}
-// GET /api/trips/:tripId/packing
-router.get('/', authenticate, (req, res) => {
+router.get('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
const items = db.prepare(
@@ -23,17 +24,17 @@ router.get('/', authenticate, (req, res) => {
res.json({ items });
});
-// POST /api/trips/:tripId/packing
-router.post('/', authenticate, (req, res) => {
+router.post('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
const { name, category, checked } = req.body;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
if (!name) return res.status(400).json({ error: 'Item name is required' });
- const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?').get(tripId);
+ const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?').get(tripId) as { max: number | null };
const sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
const result = db.prepare(
@@ -42,15 +43,15 @@ router.post('/', authenticate, (req, res) => {
const item = db.prepare('SELECT * FROM packing_items WHERE id = ?').get(result.lastInsertRowid);
res.status(201).json({ item });
- broadcast(tripId, 'packing:created', { item }, req.headers['x-socket-id']);
+ broadcast(tripId, 'packing:created', { item }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/packing/:id
-router.put('/:id', authenticate, (req, res) => {
+router.put('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
const { name, checked, category } = req.body;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
const item = db.prepare('SELECT * FROM packing_items WHERE id = ? AND trip_id = ?').get(id, tripId);
@@ -72,14 +73,14 @@ router.put('/:id', authenticate, (req, res) => {
const updated = db.prepare('SELECT * FROM packing_items WHERE id = ?').get(id);
res.json({ item: updated });
- broadcast(tripId, 'packing:updated', { item: updated }, req.headers['x-socket-id']);
+ broadcast(tripId, 'packing:updated', { item: updated }, req.headers['x-socket-id'] as string);
});
-// DELETE /api/trips/:tripId/packing/:id
-router.delete('/:id', authenticate, (req, res) => {
+router.delete('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
const item = db.prepare('SELECT id FROM packing_items WHERE id = ? AND trip_id = ?').get(id, tripId);
@@ -87,19 +88,19 @@ router.delete('/:id', authenticate, (req, res) => {
db.prepare('DELETE FROM packing_items WHERE id = ?').run(id);
res.json({ success: true });
- broadcast(tripId, 'packing:deleted', { itemId: Number(id) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'packing:deleted', { itemId: Number(id) }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/packing/reorder
-router.put('/reorder', authenticate, (req, res) => {
+router.put('/reorder', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
const { orderedIds } = req.body;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
const update = db.prepare('UPDATE packing_items SET sort_order = ? WHERE id = ? AND trip_id = ?');
- const updateMany = db.transaction((ids) => {
+ const updateMany = db.transaction((ids: number[]) => {
ids.forEach((id, index) => {
update.run(index, id, tripId);
});
@@ -109,4 +110,4 @@ router.put('/reorder', authenticate, (req, res) => {
res.json({ success: true });
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/photos.js b/server/src/routes/photos.js
deleted file mode 100644
index cd5b24512..000000000
--- a/server/src/routes/photos.js
+++ /dev/null
@@ -1,167 +0,0 @@
-const express = require('express');
-const multer = require('multer');
-const path = require('path');
-const fs = require('fs');
-const { v4: uuidv4 } = require('uuid');
-const { db, canAccessTrip } = require('../db/database');
-const { authenticate, demoUploadBlock } = require('../middleware/auth');
-
-const router = express.Router({ mergeParams: true });
-
-const photosDir = path.join(__dirname, '../../uploads/photos');
-
-const storage = multer.diskStorage({
- destination: (req, file, cb) => {
- if (!fs.existsSync(photosDir)) fs.mkdirSync(photosDir, { recursive: true });
- cb(null, photosDir);
- },
- filename: (req, file, cb) => {
- const ext = path.extname(file.originalname);
- cb(null, `${uuidv4()}${ext}`);
- },
-});
-
-const upload = multer({
- storage,
- limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
- fileFilter: (req, file, cb) => {
- const ext = path.extname(file.originalname).toLowerCase();
- const allowedExts = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
- if (file.mimetype.startsWith('image/') && !file.mimetype.includes('svg') && allowedExts.includes(ext)) {
- cb(null, true);
- } else {
- cb(new Error('Only jpg, png, gif, webp images allowed'));
- }
- },
-});
-
-function formatPhoto(photo) {
- return {
- ...photo,
- url: `/uploads/photos/${photo.filename}`,
- };
-}
-
-// GET /api/trips/:tripId/photos
-router.get('/', authenticate, (req, res) => {
- const { tripId } = req.params;
- const { day_id, place_id } = req.query;
-
- const trip = canAccessTrip(tripId, req.user.id);
- if (!trip) return res.status(404).json({ error: 'Trip not found' });
-
- let query = 'SELECT * FROM photos WHERE trip_id = ?';
- const params = [tripId];
-
- if (day_id) {
- query += ' AND day_id = ?';
- params.push(day_id);
- }
-
- if (place_id) {
- query += ' AND place_id = ?';
- params.push(place_id);
- }
-
- query += ' ORDER BY created_at DESC';
-
- const photos = db.prepare(query).all(...params);
- res.json({ photos: photos.map(formatPhoto) });
-});
-
-// POST /api/trips/:tripId/photos
-router.post('/', authenticate, demoUploadBlock, upload.array('photos', 20), (req, res) => {
- const { tripId } = req.params;
- const { day_id, place_id, caption } = req.body;
-
- const trip = canAccessTrip(tripId, req.user.id);
- if (!trip) {
- // Delete uploaded files on auth failure
- if (req.files) req.files.forEach(f => fs.unlinkSync(f.path));
- return res.status(404).json({ error: 'Trip not found' });
- }
-
- if (!req.files || req.files.length === 0) {
- return res.status(400).json({ error: 'No files uploaded' });
- }
-
- const insertPhoto = db.prepare(`
- INSERT INTO photos (trip_id, day_id, place_id, filename, original_name, file_size, mime_type, caption)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
- `);
-
- const photos = [];
- db.exec('BEGIN');
- try {
- for (const file of req.files) {
- const result = insertPhoto.run(
- tripId,
- day_id || null,
- place_id || null,
- file.filename,
- file.originalname,
- file.size,
- file.mimetype,
- caption || null
- );
- const photo = db.prepare('SELECT * FROM photos WHERE id = ?').get(result.lastInsertRowid);
- photos.push(formatPhoto(photo));
- }
- db.exec('COMMIT');
- } catch (e) {
- db.exec('ROLLBACK');
- throw e;
- }
-
- res.status(201).json({ photos });
-});
-
-// PUT /api/trips/:tripId/photos/:id
-router.put('/:id', authenticate, (req, res) => {
- const { tripId, id } = req.params;
- const { caption, day_id, place_id } = req.body;
-
- const trip = canAccessTrip(tripId, req.user.id);
- if (!trip) return res.status(404).json({ error: 'Trip not found' });
-
- const photo = db.prepare('SELECT * FROM photos WHERE id = ? AND trip_id = ?').get(id, tripId);
- if (!photo) return res.status(404).json({ error: 'Photo not found' });
-
- db.prepare(`
- UPDATE photos SET
- caption = COALESCE(?, caption),
- day_id = ?,
- place_id = ?
- WHERE id = ?
- `).run(
- caption !== undefined ? caption : photo.caption,
- day_id !== undefined ? (day_id || null) : photo.day_id,
- place_id !== undefined ? (place_id || null) : photo.place_id,
- id
- );
-
- const updated = db.prepare('SELECT * FROM photos WHERE id = ?').get(id);
- res.json({ photo: formatPhoto(updated) });
-});
-
-// DELETE /api/trips/:tripId/photos/:id
-router.delete('/:id', authenticate, (req, res) => {
- const { tripId, id } = req.params;
-
- const trip = canAccessTrip(tripId, req.user.id);
- if (!trip) return res.status(404).json({ error: 'Trip not found' });
-
- const photo = db.prepare('SELECT * FROM photos WHERE id = ? AND trip_id = ?').get(id, tripId);
- if (!photo) return res.status(404).json({ error: 'Photo not found' });
-
- // Delete file
- const filePath = path.join(photosDir, photo.filename);
- if (fs.existsSync(filePath)) {
- try { fs.unlinkSync(filePath); } catch (e) { console.error('Error deleting photo file:', e); }
- }
-
- db.prepare('DELETE FROM photos WHERE id = ?').run(id);
- res.json({ success: true });
-});
-
-module.exports = router;
diff --git a/server/src/routes/places.js b/server/src/routes/places.ts
similarity index 71%
rename from server/src/routes/places.js
rename to server/src/routes/places.ts
index 66f679402..57c916901 100644
--- a/server/src/routes/places.js
+++ b/server/src/routes/places.ts
@@ -1,32 +1,37 @@
-const express = require('express');
-const fetch = require('node-fetch');
-const { db, getPlaceWithTags, canAccessTrip } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
-const { broadcast } = require('../websocket');
-
-const router = express.Router({ mergeParams: true });
+import express, { Request, Response } from 'express';
+import fetch from 'node-fetch';
+import { db, getPlaceWithTags } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { requireTripAccess } from '../middleware/tripAccess';
+import { broadcast } from '../websocket';
+import { loadTagsByPlaceIds } from '../services/queryHelpers';
+import { validateStringLengths } from '../middleware/validate';
+import { AuthRequest, Place } from '../types';
+
+interface PlaceWithCategory extends Place {
+ category_name: string | null;
+ category_color: string | null;
+ category_icon: string | null;
+}
-function verifyTripOwnership(tripId, userId) {
- return canAccessTrip(tripId, userId);
+interface UnsplashSearchResponse {
+ results?: { id: string; urls?: { regular?: string; thumb?: string }; description?: string; alt_description?: string; user?: { name?: string }; links?: { html?: string } }[];
+ errors?: string[];
}
-// GET /api/trips/:tripId/places
-router.get('/', authenticate, (req, res) => {
+const router = express.Router({ mergeParams: true });
+
+router.get('/', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId } = req.params;
const { search, category, tag } = req.query;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
let query = `
SELECT DISTINCT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
FROM places p
LEFT JOIN categories c ON p.category_id = c.id
WHERE p.trip_id = ?
`;
- const params = [tripId];
+ const params: (string | number)[] = [tripId];
if (search) {
query += ' AND (p.name LIKE ? OR p.address LIKE ? OR p.description LIKE ?)';
@@ -46,26 +51,10 @@ router.get('/', authenticate, (req, res) => {
query += ' ORDER BY p.created_at DESC';
- const places = db.prepare(query).all(...params);
+ const places = db.prepare(query).all(...params) as PlaceWithCategory[];
- // Load all tags for these places in a single query to avoid N+1
const placeIds = places.map(p => p.id);
- const tagsByPlaceId = {};
- if (placeIds.length > 0) {
- const placeholders = placeIds.map(() => '?').join(',');
- const allTags = db.prepare(`
- SELECT t.*, pt.place_id FROM tags t
- JOIN place_tags pt ON t.id = pt.tag_id
- WHERE pt.place_id IN (${placeholders})
- `).all(...placeIds);
-
- for (const tag of allTags) {
- const pid = tag.place_id;
- delete tag.place_id;
- if (!tagsByPlaceId[pid]) tagsByPlaceId[pid] = [];
- tagsByPlaceId[pid].push(tag);
- }
- }
+ const tagsByPlaceId = loadTagsByPlaceIds(placeIds);
const placesWithTags = places.map(p => {
return {
@@ -83,15 +72,9 @@ router.get('/', authenticate, (req, res) => {
res.json({ places: placesWithTags });
});
-// POST /api/trips/:tripId/places
-router.post('/', authenticate, (req, res) => {
+router.post('/', authenticate, requireTripAccess, validateStringLengths({ name: 200, description: 2000, address: 500, notes: 2000 }), (req: Request, res: Response) => {
const { tripId } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
const {
name, description, lat, lng, address, category_id, price, currency,
place_time, end_time,
@@ -126,18 +109,12 @@ router.post('/', authenticate, (req, res) => {
const place = getPlaceWithTags(placeId);
res.status(201).json({ place });
- broadcast(tripId, 'place:created', { place }, req.headers['x-socket-id']);
+ broadcast(tripId, 'place:created', { place }, req.headers['x-socket-id'] as string);
});
-// GET /api/trips/:tripId/places/:id
-router.get('/:id', authenticate, (req, res) => {
+router.get('/:id', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
const placeCheck = db.prepare('SELECT id FROM places WHERE id = ? AND trip_id = ?').get(id, tripId);
if (!placeCheck) {
return res.status(404).json({ error: 'Place not found' });
@@ -147,21 +124,16 @@ router.get('/:id', authenticate, (req, res) => {
res.json({ place });
});
-// GET /api/trips/:tripId/places/:id/image - fetch image from Unsplash
-router.get('/:id/image', authenticate, async (req, res) => {
+router.get('/:id/image', authenticate, requireTripAccess, async (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
- const place = db.prepare('SELECT * FROM places WHERE id = ? AND trip_id = ?').get(id, tripId);
+ const place = db.prepare('SELECT * FROM places WHERE id = ? AND trip_id = ?').get(id, tripId) as Place | undefined;
if (!place) {
return res.status(404).json({ error: 'Place not found' });
}
- const user = db.prepare('SELECT unsplash_api_key FROM users WHERE id = ?').get(req.user.id);
+ const user = db.prepare('SELECT unsplash_api_key FROM users WHERE id = ?').get(authReq.user.id) as { unsplash_api_key: string | null } | undefined;
if (!user || !user.unsplash_api_key) {
return res.status(400).json({ error: 'No Unsplash API key configured' });
}
@@ -171,13 +143,13 @@ router.get('/:id/image', authenticate, async (req, res) => {
const response = await fetch(
`https://api.unsplash.com/search/photos?query=${query}&per_page=5&client_id=${user.unsplash_api_key}`
);
- const data = await response.json();
+ const data = await response.json() as UnsplashSearchResponse;
if (!response.ok) {
return res.status(response.status).json({ error: data.errors?.[0] || 'Unsplash API error' });
}
- const photos = (data.results || []).map(p => ({
+ const photos = (data.results || []).map((p: NonNullable<UnsplashSearchResponse['results']>[number]) => ({
id: p.id,
url: p.urls?.regular,
thumb: p.urls?.thumb,
@@ -187,22 +159,16 @@ router.get('/:id/image', authenticate, async (req, res) => {
}));
res.json({ photos });
- } catch (err) {
+ } catch (err: unknown) {
console.error('Unsplash error:', err);
res.status(500).json({ error: 'Error searching for image' });
}
});
-// PUT /api/trips/:tripId/places/:id
-router.put('/:id', authenticate, (req, res) => {
+router.put('/:id', authenticate, requireTripAccess, validateStringLengths({ name: 200, description: 2000, address: 500, notes: 2000 }), (req: Request, res: Response) => {
const { tripId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
- const existingPlace = db.prepare('SELECT * FROM places WHERE id = ? AND trip_id = ?').get(id, tripId);
+ const existingPlace = db.prepare('SELECT * FROM places WHERE id = ? AND trip_id = ?').get(id, tripId) as Place | undefined;
if (!existingPlace) {
return res.status(404).json({ error: 'Place not found' });
}
@@ -268,18 +234,12 @@ router.put('/:id', authenticate, (req, res) => {
const place = getPlaceWithTags(id);
res.json({ place });
- broadcast(tripId, 'place:updated', { place }, req.headers['x-socket-id']);
+ broadcast(tripId, 'place:updated', { place }, req.headers['x-socket-id'] as string);
});
-// DELETE /api/trips/:tripId/places/:id
-router.delete('/:id', authenticate, (req, res) => {
+router.delete('/:id', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
- if (!trip) {
- return res.status(404).json({ error: 'Trip not found' });
- }
-
const place = db.prepare('SELECT id FROM places WHERE id = ? AND trip_id = ?').get(id, tripId);
if (!place) {
return res.status(404).json({ error: 'Place not found' });
@@ -287,7 +247,7 @@ router.delete('/:id', authenticate, (req, res) => {
db.prepare('DELETE FROM places WHERE id = ?').run(id);
res.json({ success: true });
- broadcast(tripId, 'place:deleted', { placeId: Number(id) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'place:deleted', { placeId: Number(id) }, req.headers['x-socket-id'] as string);
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/reservations.js b/server/src/routes/reservations.ts
similarity index 77%
rename from server/src/routes/reservations.js
rename to server/src/routes/reservations.ts
index d97bc5ff0..7cbbc663a 100644
--- a/server/src/routes/reservations.js
+++ b/server/src/routes/reservations.ts
@@ -1,19 +1,20 @@
-const express = require('express');
-const { db, canAccessTrip } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
-const { broadcast } = require('../websocket');
+import express, { Request, Response } from 'express';
+import { db, canAccessTrip } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { broadcast } from '../websocket';
+import { AuthRequest, Reservation } from '../types';
const router = express.Router({ mergeParams: true });
-function verifyTripOwnership(tripId, userId) {
+function verifyTripOwnership(tripId: string | number, userId: number) {
return canAccessTrip(tripId, userId);
}
-// GET /api/trips/:tripId/reservations
-router.get('/', authenticate, (req, res) => {
+router.get('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
const reservations = db.prepare(`
@@ -28,12 +29,12 @@ router.get('/', authenticate, (req, res) => {
res.json({ reservations });
});
-// POST /api/trips/:tripId/reservations
-router.post('/', authenticate, (req, res) => {
+router.post('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId } = req.params;
const { title, reservation_time, reservation_end_time, location, confirmation_number, notes, day_id, place_id, assignment_id, status, type } = req.body;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
if (!title) return res.status(400).json({ error: 'Title is required' });
@@ -65,18 +66,18 @@ router.post('/', authenticate, (req, res) => {
`).get(result.lastInsertRowid);
res.status(201).json({ reservation });
- broadcast(tripId, 'reservation:created', { reservation }, req.headers['x-socket-id']);
+ broadcast(tripId, 'reservation:created', { reservation }, req.headers['x-socket-id'] as string);
});
-// PUT /api/trips/:tripId/reservations/:id
-router.put('/:id', authenticate, (req, res) => {
+router.put('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
const { title, reservation_time, reservation_end_time, location, confirmation_number, notes, day_id, place_id, assignment_id, status, type } = req.body;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
- const reservation = db.prepare('SELECT * FROM reservations WHERE id = ? AND trip_id = ?').get(id, tripId);
+ const reservation = db.prepare('SELECT * FROM reservations WHERE id = ? AND trip_id = ?').get(id, tripId) as Reservation | undefined;
if (!reservation) return res.status(404).json({ error: 'Reservation not found' });
db.prepare(`
@@ -117,14 +118,14 @@ router.put('/:id', authenticate, (req, res) => {
`).get(id);
res.json({ reservation: updated });
- broadcast(tripId, 'reservation:updated', { reservation: updated }, req.headers['x-socket-id']);
+ broadcast(tripId, 'reservation:updated', { reservation: updated }, req.headers['x-socket-id'] as string);
});
-// DELETE /api/trips/:tripId/reservations/:id
-router.delete('/:id', authenticate, (req, res) => {
+router.delete('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { tripId, id } = req.params;
- const trip = verifyTripOwnership(tripId, req.user.id);
+ const trip = verifyTripOwnership(tripId, authReq.user.id);
if (!trip) return res.status(404).json({ error: 'Trip not found' });
const reservation = db.prepare('SELECT id FROM reservations WHERE id = ? AND trip_id = ?').get(id, tripId);
@@ -132,7 +133,7 @@ router.delete('/:id', authenticate, (req, res) => {
db.prepare('DELETE FROM reservations WHERE id = ?').run(id);
res.json({ success: true });
- broadcast(tripId, 'reservation:deleted', { reservationId: Number(id) }, req.headers['x-socket-id']);
+ broadcast(tripId, 'reservation:deleted', { reservationId: Number(id) }, req.headers['x-socket-id'] as string);
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/settings.js b/server/src/routes/settings.ts
similarity index 63%
rename from server/src/routes/settings.js
rename to server/src/routes/settings.ts
index 883e12df7..06b6d6a9b 100644
--- a/server/src/routes/settings.js
+++ b/server/src/routes/settings.ts
@@ -1,13 +1,14 @@
-const express = require('express');
-const { db } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
+import express, { Request, Response } from 'express';
+import { db } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { AuthRequest } from '../types';
const router = express.Router();
-// GET /api/settings - return all settings for user
-router.get('/', authenticate, (req, res) => {
- const rows = db.prepare('SELECT key, value FROM settings WHERE user_id = ?').all(req.user.id);
- const settings = {};
+router.get('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const rows = db.prepare('SELECT key, value FROM settings WHERE user_id = ?').all(authReq.user.id) as { key: string; value: string }[];
+ const settings: Record<string, unknown> = {};
for (const row of rows) {
try {
settings[row.key] = JSON.parse(row.value);
@@ -18,8 +19,8 @@ router.get('/', authenticate, (req, res) => {
res.json({ settings });
});
-// PUT /api/settings - upsert single setting
-router.put('/', authenticate, (req, res) => {
+router.put('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { key, value } = req.body;
if (!key) return res.status(400).json({ error: 'Key is required' });
@@ -29,13 +30,13 @@ router.put('/', authenticate, (req, res) => {
db.prepare(`
INSERT INTO settings (user_id, key, value) VALUES (?, ?, ?)
ON CONFLICT(user_id, key) DO UPDATE SET value = excluded.value
- `).run(req.user.id, key, serialized);
+ `).run(authReq.user.id, key, serialized);
res.json({ success: true, key, value });
});
-// POST /api/settings/bulk - upsert multiple settings
-router.post('/bulk', authenticate, (req, res) => {
+router.post('/bulk', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { settings } = req.body;
if (!settings || typeof settings !== 'object') {
@@ -51,15 +52,16 @@ router.post('/bulk', authenticate, (req, res) => {
db.exec('BEGIN');
for (const [key, value] of Object.entries(settings)) {
const serialized = typeof value === 'object' ? JSON.stringify(value) : String(value !== undefined ? value : '');
- upsert.run(req.user.id, key, serialized);
+ upsert.run(authReq.user.id, key, serialized);
}
db.exec('COMMIT');
- } catch (err) {
+ } catch (err: unknown) {
db.exec('ROLLBACK');
- return res.status(500).json({ error: 'Error saving settings', detail: err.message });
+ console.error('Error saving settings:', err);
+ return res.status(500).json({ error: 'Error saving settings' });
}
res.json({ success: true, updated: Object.keys(settings).length });
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/tags.js b/server/src/routes/tags.ts
similarity index 59%
rename from server/src/routes/tags.js
rename to server/src/routes/tags.ts
index a19042d1c..039863111 100644
--- a/server/src/routes/tags.js
+++ b/server/src/routes/tags.ts
@@ -1,35 +1,36 @@
-const express = require('express');
-const { db } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
+import express, { Request, Response } from 'express';
+import { db } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { AuthRequest } from '../types';
const router = express.Router();
-// GET /api/tags
-router.get('/', authenticate, (req, res) => {
+router.get('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const tags = db.prepare(
'SELECT * FROM tags WHERE user_id = ? ORDER BY name ASC'
- ).all(req.user.id);
+ ).all(authReq.user.id);
res.json({ tags });
});
-// POST /api/tags
-router.post('/', authenticate, (req, res) => {
+router.post('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { name, color } = req.body;
if (!name) return res.status(400).json({ error: 'Tag name is required' });
const result = db.prepare(
'INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)'
- ).run(req.user.id, name, color || '#10b981');
+ ).run(authReq.user.id, name, color || '#10b981');
const tag = db.prepare('SELECT * FROM tags WHERE id = ?').get(result.lastInsertRowid);
res.status(201).json({ tag });
});
-// PUT /api/tags/:id
-router.put('/:id', authenticate, (req, res) => {
+router.put('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { name, color } = req.body;
- const tag = db.prepare('SELECT * FROM tags WHERE id = ? AND user_id = ?').get(req.params.id, req.user.id);
+ const tag = db.prepare('SELECT * FROM tags WHERE id = ? AND user_id = ?').get(req.params.id, authReq.user.id);
if (!tag) return res.status(404).json({ error: 'Tag not found' });
@@ -40,13 +41,13 @@ router.put('/:id', authenticate, (req, res) => {
res.json({ tag: updated });
});
-// DELETE /api/tags/:id
-router.delete('/:id', authenticate, (req, res) => {
- const tag = db.prepare('SELECT * FROM tags WHERE id = ? AND user_id = ?').get(req.params.id, req.user.id);
+router.delete('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const tag = db.prepare('SELECT * FROM tags WHERE id = ? AND user_id = ?').get(req.params.id, authReq.user.id);
if (!tag) return res.status(404).json({ error: 'Tag not found' });
db.prepare('DELETE FROM tags WHERE id = ?').run(req.params.id);
res.json({ success: true });
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/trips.js b/server/src/routes/trips.ts
similarity index 72%
rename from server/src/routes/trips.js
rename to server/src/routes/trips.ts
index 131bf4541..ad5231db8 100644
--- a/server/src/routes/trips.js
+++ b/server/src/routes/trips.ts
@@ -1,29 +1,34 @@
-const express = require('express');
-const multer = require('multer');
-const path = require('path');
-const fs = require('fs');
-const { v4: uuidv4 } = require('uuid');
-const { db, canAccessTrip, isOwner } = require('../db/database');
-const { authenticate, demoUploadBlock } = require('../middleware/auth');
-const { broadcast } = require('../websocket');
+import express, { Request, Response } from 'express';
+import multer from 'multer';
+import path from 'path';
+import fs from 'fs';
+import { v4 as uuidv4 } from 'uuid';
+import { db, canAccessTrip, isOwner } from '../db/database';
+import { authenticate, demoUploadBlock } from '../middleware/auth';
+import { broadcast } from '../websocket';
+import { AuthRequest, Trip, User } from '../types';
const router = express.Router();
+const MS_PER_DAY = 86400000;
+const MAX_TRIP_DAYS = 90;
+const MAX_COVER_SIZE = 20 * 1024 * 1024; // 20 MB
+
const coversDir = path.join(__dirname, '../../uploads/covers');
const coverStorage = multer.diskStorage({
- destination: (req, file, cb) => {
+ destination: (_req, _file, cb) => {
if (!fs.existsSync(coversDir)) fs.mkdirSync(coversDir, { recursive: true });
cb(null, coversDir);
},
- filename: (req, file, cb) => {
+ filename: (_req, file, cb) => {
const ext = path.extname(file.originalname);
cb(null, `${uuidv4()}${ext}`);
},
});
const uploadCover = multer({
storage: coverStorage,
- limits: { fileSize: 20 * 1024 * 1024 },
- fileFilter: (req, file, cb) => {
+ limits: { fileSize: MAX_COVER_SIZE },
+ fileFilter: (_req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase();
const allowedExts = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
if (file.mimetype.startsWith('image/') && !file.mimetype.includes('svg') && allowedExts.includes(ext)) {
@@ -45,74 +50,62 @@ const TRIP_SELECT = `
JOIN users u ON u.id = t.user_id
`;
-function generateDays(tripId, startDate, endDate) {
- const existing = db.prepare('SELECT id, day_number, date FROM days WHERE trip_id = ?').all(tripId);
+function generateDays(tripId: number | bigint | string, startDate: string | null, endDate: string | null) {
+ const existing = db.prepare('SELECT id, day_number, date FROM days WHERE trip_id = ?').all(tripId) as { id: number; day_number: number; date: string | null }[];
if (!startDate || !endDate) {
- // No dates — keep up to 7 dateless days, reuse existing ones
const datelessExisting = existing.filter(d => !d.date).sort((a, b) => a.day_number - b.day_number);
- // Remove days with dates (they no longer apply)
const withDates = existing.filter(d => d.date);
if (withDates.length > 0) {
db.prepare(`DELETE FROM days WHERE trip_id = ? AND date IS NOT NULL`).run(tripId);
}
- // Ensure exactly 7 dateless days
const needed = 7 - datelessExisting.length;
if (needed > 0) {
const insert = db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, NULL)');
for (let i = 0; i < needed; i++) insert.run(tripId, datelessExisting.length + i + 1);
} else if (needed < 0) {
- // Too many dateless days — remove extras (highest day_number first to preserve earlier assignments)
const toRemove = datelessExisting.slice(7);
const del = db.prepare('DELETE FROM days WHERE id = ?');
for (const d of toRemove) del.run(d.id);
}
- // Renumber — use negative temp values first to avoid UNIQUE conflicts
- const remaining = db.prepare('SELECT id FROM days WHERE trip_id = ? ORDER BY day_number').all(tripId);
+ const remaining = db.prepare('SELECT id FROM days WHERE trip_id = ? ORDER BY day_number').all(tripId) as { id: number }[];
const tmpUpd = db.prepare('UPDATE days SET day_number = ? WHERE id = ?');
remaining.forEach((d, i) => tmpUpd.run(-(i + 1), d.id));
remaining.forEach((d, i) => tmpUpd.run(i + 1, d.id));
return;
}
- // Use pure string-based date math to avoid timezone/DST issues
const [sy, sm, sd] = startDate.split('-').map(Number);
const [ey, em, ed] = endDate.split('-').map(Number);
const startMs = Date.UTC(sy, sm - 1, sd);
const endMs = Date.UTC(ey, em - 1, ed);
- const numDays = Math.min(Math.floor((endMs - startMs) / 86400000) + 1, 90);
+ const numDays = Math.min(Math.floor((endMs - startMs) / MS_PER_DAY) + 1, MAX_TRIP_DAYS);
- // Build target dates
- const targetDates = [];
+ const targetDates: string[] = [];
for (let i = 0; i < numDays; i++) {
- const d = new Date(startMs + i * 86400000);
+ const d = new Date(startMs + i * MS_PER_DAY);
const yyyy = d.getUTCFullYear();
const mm = String(d.getUTCMonth() + 1).padStart(2, '0');
const dd = String(d.getUTCDate()).padStart(2, '0');
targetDates.push(`${yyyy}-${mm}-${dd}`);
}
- // Index existing days by date
- const existingByDate = new Map();
+ const existingByDate = new Map<string, { id: number; day_number: number; date: string | null }>();
for (const d of existing) {
if (d.date) existingByDate.set(d.date, d);
}
const targetDateSet = new Set(targetDates);
- // Delete days whose date is no longer in the new range
const toDelete = existing.filter(d => d.date && !targetDateSet.has(d.date));
- // Also delete dateless days (they are replaced by dated ones)
const datelessToDelete = existing.filter(d => !d.date);
const del = db.prepare('DELETE FROM days WHERE id = ?');
for (const d of [...toDelete, ...datelessToDelete]) del.run(d.id);
- // Move all kept days to negative day_numbers to avoid UNIQUE conflicts
const setTemp = db.prepare('UPDATE days SET day_number = ? WHERE id = ?');
const kept = existing.filter(d => d.date && targetDateSet.has(d.date));
for (let i = 0; i < kept.length; i++) setTemp.run(-(i + 1), kept[i].id);
- // Now assign correct day_numbers and insert missing days
const insert = db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, ?)');
const update = db.prepare('UPDATE days SET day_number = ? WHERE id = ?');
@@ -127,10 +120,10 @@ function generateDays(tripId, startDate, endDate) {
}
}
-// GET /api/trips — active or archived, includes shared trips
-router.get('/', authenticate, (req, res) => {
+router.get('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const archived = req.query.archived === '1' ? 1 : 0;
- const userId = req.user.id;
+ const userId = authReq.user.id;
const trips = db.prepare(`
${TRIP_SELECT}
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = :userId
@@ -140,8 +133,8 @@ router.get('/', authenticate, (req, res) => {
res.json({ trips });
});
-// POST /api/trips
-router.post('/', authenticate, (req, res) => {
+router.post('/', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { title, description, start_date, end_date, currency } = req.body;
if (!title) return res.status(400).json({ error: 'Title is required' });
if (start_date && end_date && new Date(end_date) < new Date(start_date))
@@ -150,17 +143,17 @@ router.post('/', authenticate, (req, res) => {
const result = db.prepare(`
INSERT INTO trips (user_id, title, description, start_date, end_date, currency)
VALUES (?, ?, ?, ?, ?, ?)
- `).run(req.user.id, title, description || null, start_date || null, end_date || null, currency || 'EUR');
+ `).run(authReq.user.id, title, description || null, start_date || null, end_date || null, currency || 'EUR');
const tripId = result.lastInsertRowid;
generateDays(tripId, start_date, end_date);
- const trip = db.prepare(`${TRIP_SELECT} WHERE t.id = :tripId`).get({ userId: req.user.id, tripId });
+ const trip = db.prepare(`${TRIP_SELECT} WHERE t.id = :tripId`).get({ userId: authReq.user.id, tripId });
res.status(201).json({ trip });
});
-// GET /api/trips/:id
-router.get('/:id', authenticate, (req, res) => {
- const userId = req.user.id;
+router.get('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const userId = authReq.user.id;
const trip = db.prepare(`
${TRIP_SELECT}
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = :userId
@@ -170,16 +163,17 @@ router.get('/:id', authenticate, (req, res) => {
res.json({ trip });
});
-// PUT /api/trips/:id — all members can edit; archive/cover owner-only
-router.put('/:id', authenticate, (req, res) => {
- const access = canAccessTrip(req.params.id, req.user.id);
+router.put('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const access = canAccessTrip(req.params.id, authReq.user.id);
if (!access) return res.status(404).json({ error: 'Trip not found' });
const ownerOnly = req.body.is_archived !== undefined || req.body.cover_image !== undefined;
- if (ownerOnly && !isOwner(req.params.id, req.user.id))
+ if (ownerOnly && !isOwner(req.params.id, authReq.user.id))
return res.status(403).json({ error: 'Only the owner can change this setting' });
- const trip = db.prepare('SELECT * FROM trips WHERE id = ?').get(req.params.id);
+ const trip = db.prepare('SELECT * FROM trips WHERE id = ?').get(req.params.id) as Trip | undefined;
+ if (!trip) return res.status(404).json({ error: 'Trip not found' });
const { title, description, start_date, end_date, currency, is_archived, cover_image } = req.body;
if (start_date && end_date && new Date(end_date) < new Date(start_date))
@@ -202,17 +196,17 @@ router.put('/:id', authenticate, (req, res) => {
if (newStart !== trip.start_date || newEnd !== trip.end_date)
generateDays(req.params.id, newStart, newEnd);
- const updatedTrip = db.prepare(`${TRIP_SELECT} WHERE t.id = :tripId`).get({ userId: req.user.id, tripId: req.params.id });
+ const updatedTrip = db.prepare(`${TRIP_SELECT} WHERE t.id = :tripId`).get({ userId: authReq.user.id, tripId: req.params.id });
res.json({ trip: updatedTrip });
- broadcast(req.params.id, 'trip:updated', { trip: updatedTrip }, req.headers['x-socket-id']);
+ broadcast(req.params.id, 'trip:updated', { trip: updatedTrip }, req.headers['x-socket-id'] as string);
});
-// POST /api/trips/:id/cover
-router.post('/:id/cover', authenticate, demoUploadBlock, uploadCover.single('cover'), (req, res) => {
- if (!isOwner(req.params.id, req.user.id))
+router.post('/:id/cover', authenticate, demoUploadBlock, uploadCover.single('cover'), (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ if (!isOwner(req.params.id, authReq.user.id))
return res.status(403).json({ error: 'Only the owner can change the cover image' });
- const trip = db.prepare('SELECT * FROM trips WHERE id = ?').get(req.params.id);
+ const trip = db.prepare('SELECT * FROM trips WHERE id = ?').get(req.params.id) as Trip | undefined;
if (!trip) return res.status(404).json({ error: 'Trip not found' });
if (!req.file) return res.status(400).json({ error: 'No image uploaded' });
@@ -230,24 +224,22 @@ router.post('/:id/cover', authenticate, demoUploadBlock, uploadCover.single('cov
res.json({ cover_image: coverUrl });
});
-// DELETE /api/trips/:id — owner only
-router.delete('/:id', authenticate, (req, res) => {
- if (!isOwner(req.params.id, req.user.id))
+router.delete('/:id', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ if (!isOwner(req.params.id, authReq.user.id))
return res.status(403).json({ error: 'Only the owner can delete the trip' });
const deletedTripId = Number(req.params.id);
db.prepare('DELETE FROM trips WHERE id = ?').run(req.params.id);
res.json({ success: true });
- broadcast(deletedTripId, 'trip:deleted', { id: deletedTripId }, req.headers['x-socket-id']);
+ broadcast(deletedTripId, 'trip:deleted', { id: deletedTripId }, req.headers['x-socket-id'] as string);
});
-// ── Member Management ────────────────────────────────────────────────────────
-
-// GET /api/trips/:id/members
-router.get('/:id/members', authenticate, (req, res) => {
- if (!canAccessTrip(req.params.id, req.user.id))
+router.get('/:id/members', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ if (!canAccessTrip(req.params.id, authReq.user.id))
return res.status(404).json({ error: 'Trip not found' });
- const trip = db.prepare('SELECT user_id FROM trips WHERE id = ?').get(req.params.id);
+ const trip = db.prepare('SELECT user_id FROM trips WHERE id = ?').get(req.params.id) as { user_id: number };
const members = db.prepare(`
SELECT u.id, u.username, u.email, u.avatar,
CASE WHEN u.id = ? THEN 'owner' ELSE 'member' END as role,
@@ -258,55 +250,55 @@ router.get('/:id/members', authenticate, (req, res) => {
LEFT JOIN users ib ON ib.id = m.invited_by
WHERE m.trip_id = ?
ORDER BY m.added_at ASC
- `).all(trip.user_id, req.params.id);
+ `).all(trip.user_id, req.params.id) as { id: number; username: string; email: string; avatar: string | null; role: string; added_at: string; invited_by_username: string | null }[];
- const owner = db.prepare('SELECT id, username, email, avatar FROM users WHERE id = ?').get(trip.user_id);
+ const owner = db.prepare('SELECT id, username, email, avatar FROM users WHERE id = ?').get(trip.user_id) as Pick<User, 'id' | 'username' | 'email' | 'avatar'>;
res.json({
owner: { ...owner, role: 'owner', avatar_url: owner.avatar ? `/uploads/avatars/${owner.avatar}` : null },
members: members.map(m => ({ ...m, avatar_url: m.avatar ? `/uploads/avatars/${m.avatar}` : null })),
- current_user_id: req.user.id,
+ current_user_id: authReq.user.id,
});
});
-// POST /api/trips/:id/members — add by email or username
-router.post('/:id/members', authenticate, (req, res) => {
- if (!canAccessTrip(req.params.id, req.user.id))
+router.post('/:id/members', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ if (!canAccessTrip(req.params.id, authReq.user.id))
return res.status(404).json({ error: 'Trip not found' });
- const { identifier } = req.body; // email or username
+ const { identifier } = req.body;
if (!identifier) return res.status(400).json({ error: 'Email or username required' });
const target = db.prepare(
'SELECT id, username, email, avatar FROM users WHERE email = ? OR username = ?'
- ).get(identifier.trim(), identifier.trim());
+ ).get(identifier.trim(), identifier.trim()) as Pick<User, 'id' | 'username' | 'email' | 'avatar'> | undefined;
if (!target) return res.status(404).json({ error: 'User not found' });
- const trip = db.prepare('SELECT user_id FROM trips WHERE id = ?').get(req.params.id);
+ const trip = db.prepare('SELECT user_id FROM trips WHERE id = ?').get(req.params.id) as { user_id: number };
if (target.id === trip.user_id)
return res.status(400).json({ error: 'Trip owner is already a member' });
const existing = db.prepare('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?').get(req.params.id, target.id);
if (existing) return res.status(400).json({ error: 'User already has access' });
- db.prepare('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(req.params.id, target.id, req.user.id);
+ db.prepare('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(req.params.id, target.id, authReq.user.id);
res.status(201).json({ member: { ...target, role: 'member', avatar_url: target.avatar ? `/uploads/avatars/${target.avatar}` : null } });
});
-// DELETE /api/trips/:id/members/:userId — owner removes anyone; member removes self
-router.delete('/:id/members/:userId', authenticate, (req, res) => {
- if (!canAccessTrip(req.params.id, req.user.id))
+router.delete('/:id/members/:userId', authenticate, (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ if (!canAccessTrip(req.params.id, authReq.user.id))
return res.status(404).json({ error: 'Trip not found' });
const targetId = parseInt(req.params.userId);
- const isSelf = targetId === req.user.id;
- if (!isSelf && !isOwner(req.params.id, req.user.id))
+ const isSelf = targetId === authReq.user.id;
+ if (!isSelf && !isOwner(req.params.id, authReq.user.id))
return res.status(403).json({ error: 'No permission' });
db.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(req.params.id, targetId);
res.json({ success: true });
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/vacay.js b/server/src/routes/vacay.ts
similarity index 66%
rename from server/src/routes/vacay.js
rename to server/src/routes/vacay.ts
index af41a7840..fcf9e9402 100644
--- a/server/src/routes/vacay.js
+++ b/server/src/routes/vacay.ts
@@ -1,99 +1,127 @@
-const express = require('express');
-const { db } = require('../db/database');
-const { authenticate } = require('../middleware/auth');
+import express, { Request, Response } from 'express';
+import { db } from '../db/database';
+import { authenticate } from '../middleware/auth';
+import { AuthRequest } from '../types';
+
+interface VacayPlan {
+ id: number;
+ owner_id: number;
+ block_weekends: number;
+ holidays_enabled: number;
+ holidays_region: string | null;
+ company_holidays_enabled: number;
+ carry_over_enabled: number;
+}
+
+interface VacayUserYear {
+ user_id: number;
+ plan_id: number;
+ year: number;
+ vacation_days: number;
+ carried_over: number;
+}
-// In-memory cache for holiday API results (key: "year-country", ttl: 24h)
-const holidayCache = new Map();
+interface VacayUser {
+ id: number;
+ username: string;
+ email: string;
+}
+
+interface VacayPlanMember {
+ id: number;
+ plan_id: number;
+ user_id: number;
+ status: string;
+ created_at?: string;
+}
+
+interface Holiday {
+ date: string;
+ localName?: string;
+ name?: string;
+ global?: boolean;
+ counties?: string[] | null;
+}
+
+const holidayCache = new Map<string, { data: unknown; time: number }>();
const CACHE_TTL = 24 * 60 * 60 * 1000;
const router = express.Router();
router.use(authenticate);
-// Broadcast vacay updates to all users in the same plan (exclude only the triggering socket, not the whole user)
-function notifyPlanUsers(planId, excludeSid, event = 'vacay:update') {
+function notifyPlanUsers(planId: number, excludeSid: string | undefined, event = 'vacay:update') {
try {
const { broadcastToUser } = require('../websocket');
- const plan = db.prepare('SELECT owner_id FROM vacay_plans WHERE id = ?').get(planId);
+ const plan = db.prepare('SELECT owner_id FROM vacay_plans WHERE id = ?').get(planId) as { owner_id: number } | undefined;
if (!plan) return;
const userIds = [plan.owner_id];
- const members = db.prepare("SELECT user_id FROM vacay_plan_members WHERE plan_id = ? AND status = 'accepted'").all(planId);
+ const members = db.prepare("SELECT user_id FROM vacay_plan_members WHERE plan_id = ? AND status = 'accepted'").all(planId) as { user_id: number }[];
members.forEach(m => userIds.push(m.user_id));
userIds.forEach(id => broadcastToUser(id, { type: event }, excludeSid));
} catch { /* */ }
}
-// ── Helpers ────────────────────────────────────────────────
-
-// Get or create the user's own plan
-function getOwnPlan(userId) {
- let plan = db.prepare('SELECT * FROM vacay_plans WHERE owner_id = ?').get(userId);
+function getOwnPlan(userId: number) {
+ let plan = db.prepare('SELECT * FROM vacay_plans WHERE owner_id = ?').get(userId) as VacayPlan | undefined;
if (!plan) {
db.prepare('INSERT INTO vacay_plans (owner_id) VALUES (?)').run(userId);
- plan = db.prepare('SELECT * FROM vacay_plans WHERE owner_id = ?').get(userId);
+ plan = db.prepare('SELECT * FROM vacay_plans WHERE owner_id = ?').get(userId) as VacayPlan;
const yr = new Date().getFullYear();
db.prepare('INSERT OR IGNORE INTO vacay_years (plan_id, year) VALUES (?, ?)').run(plan.id, yr);
- // Create user config for current year
db.prepare('INSERT OR IGNORE INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, 30, 0)').run(userId, plan.id, yr);
}
return plan;
}
-// Get the plan the user is currently part of (own or fused)
-function getActivePlan(userId) {
- // Check if user has accepted a fusion
+function getActivePlan(userId: number) {
const membership = db.prepare(`
SELECT plan_id FROM vacay_plan_members WHERE user_id = ? AND status = 'accepted'
- `).get(userId);
+ `).get(userId) as { plan_id: number } | undefined;
if (membership) {
- return db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(membership.plan_id);
+ return db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(membership.plan_id) as VacayPlan;
}
return getOwnPlan(userId);
}
-function getActivePlanId(userId) {
+function getActivePlanId(userId: number): number {
return getActivePlan(userId).id;
}
-// Get all users in a plan (owner + accepted members)
-function getPlanUsers(planId) {
- const plan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId);
+function getPlanUsers(planId: number) {
+ const plan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId) as VacayPlan | undefined;
if (!plan) return [];
- const owner = db.prepare('SELECT id, username, email FROM users WHERE id = ?').get(plan.owner_id);
+ const owner = db.prepare('SELECT id, username, email FROM users WHERE id = ?').get(plan.owner_id) as VacayUser;
const members = db.prepare(`
SELECT u.id, u.username, u.email FROM vacay_plan_members m
JOIN users u ON m.user_id = u.id
WHERE m.plan_id = ? AND m.status = 'accepted'
- `).all(planId);
+ `).all(planId) as VacayUser[];
return [owner, ...members];
}
-// ── Plan ───────────────────────────────────────────────────
-
-router.get('/plan', (req, res) => {
- const plan = getActivePlan(req.user.id);
+router.get('/plan', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const plan = getActivePlan(authReq.user.id);
const activePlanId = plan.id;
- // Get user colors
const users = getPlanUsers(activePlanId).map(u => {
- const colorRow = db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(u.id, activePlanId);
+ const colorRow = db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(u.id, activePlanId) as { color: string } | undefined;
return { ...u, color: colorRow?.color || '#6366f1' };
});
- // Pending invites (sent from this plan)
const pendingInvites = db.prepare(`
SELECT m.id, m.user_id, u.username, u.email, m.created_at
FROM vacay_plan_members m JOIN users u ON m.user_id = u.id
WHERE m.plan_id = ? AND m.status = 'pending'
`).all(activePlanId);
- // Pending invites FOR this user (from others)
const incomingInvites = db.prepare(`
SELECT m.id, m.plan_id, u.username, u.email, m.created_at
FROM vacay_plan_members m
JOIN vacay_plans p ON m.plan_id = p.id
JOIN users u ON p.owner_id = u.id
WHERE m.user_id = ? AND m.status = 'pending'
- `).all(req.user.id);
+ `).all(authReq.user.id);
res.json({
plan: {
@@ -106,22 +134,22 @@ router.get('/plan', (req, res) => {
users,
pendingInvites,
incomingInvites,
- isOwner: plan.owner_id === req.user.id,
+ isOwner: plan.owner_id === authReq.user.id,
isFused: users.length > 1,
});
});
-router.put('/plan', async (req, res) => {
- const planId = getActivePlanId(req.user.id);
+router.put('/plan', async (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const planId = getActivePlanId(authReq.user.id);
const { block_weekends, holidays_enabled, holidays_region, company_holidays_enabled, carry_over_enabled } = req.body;
- const updates = [];
- const params = [];
+ const updates: string[] = [];
+ const params: (string | number)[] = [];
if (block_weekends !== undefined) { updates.push('block_weekends = ?'); params.push(block_weekends ? 1 : 0); }
if (holidays_enabled !== undefined) { updates.push('holidays_enabled = ?'); params.push(holidays_enabled ? 1 : 0); }
if (holidays_region !== undefined) { updates.push('holidays_region = ?'); params.push(holidays_region); }
if (company_holidays_enabled !== undefined) { updates.push('company_holidays_enabled = ?'); params.push(company_holidays_enabled ? 1 : 0); }
-
if (carry_over_enabled !== undefined) { updates.push('carry_over_enabled = ?'); params.push(carry_over_enabled ? 1 : 0); }
if (updates.length > 0) {
@@ -129,32 +157,28 @@ router.put('/plan', async (req, res) => {
db.prepare(`UPDATE vacay_plans SET ${updates.join(', ')} WHERE id = ?`).run(...params);
}
- // If company holidays re-enabled, remove vacation entries that overlap with company holidays
if (company_holidays_enabled === true) {
- const companyDates = db.prepare('SELECT date FROM vacay_company_holidays WHERE plan_id = ?').all(planId);
+ const companyDates = db.prepare('SELECT date FROM vacay_company_holidays WHERE plan_id = ?').all(planId) as { date: string }[];
for (const { date } of companyDates) {
db.prepare('DELETE FROM vacay_entries WHERE plan_id = ? AND date = ?').run(planId, date);
}
}
- // If public holidays enabled (or region changed), remove vacation entries that land on holidays
- // Only if a full region is selected (for countries that require it)
- const updatedPlan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId);
+ const updatedPlan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId) as VacayPlan;
if (updatedPlan.holidays_enabled && updatedPlan.holidays_region) {
const country = updatedPlan.holidays_region.split('-')[0];
const region = updatedPlan.holidays_region.includes('-') ? updatedPlan.holidays_region : null;
- const years = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ?').all(planId);
+ const years = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ?').all(planId) as { year: number }[];
for (const { year } of years) {
try {
const cacheKey = `${year}-${country}`;
- let holidays = holidayCache.get(cacheKey)?.data;
+ let holidays = holidayCache.get(cacheKey)?.data as Holiday[] | undefined;
if (!holidays) {
const resp = await fetch(`https://date.nager.at/api/v3/PublicHolidays/${year}/${country}`);
- holidays = await resp.json();
+ holidays = await resp.json() as Holiday[];
holidayCache.set(cacheKey, { data: holidays, time: Date.now() });
}
- const hasRegions = holidays.some(h => h.counties && h.counties.length > 0);
- // If country has regions but no region selected, skip cleanup
+ const hasRegions = (holidays as Holiday[]).some((h: Holiday) => h.counties && h.counties.length > 0);
if (hasRegions && !region) continue;
for (const h of holidays) {
if (h.global || !h.counties || (region && h.counties.includes(region))) {
@@ -166,21 +190,19 @@ router.put('/plan', async (req, res) => {
}
}
- // If carry-over was just disabled, reset all carried_over values to 0
if (carry_over_enabled === false) {
db.prepare('UPDATE vacay_user_years SET carried_over = 0 WHERE plan_id = ?').run(planId);
}
- // If carry-over was just enabled, recalculate all years
if (carry_over_enabled === true) {
- const years = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ? ORDER BY year').all(planId);
+ const years = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ? ORDER BY year').all(planId) as { year: number }[];
const users = getPlanUsers(planId);
for (let i = 0; i < years.length - 1; i++) {
const yr = years[i].year;
const nextYr = years[i + 1].year;
for (const u of users) {
- const used = db.prepare("SELECT COUNT(*) as count FROM vacay_entries WHERE user_id = ? AND plan_id = ? AND date LIKE ?").get(u.id, planId, `${yr}-%`).count;
- const config = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?').get(u.id, planId, yr);
+ const used = (db.prepare("SELECT COUNT(*) as count FROM vacay_entries WHERE user_id = ? AND plan_id = ? AND date LIKE ?").get(u.id, planId, `${yr}-%`) as { count: number }).count;
+ const config = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?').get(u.id, planId, yr) as VacayUserYear | undefined;
const total = (config ? config.vacation_days : 30) + (config ? config.carried_over : 0);
const carry = Math.max(0, total - used);
db.prepare(`
@@ -191,20 +213,19 @@ router.put('/plan', async (req, res) => {
}
}
- notifyPlanUsers(planId, req.headers['x-socket-id'], 'vacay:settings');
+ notifyPlanUsers(planId, req.headers['x-socket-id'] as string, 'vacay:settings');
- const updated = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId);
+ const updated = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId) as VacayPlan;
res.json({
plan: { ...updated, block_weekends: !!updated.block_weekends, holidays_enabled: !!updated.holidays_enabled, company_holidays_enabled: !!updated.company_holidays_enabled, carry_over_enabled: !!updated.carry_over_enabled }
});
});
-// ── User color ─────────────────────────────────────────────
-
-router.put('/color', (req, res) => {
+router.put('/color', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { color, target_user_id } = req.body;
- const planId = getActivePlanId(req.user.id);
- const userId = target_user_id ? parseInt(target_user_id) : req.user.id;
+ const planId = getActivePlanId(authReq.user.id);
+ const userId = target_user_id ? parseInt(target_user_id) : authReq.user.id;
const planUsers = getPlanUsers(planId);
if (!planUsers.find(u => u.id === userId)) {
return res.status(403).json({ error: 'User not in plan' });
@@ -213,42 +234,37 @@ router.put('/color', (req, res) => {
INSERT INTO vacay_user_colors (user_id, plan_id, color) VALUES (?, ?, ?)
ON CONFLICT(user_id, plan_id) DO UPDATE SET color = excluded.color
`).run(userId, planId, color || '#6366f1');
- notifyPlanUsers(planId, req.headers['x-socket-id'], 'vacay:update');
+ notifyPlanUsers(planId, req.headers['x-socket-id'] as string, 'vacay:update');
res.json({ success: true });
});
-// ── Invite / Accept / Decline / Dissolve ───────────────────
-
-// Invite a user
-router.post('/invite', (req, res) => {
+router.post('/invite', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { user_id } = req.body;
if (!user_id) return res.status(400).json({ error: 'user_id required' });
- if (user_id === req.user.id) return res.status(400).json({ error: 'Cannot invite yourself' });
+ if (user_id === authReq.user.id) return res.status(400).json({ error: 'Cannot invite yourself' });
const targetUser = db.prepare('SELECT id, username FROM users WHERE id = ?').get(user_id);
if (!targetUser) return res.status(404).json({ error: 'User not found' });
- const plan = getActivePlan(req.user.id);
+ const plan = getActivePlan(authReq.user.id);
- // Check if already invited or member
- const existing = db.prepare('SELECT id, status FROM vacay_plan_members WHERE plan_id = ? AND user_id = ?').get(plan.id, user_id);
+ const existing = db.prepare('SELECT id, status FROM vacay_plan_members WHERE plan_id = ? AND user_id = ?').get(plan.id, user_id) as { id: number; status: string } | undefined;
if (existing) {
if (existing.status === 'accepted') return res.status(400).json({ error: 'Already fused' });
if (existing.status === 'pending') return res.status(400).json({ error: 'Invite already pending' });
}
- // Check if target user is already fused with someone else
const targetFusion = db.prepare("SELECT id FROM vacay_plan_members WHERE user_id = ? AND status = 'accepted'").get(user_id);
if (targetFusion) return res.status(400).json({ error: 'User is already fused with another plan' });
db.prepare('INSERT INTO vacay_plan_members (plan_id, user_id, status) VALUES (?, ?, ?)').run(plan.id, user_id, 'pending');
- // Broadcast via WebSocket if available
try {
const { broadcastToUser } = require('../websocket');
broadcastToUser(user_id, {
type: 'vacay:invite',
- from: { id: req.user.id, username: req.user.username },
+ from: { id: authReq.user.id, username: authReq.user.username },
planId: plan.id,
});
} catch { /* websocket not available */ }
@@ -256,69 +272,59 @@ router.post('/invite', (req, res) => {
res.json({ success: true });
});
-// Accept invite
-router.post('/invite/accept', (req, res) => {
+router.post('/invite/accept', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { plan_id } = req.body;
- const invite = db.prepare("SELECT * FROM vacay_plan_members WHERE plan_id = ? AND user_id = ? AND status = 'pending'").get(plan_id, req.user.id);
+ const invite = db.prepare("SELECT * FROM vacay_plan_members WHERE plan_id = ? AND user_id = ? AND status = 'pending'").get(plan_id, authReq.user.id) as VacayPlanMember | undefined;
if (!invite) return res.status(404).json({ error: 'No pending invite' });
- // Accept
db.prepare("UPDATE vacay_plan_members SET status = 'accepted' WHERE id = ?").run(invite.id);
- // Migrate user's own entries into the fused plan
- const ownPlan = db.prepare('SELECT id FROM vacay_plans WHERE owner_id = ?').get(req.user.id);
+ const ownPlan = db.prepare('SELECT id FROM vacay_plans WHERE owner_id = ?').get(authReq.user.id) as { id: number } | undefined;
if (ownPlan && ownPlan.id !== plan_id) {
- // Move entries
- db.prepare('UPDATE vacay_entries SET plan_id = ? WHERE plan_id = ? AND user_id = ?').run(plan_id, ownPlan.id, req.user.id);
- // Copy year configs
- const ownYears = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ?').all(req.user.id, ownPlan.id);
+ db.prepare('UPDATE vacay_entries SET plan_id = ? WHERE plan_id = ? AND user_id = ?').run(plan_id, ownPlan.id, authReq.user.id);
+ const ownYears = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ?').all(authReq.user.id, ownPlan.id) as VacayUserYear[];
for (const y of ownYears) {
- db.prepare('INSERT OR IGNORE INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, ?, ?)').run(req.user.id, plan_id, y.year, y.vacation_days, y.carried_over);
+ db.prepare('INSERT OR IGNORE INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, ?, ?)').run(authReq.user.id, plan_id, y.year, y.vacation_days, y.carried_over);
}
- // Copy color
- const colorRow = db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(req.user.id, ownPlan.id);
+ const colorRow = db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(authReq.user.id, ownPlan.id) as { color: string } | undefined;
if (colorRow) {
- db.prepare('INSERT OR IGNORE INTO vacay_user_colors (user_id, plan_id, color) VALUES (?, ?, ?)').run(req.user.id, plan_id, colorRow.color);
+ db.prepare('INSERT OR IGNORE INTO vacay_user_colors (user_id, plan_id, color) VALUES (?, ?, ?)').run(authReq.user.id, plan_id, colorRow.color);
}
}
- // Auto-change color if it collides with existing plan users
const COLORS = ['#6366f1','#ec4899','#14b8a6','#8b5cf6','#ef4444','#3b82f6','#22c55e','#06b6d4','#f43f5e','#a855f7','#10b981','#0ea5e9','#64748b','#be185d','#0d9488'];
- const existingColors = db.prepare('SELECT color FROM vacay_user_colors WHERE plan_id = ? AND user_id != ?').all(plan_id, req.user.id).map(r => r.color);
- const myColor = db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(req.user.id, plan_id);
+ const existingColors = (db.prepare('SELECT color FROM vacay_user_colors WHERE plan_id = ? AND user_id != ?').all(plan_id, authReq.user.id) as { color: string }[]).map(r => r.color);
+ const myColor = db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(authReq.user.id, plan_id) as { color: string } | undefined;
if (myColor && existingColors.includes(myColor.color)) {
const available = COLORS.find(c => !existingColors.includes(c));
if (available) {
- db.prepare('UPDATE vacay_user_colors SET color = ? WHERE user_id = ? AND plan_id = ?').run(available, req.user.id, plan_id);
+ db.prepare('UPDATE vacay_user_colors SET color = ? WHERE user_id = ? AND plan_id = ?').run(available, authReq.user.id, plan_id);
}
}
- // Ensure years exist in target plan
- const targetYears = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ?').all(plan_id);
+ const targetYears = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ?').all(plan_id) as { year: number }[];
for (const y of targetYears) {
- db.prepare('INSERT OR IGNORE INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, 30, 0)').run(req.user.id, plan_id, y.year);
+ db.prepare('INSERT OR IGNORE INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, 30, 0)').run(authReq.user.id, plan_id, y.year);
}
- // Notify all plan users (not just owner)
- notifyPlanUsers(plan_id, req.headers['x-socket-id'], 'vacay:accepted');
+ notifyPlanUsers(plan_id, req.headers['x-socket-id'] as string, 'vacay:accepted');
res.json({ success: true });
});
-// Decline invite
-router.post('/invite/decline', (req, res) => {
+router.post('/invite/decline', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { plan_id } = req.body;
- db.prepare("DELETE FROM vacay_plan_members WHERE plan_id = ? AND user_id = ? AND status = 'pending'").run(plan_id, req.user.id);
-
- notifyPlanUsers(plan_id, req.headers['x-socket-id'], 'vacay:declined');
-
+ db.prepare("DELETE FROM vacay_plan_members WHERE plan_id = ? AND user_id = ? AND status = 'pending'").run(plan_id, authReq.user.id);
+ notifyPlanUsers(plan_id, req.headers['x-socket-id'] as string, 'vacay:declined');
res.json({ success: true });
});
-// Cancel pending invite (by inviter)
-router.post('/invite/cancel', (req, res) => {
+router.post('/invite/cancel', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { user_id } = req.body;
- const plan = getActivePlan(req.user.id);
+ const plan = getActivePlan(authReq.user.id);
db.prepare("DELETE FROM vacay_plan_members WHERE plan_id = ? AND user_id = ? AND status = 'pending'").run(plan.id, user_id);
try {
@@ -329,50 +335,44 @@ router.post('/invite/cancel', (req, res) => {
res.json({ success: true });
});
-// Dissolve fusion
-router.post('/dissolve', (req, res) => {
- const plan = getActivePlan(req.user.id);
- const isOwner = plan.owner_id === req.user.id;
+router.post('/dissolve', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const plan = getActivePlan(authReq.user.id);
+ const isOwnerFlag = plan.owner_id === authReq.user.id;
- // Collect all user IDs and company holidays before dissolving
const allUserIds = getPlanUsers(plan.id).map(u => u.id);
- const companyHolidays = db.prepare('SELECT date, note FROM vacay_company_holidays WHERE plan_id = ?').all(plan.id);
+ const companyHolidays = db.prepare('SELECT date, note FROM vacay_company_holidays WHERE plan_id = ?').all(plan.id) as { date: string; note: string }[];
- if (isOwner) {
- const members = db.prepare("SELECT user_id FROM vacay_plan_members WHERE plan_id = ? AND status = 'accepted'").all(plan.id);
+ if (isOwnerFlag) {
+ const members = db.prepare("SELECT user_id FROM vacay_plan_members WHERE plan_id = ? AND status = 'accepted'").all(plan.id) as { user_id: number }[];
for (const m of members) {
const memberPlan = getOwnPlan(m.user_id);
db.prepare('UPDATE vacay_entries SET plan_id = ? WHERE plan_id = ? AND user_id = ?').run(memberPlan.id, plan.id, m.user_id);
- // Copy company holidays to member's own plan
for (const ch of companyHolidays) {
db.prepare('INSERT OR IGNORE INTO vacay_company_holidays (plan_id, date, note) VALUES (?, ?, ?)').run(memberPlan.id, ch.date, ch.note);
}
}
db.prepare('DELETE FROM vacay_plan_members WHERE plan_id = ?').run(plan.id);
} else {
- const ownPlan = getOwnPlan(req.user.id);
- db.prepare('UPDATE vacay_entries SET plan_id = ? WHERE plan_id = ? AND user_id = ?').run(ownPlan.id, plan.id, req.user.id);
- // Copy company holidays to own plan
+ const ownPlan = getOwnPlan(authReq.user.id);
+ db.prepare('UPDATE vacay_entries SET plan_id = ? WHERE plan_id = ? AND user_id = ?').run(ownPlan.id, plan.id, authReq.user.id);
for (const ch of companyHolidays) {
db.prepare('INSERT OR IGNORE INTO vacay_company_holidays (plan_id, date, note) VALUES (?, ?, ?)').run(ownPlan.id, ch.date, ch.note);
}
- db.prepare("DELETE FROM vacay_plan_members WHERE plan_id = ? AND user_id = ?").run(plan.id, req.user.id);
+ db.prepare("DELETE FROM vacay_plan_members WHERE plan_id = ? AND user_id = ?").run(plan.id, authReq.user.id);
}
- // Notify all former plan members
try {
const { broadcastToUser } = require('../websocket');
- allUserIds.filter(id => id !== req.user.id).forEach(id => broadcastToUser(id, { type: 'vacay:dissolved' }));
+ allUserIds.filter(id => id !== authReq.user.id).forEach(id => broadcastToUser(id, { type: 'vacay:dissolved' }));
} catch { /* */ }
res.json({ success: true });
});
-// ── Available users to invite ──────────────────────────────
-
-router.get('/available-users', (req, res) => {
- const planId = getActivePlanId(req.user.id);
- // All users except: self, already in this plan, already fused elsewhere
+router.get('/available-users', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const planId = getActivePlanId(authReq.user.id);
const users = db.prepare(`
SELECT u.id, u.username, u.email FROM users u
WHERE u.id != ?
@@ -382,34 +382,33 @@ router.get('/available-users', (req, res) => {
SELECT plan_id FROM vacay_plan_members WHERE status = 'accepted'
))
ORDER BY u.username
- `).all(req.user.id, planId);
+ `).all(authReq.user.id, planId);
res.json({ users });
});
-// ── Years ──────────────────────────────────────────────────
-
-router.get('/years', (req, res) => {
- const planId = getActivePlanId(req.user.id);
- const years = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ? ORDER BY year').all(planId);
+router.get('/years', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
+ const planId = getActivePlanId(authReq.user.id);
+ const years = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ? ORDER BY year').all(planId) as { year: number }[];
res.json({ years: years.map(y => y.year) });
});
-router.post('/years', (req, res) => {
+router.post('/years', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { year } = req.body;
if (!year) return res.status(400).json({ error: 'Year required' });
- const planId = getActivePlanId(req.user.id);
+ const planId = getActivePlanId(authReq.user.id);
try {
db.prepare('INSERT INTO vacay_years (plan_id, year) VALUES (?, ?)').run(planId, year);
- const plan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId);
+ const plan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId) as VacayPlan | undefined;
const carryOverEnabled = plan ? !!plan.carry_over_enabled : true;
const users = getPlanUsers(planId);
for (const u of users) {
- // Calculate carry-over from previous year if enabled
let carriedOver = 0;
if (carryOverEnabled) {
- const prevConfig = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?').get(u.id, planId, year - 1);
+ const prevConfig = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?').get(u.id, planId, year - 1) as VacayUserYear | undefined;
if (prevConfig) {
- const used = db.prepare("SELECT COUNT(*) as count FROM vacay_entries WHERE user_id = ? AND plan_id = ? AND date LIKE ?").get(u.id, planId, `${year - 1}-%`).count;
+ const used = (db.prepare("SELECT COUNT(*) as count FROM vacay_entries WHERE user_id = ? AND plan_id = ? AND date LIKE ?").get(u.id, planId, `${year - 1}-%`) as { count: number }).count;
const total = prevConfig.vacation_days + prevConfig.carried_over;
carriedOver = Math.max(0, total - used);
}
@@ -417,27 +416,27 @@ router.post('/years', (req, res) => {
db.prepare('INSERT OR IGNORE INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, 30, ?)').run(u.id, planId, year, carriedOver);
}
} catch { /* exists */ }
- notifyPlanUsers(planId, req.headers['x-socket-id'], 'vacay:settings');
- const years = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ? ORDER BY year').all(planId);
+ notifyPlanUsers(planId, req.headers['x-socket-id'] as string, 'vacay:settings');
+ const years = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ? ORDER BY year').all(planId) as { year: number }[];
res.json({ years: years.map(y => y.year) });
});
-router.delete('/years/:year', (req, res) => {
+router.delete('/years/:year', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const year = parseInt(req.params.year);
- const planId = getActivePlanId(req.user.id);
+ const planId = getActivePlanId(authReq.user.id);
db.prepare('DELETE FROM vacay_years WHERE plan_id = ? AND year = ?').run(planId, year);
db.prepare("DELETE FROM vacay_entries WHERE plan_id = ? AND date LIKE ?").run(planId, `${year}-%`);
db.prepare("DELETE FROM vacay_company_holidays WHERE plan_id = ? AND date LIKE ?").run(planId, `${year}-%`);
- notifyPlanUsers(planId, req.headers['x-socket-id'], 'vacay:settings');
- const years = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ? ORDER BY year').all(planId);
+ notifyPlanUsers(planId, req.headers['x-socket-id'] as string, 'vacay:settings');
+ const years = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ? ORDER BY year').all(planId) as { year: number }[];
res.json({ years: years.map(y => y.year) });
});
-// ── Entries ────────────────────────────────────────────────
-
-router.get('/entries/:year', (req, res) => {
+router.get('/entries/:year', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const year = req.params.year;
- const planId = getActivePlanId(req.user.id);
+ const planId = getActivePlanId(authReq.user.id);
const entries = db.prepare(`
SELECT e.*, u.username as person_name, COALESCE(c.color, '#6366f1') as person_color
FROM vacay_entries e
@@ -449,13 +448,13 @@ router.get('/entries/:year', (req, res) => {
res.json({ entries, companyHolidays });
});
-router.post('/entries/toggle', (req, res) => {
+router.post('/entries/toggle', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { date, target_user_id } = req.body;
if (!date) return res.status(400).json({ error: 'date required' });
- const planId = getActivePlanId(req.user.id);
- // Allow toggling for another user if they are in the same plan
- let userId = req.user.id;
- if (target_user_id && parseInt(target_user_id) !== req.user.id) {
+ const planId = getActivePlanId(authReq.user.id);
+ let userId = authReq.user.id;
+ if (target_user_id && parseInt(target_user_id) !== authReq.user.id) {
const planUsers = getPlanUsers(planId);
const tid = parseInt(target_user_id);
if (!planUsers.find(u => u.id === tid)) {
@@ -463,54 +462,52 @@ router.post('/entries/toggle', (req, res) => {
}
userId = tid;
}
- const existing = db.prepare('SELECT id FROM vacay_entries WHERE user_id = ? AND date = ? AND plan_id = ?').get(userId, date, planId);
+ const existing = db.prepare('SELECT id FROM vacay_entries WHERE user_id = ? AND date = ? AND plan_id = ?').get(userId, date, planId) as { id: number } | undefined;
if (existing) {
db.prepare('DELETE FROM vacay_entries WHERE id = ?').run(existing.id);
- notifyPlanUsers(planId, req.headers['x-socket-id']);
+ notifyPlanUsers(planId, req.headers['x-socket-id'] as string);
res.json({ action: 'removed' });
} else {
db.prepare('INSERT INTO vacay_entries (plan_id, user_id, date, note) VALUES (?, ?, ?, ?)').run(planId, userId, date, '');
- notifyPlanUsers(planId, req.headers['x-socket-id']);
+ notifyPlanUsers(planId, req.headers['x-socket-id'] as string);
res.json({ action: 'added' });
}
});
-router.post('/entries/company-holiday', (req, res) => {
+router.post('/entries/company-holiday', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const { date, note } = req.body;
- const planId = getActivePlanId(req.user.id);
- const existing = db.prepare('SELECT id FROM vacay_company_holidays WHERE plan_id = ? AND date = ?').get(planId, date);
+ const planId = getActivePlanId(authReq.user.id);
+ const existing = db.prepare('SELECT id FROM vacay_company_holidays WHERE plan_id = ? AND date = ?').get(planId, date) as { id: number } | undefined;
if (existing) {
db.prepare('DELETE FROM vacay_company_holidays WHERE id = ?').run(existing.id);
- notifyPlanUsers(planId, req.headers['x-socket-id']);
+ notifyPlanUsers(planId, req.headers['x-socket-id'] as string);
res.json({ action: 'removed' });
} else {
db.prepare('INSERT INTO vacay_company_holidays (plan_id, date, note) VALUES (?, ?, ?)').run(planId, date, note || '');
- // Remove any vacation entries on this date
db.prepare('DELETE FROM vacay_entries WHERE plan_id = ? AND date = ?').run(planId, date);
- notifyPlanUsers(planId, req.headers['x-socket-id']);
+ notifyPlanUsers(planId, req.headers['x-socket-id'] as string);
res.json({ action: 'added' });
}
});
-// ── Stats ──────────────────────────────────────────────────
-
-router.get('/stats/:year', (req, res) => {
+router.get('/stats/:year', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const year = parseInt(req.params.year);
- const planId = getActivePlanId(req.user.id);
- const plan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId);
+ const planId = getActivePlanId(authReq.user.id);
+ const plan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId) as VacayPlan | undefined;
const carryOverEnabled = plan ? !!plan.carry_over_enabled : true;
const users = getPlanUsers(planId);
const stats = users.map(u => {
- const used = db.prepare("SELECT COUNT(*) as count FROM vacay_entries WHERE user_id = ? AND plan_id = ? AND date LIKE ?").get(u.id, planId, `${year}-%`).count;
- const config = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?').get(u.id, planId, year);
+ const used = (db.prepare("SELECT COUNT(*) as count FROM vacay_entries WHERE user_id = ? AND plan_id = ? AND date LIKE ?").get(u.id, planId, `${year}-%`) as { count: number }).count;
+ const config = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?').get(u.id, planId, year) as VacayUserYear | undefined;
const vacationDays = config ? config.vacation_days : 30;
const carriedOver = carryOverEnabled ? (config ? config.carried_over : 0) : 0;
const total = vacationDays + carriedOver;
const remaining = total - used;
- const colorRow = db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(u.id, planId);
+ const colorRow = db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(u.id, planId) as { color: string } | undefined;
- // Auto-update carry-over into next year (only if enabled)
const nextYearExists = db.prepare('SELECT id FROM vacay_years WHERE plan_id = ? AND year = ?').get(planId, year + 1);
if (nextYearExists && carryOverEnabled) {
const carry = Math.max(0, remaining);
@@ -530,12 +527,12 @@ router.get('/stats/:year', (req, res) => {
res.json({ stats });
});
-// Update vacation days for a year (own or fused partner)
-router.put('/stats/:year', (req, res) => {
+router.put('/stats/:year', (req: Request, res: Response) => {
+ const authReq = req as AuthRequest;
const year = parseInt(req.params.year);
const { vacation_days, target_user_id } = req.body;
- const planId = getActivePlanId(req.user.id);
- const userId = target_user_id ? parseInt(target_user_id) : req.user.id;
+ const planId = getActivePlanId(authReq.user.id);
+ const userId = target_user_id ? parseInt(target_user_id) : authReq.user.id;
const planUsers = getPlanUsers(planId);
if (!planUsers.find(u => u.id === userId)) {
return res.status(403).json({ error: 'User not in plan' });
@@ -544,13 +541,11 @@ router.put('/stats/:year', (req, res) => {
INSERT INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, ?, 0)
ON CONFLICT(user_id, plan_id, year) DO UPDATE SET vacation_days = excluded.vacation_days
`).run(userId, planId, year, vacation_days);
- notifyPlanUsers(planId, req.headers['x-socket-id']);
+ notifyPlanUsers(planId, req.headers['x-socket-id'] as string);
res.json({ success: true });
});
-// ── Public Holidays API (proxy to Nager.Date) ─────────────
-
-router.get('/holidays/countries', async (req, res) => {
+router.get('/holidays/countries', async (_req: Request, res: Response) => {
const cacheKey = 'countries';
const cached = holidayCache.get(cacheKey);
if (cached && Date.now() - cached.time < CACHE_TTL) return res.json(cached.data);
@@ -564,7 +559,7 @@ router.get('/holidays/countries', async (req, res) => {
}
});
-router.get('/holidays/:year/:country', async (req, res) => {
+router.get('/holidays/:year/:country', async (req: Request, res: Response) => {
const { year, country } = req.params;
const cacheKey = `${year}-${country}`;
const cached = holidayCache.get(cacheKey);
@@ -579,4 +574,4 @@ router.get('/holidays/:year/:country', async (req, res) => {
}
});
-module.exports = router;
+export default router;
diff --git a/server/src/routes/weather.js b/server/src/routes/weather.ts
similarity index 66%
rename from server/src/routes/weather.js
rename to server/src/routes/weather.ts
index d20d748b4..05771611d 100644
--- a/server/src/routes/weather.js
+++ b/server/src/routes/weather.ts
@@ -1,23 +1,89 @@
-const express = require('express');
-const fetch = require('node-fetch');
-const { authenticate } = require('../middleware/auth');
+import express, { Request, Response } from 'express';
+import fetch from 'node-fetch';
+import { authenticate } from '../middleware/auth';
const router = express.Router();
-// --------------- In-memory weather cache ---------------
-const weatherCache = new Map();
+interface WeatherResult {
+ temp: number;
+ temp_max?: number;
+ temp_min?: number;
+ main: string;
+ description: string;
+ type: string;
+ sunrise?: string | null;
+ sunset?: string | null;
+ precipitation_sum?: number;
+ precipitation_probability_max?: number;
+ wind_max?: number;
+ hourly?: HourlyEntry[];
+ error?: string;
+}
+
+interface HourlyEntry {
+ hour: number;
+ temp: number;
+ precipitation: number;
+ precipitation_probability: number;
+ main: string;
+ wind: number;
+ humidity: number;
+}
+
+interface OpenMeteoForecast {
+ error?: boolean;
+ reason?: string;
+ current?: { temperature_2m: number; weathercode: number };
+ daily?: {
+ time: string[];
+ temperature_2m_max: number[];
+ temperature_2m_min: number[];
+ weathercode: number[];
+ precipitation_sum?: number[];
+ precipitation_probability_max?: number[];
+ windspeed_10m_max?: number[];
+ sunrise?: string[];
+ sunset?: string[];
+ };
+ hourly?: {
+ time: string[];
+ temperature_2m: number[];
+ precipitation_probability?: number[];
+ precipitation?: number[];
+ weathercode?: number[];
+ windspeed_10m?: number[];
+ relativehumidity_2m?: number[];
+ };
+}
+
+const weatherCache = new Map<string, { data: WeatherResult; expiresAt: number }>();
+const CACHE_MAX_ENTRIES = 1000;
+const CACHE_PRUNE_TARGET = 500;
+const CACHE_CLEANUP_INTERVAL = 5 * 60 * 1000; // 5 minutes
+
+setInterval(() => {
+ const now = Date.now();
+ for (const [key, entry] of weatherCache) {
+ if (now > entry.expiresAt) weatherCache.delete(key);
+ }
+ if (weatherCache.size > CACHE_MAX_ENTRIES) {
+ const entries = [...weatherCache.entries()].sort((a, b) => a[1].expiresAt - b[1].expiresAt);
+ const toDelete = entries.slice(0, entries.length - CACHE_PRUNE_TARGET);
+ toDelete.forEach(([key]) => weatherCache.delete(key));
+ }
+}, CACHE_CLEANUP_INTERVAL);
-const TTL_FORECAST_MS = 60 * 60 * 1000; // 1 hour
-const TTL_CURRENT_MS = 15 * 60 * 1000; // 15 minutes
-const TTL_CLIMATE_MS = 24 * 60 * 60 * 1000; // 24 hours (historical data doesn't change)
+const TTL_FORECAST_MS = 60 * 60 * 1000; // 1 hour
+const TTL_CURRENT_MS = 15 * 60 * 1000; // 15 minutes
+const TTL_CLIMATE_MS = 24 * 60 * 60 * 1000; // 24 hours
-function cacheKey(lat, lng, date) {
+function cacheKey(lat: string, lng: string, date?: string): string {
const rlat = parseFloat(lat).toFixed(2);
const rlng = parseFloat(lng).toFixed(2);
return `${rlat}_${rlng}_${date || 'current'}`;
}
-function getCached(key) {
+function getCached(key: string) {
const entry = weatherCache.get(key);
if (!entry) return null;
if (Date.now() > entry.expiresAt) {
@@ -27,116 +93,56 @@ function getCached(key) {
return entry.data;
}
-function setCache(key, data, ttlMs) {
+function setCache(key: string, data: WeatherResult, ttlMs: number) {
weatherCache.set(key, { data, expiresAt: Date.now() + ttlMs });
}
-// WMO weather code mapping → condition string used by client icon map
-const WMO_MAP = {
- 0: 'Clear',
- 1: 'Clear', // mainly clear
- 2: 'Clouds', // partly cloudy
- 3: 'Clouds', // overcast
- 45: 'Fog',
- 48: 'Fog',
- 51: 'Drizzle',
- 53: 'Drizzle',
- 55: 'Drizzle',
- 56: 'Drizzle', // freezing drizzle
- 57: 'Drizzle',
- 61: 'Rain',
- 63: 'Rain',
- 65: 'Rain', // heavy rain
- 66: 'Rain', // freezing rain
- 67: 'Rain',
- 71: 'Snow',
- 73: 'Snow',
- 75: 'Snow',
- 77: 'Snow', // snow grains
- 80: 'Rain', // rain showers
- 81: 'Rain',
- 82: 'Rain',
- 85: 'Snow', // snow showers
- 86: 'Snow',
- 95: 'Thunderstorm',
- 96: 'Thunderstorm',
- 99: 'Thunderstorm',
+const WMO_MAP: Record<number, string> = {
+ 0: 'Clear', 1: 'Clear', 2: 'Clouds', 3: 'Clouds',
+ 45: 'Fog', 48: 'Fog',
+ 51: 'Drizzle', 53: 'Drizzle', 55: 'Drizzle', 56: 'Drizzle', 57: 'Drizzle',
+ 61: 'Rain', 63: 'Rain', 65: 'Rain', 66: 'Rain', 67: 'Rain',
+ 71: 'Snow', 73: 'Snow', 75: 'Snow', 77: 'Snow',
+ 80: 'Rain', 81: 'Rain', 82: 'Rain',
+ 85: 'Snow', 86: 'Snow',
+ 95: 'Thunderstorm', 96: 'Thunderstorm', 99: 'Thunderstorm',
};
-const WMO_DESCRIPTION_DE = {
- 0: 'Klar',
- 1: 'Überwiegend klar',
- 2: 'Teilweise bewölkt',
- 3: 'Bewölkt',
- 45: 'Nebel',
- 48: 'Nebel mit Reif',
- 51: 'Leichter Nieselregen',
- 53: 'Nieselregen',
- 55: 'Starker Nieselregen',
- 56: 'Gefrierender Nieselregen',
- 57: 'Starker gefr. Nieselregen',
- 61: 'Leichter Regen',
- 63: 'Regen',
- 65: 'Starker Regen',
- 66: 'Gefrierender Regen',
- 67: 'Starker gefr. Regen',
- 71: 'Leichter Schneefall',
- 73: 'Schneefall',
- 75: 'Starker Schneefall',
- 77: 'Schneekörner',
- 80: 'Leichte Regenschauer',
- 81: 'Regenschauer',
- 82: 'Starke Regenschauer',
- 85: 'Leichte Schneeschauer',
- 86: 'Starke Schneeschauer',
- 95: 'Gewitter',
- 96: 'Gewitter mit Hagel',
- 99: 'Starkes Gewitter mit Hagel',
+const WMO_DESCRIPTION_DE: Record<number, string> = {
+ 0: 'Klar', 1: 'Uberwiegend klar', 2: 'Teilweise bewolkt', 3: 'Bewolkt',
+ 45: 'Nebel', 48: 'Nebel mit Reif',
+ 51: 'Leichter Nieselregen', 53: 'Nieselregen', 55: 'Starker Nieselregen',
+ 56: 'Gefrierender Nieselregen', 57: 'Starker gefr. Nieselregen',
+ 61: 'Leichter Regen', 63: 'Regen', 65: 'Starker Regen',
+ 66: 'Gefrierender Regen', 67: 'Starker gefr. Regen',
+ 71: 'Leichter Schneefall', 73: 'Schneefall', 75: 'Starker Schneefall', 77: 'Schneekorner',
+ 80: 'Leichte Regenschauer', 81: 'Regenschauer', 82: 'Starke Regenschauer',
+ 85: 'Leichte Schneeschauer', 86: 'Starke Schneeschauer',
+ 95: 'Gewitter', 96: 'Gewitter mit Hagel', 99: 'Starkes Gewitter mit Hagel',
};
-const WMO_DESCRIPTION_EN = {
- 0: 'Clear sky',
- 1: 'Mainly clear',
- 2: 'Partly cloudy',
- 3: 'Overcast',
- 45: 'Fog',
- 48: 'Rime fog',
- 51: 'Light drizzle',
- 53: 'Drizzle',
- 55: 'Heavy drizzle',
- 56: 'Freezing drizzle',
- 57: 'Heavy freezing drizzle',
- 61: 'Light rain',
- 63: 'Rain',
- 65: 'Heavy rain',
- 66: 'Freezing rain',
- 67: 'Heavy freezing rain',
- 71: 'Light snowfall',
- 73: 'Snowfall',
- 75: 'Heavy snowfall',
- 77: 'Snow grains',
- 80: 'Light rain showers',
- 81: 'Rain showers',
- 82: 'Heavy rain showers',
- 85: 'Light snow showers',
- 86: 'Heavy snow showers',
- 95: 'Thunderstorm',
- 96: 'Thunderstorm with hail',
- 99: 'Severe thunderstorm with hail',
+const WMO_DESCRIPTION_EN: Record<number, string> = {
+ 0: 'Clear sky', 1: 'Mainly clear', 2: 'Partly cloudy', 3: 'Overcast',
+ 45: 'Fog', 48: 'Rime fog',
+ 51: 'Light drizzle', 53: 'Drizzle', 55: 'Heavy drizzle',
+ 56: 'Freezing drizzle', 57: 'Heavy freezing drizzle',
+ 61: 'Light rain', 63: 'Rain', 65: 'Heavy rain',
+ 66: 'Freezing rain', 67: 'Heavy freezing rain',
+ 71: 'Light snowfall', 73: 'Snowfall', 75: 'Heavy snowfall', 77: 'Snow grains',
+ 80: 'Light rain showers', 81: 'Rain showers', 82: 'Heavy rain showers',
+ 85: 'Light snow showers', 86: 'Heavy snow showers',
+ 95: 'Thunderstorm', 96: 'Thunderstorm with hail', 99: 'Severe thunderstorm with hail',
};
-// Estimate weather condition from average temperature + precipitation
-function estimateCondition(tempAvg, precipMm) {
+function estimateCondition(tempAvg: number, precipMm: number): string {
if (precipMm > 5) return tempAvg <= 0 ? 'Snow' : 'Rain';
if (precipMm > 1) return tempAvg <= 0 ? 'Snow' : 'Drizzle';
if (precipMm > 0.3) return 'Clouds';
return tempAvg > 15 ? 'Clear' : 'Clouds';
}
-// -------------------------------------------------------
-// GET /api/weather?lat=&lng=&date=&lang=de
-router.get('/', authenticate, async (req, res) => {
- const { lat, lng, date, lang = 'de' } = req.query;
+router.get('/', authenticate, async (req: Request, res: Response) => {
+ const { lat, lng, date, lang = 'de' } = req.query as { lat: string; lng: string; date?: string; lang?: string };
if (!lat || !lng) {
return res.status(400).json({ error: 'Latitude and longitude are required' });
@@ -145,20 +151,18 @@ router.get('/', authenticate, async (req, res) => {
const ck = cacheKey(lat, lng, date);
try {
- // ── Forecast for a specific date ──
if (date) {
const cached = getCached(ck);
if (cached) return res.json(cached);
const targetDate = new Date(date);
const now = new Date();
- const diffDays = (targetDate - now) / (1000 * 60 * 60 * 24);
+ const diffDays = (targetDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24);
- // Within 16-day forecast window → real forecast
if (diffDays >= -1 && diffDays <= 16) {
const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}&daily=temperature_2m_max,temperature_2m_min,weathercode&timezone=auto&forecast_days=16`;
const response = await fetch(url);
- const data = await response.json();
+ const data = await response.json() as OpenMeteoForecast;
if (!response.ok || data.error) {
return res.status(response.status || 500).json({ error: data.reason || 'Open-Meteo API error' });
@@ -183,14 +187,11 @@ router.get('/', authenticate, async (req, res) => {
setCache(ck, result, TTL_FORECAST_MS);
return res.json(result);
}
- // Forecast didn't include this date — fall through to climate
}
- // Beyond forecast range or forecast gap → historical climate average
if (diffDays > -1) {
const month = targetDate.getMonth() + 1;
const day = targetDate.getDate();
- // Query a 5-day window around the target date for smoother averages (using last year as reference)
const refYear = targetDate.getFullYear() - 1;
const startDate = new Date(refYear, month - 1, day - 2);
const endDate = new Date(refYear, month - 1, day + 2);
@@ -199,7 +200,7 @@ router.get('/', authenticate, async (req, res) => {
const url = `https://archive-api.open-meteo.com/v1/archive?latitude=${lat}&longitude=${lng}&start_date=${startStr}&end_date=${endStr}&daily=temperature_2m_max,temperature_2m_min,precipitation_sum&timezone=auto`;
const response = await fetch(url);
- const data = await response.json();
+ const data = await response.json() as OpenMeteoForecast;
if (!response.ok || data.error) {
return res.status(response.status || 500).json({ error: data.reason || 'Open-Meteo Climate API error' });
@@ -210,7 +211,6 @@ router.get('/', authenticate, async (req, res) => {
return res.json({ error: 'no_forecast' });
}
- // Average across the window
let sumMax = 0, sumMin = 0, sumPrecip = 0, count = 0;
for (let i = 0; i < daily.time.length; i++) {
if (daily.temperature_2m_max[i] != null && daily.temperature_2m_min[i] != null) {
@@ -244,17 +244,15 @@ router.get('/', authenticate, async (req, res) => {
return res.json(result);
}
- // Past dates beyond yesterday
return res.json({ error: 'no_forecast' });
}
- // ── Current weather (no date) ──
const cached = getCached(ck);
if (cached) return res.json(cached);
const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}&current=temperature_2m,weathercode&timezone=auto`;
const response = await fetch(url);
- const data = await response.json();
+ const data = await response.json() as OpenMeteoForecast;
if (!response.ok || data.error) {
return res.status(response.status || 500).json({ error: data.reason || 'Open-Meteo API error' });
@@ -272,15 +270,14 @@ router.get('/', authenticate, async (req, res) => {
setCache(ck, result, TTL_CURRENT_MS);
res.json(result);
- } catch (err) {
+ } catch (err: unknown) {
console.error('Weather error:', err);
res.status(500).json({ error: 'Error fetching weather data' });
}
});
-// GET /api/weather/detailed?lat=&lng=&date=&lang=de
-router.get('/detailed', authenticate, async (req, res) => {
- const { lat, lng, date, lang = 'de' } = req.query;
+router.get('/detailed', authenticate, async (req: Request, res: Response) => {
+ const { lat, lng, date, lang = 'de' } = req.query as { lat: string; lng: string; date: string; lang?: string };
if (!lat || !lng || !date) {
return res.status(400).json({ error: 'Latitude, longitude, and date are required' });
@@ -294,11 +291,10 @@ router.get('/detailed', authenticate, async (req, res) => {
const targetDate = new Date(date);
const now = new Date();
- const diffDays = (targetDate - now) / (1000 * 60 * 60 * 24);
+ const diffDays = (targetDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24);
const dateStr = targetDate.toISOString().slice(0, 10);
const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN;
- // Beyond 16-day forecast window → archive API with hourly data from same date last year
if (diffDays > 16) {
const refYear = targetDate.getFullYear() - 1;
const refDateStr = `${refYear}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}`;
@@ -309,7 +305,7 @@ router.get('/detailed', authenticate, async (req, res) => {
+ `&daily=temperature_2m_max,temperature_2m_min,weathercode,precipitation_sum,windspeed_10m_max,sunrise,sunset`
+ `&timezone=auto`;
const response = await fetch(url);
- const data = await response.json();
+ const data = await response.json() as OpenMeteoForecast;
if (!response.ok || data.error) {
return res.status(response.status || 500).json({ error: data.reason || 'Open-Meteo Climate API error' });
@@ -326,8 +322,7 @@ router.get('/detailed', authenticate, async (req, res) => {
const avgMax = daily.temperature_2m_max[idx];
const avgMin = daily.temperature_2m_min[idx];
- // Build hourly array
- const hourlyData = [];
+ const hourlyData: HourlyEntry[] = [];
if (hourly?.time) {
for (let i = 0; i < hourly.time.length; i++) {
const hour = new Date(hourly.time[i]).getHours();
@@ -336,7 +331,7 @@ router.get('/detailed', authenticate, async (req, res) => {
hour,
temp: Math.round(hourly.temperature_2m[i]),
precipitation: hourly.precipitation?.[i] || 0,
- precipitation_probability: 0, // archive has no probability
+ precipitation_probability: 0,
main: WMO_MAP[hCode] || 'Clouds',
wind: Math.round(hourly.windspeed_10m?.[i] || 0),
humidity: hourly.relativehumidity_2m?.[i] || 0,
@@ -344,8 +339,7 @@ router.get('/detailed', authenticate, async (req, res) => {
}
}
- // Format sunrise/sunset
- let sunrise = null, sunset = null;
+ let sunrise: string | null = null, sunset: string | null = null;
if (daily.sunrise?.[idx]) sunrise = daily.sunrise[idx].split('T')[1]?.slice(0, 5);
if (daily.sunset?.[idx]) sunset = daily.sunset[idx].split('T')[1]?.slice(0, 5);
@@ -367,14 +361,13 @@ router.get('/detailed', authenticate, async (req, res) => {
return res.json(result);
}
- // Within 16-day forecast window → full forecast with hourly data
const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}`
+ `&hourly=temperature_2m,precipitation_probability,precipitation,weathercode,windspeed_10m,relativehumidity_2m`
+ `&daily=temperature_2m_max,temperature_2m_min,weathercode,sunrise,sunset,precipitation_probability_max,precipitation_sum,windspeed_10m_max`
+ `&timezone=auto&start_date=${dateStr}&end_date=${dateStr}`;
const response = await fetch(url);
- const data = await response.json();
+ const data = await response.json() as OpenMeteoForecast;
if (!response.ok || data.error) {
return res.status(response.status || 500).json({ error: data.reason || 'Open-Meteo API error' });
@@ -387,18 +380,16 @@ router.get('/detailed', authenticate, async (req, res) => {
return res.json({ error: 'no_forecast' });
}
- const dayIdx = 0; // We requested a single day
+ const dayIdx = 0;
const code = daily.weathercode[dayIdx];
- // Parse sunrise/sunset to HH:MM
- const formatTime = (isoStr) => {
+ const formatTime = (isoStr: string) => {
if (!isoStr) return '';
const d = new Date(isoStr);
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
};
- // Build hourly array
- const hourlyData = [];
+ const hourlyData: HourlyEntry[] = [];
if (hourly && hourly.time) {
for (let i = 0; i < hourly.time.length; i++) {
const h = new Date(hourly.time[i]).getHours();
@@ -431,10 +422,10 @@ router.get('/detailed', authenticate, async (req, res) => {
setCache(ck, result, TTL_FORECAST_MS);
return res.json(result);
- } catch (err) {
+ } catch (err: unknown) {
console.error('Detailed weather error:', err);
res.status(500).json({ error: 'Error fetching detailed weather data' });
}
});
-module.exports = router;
+export default router;
diff --git a/server/src/scheduler.js b/server/src/scheduler.ts
similarity index 72%
rename from server/src/scheduler.js
rename to server/src/scheduler.ts
index b3ce47b60..0d415f377 100644
--- a/server/src/scheduler.js
+++ b/server/src/scheduler.ts
@@ -1,14 +1,14 @@
-const cron = require('node-cron');
-const archiver = require('archiver');
-const path = require('path');
-const fs = require('fs');
+import cron from 'node-cron';
+import archiver from 'archiver';
+import path from 'path';
+import fs from 'fs';
const dataDir = path.join(__dirname, '../data');
const backupsDir = path.join(dataDir, 'backups');
const uploadsDir = path.join(__dirname, '../uploads');
const settingsFile = path.join(dataDir, 'backup-settings.json');
-const CRON_EXPRESSIONS = {
+const CRON_EXPRESSIONS: Record<string, string> = {
hourly: '0 * * * *',
daily: '0 2 * * *',
weekly: '0 2 * * 0',
@@ -17,9 +17,15 @@ const CRON_EXPRESSIONS = {
const VALID_INTERVALS = Object.keys(CRON_EXPRESSIONS);
-let currentTask = null;
+interface BackupSettings {
+ enabled: boolean;
+ interval: string;
+ keep_days: number;
+}
+
+let currentTask: cron.ScheduledTask | null = null;
-function loadSettings() {
+function loadSettings(): BackupSettings {
try {
if (fs.existsSync(settingsFile)) {
return JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
@@ -28,12 +34,12 @@ function loadSettings() {
return { enabled: false, interval: 'daily', keep_days: 7 };
}
-function saveSettings(settings) {
+function saveSettings(settings: BackupSettings): void {
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
fs.writeFileSync(settingsFile, JSON.stringify(settings, null, 2));
}
-async function runBackup() {
+async function runBackup(): Promise<void> {
if (!fs.existsSync(backupsDir)) fs.mkdirSync(backupsDir, { recursive: true });
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
@@ -44,7 +50,7 @@ async function runBackup() {
// Flush WAL to main DB file before archiving
try { const { db } = require('./db/database'); db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
- await new Promise((resolve, reject) => {
+ await new Promise<void>((resolve, reject) => {
const output = fs.createWriteStream(outputPath);
const archive = archiver('zip', { zlib: { level: 9 } });
output.on('close', resolve);
@@ -56,8 +62,8 @@ async function runBackup() {
archive.finalize();
});
console.log(`[Auto-Backup] Created: ${filename}`);
- } catch (err) {
- console.error('[Auto-Backup] Error:', err.message);
+ } catch (err: unknown) {
+ console.error('[Auto-Backup] Error:', err instanceof Error ? err.message : err);
if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath);
return;
}
@@ -68,9 +74,10 @@ async function runBackup() {
}
}
-function cleanupOldBackups(keepDays) {
+function cleanupOldBackups(keepDays: number): void {
try {
- const cutoff = Date.now() - keepDays * 24 * 60 * 60 * 1000;
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
+ const cutoff = Date.now() - keepDays * MS_PER_DAY;
const files = fs.readdirSync(backupsDir).filter(f => f.endsWith('.zip'));
for (const file of files) {
const filePath = path.join(backupsDir, file);
@@ -80,12 +87,12 @@ function cleanupOldBackups(keepDays) {
console.log(`[Auto-Backup] Old backup deleted: ${file}`);
}
}
- } catch (err) {
- console.error('[Auto-Backup] Cleanup error:', err.message);
+ } catch (err: unknown) {
+ console.error('[Auto-Backup] Cleanup error:', err instanceof Error ? err.message : err);
}
}
-function start() {
+function start(): void {
if (currentTask) {
currentTask.stop();
currentTask = null;
@@ -103,9 +110,9 @@ function start() {
}
// Demo mode: hourly reset of demo user data
-let demoTask = null;
+let demoTask: cron.ScheduledTask | null = null;
-function startDemoReset() {
+function startDemoReset(): void {
if (demoTask) { demoTask.stop(); demoTask = null; }
if (process.env.DEMO_MODE !== 'true') return;
@@ -113,16 +120,16 @@ function startDemoReset() {
try {
const { resetDemoUser } = require('./demo/demo-reset');
resetDemoUser();
- } catch (err) {
- console.error('[Demo Reset] Error:', err.message);
+ } catch (err: unknown) {
+ console.error('[Demo Reset] Error:', err instanceof Error ? err.message : err);
}
});
console.log('[Demo] Hourly reset scheduled (at :00 every hour)');
}
-function stop() {
+function stop(): void {
if (currentTask) { currentTask.stop(); currentTask = null; }
if (demoTask) { demoTask.stop(); demoTask = null; }
}
-module.exports = { start, stop, startDemoReset, loadSettings, saveSettings, VALID_INTERVALS };
+export { start, stop, startDemoReset, loadSettings, saveSettings, VALID_INTERVALS };
diff --git a/server/src/services/queryHelpers.ts b/server/src/services/queryHelpers.ts
new file mode 100644
index 000000000..1d316eb6b
--- /dev/null
+++ b/server/src/services/queryHelpers.ts
@@ -0,0 +1,93 @@
+import { db } from '../db/database';
+import { AssignmentRow, Tag, Participant } from '../types';
+
+interface TagRow extends Tag {
+ place_id: number;
+}
+
+interface ParticipantRow {
+ assignment_id: number;
+ user_id: number;
+ username: string;
+ avatar: string | null;
+}
+
+/** Batch-load tags for multiple places in a single query, indexed by place ID. */
+function loadTagsByPlaceIds(placeIds: number[], { compact }: { compact?: boolean } = {}): Record<number, Partial<Tag>[]> {
+ const tagsByPlaceId: Record<number, Partial<Tag>[]> = {};
+ if (placeIds.length > 0) {
+ const placeholders = placeIds.map(() => '?').join(',');
+ const allTags = db.prepare(`
+ SELECT t.*, pt.place_id FROM tags t
+ JOIN place_tags pt ON t.id = pt.tag_id
+ WHERE pt.place_id IN (${placeholders})
+ `).all(...placeIds) as TagRow[];
+
+ for (const tag of allTags) {
+ const pid = tag.place_id;
+ if (!tagsByPlaceId[pid]) tagsByPlaceId[pid] = [];
+ if (compact) {
+ tagsByPlaceId[pid].push({ id: tag.id, name: tag.name, color: tag.color, created_at: tag.created_at });
+ } else {
+ const { place_id, ...rest } = tag;
+ tagsByPlaceId[pid].push(rest);
+ }
+ }
+ }
+ return tagsByPlaceId;
+}
+
+/** Batch-load participants for multiple day-assignments in a single query, indexed by assignment ID. */
+function loadParticipantsByAssignmentIds(assignmentIds: number[]): Record<number, Participant[]> {
+ const participantsByAssignment: Record<number, Participant[]> = {};
+ if (assignmentIds.length > 0) {
+ const allParticipants = db.prepare(`SELECT ap.assignment_id, ap.user_id, u.username, u.avatar FROM assignment_participants ap JOIN users u ON ap.user_id = u.id WHERE ap.assignment_id IN (${assignmentIds.map(() => '?').join(',')})`)
+ .all(...assignmentIds) as ParticipantRow[];
+ for (const p of allParticipants) {
+ if (!participantsByAssignment[p.assignment_id]) participantsByAssignment[p.assignment_id] = [];
+ participantsByAssignment[p.assignment_id].push({ user_id: p.user_id, username: p.username, avatar: p.avatar });
+ }
+ }
+ return participantsByAssignment;
+}
+
+/** Reshape a flat assignment+place DB row into the nested API response shape with embedded place, tags, and participants. */
+function formatAssignmentWithPlace(a: AssignmentRow, tags: Partial<Tag>[], participants: Participant[]) {
+ return {
+ id: a.id,
+ day_id: a.day_id,
+ order_index: a.order_index,
+ notes: a.notes,
+ participants: participants || [],
+ created_at: a.created_at,
+ place: {
+ id: a.place_id,
+ name: a.place_name,
+ description: a.place_description,
+ lat: a.lat,
+ lng: a.lng,
+ address: a.address,
+ category_id: a.category_id,
+ price: a.price,
+ currency: a.place_currency,
+ place_time: a.place_time,
+ end_time: a.end_time,
+ duration_minutes: a.duration_minutes,
+ notes: a.place_notes,
+ image_url: a.image_url,
+ transport_mode: a.transport_mode,
+ google_place_id: a.google_place_id,
+ website: a.website,
+ phone: a.phone,
+ category: a.category_id ? {
+ id: a.category_id,
+ name: a.category_name,
+ color: a.category_color,
+ icon: a.category_icon,
+ } : null,
+ tags: tags || [],
+ }
+ };
+}
+
+export { loadTagsByPlaceIds, loadParticipantsByAssignmentIds, formatAssignmentWithPlace };
diff --git a/server/src/types.ts b/server/src/types.ts
new file mode 100644
index 000000000..cce6dbd9d
--- /dev/null
+++ b/server/src/types.ts
@@ -0,0 +1,291 @@
+import { Request } from 'express';
+
+export interface User {
+ id: number;
+ username: string;
+ email: string;
+ role: 'admin' | 'user';
+ password_hash?: string;
+ maps_api_key?: string | null;
+ unsplash_api_key?: string | null;
+ openweather_api_key?: string | null;
+ avatar?: string | null;
+ oidc_sub?: string | null;
+ oidc_issuer?: string | null;
+ last_login?: string | null;
+ created_at?: string;
+ updated_at?: string;
+}
+
+export interface Trip {
+ id: number;
+ user_id: number;
+ title: string;
+ description?: string | null;
+ start_date?: string | null;
+ end_date?: string | null;
+ currency: string;
+ cover_image?: string | null;
+ is_archived: number;
+ created_at?: string;
+ updated_at?: string;
+}
+
+export interface Day {
+ id: number;
+ trip_id: number;
+ day_number: number;
+ date?: string | null;
+ notes?: string | null;
+ title?: string | null;
+}
+
+export interface Place {
+ id: number;
+ trip_id: number;
+ name: string;
+ description?: string | null;
+ lat?: number | null;
+ lng?: number | null;
+ address?: string | null;
+ category_id?: number | null;
+ price?: number | null;
+ currency?: string | null;
+ reservation_status?: string;
+ reservation_notes?: string | null;
+ reservation_datetime?: string | null;
+ place_time?: string | null;
+ end_time?: string | null;
+ duration_minutes?: number;
+ notes?: string | null;
+ image_url?: string | null;
+ google_place_id?: string | null;
+ website?: string | null;
+ phone?: string | null;
+ transport_mode?: string;
+ created_at?: string;
+ updated_at?: string;
+}
+
+export interface Category {
+ id: number;
+ name: string;
+ color: string;
+ icon: string;
+ user_id?: number | null;
+ created_at?: string;
+}
+
+export interface Tag {
+ id: number;
+ user_id: number;
+ name: string;
+ color: string;
+ created_at?: string;
+}
+
+export interface DayAssignment {
+ id: number;
+ day_id: number;
+ place_id: number;
+ order_index: number;
+ notes?: string | null;
+ reservation_status?: string;
+ reservation_notes?: string | null;
+ reservation_datetime?: string | null;
+ assignment_time?: string | null;
+ assignment_end_time?: string | null;
+ created_at?: string;
+}
+
+export interface PackingItem {
+ id: number;
+ trip_id: number;
+ name: string;
+ checked: number;
+ category?: string | null;
+ sort_order: number;
+ created_at?: string;
+}
+
+export interface BudgetItem {
+ id: number;
+ trip_id: number;
+ category: string;
+ name: string;
+ total_price: number;
+ persons?: number | null;
+ days?: number | null;
+ note?: string | null;
+ sort_order: number;
+ created_at?: string;
+ members?: BudgetItemMember[];
+}
+
+export interface BudgetItemMember {
+ user_id: number;
+ paid: number;
+ username: string;
+ avatar_url?: string | null;
+ avatar?: string | null;
+ budget_item_id?: number;
+}
+
+export interface Reservation {
+ id: number;
+ trip_id: number;
+ day_id?: number | null;
+ place_id?: number | null;
+ assignment_id?: number | null;
+ title: string;
+ reservation_time?: string | null;
+ reservation_end_time?: string | null;
+ location?: string | null;
+ confirmation_number?: string | null;
+ notes?: string | null;
+ status: string;
+ type: string;
+ created_at?: string;
+ day_number?: number;
+ place_name?: string;
+}
+
+export interface TripFile {
+ id: number;
+ trip_id: number;
+ place_id?: number | null;
+ reservation_id?: number | null;
+ note_id?: number | null;
+ filename: string;
+ original_name: string;
+ file_size?: number | null;
+ mime_type?: string | null;
+ description?: string | null;
+ created_at?: string;
+ reservation_title?: string;
+ url?: string;
+}
+
+export interface TripMember {
+ id: number;
+ trip_id: number;
+ user_id: number;
+ invited_by?: number | null;
+ added_at?: string;
+}
+
+export interface DayNote {
+ id: number;
+ day_id: number;
+ trip_id: number;
+ text: string;
+ time?: string | null;
+ icon: string;
+ sort_order: number;
+ created_at?: string;
+}
+
+export interface CollabNote {
+ id: number;
+ trip_id: number;
+ user_id: number;
+ category: string;
+ title: string;
+ content?: string | null;
+ color: string;
+ pinned: number;
+ website?: string | null;
+ username?: string;
+ avatar?: string | null;
+ created_at?: string;
+ updated_at?: string;
+}
+
+export interface CollabPoll {
+ id: number;
+ trip_id: number;
+ user_id: number;
+ question: string;
+ options: string;
+ multiple: number;
+ closed: number;
+ deadline?: string | null;
+ username?: string;
+ avatar?: string | null;
+ created_at?: string;
+}
+
+export interface CollabMessage {
+ id: number;
+ trip_id: number;
+ user_id: number;
+ text: string;
+ reply_to?: number | null;
+ deleted?: number;
+ username?: string;
+ avatar?: string | null;
+ reply_text?: string | null;
+ reply_username?: string | null;
+ created_at?: string;
+}
+
+export interface Addon {
+ id: string;
+ name: string;
+ description?: string | null;
+ type: string;
+ icon: string;
+ enabled: number;
+ config: string;
+ sort_order: number;
+}
+
+export interface AppSetting {
+ key: string;
+ value?: string | null;
+}
+
+export interface Setting {
+ id: number;
+ user_id: number;
+ key: string;
+ value?: string | null;
+}
+
+export interface AuthRequest extends Request {
+ user: { id: number; username: string; email: string; role: string };
+ trip?: { id: number; user_id: number };
+}
+
+export interface OptionalAuthRequest extends Request {
+ user: { id: number; username: string; email: string; role: string } | null;
+}
+
+export interface AssignmentRow extends DayAssignment {
+ place_name: string;
+ place_description: string | null;
+ lat: number | null;
+ lng: number | null;
+ address: string | null;
+ category_id: number | null;
+ price: number | null;
+ place_currency: string | null;
+ place_time: string | null;
+ end_time: string | null;
+ duration_minutes: number;
+ place_notes: string | null;
+ image_url: string | null;
+ transport_mode: string;
+ google_place_id: string | null;
+ website: string | null;
+ phone: string | null;
+ category_name: string | null;
+ category_color: string | null;
+ category_icon: string | null;
+}
+
+export interface Participant {
+ user_id: number;
+ username: string;
+ avatar?: string | null;
+}
diff --git a/server/src/websocket.js b/server/src/websocket.js
deleted file mode 100644
index af801cb90..000000000
--- a/server/src/websocket.js
+++ /dev/null
@@ -1,168 +0,0 @@
-const { WebSocketServer } = require('ws');
-const jwt = require('jsonwebtoken');
-const { JWT_SECRET } = require('./config');
-const { db, canAccessTrip } = require('./db/database');
-
-// Room management: tripId → Set<WebSocket>
-const rooms = new Map();
-
-// Track which rooms each socket is in
-const socketRooms = new WeakMap();
-
-// Track user info per socket
-const socketUser = new WeakMap();
-
-// Track unique socket ID
-const socketId = new WeakMap();
-let nextSocketId = 1;
-
-let wss;
-
-function setupWebSocket(server) {
- wss = new WebSocketServer({ server, path: '/ws' });
-
- // Heartbeat: ping every 30s, terminate if no pong
- const heartbeat = setInterval(() => {
- wss.clients.forEach((ws) => {
- if (ws.isAlive === false) return ws.terminate();
- ws.isAlive = false;
- ws.ping();
- });
- }, 30000);
-
- wss.on('close', () => clearInterval(heartbeat));
-
- wss.on('connection', (ws, req) => {
- // Extract token from query param
- const url = new URL(req.url, 'http://localhost');
- const token = url.searchParams.get('token');
-
- if (!token) {
- ws.close(4001, 'Authentication required');
- return;
- }
-
- let user;
- try {
- const decoded = jwt.verify(token, JWT_SECRET);
- user = db.prepare(
- 'SELECT id, username, email, role FROM users WHERE id = ?'
- ).get(decoded.id);
- if (!user) {
- ws.close(4001, 'User not found');
- return;
- }
- } catch (err) {
- ws.close(4001, 'Invalid or expired token');
- return;
- }
-
- ws.isAlive = true;
- const sid = nextSocketId++;
- socketId.set(ws, sid);
- socketUser.set(ws, user);
- socketRooms.set(ws, new Set());
- ws.send(JSON.stringify({ type: 'welcome', socketId: sid }));
-
- ws.on('pong', () => { ws.isAlive = true; });
-
- ws.on('message', (data) => {
- let msg;
- try {
- msg = JSON.parse(data.toString());
- } catch {
- return;
- }
-
- if (msg.type === 'join' && msg.tripId) {
- const tripId = Number(msg.tripId);
- // Verify the user has access to this trip
- if (!canAccessTrip(tripId, user.id)) {
- ws.send(JSON.stringify({ type: 'error', message: 'Access denied' }));
- return;
- }
- // Add to room
- if (!rooms.has(tripId)) rooms.set(tripId, new Set());
- rooms.get(tripId).add(ws);
- socketRooms.get(ws).add(tripId);
- ws.send(JSON.stringify({ type: 'joined', tripId }));
- }
-
- if (msg.type === 'leave' && msg.tripId) {
- const tripId = Number(msg.tripId);
- leaveRoom(ws, tripId);
- ws.send(JSON.stringify({ type: 'left', tripId }));
- }
- });
-
- ws.on('close', () => {
- // Clean up all rooms this socket was in
- const myRooms = socketRooms.get(ws);
- if (myRooms) {
- for (const tripId of myRooms) {
- leaveRoom(ws, tripId);
- }
- }
- });
- });
-
- console.log('WebSocket server attached at /ws');
-}
-
-function leaveRoom(ws, tripId) {
- const room = rooms.get(tripId);
- if (room) {
- room.delete(ws);
- if (room.size === 0) rooms.delete(tripId);
- }
- const myRooms = socketRooms.get(ws);
- if (myRooms) myRooms.delete(tripId);
-}
-
-/**
- * Broadcast an event to all sockets in a trip room, optionally excluding a user.
- * @param {number} tripId
- * @param {string} eventType e.g. 'place:created'
- * @param {object} payload the data to send
- * @param {number} [excludeUserId] don't send to this user (the one who triggered the change)
- */
-function broadcast(tripId, eventType, payload, excludeSid) {
- tripId = Number(tripId);
- const room = rooms.get(tripId);
- if (!room || room.size === 0) return;
-
- const excludeNum = excludeSid ? Number(excludeSid) : null;
-
- for (const ws of room) {
- if (ws.readyState !== 1) continue; // WebSocket.OPEN === 1
- // Exclude the specific socket that triggered the change
- if (excludeNum && socketId.get(ws) === excludeNum) continue;
- ws.send(JSON.stringify({ type: eventType, tripId, ...payload }));
- }
-}
-
-function broadcastToUser(userId, payload, excludeSid) {
- if (!wss) return;
- const excludeNum = excludeSid ? Number(excludeSid) : null;
- for (const ws of wss.clients) {
- if (ws.readyState !== 1) continue;
- if (excludeNum && socketId.get(ws) === excludeNum) continue;
- const user = socketUser.get(ws);
- if (user && user.id === userId) {
- ws.send(JSON.stringify(payload));
- }
- }
-}
-
-function getOnlineUserIds() {
- const ids = new Set();
- if (!wss) return ids;
- for (const ws of wss.clients) {
- if (ws.readyState !== 1) continue;
- const user = socketUser.get(ws);
- if (user) ids.add(user.id);
- }
- return ids;
-}
-
-module.exports = { setupWebSocket, broadcast, broadcastToUser, getOnlineUserIds };
diff --git a/server/src/websocket.ts b/server/src/websocket.ts
new file mode 100644
index 000000000..1e28ddbc4
--- /dev/null
+++ b/server/src/websocket.ts
@@ -0,0 +1,176 @@
+import { WebSocketServer, WebSocket } from 'ws';
+import jwt from 'jsonwebtoken';
+import { JWT_SECRET } from './config';
+import { db, canAccessTrip } from './db/database';
+import { User } from './types';
+import http from 'http';
+
+interface NomadWebSocket extends WebSocket {
+ isAlive: boolean;
+}
+
+// Room management: tripId -> Set<WebSocket>
+const rooms = new Map<number, Set<NomadWebSocket>>();
+
+// Track which rooms each socket is in
+const socketRooms = new WeakMap<NomadWebSocket, Set<number>>();
+
+// Track user info per socket
+const socketUser = new WeakMap<NomadWebSocket, User>();
+
+// Track unique socket ID
+const socketId = new WeakMap<NomadWebSocket, number>();
+let nextSocketId = 1;
+
+let wss: WebSocketServer | null = null;
+
+/** Attaches a WebSocket server with JWT auth, room-based trip channels, and heartbeat keep-alive. */
+function setupWebSocket(server: http.Server): void {
+ wss = new WebSocketServer({ server, path: '/ws' });
+
+ const HEARTBEAT_INTERVAL = 30000; // 30 seconds
+ const heartbeat = setInterval(() => {
+ wss!.clients.forEach((ws) => {
+ const nws = ws as NomadWebSocket;
+ if (nws.isAlive === false) return nws.terminate();
+ nws.isAlive = false;
+ nws.ping();
+ });
+ }, HEARTBEAT_INTERVAL);
+
+ wss.on('close', () => clearInterval(heartbeat));
+
+ wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => {
+ const nws = ws as NomadWebSocket;
+ // Extract token from query param
+ const url = new URL(req.url!, 'http://localhost');
+ const token = url.searchParams.get('token');
+
+ if (!token) {
+ nws.close(4001, 'Authentication required');
+ return;
+ }
+
+ let user: User | undefined;
+ try {
+ const decoded = jwt.verify(token, JWT_SECRET) as { id: number };
+ user = db.prepare(
+ 'SELECT id, username, email, role FROM users WHERE id = ?'
+ ).get(decoded.id) as User | undefined;
+ if (!user) {
+ nws.close(4001, 'User not found');
+ return;
+ }
+ } catch (err: unknown) {
+ nws.close(4001, 'Invalid or expired token');
+ return;
+ }
+
+ nws.isAlive = true;
+ const sid = nextSocketId++;
+ socketId.set(nws, sid);
+ socketUser.set(nws, user);
+ socketRooms.set(nws, new Set());
+ nws.send(JSON.stringify({ type: 'welcome', socketId: sid }));
+
+ nws.on('pong', () => { nws.isAlive = true; });
+
+ nws.on('message', (data) => {
+ let msg: { type: string; tripId?: number | string };
+ try {
+ msg = JSON.parse(data.toString());
+ } catch {
+ return;
+ }
+
+ if (msg.type === 'join' && msg.tripId) {
+ const tripId = Number(msg.tripId);
+ // Verify the user has access to this trip
+ if (!canAccessTrip(tripId, user!.id)) {
+ nws.send(JSON.stringify({ type: 'error', message: 'Access denied' }));
+ return;
+ }
+ // Add to room
+ if (!rooms.has(tripId)) rooms.set(tripId, new Set());
+ rooms.get(tripId)!.add(nws);
+ socketRooms.get(nws)!.add(tripId);
+ nws.send(JSON.stringify({ type: 'joined', tripId }));
+ }
+
+ if (msg.type === 'leave' && msg.tripId) {
+ const tripId = Number(msg.tripId);
+ leaveRoom(nws, tripId);
+ nws.send(JSON.stringify({ type: 'left', tripId }));
+ }
+ });
+
+ nws.on('close', () => {
+ // Clean up all rooms this socket was in
+ const myRooms = socketRooms.get(nws);
+ if (myRooms) {
+ for (const tripId of myRooms) {
+ leaveRoom(nws, tripId);
+ }
+ }
+ });
+ });
+
+ console.log('WebSocket server attached at /ws');
+}
+
+function leaveRoom(ws: NomadWebSocket, tripId: number): void {
+ const room = rooms.get(tripId);
+ if (room) {
+ room.delete(ws);
+ if (room.size === 0) rooms.delete(tripId);
+ }
+ const myRooms = socketRooms.get(ws);
+ if (myRooms) myRooms.delete(tripId);
+}
+
+/**
+ * Broadcast an event to all sockets in a trip room, optionally excluding a socket.
+ */
+function broadcast(tripId: number | string, eventType: string, payload: Record<string, unknown>, excludeSid?: number | string): void {
+ tripId = Number(tripId);
+ const room = rooms.get(tripId);
+ if (!room || room.size === 0) return;
+
+ const excludeNum = excludeSid ? Number(excludeSid) : null;
+
+ for (const ws of room) {
+ if (ws.readyState !== 1) continue; // WebSocket.OPEN === 1
+ // Exclude the specific socket that triggered the change
+ if (excludeNum && socketId.get(ws) === excludeNum) continue;
+ ws.send(JSON.stringify({ type: eventType, tripId, ...payload }));
+ }
+}
+
+/** Send a message to all sockets belonging to a specific user (e.g., for trip invitations). */
+function broadcastToUser(userId: number, payload: Record<string, unknown>, excludeSid?: number | string): void {
+ if (!wss) return;
+ const excludeNum = excludeSid ? Number(excludeSid) : null;
+ for (const ws of wss.clients) {
+ const nws = ws as NomadWebSocket;
+ if (nws.readyState !== 1) continue;
+ if (excludeNum && socketId.get(nws) === excludeNum) continue;
+ const user = socketUser.get(nws);
+ if (user && user.id === userId) {
+ nws.send(JSON.stringify(payload));
+ }
+ }
+}
+
+function getOnlineUserIds(): Set<number> {
+ const ids = new Set<number>();
+ if (!wss) return ids;
+ for (const ws of wss.clients) {
+ const nws = ws as NomadWebSocket;
+ if (nws.readyState !== 1) continue;
+ const user = socketUser.get(nws);
+ if (user) ids.add(user.id);
+ }
+ return ids;
+}
+
+export { setupWebSocket, broadcast, broadcastToUser, getOnlineUserIds };
diff --git a/server/tsconfig.json b/server/tsconfig.json
new file mode 100644
index 000000000..0ecff3772
--- /dev/null
+++ b/server/tsconfig.json
@@ -0,0 +1,21 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "commonjs",
+ "lib": ["ES2022"],
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "strict": false,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "declaration": false,
+ "sourceMap": true,
+ "allowJs": true,
+ "noUnusedLocals": false,
+ "noUnusedParameters": false
+ },
+ "include": ["src"],
+ "exclude": ["node_modules", "dist"]
+}