mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-06-21 22:31:46 +00:00
Migrate TREK 3 to NestJS + React 19 (shared Zod contracts) (#1087)
* Migrate TREK 3 to NestJS + React 19 with a shared Zod contract layer
Brownfield strangler migration of the backend onto NestJS modules
(auth, trips, days, places, assignments, packing, todo, budget,
reservations, collab, files, photos, journey, share, settings, backup,
oidc, oauth, admin, atlas, vacay, weather, airports, maps, categories,
tags, notifications, system-notices) served through a per-prefix
dispatcher, keeping the existing SQLite/better-sqlite3 DB and JWT
httpOnly cookie auth, with behavioural parity for every route.
Client: React 19 upgrade, "page = wiring container + data hook"
pattern across all pages, per-domain Zustand stores bound to
@trek/shared contracts, and decomposition of the large components
(DayPlanSidebar, PackingListPanel, CollabNotes, FileManager,
MemoriesPanel, PlacesSidebar, CollabChat, SystemNoticeModal,
BudgetPanel, PlaceFormModal, ...) into focused render units backed by
in-file hooks.
Apply the shared global request pipeline (helmet/CSP, CORS, HSTS,
forced HTTPS, the global MFA policy and request logging) to the NestJS
instance as well, so a migrated route is protected identically to the
legacy fallback rather than bypassing it.
* Finish the NestJS migration — drop the legacy Express app
NestJS now serves the whole surface: every /api domain plus the platform
routes (uploads, /mcp, the OAuth/MCP SDK + /.well-known metadata and the
production SPA fallback). Removed server/src/app.ts, all of
server/src/routes/* and the strangler dispatcher; index.ts and the
integration suite share a single buildApp() bootstrap so prod and tests
can't drift.
- Platform/transport routes extracted to nest/platform/platform.routes.ts
and mounted before app.init() — Nest's router answers an unmatched
request with a 404, so a route registered after init is never reached.
The SPA fallback is a NotFoundException filter and the catch-all uses a
RegExp (Express 5's path-to-regexp rejects a bare '*').
- New modules: memories (/api/integrations/memories — the Journey
gallery's Immich/Synology proxy), addons (GET /api/addons) and the
cross-trip GET /api/reservations/upcoming.
- TrekExceptionFilter reproduces the old multer / err.statusCode handling
so upload rejections keep their 400/413 { error } body and non-ASCII
filenames survive (defParamCharset).
- addTripToJourney and the MCP get_journey_share_link tool gained the
trip-access check they were missing.
- Re-pointed the 34 integration tests + the websocket test onto the Nest
app; removed the now-meaningless Express-vs-Nest parity tests and a few
orphaned client components.
* Restore the reset-password rate limit and fix copyTrip reservation links
Two correctness/security gaps the NestJS migration introduced:
- POST /api/auth/reset-password lost its per-IP rate limiter. Restore it
(5 attempts / 15 min on a dedicated bucket, same as the old resetLimiter)
so reset tokens can't be brute-forced unthrottled. Covered by AUTH-019.
- copyTripById did not copy reservations.end_day_id (a day reference — now
remapped through dayMap like day_id) or needs_review, so a duplicated trip
lost multi-day transport end-day links and reset the review flag.
* Clean up dead code, dedupe helpers, fix the reset-password contract
- Remove server exports orphaned by the Express removal: the immich
album-link helpers, seven route-only service exports, getFileByIdFull;
de-export internal-only helpers (utcSuffix).
- De-duplicate verifyTripAccess (9 identical copies -> services/tripAccess.ts)
and avatarUrl (3 -> services/avatarUrl.ts); name the bcrypt cost
(BCRYPT_COST) and the email regex (EMAIL_REGEX). Public API unchanged.
- resetPasswordRequestSchema declared `password`, but the client sends and
the service reads `new_password` — rename it so the contract matches and
the client types resolve.
- Make ATLAS-013 deterministic: stub the admin-1 GeoJSON download instead of
fetching ~4600 features from GitHub during the test (it hung the suite).
* Make the client typecheck runnable (vitest/vite ambient types)
The client had no `typecheck` script and tsc couldn't even start (the
baseUrl deprecation errored out, same as server/shared already silence).
Add `ignoreDeprecations: "6.0"` to match the other workspaces, a `typecheck`
npm script, and a src/vite-env.d.ts referencing vite/client + vitest/globals
so tsc knows the test globals (describe/it/expect/vi). This turns ~3600
phantom "Cannot find name" errors into a real, measurable count (~590 actual
type errors remain, to be worked down). Type-only; no runtime change.
* Derive client domain types from the shared schema contracts
Add entity/response Zod schemas to @trek/shared (place, trip, assignment, day, budget, packing, reservation), each matched against the producing server service, and re-export them from client types.ts instead of the hand-written duplicates that had drifted (name/title, amount/total_price, owner_id/user_id, cover_url/cover_image, ...). Updates the call sites and test fixtures the corrected types surfaced; type-only, no runtime behaviour change.
* chore(db): log swallowed errors in addon-disable migration + guard against destructive migrations
The migration that disables the legacy "memories" addon swallowed any
error in an empty catch, as did ~30 other catch blocks in the migration
runner (column adds, the journey rebuild, index probes). Replace each
silent catch with the existing console.warn('[migrations] ...') log so
failures are visible. Control flow is unchanged: every step stays
non-fatal, nothing new is thrown.
Add a static guardrail test that scans the migration source and fails
when a new destructive statement (DROP TABLE / DROP COLUMN / TRUNCATE /
DELETE FROM / ALTER ... DROP) appears outside a reviewed allowlist, and
when an empty/silent catch block is reintroduced. The existing
destructive statements are all legitimate table rebuilds or
bounded cleanups and are recorded in the allowlist with a reason.
* Re-check SSRF on every redirect hop when resolving short links
Replace the one-shot checkSsrf + fetch(redirect:'follow') in the maps and place short-link resolvers with safeFetchFollow, which follows redirects manually and re-runs checkSsrf against the DNS-pinned IP of each hop (max 5). A redirect to an internal/loopback address is now blocked even when the initial URL is public, while legitimate cross-host redirects (goo.gl -> maps.google.com) still resolve.
* Reject WebSocket tokens minted before a password change
Stamp the user's password_version onto the ephemeral ws token and verify it on connect, closing the socket (4001) when it no longer matches, so a token issued before a password reset can't be replayed. Tokens minted without a version are treated as version 0, matching the JWT pv-claim semantics.
* fix(i18n): guard locale key parity and finish the OAuth consent page strings
Every non-en locale now exposes the exact same flat key set as en. Keys that
had drifted out of sync are backfilled with the English source value (tagged
en-fallback) so t() resolves a real string instead of relying on the silent
runtime fallback; no existing translation was touched and no key was removed.
Add a parity test that imports each aggregated locale bundle and asserts its
key set matches en, with a diagnostic listing of any missing/extra keys. This
complements the file-level check in shared/scripts by guarding the merged
export the app actually serves.
Finish internationalising OAuthAuthorizePage: the ~15 remaining hardcoded
English chrome strings now go through oauth.authorize.* keys (English source
in en, en-fallback placeholders elsewhere). Markup and behaviour are unchanged.
* Add semantic theme color tokens to Tailwind
Map the CSS theme variables from src/index.css (:root light / .dark dark) to named Tailwind utilities — bg-surface, text-content, border-edge, bg-accent and their variants. This gives components a Tailwind-native target for the theme colors so we can replace inline `style={{ ... 'var(--...)' }}` with utility classes without changing the rendered values.
* Surface silent store failures to the user and validate API responses in dev
Reservation toggle, todo/packing toggle and budget reorder were swallowing API errors after rolling back, so the user saw the change silently snap back with no explanation. Route those failures through the existing toast channel (new store/notify.ts bridges to window.__addToast, the same channel SystemNoticeBanner uses); the reservation toggle re-throws so ReservationsPanel's own translated toast finally fires. Also wire the existing parseInDev/checkInDev response validation into the maps and notification-test endpoints to catch contract drift in dev.
* Migrate static theme inline styles to Tailwind utilities and extract page sub-components
Replace the static, color-only inline `style={{ ... 'var(--bg-primary)' ... }}` props with the new semantic Tailwind utilities (bg-surface, text-content, border-edge, ...) wherever the result is byte-identical; dynamic/conditional theme styles and hardcoded status colors are left inline. Extract the Atlas country-search autocomplete, the Admin update banner, and two Journey dialogs into their own presentational components to shrink the oversized page files, keeping behaviour and markup identical.
* Remove the unrouted photos page and its dead photo components
PhotosPage was never wired into the router and its usePhotos hook read a tripStore photos slice that was never implemented; the Photos gallery, lightbox and upload components were only reachable through it. Per-trip photos now live in the Journey gallery (Immich/Synology). Removed the dead page, hook and components — the live Journey PhotoLightbox is a separate component and stays.
* Resolve the remaining client type errors and the trip.title navbar bug
Drive the client typecheck to zero without any/ts-ignore: convert the tripId route param to a number once at the page boundary so it matches the numeric props and store actions it feeds, fix trip.name -> trip.title (the wire field is title, so the old read rendered blank in the files/offline views), and tighten the scattered handler-arity, DOM-cast and untyped-payload sites. No runtime behaviour change.
* Convert the remaining dynamic and hardcoded inline styles to Tailwind utilities
Second styling pass over the components and pages: move conditional theme colors into className ternaries (bg-accent / bg-surface-hover etc.), turn reused CSSProperties constants into className constants, and express static hardcoded hex/rgba colors as Tailwind arbitrary values so the exact rendered colour is preserved. Truly dynamic styling (computed geometry, gradients, multi-part shadows, data-driven colours, the undefined --sidebar/--nav layout vars) stays inline as it cannot be expressed as a static class. Updated three component tests that asserted the old inline active-state styles to assert the equivalent utility class instead.
Verified: client typecheck 0, full client suite green, and a live light/dark render check in the dev server confirms the semantic theme tokens resolve correctly (the earlier 'transparent popups' were a stale dev server that pre-dated the tailwind.config token addition, not a code issue).
* Add eslint flat-config for client and server and gate typecheck, lint and pages in CI
client and server had lint scripts but no eslint config (only shared was linted in CI). Add flat configs mirroring shared's stack (js + typescript-eslint recommended + eslint-config-prettier) plus the client's react-hooks/react-refresh plugins. Pre-existing patterns in this never-linted code (explicit any, require() in the CommonJS server, empty catches, exhaustive-deps) are set to 'warn' rather than 'error' so the gate passes at 0 errors without a repo-wide reformat — these can be ratcheted to errors over time. Wire blocking typecheck + lint + lint:pages steps into the client and server CI jobs (now that both typechecks are clean) and promote the server typecheck from informational to blocking.
* Decompose the remaining God Components into hooks, helpers and sub-components
FE6: split the oversized page and panel components into thin layout shells plus colocated use<Component> hooks, .constants.ts, .helpers.ts (with tests) and presentational sub-components, following the established 'logic in a hook, render in slices' pattern. Behaviour, markup, classes and effect order are unchanged. Largest reductions: PackingListPanel 1598->42, FileManager 1055->36, AdminPage 1525->167, BudgetPanel 1266->146, JourneyDetailPage 2822->547, PlacesSidebar 945->66, CollabChat 861->106, CollabNotes 1417->532. DayPlanSidebar's drag-and-drop render body was left intact (ref-identity sensitive) and only its toolbar/modals/constants were extracted.
* Fix duplicate React keys in the file-assign place list
When a place is assigned to the same day more than once it appeared twice in a day's list, so the place-button key={p.id} collided and React warned about duplicate keys. Key by place id + render index so siblings stay unique. Pre-existing in the old FileManager; behaviour unchanged.
* Format the shared package and drop an unused import to satisfy the lint gate
The i18n and schema changes added code that wasn't prettier-formatted, and place.schema.ts imported categorySchema without using it. Run prettier over shared and remove the import so 'npm run lint' + 'format:check' pass.
* Install all workspaces in the server CI job so SWC's native binary is present
The server vitest config transforms via unplugin-swc, which needs @swc/core's platform-specific native binary. A workspace-scoped 'npm ci --workspace server' skips that optional dependency, so vitest failed to load the config on the Linux runner. Use a full 'npm ci'.
* Re-resolve dependencies with npm install in the server CI job for SWC
Full 'npm ci' still skipped @swc/core's Linux native binary because the committed lockfile was generated on Windows and lacks the Linux optional-dep install metadata. 'npm install' re-resolves and fetches the platform-matching binary, which the server's unplugin-swc transform needs to load vitest.config.ts.
* Install @swc/core's Linux binary explicitly in the server CI job
Neither npm ci nor npm install fetched @swc/core-linux-x64-gnu on the Linux runner because the lockfile was generated on Windows and lacks the Linux optional-dep metadata. Add a step that installs the matching @swc/core-linux-x64-gnu version (no-save, no-lockfile) so unplugin-swc can load the server's vitest config.
* Use legacy-peer-deps when installing the SWC Linux binary in CI
The explicit @swc/core-linux-x64-gnu install re-resolved the tree and hit the pre-existing lucide-react/react-19 peer conflict that the lockfile was generated around. Add --legacy-peer-deps so the step matches the project's resolution and installs the binary.
* Keep the lockfile when installing the SWC binary so other deps stay pinned
Dropping --no-package-lock made npm re-resolve the whole tree and upgrade eslint, whose newer recommended config flagged no-useless-assignment as an error in the server lint step. Keep the lockfile so only @swc/core-linux-x64-gnu is added and every other dependency (incl. eslint) stays at its locked version.
This commit is contained in:
@@ -360,7 +360,7 @@ describe('AdminPage', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: /settings/i }));
|
||||
|
||||
const heading = await screen.findByRole('heading', { name: /authentication methods/i });
|
||||
const card = heading.closest('.bg-white');
|
||||
const card = heading.closest<HTMLElement>('.bg-white');
|
||||
const toggles = within(card!).getAllByRole('button');
|
||||
fireEvent.click(toggles[0]); // First toggle = password_login
|
||||
|
||||
@@ -474,7 +474,7 @@ describe('AdminPage', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: /settings/i }));
|
||||
|
||||
const mfaHeading = await screen.findByRole('heading', { name: /require two-factor/i });
|
||||
const mfaCard = mfaHeading.closest('.bg-white');
|
||||
const mfaCard = mfaHeading.closest<HTMLElement>('.bg-white');
|
||||
const mfaToggle = within(mfaCard!).getByRole('button');
|
||||
fireEvent.click(mfaToggle);
|
||||
|
||||
@@ -739,7 +739,7 @@ describe('AdminPage', () => {
|
||||
|
||||
// Find and click the Save button in the file types section
|
||||
const fileTypesHeading = screen.getByRole('heading', { name: /allowed file types/i });
|
||||
const fileTypesCard = fileTypesHeading.closest('.bg-white');
|
||||
const fileTypesCard = fileTypesHeading.closest<HTMLElement>('.bg-white');
|
||||
const saveBtn = within(fileTypesCard!).getByRole('button', { name: /save/i });
|
||||
fireEvent.click(saveBtn);
|
||||
|
||||
@@ -765,7 +765,7 @@ describe('AdminPage', () => {
|
||||
|
||||
// Wait for OIDC section to appear
|
||||
const oidcHeading = await screen.findByRole('heading', { name: /single sign-on/i });
|
||||
const oidcCard = oidcHeading.closest('.bg-white');
|
||||
const oidcCard = oidcHeading.closest<HTMLElement>('.bg-white');
|
||||
|
||||
// Type in the display name field (placeholder is 'z.B. Google, Authentik, Keycloak')
|
||||
const displayNameInput = within(oidcCard!).getByPlaceholderText('z.B. Google, Authentik, Keycloak');
|
||||
@@ -800,7 +800,7 @@ describe('AdminPage', () => {
|
||||
|
||||
// The Email (SMTP) panel header has the enable toggle
|
||||
const emailHeading = await screen.findByRole('heading', { name: /email \(smtp\)/i });
|
||||
const emailPanel = emailHeading.closest('.bg-white');
|
||||
const emailPanel = emailHeading.closest<HTMLElement>('.bg-white');
|
||||
const emailToggle = within(emailPanel!).getAllByRole('button')[0];
|
||||
fireEvent.click(emailToggle);
|
||||
|
||||
@@ -842,7 +842,7 @@ describe('AdminPage', () => {
|
||||
|
||||
// Click Save in the email panel
|
||||
const emailHeading = screen.getByRole('heading', { name: /email \(smtp\)/i });
|
||||
const emailPanel = emailHeading.closest('.bg-white');
|
||||
const emailPanel = emailHeading.closest<HTMLElement>('.bg-white');
|
||||
const saveBtn = within(emailPanel!).getByRole('button', { name: /^save$/i });
|
||||
fireEvent.click(saveBtn);
|
||||
|
||||
@@ -964,7 +964,7 @@ describe('AdminPage', () => {
|
||||
|
||||
// Wait for the API Keys section to appear
|
||||
const apiKeysHeading = await screen.findByRole('heading', { name: /^api keys$/i });
|
||||
const apiKeysCard = apiKeysHeading.closest('.bg-white');
|
||||
const apiKeysCard = apiKeysHeading.closest<HTMLElement>('.bg-white');
|
||||
|
||||
// Type in the maps key field (type="password" by default)
|
||||
const keyInputs = within(apiKeysCard!).getAllByPlaceholderText('Enter key...');
|
||||
@@ -999,7 +999,7 @@ describe('AdminPage', () => {
|
||||
|
||||
// Wait for the API Keys section
|
||||
const apiKeysHeading = await screen.findByRole('heading', { name: /^api keys$/i });
|
||||
const apiKeysCard = apiKeysHeading.closest('.bg-white');
|
||||
const apiKeysCard = apiKeysHeading.closest<HTMLElement>('.bg-white');
|
||||
|
||||
// Type a key value to enable the Test button
|
||||
const keyInputs = within(apiKeysCard!).getAllByPlaceholderText('Enter key...');
|
||||
@@ -1126,7 +1126,7 @@ describe('AdminPage', () => {
|
||||
|
||||
// Click the TLS toggle (skip TLS certificate check)
|
||||
const tlsToggleText = screen.getByText('Skip TLS certificate check');
|
||||
const tlsCard = tlsToggleText.closest('div');
|
||||
const tlsCard = tlsToggleText.closest<HTMLElement>('div');
|
||||
// The toggle button is a sibling container
|
||||
const allToggles = screen.getAllByRole('button');
|
||||
// Find toggle near the TLS text
|
||||
@@ -1170,7 +1170,7 @@ describe('AdminPage', () => {
|
||||
|
||||
// Find the email panel and click its "Send test email" button (scoped to avoid admin webhook panel)
|
||||
const emailHeading = screen.getByRole('heading', { name: /email \(smtp\)/i });
|
||||
const emailPanel = emailHeading.closest('.bg-white');
|
||||
const emailPanel = emailHeading.closest<HTMLElement>('.bg-white');
|
||||
const testBtn = within(emailPanel!).getByRole('button', { name: /send test email/i });
|
||||
fireEvent.click(testBtn);
|
||||
|
||||
@@ -1207,7 +1207,7 @@ describe('AdminPage', () => {
|
||||
|
||||
// Find the webhook panel heading ('Webhook') — exact match to avoid 'Admin Webhook'
|
||||
const webhookHeading = screen.getByRole('heading', { name: /^webhook$/i });
|
||||
const webhookCard = webhookHeading.closest('.bg-white');
|
||||
const webhookCard = webhookHeading.closest<HTMLElement>('.bg-white');
|
||||
// Find the toggle button in webhook card
|
||||
const webhookToggle = within(webhookCard!).getByRole('button');
|
||||
fireEvent.click(webhookToggle);
|
||||
@@ -1245,7 +1245,7 @@ describe('AdminPage', () => {
|
||||
|
||||
// Find the Save button in the admin webhook panel
|
||||
const adminWebhookHeading = screen.getByRole('heading', { name: /admin webhook/i });
|
||||
const adminWebhookCard = adminWebhookHeading.closest('.bg-white');
|
||||
const adminWebhookCard = adminWebhookHeading.closest<HTMLElement>('.bg-white');
|
||||
const saveBtn = within(adminWebhookCard!).getByRole('button', { name: /save/i });
|
||||
fireEvent.click(saveBtn);
|
||||
|
||||
@@ -1284,7 +1284,7 @@ describe('AdminPage', () => {
|
||||
// The channel column header is t('settings.notificationPreferences.email') = 'Email' (CSS uppercases it)
|
||||
// Find the AdminNotificationsPanel by its h2 heading role='heading'
|
||||
const matrixHeading = await screen.findByRole('heading', { name: /^notifications$/i });
|
||||
const matrixCard = matrixHeading.closest('.bg-white');
|
||||
const matrixCard = matrixHeading.closest<HTMLElement>('.bg-white');
|
||||
|
||||
// The matrix toggle button is inside the card (not a checkbox — it's a button toggle)
|
||||
const matrixToggle = matrixCard?.querySelector('button');
|
||||
@@ -1308,7 +1308,7 @@ describe('AdminPage', () => {
|
||||
|
||||
// Wait for the OIDC section — heading is 'Single Sign-On (OIDC)'
|
||||
const oidcHeading = await screen.findByRole('heading', { name: /single sign-on/i });
|
||||
const oidcCard = oidcHeading.closest('.bg-white');
|
||||
const oidcCard = oidcHeading.closest<HTMLElement>('.bg-white');
|
||||
|
||||
// Issuer field (placeholder: https://accounts.google.com)
|
||||
const issuerInput = within(oidcCard!).getByPlaceholderText('https://accounts.google.com');
|
||||
@@ -1320,12 +1320,12 @@ describe('AdminPage', () => {
|
||||
|
||||
// Client ID field
|
||||
const clientIdLabel = within(oidcCard!).getByText('Client ID');
|
||||
const clientIdInput = clientIdLabel.closest('div')!.querySelector('input')!;
|
||||
const clientIdInput = clientIdLabel.closest<HTMLElement>('div')!.querySelector('input')!;
|
||||
fireEvent.change(clientIdInput, { target: { value: 'my-client-id' } });
|
||||
|
||||
// Client Secret field
|
||||
const clientSecretLabel = within(oidcCard!).getByText('Client Secret');
|
||||
const clientSecretInput = clientSecretLabel.closest('div')!.querySelector('input')!;
|
||||
const clientSecretInput = clientSecretLabel.closest<HTMLElement>('div')!.querySelector('input')!;
|
||||
fireEvent.change(clientSecretInput, { target: { value: 'my-client-secret' } });
|
||||
|
||||
// Verify the inputs updated
|
||||
|
||||
+32
-1746
File diff suppressed because it is too large
Load Diff
@@ -1426,7 +1426,7 @@ describe('AtlasPage', () => {
|
||||
|
||||
// Find and click the Add button (should be enabled now since bucketForm.name is set)
|
||||
const addButtons = screen.queryAllByRole('button').filter(
|
||||
(b) => !b.disabled && (b.textContent?.trim() === 'Add' || b.textContent?.includes('Add')),
|
||||
(b) => !(b as HTMLButtonElement).disabled && (b.textContent?.trim() === 'Add' || b.textContent?.includes('Add')),
|
||||
);
|
||||
if (addButtons.length > 0) {
|
||||
await user.click(addButtons[addButtons.length - 1]);
|
||||
|
||||
+128
-891
File diff suppressed because it is too large
Load Diff
@@ -209,7 +209,7 @@ describe('DashboardPage', () => {
|
||||
|
||||
describe('FE-PAGE-DASH-011: Archive trip moves it to the archive filter', () => {
|
||||
it('archiving a trip removes it from active and shows it under the archive filter', async () => {
|
||||
const archivedTrip = buildTrip({ title: 'Paris Adventure', start_date: '2026-07-01', end_date: '2026-07-10', is_archived: true });
|
||||
const archivedTrip = buildTrip({ title: 'Paris Adventure', start_date: '2026-07-01', end_date: '2026-07-10', is_archived: 1 });
|
||||
server.use(
|
||||
http.put('/api/trips/:id', () => HttpResponse.json({ trip: archivedTrip })),
|
||||
);
|
||||
@@ -273,7 +273,7 @@ describe('DashboardPage', () => {
|
||||
|
||||
describe('FE-PAGE-DASH-014: Archive filter reveals archived trips', () => {
|
||||
it('shows archived trips when the archive filter is selected', async () => {
|
||||
const oldTrip = buildTrip({ title: 'Old Rome Trip', start_date: '2024-01-01', end_date: '2024-01-07', is_archived: true });
|
||||
const oldTrip = buildTrip({ title: 'Old Rome Trip', start_date: '2024-01-01', end_date: '2024-01-07', is_archived: 1 });
|
||||
server.use(
|
||||
http.get('/api/trips', ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
@@ -414,8 +414,8 @@ describe('DashboardPage', () => {
|
||||
describe('FE-PAGE-DASH-020: Archived section - restore trip', () => {
|
||||
it('clicking restore in archived section moves trip back to active list', async () => {
|
||||
const activeTrip = buildTrip({ title: 'Paris Adventure', start_date: '2026-07-01', end_date: '2026-07-10' });
|
||||
const archivedTrip = buildTrip({ title: 'Old Rome Trip', start_date: '2024-01-01', end_date: '2024-01-07', is_archived: true });
|
||||
const restoredTrip = { ...archivedTrip, is_archived: false };
|
||||
const archivedTrip = buildTrip({ title: 'Old Rome Trip', start_date: '2024-01-01', end_date: '2024-01-07', is_archived: 1 });
|
||||
const restoredTrip = { ...archivedTrip, is_archived: 0 };
|
||||
|
||||
server.use(
|
||||
http.get('/api/trips', ({ request }) => {
|
||||
@@ -624,7 +624,7 @@ describe('DashboardPage', () => {
|
||||
describe('FE-PAGE-DASH-027: Archive filter toggles archived trips in and out of view', () => {
|
||||
it('shows archived trips under the archive filter and hides them under planned', async () => {
|
||||
const activeTrip = buildTrip({ title: 'Active Trip', start_date: '2026-08-01', end_date: '2026-08-10' });
|
||||
const archivedTrip = buildTrip({ title: 'Old Archived Trip', start_date: '2024-03-01', end_date: '2024-03-07', is_archived: true });
|
||||
const archivedTrip = buildTrip({ title: 'Old Archived Trip', start_date: '2024-03-01', end_date: '2024-03-07', is_archived: 1 });
|
||||
|
||||
server.use(
|
||||
http.get('/api/trips', ({ request }) => {
|
||||
@@ -660,8 +660,8 @@ describe('DashboardPage', () => {
|
||||
describe('FE-PAGE-DASH-028: Unarchive action restores trip to active list', () => {
|
||||
it('clicking restore on an archived trip removes it from archived section', async () => {
|
||||
const activeTrip = buildTrip({ title: 'My Active Trip', start_date: '2026-08-01', end_date: '2026-08-10' });
|
||||
const archivedTrip = buildTrip({ title: 'Restored Trip', start_date: '2024-06-01', end_date: '2024-06-07', is_archived: true });
|
||||
const restoredTrip = { ...archivedTrip, is_archived: false };
|
||||
const archivedTrip = buildTrip({ title: 'Restored Trip', start_date: '2024-06-01', end_date: '2024-06-07', is_archived: 1 });
|
||||
const restoredTrip = { ...archivedTrip, is_archived: 0 };
|
||||
|
||||
server.use(
|
||||
http.get('/api/trips', ({ request }) => {
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { tripsApi, authApi, reservationsApi } from '../api/client'
|
||||
import { tripRepo } from '../repo/tripRepo'
|
||||
import { useAuthStore } from '../store/authStore'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { getApiErrorMessage } from '../types'
|
||||
import Navbar from '../components/Layout/Navbar'
|
||||
import DemoBanner from '../components/Layout/DemoBanner'
|
||||
import TripFormModal from '../components/Trips/TripFormModal'
|
||||
@@ -13,7 +8,11 @@ import CopyTripDialog from '../components/shared/CopyTripDialog'
|
||||
import CustomSelect from '../components/shared/CustomSelect'
|
||||
import PlaceAvatar from '../components/shared/PlaceAvatar'
|
||||
import MobileTopBar from '../components/Layout/MobileTopBar'
|
||||
import { useToast } from '../components/shared/Toast'
|
||||
import { useDashboard } from './dashboard/useDashboard'
|
||||
import {
|
||||
type DashboardTrip, type HeroBundle, type TravelStats, type UpcomingReservation,
|
||||
MS_PER_DAY, daysUntil, getTripStatus,
|
||||
} from './dashboard/dashboardModel'
|
||||
import {
|
||||
Plus, Edit2, Trash2, Archive, Copy, ArrowRight, MapPin,
|
||||
Plane, Hotel, Utensils, Clock, RefreshCw, ArrowRightLeft, Calendar,
|
||||
@@ -21,58 +20,6 @@ import {
|
||||
} from 'lucide-react'
|
||||
import '../styles/dashboard.css'
|
||||
|
||||
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
|
||||
shared_count?: number
|
||||
[key: string]: string | number | boolean | null | undefined
|
||||
}
|
||||
|
||||
const MS_PER_DAY = 86400000
|
||||
|
||||
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.getTime() - today.getTime()) / MS_PER_DAY)
|
||||
}
|
||||
|
||||
function getTripStatus(trip: DashboardTrip): 'ongoing' | 'today' | 'tomorrow' | 'future' | 'past' | 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)
|
||||
if (until === null) return null
|
||||
if (until === 0) return 'today'
|
||||
if (until === 1) return 'tomorrow'
|
||||
if (until > 1) return 'future'
|
||||
return 'past'
|
||||
}
|
||||
|
||||
function sortTrips(trips: DashboardTrip[]): DashboardTrip[] {
|
||||
const today = new Date().toISOString().split('T')[0]
|
||||
const rank = (t: DashboardTrip) => {
|
||||
if (t.start_date && t.end_date && t.start_date <= today && t.end_date >= today) return 0
|
||||
if (t.start_date && t.start_date >= today) return 1
|
||||
return 2
|
||||
}
|
||||
return [...trips].sort((a, b) => {
|
||||
const ra = rank(a), rb = rank(b)
|
||||
if (ra !== rb) return ra - rb
|
||||
const ad = a.start_date || '', bd = b.start_date || ''
|
||||
if (ra <= 1) return ad.localeCompare(bd)
|
||||
return bd.localeCompare(ad)
|
||||
})
|
||||
}
|
||||
|
||||
const GRADIENTS = [
|
||||
'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
|
||||
'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
|
||||
@@ -111,20 +58,6 @@ function initials(name: string | null | undefined): string {
|
||||
return name.slice(0, 2).toUpperCase()
|
||||
}
|
||||
|
||||
interface Member { id: number; username: string; avatar_url?: string | null }
|
||||
interface Place {
|
||||
id: number; name: string; image_url: string | null; lat: number | null; lng: number | null
|
||||
google_place_id: string | null; osm_id: string | null
|
||||
category_color?: string | null; category_icon?: string | null
|
||||
}
|
||||
interface HeroBundle { members: Member[]; places: Place[] }
|
||||
interface TravelStats { totalTrips?: number; totalDays?: number; totalPlaces?: number; totalDistanceKm?: number; countries?: string[] }
|
||||
interface UpcomingReservation {
|
||||
id: number; trip_id: number; title: string; type: string
|
||||
reservation_time?: string | null; day_date?: string | null
|
||||
location?: string | null; place_name?: string | null; trip_title?: string | null
|
||||
}
|
||||
|
||||
const RES_ICON: Record<string, React.ReactElement> = {
|
||||
flight: <Plane size={16} />, hotel: <Hotel size={16} />, restaurant: <Utensils size={16} />,
|
||||
}
|
||||
@@ -143,157 +76,24 @@ function useIsMobile(): boolean {
|
||||
}
|
||||
|
||||
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 [viewMode, setViewMode] = useState<'grid' | 'list'>(() => (localStorage.getItem('trek_dashboard_view') as 'grid' | 'list') || 'grid')
|
||||
const [deleteTrip, setDeleteTrip] = useState<DashboardTrip | null>(null)
|
||||
const [copyTrip, setCopyTrip] = useState<DashboardTrip | null>(null)
|
||||
const [tripFilter, setTripFilter] = useState<'planned' | 'archive' | 'completed'>('planned')
|
||||
|
||||
const [stats, setStats] = useState<TravelStats | null>(null)
|
||||
const [upcoming, setUpcoming] = useState<UpcomingReservation[]>([])
|
||||
const [heroBundle, setHeroBundle] = useState<HeroBundle | null>(null)
|
||||
|
||||
const navigate = useNavigate()
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const toast = useToast()
|
||||
const { t, locale } = useTranslation()
|
||||
const { demoMode } = useAuthStore()
|
||||
|
||||
const toggleViewMode = () => {
|
||||
setViewMode(prev => {
|
||||
const next = prev === 'grid' ? 'list' : 'grid'
|
||||
localStorage.setItem('trek_dashboard_view', next)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (searchParams.get('create') === '1') {
|
||||
setShowForm(true)
|
||||
setSearchParams({}, { replace: true })
|
||||
}
|
||||
}, [searchParams])
|
||||
|
||||
useEffect(() => { loadTrips() }, [])
|
||||
|
||||
// Travel stats + upcoming reservations power the atlas row and the sidebar.
|
||||
// Both are best-effort: a failure just leaves that section empty.
|
||||
useEffect(() => {
|
||||
authApi.travelStats().then(setStats).catch(() => {})
|
||||
reservationsApi.upcoming().then((r: { reservations: UpcomingReservation[] }) => setUpcoming(r.reservations || [])).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const loadTrips = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const { trips, archivedTrips } = await tripRepo.list()
|
||||
setTrips(sortTrips(trips))
|
||||
setArchivedTrips(sortTrips(archivedTrips))
|
||||
} catch {
|
||||
toast.error(t('dashboard.toast.loadError'))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const today = new Date().toISOString().split('T')[0]
|
||||
const spotlight = trips.find(t => t.start_date && t.end_date && t.start_date <= today && t.end_date >= today)
|
||||
|| trips.find(t => t.start_date && t.start_date >= today)
|
||||
|| trips[0]
|
||||
|| null
|
||||
const rest = spotlight ? trips.filter(t => t.id !== spotlight.id) : trips
|
||||
|
||||
// Pull the spotlight trip's members + places so the boarding pass can show
|
||||
// real buddies and place thumbnails instead of placeholders.
|
||||
useEffect(() => {
|
||||
if (!spotlight) { setHeroBundle(null); return }
|
||||
let cancelled = false
|
||||
tripsApi.bundle(spotlight.id)
|
||||
.then((b: HeroBundle) => { if (!cancelled) setHeroBundle({ members: b.members || [], places: b.places || [] }) })
|
||||
.catch(() => { if (!cancelled) setHeroBundle(null) })
|
||||
return () => { cancelled = true }
|
||||
}, [spotlight?.id])
|
||||
|
||||
const handleCreate = async (tripData: Record<string, unknown>) => {
|
||||
try {
|
||||
const data = await tripsApi.create(tripData)
|
||||
setTrips(prev => sortTrips([data.trip, ...prev]))
|
||||
toast.success(t('dashboard.toast.created'))
|
||||
return data
|
||||
} catch (err: unknown) {
|
||||
throw new Error(getApiErrorMessage(err, t('dashboard.toast.createError')))
|
||||
}
|
||||
}
|
||||
|
||||
const handleUpdate = async (tripData: Record<string, unknown>) => {
|
||||
if (!editingTrip) return
|
||||
try {
|
||||
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: unknown) {
|
||||
throw new Error(getApiErrorMessage(err, t('dashboard.toast.updateError')))
|
||||
}
|
||||
}
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!deleteTrip) return
|
||||
try {
|
||||
await tripsApi.delete(deleteTrip.id)
|
||||
setTrips(prev => prev.filter(t => t.id !== deleteTrip.id))
|
||||
setArchivedTrips(prev => prev.filter(t => t.id !== deleteTrip.id))
|
||||
toast.success(t('dashboard.toast.deleted'))
|
||||
} catch {
|
||||
toast.error(t('dashboard.toast.deleteError'))
|
||||
}
|
||||
setDeleteTrip(null)
|
||||
}
|
||||
|
||||
const handleArchive = async (id: number) => {
|
||||
try {
|
||||
const data = await tripsApi.archive(id)
|
||||
setTrips(prev => prev.filter(t => t.id !== id))
|
||||
setArchivedTrips(prev => sortTrips([data.trip, ...prev]))
|
||||
toast.success(t('dashboard.toast.archived'))
|
||||
} catch {
|
||||
toast.error(t('dashboard.toast.archiveError'))
|
||||
}
|
||||
}
|
||||
|
||||
const handleUnarchive = async (id: number) => {
|
||||
try {
|
||||
const data = await tripsApi.unarchive(id)
|
||||
setArchivedTrips(prev => prev.filter(t => t.id !== id))
|
||||
setTrips(prev => sortTrips([data.trip, ...prev]))
|
||||
toast.success(t('dashboard.toast.restored'))
|
||||
} catch {
|
||||
toast.error(t('dashboard.toast.restoreError'))
|
||||
}
|
||||
}
|
||||
|
||||
const confirmCopy = async () => {
|
||||
if (!copyTrip) return
|
||||
try {
|
||||
const data = await tripsApi.copy(copyTrip.id, { title: `${copyTrip.title} (${t('dashboard.copySuffix')})` })
|
||||
setTrips(prev => sortTrips([data.trip, ...prev]))
|
||||
toast.success(t('dashboard.toast.copied'))
|
||||
} catch {
|
||||
toast.error(t('dashboard.toast.copyError'))
|
||||
}
|
||||
setCopyTrip(null)
|
||||
}
|
||||
|
||||
const gridTrips = tripFilter === 'archive' ? archivedTrips
|
||||
: tripFilter === 'completed' ? rest.filter(t => getTripStatus(t) === 'past')
|
||||
: rest.filter(t => getTripStatus(t) !== 'past')
|
||||
// Page = wiring container: all state, data loading and mutations live in the
|
||||
// useDashboard data hook; this component only renders what it returns.
|
||||
const {
|
||||
demoMode, locale, t, navigate,
|
||||
spotlight, heroBundle, stats, upcoming, gridTrips, isLoading,
|
||||
tripFilter, setTripFilter, viewMode, toggleViewMode,
|
||||
showForm, setShowForm, editingTrip, setEditingTrip,
|
||||
deleteTrip, setDeleteTrip, copyTrip, setCopyTrip, setTrips,
|
||||
handleCreate, handleUpdate, confirmDelete, handleArchive, handleUnarchive, confirmCopy,
|
||||
} = useDashboard()
|
||||
|
||||
return (
|
||||
<div className="trek-dash trek-dash-shell">
|
||||
<>
|
||||
{/* Navbar lives outside .trek-dash so it keeps the app-wide font + button
|
||||
styling instead of inheriting the dashboard scope's Geist font and the
|
||||
`.trek-dash button` reset (which shifted the bell icon + menu items). */}
|
||||
<Navbar />
|
||||
<div className="trek-dash trek-dash-shell">
|
||||
{demoMode && <DemoBanner />}
|
||||
<div className="trek-dash-scroll">
|
||||
<MobileTopBar />
|
||||
@@ -404,7 +204,8 @@ export default function DashboardPage(): React.ReactElement {
|
||||
onClose={() => setCopyTrip(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -551,7 +352,7 @@ function AtlasStats({ stats }: { stats: TravelStats | null }): React.ReactElemen
|
||||
<section className="atlas">
|
||||
<div className="atlas-card passport">
|
||||
<div className="label">{t('dashboard.atlas.countriesVisited')}</div>
|
||||
<div className="value mono">{countries.length} <span className="unit" style={{ color: 'oklch(1 0 0 / .55)' }}>{t('dashboard.atlas.ofTotal', { total: 195 })}</span></div>
|
||||
<div className="value mono">{countries.length} <span className="unit text-[oklch(1_0_0_/_.55)]">{t('dashboard.atlas.ofTotal', { total: 195 })}</span></div>
|
||||
<div className="passport-flags">
|
||||
{countries.slice(0, 5).map((c, i) => (
|
||||
<span key={i} className="flag" title={c}>
|
||||
@@ -689,13 +490,13 @@ function CurrencyTool(): React.ReactElement {
|
||||
<div className="fx-field">
|
||||
<div className="lbl">{t('dashboard.fx.from')}</div>
|
||||
<input className="amt mono" value={amount} onChange={e => setAmount(e.target.value)} inputMode="decimal" />
|
||||
<CustomSelect value={from} onChange={setFrom} options={ccyOptions} searchable size="sm" style={{ marginTop: 6 }} />
|
||||
<CustomSelect value={from} onChange={v => setFrom(String(v))} options={ccyOptions} searchable size="sm" style={{ marginTop: 6 }} />
|
||||
</div>
|
||||
<button className="fx-swap" aria-label={t('dashboard.aria.swapCurrencies')} onClick={swap}><ArrowRightLeft size={14} /></button>
|
||||
<div className="fx-field">
|
||||
<div className="lbl">{t('dashboard.fx.to')}</div>
|
||||
<input className="amt mono" value={converted != null ? converted.toFixed(2) : '—'} readOnly />
|
||||
<CustomSelect value={to} onChange={setTo} options={ccyOptions} searchable size="sm" style={{ marginTop: 6 }} />
|
||||
<CustomSelect value={to} onChange={v => setTo(String(v))} options={ccyOptions} searchable size="sm" style={{ marginTop: 6 }} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="fx-rate">
|
||||
|
||||
@@ -60,7 +60,7 @@ describe('FilesPage', () => {
|
||||
|
||||
describe('FE-PAGE-FILES-002: Trip name displayed in Navbar after load', () => {
|
||||
it('passes the trip name to Navbar after data loads', async () => {
|
||||
const trip = buildTrip({ id: 1, name: 'Rome Trip' });
|
||||
const trip = buildTrip({ id: 1, title: 'Rome Trip' });
|
||||
server.use(
|
||||
http.get('/api/trips/:id', () => HttpResponse.json({ trip })),
|
||||
);
|
||||
@@ -130,7 +130,7 @@ describe('FilesPage', () => {
|
||||
renderFilesPage(1);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockLoadFiles).toHaveBeenCalledWith('1');
|
||||
expect(mockLoadFiles).toHaveBeenCalledWith(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,71 +1,28 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useParams, useNavigate, Link } from 'react-router-dom'
|
||||
import { useTripStore } from '../store/tripStore'
|
||||
import { tripRepo } from '../repo/tripRepo'
|
||||
import { placeRepo } from '../repo/placeRepo'
|
||||
import Navbar from '../components/Layout/Navbar'
|
||||
import React from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import PageShell from '../components/Layout/PageShell'
|
||||
import { PageSpinner } from '../components/shared/Spinner'
|
||||
import FileManager from '../components/Files/FileManager'
|
||||
import { ArrowLeft } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
import type { Trip, Place, TripFile } from '../types'
|
||||
import { useFiles } from './files/useFiles'
|
||||
|
||||
export default function FilesPage(): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const { id: tripId } = useParams<{ id: string }>()
|
||||
const navigate = useNavigate()
|
||||
const tripStore = useTripStore()
|
||||
|
||||
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 (): Promise<void> => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const [tripData, placesData] = await Promise.all([
|
||||
tripRepo.get(tripId),
|
||||
placeRepo.list(tripId),
|
||||
])
|
||||
setTrip(tripData.trip)
|
||||
setPlaces(placesData.places)
|
||||
await tripStore.loadFiles(tripId)
|
||||
} catch (err: unknown) {
|
||||
navigate('/dashboard')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setFiles(tripStore.files)
|
||||
}, [tripStore.files])
|
||||
|
||||
const handleUpload = async (formData: FormData): Promise<void> => {
|
||||
await tripStore.addFile(tripId, formData)
|
||||
}
|
||||
|
||||
const handleDelete = async (fileId: number): Promise<void> => {
|
||||
await tripStore.deleteFile(tripId, fileId)
|
||||
}
|
||||
// Page = wiring container: trip/places load, file sync + handlers live in the hook.
|
||||
const { tripId, navigate, trip, places, files, isLoading, handleUpload, handleDelete } = useFiles()
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50">
|
||||
<div className="w-10 h-10 border-4 border-slate-200 border-t-slate-700 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
<PageSpinner
|
||||
wrapperClassName="min-h-screen flex items-center justify-center bg-slate-50"
|
||||
className="w-10 h-10 border-4 border-slate-200 border-t-slate-700"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50">
|
||||
<Navbar tripTitle={trip?.name} tripId={tripId} showBack onBack={() => navigate(`/trips/${tripId}`)} />
|
||||
|
||||
<div style={{ paddingTop: 'var(--nav-h)' }}>
|
||||
<PageShell className="bg-slate-50" navbar={{ tripTitle: trip?.title, tripId, showBack: true, onBack: () => navigate(`/trips/${tripId}`) }}>
|
||||
<div className="max-w-5xl mx-auto px-4 py-6">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<Link
|
||||
@@ -80,7 +37,7 @@ export default function FilesPage(): React.ReactElement {
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">{t('files.pageTitle')}</h1>
|
||||
<p className="text-gray-500 text-sm">{t('files.subtitle', { count: files.length, trip: trip?.name })}</p>
|
||||
<p className="text-gray-500 text-sm">{t('files.subtitle', { count: files.length, trip: trip?.title })}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -92,7 +49,6 @@ export default function FilesPage(): React.ReactElement {
|
||||
tripId={tripId}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PageShell>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import React, { useState, useEffect, FormEvent, ChangeEvent } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import React, { ChangeEvent } from 'react'
|
||||
import { Mail, ArrowLeft, CheckCircle2, Terminal } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { authApi } from '../api/client'
|
||||
import { useForgotPassword } from './forgotPassword/useForgotPassword'
|
||||
|
||||
const inputBase: React.CSSProperties = {
|
||||
width: '100%', padding: '11px 12px 11px 38px', borderRadius: 12,
|
||||
@@ -13,36 +12,8 @@ const inputBase: React.CSSProperties = {
|
||||
|
||||
const ForgotPasswordPage: React.FC = () => {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const [email, setEmail] = useState('')
|
||||
const [submitted, setSubmitted] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [smtpConfigured, setSmtpConfigured] = useState<boolean | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Probe whether SMTP is configured so we can warn the user up-front
|
||||
// that the link will land in the server console instead of their
|
||||
// inbox. Null while pending — hint is hidden until we know.
|
||||
authApi.getAppConfig?.()
|
||||
.then((cfg: any) => {
|
||||
const hasEmail = !!cfg?.available_channels?.email
|
||||
setSmtpConfigured(hasEmail)
|
||||
})
|
||||
.catch(() => setSmtpConfigured(null))
|
||||
}, [])
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (isLoading) return
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await authApi.forgotPassword({ email: email.trim() })
|
||||
} catch {
|
||||
// Enumeration-safe: success UX regardless of server outcome.
|
||||
}
|
||||
setSubmitted(true)
|
||||
setIsLoading(false)
|
||||
}
|
||||
// Page = wiring container: form state, the SMTP probe and submit live in the hook.
|
||||
const { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit } = useForgotPassword()
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
@@ -84,7 +55,7 @@ const ForgotPasswordPage: React.FC = () => {
|
||||
borderRadius: 10, textAlign: 'left',
|
||||
display: 'flex', alignItems: 'flex-start', gap: 10,
|
||||
}}>
|
||||
<Terminal size={16} style={{ color: '#92400e', marginTop: 1, flexShrink: 0 }} />
|
||||
<Terminal size={16} className="text-[#92400e]" style={{ marginTop: 1, flexShrink: 0 }} />
|
||||
<p style={{ fontSize: 12.5, color: '#92400e', lineHeight: 1.55, margin: 0 }}>
|
||||
{t('login.forgotPasswordSmtpHintOff')}
|
||||
</p>
|
||||
@@ -110,7 +81,7 @@ const ForgotPasswordPage: React.FC = () => {
|
||||
background: '#fffbeb', border: '1px solid #fde68a',
|
||||
borderRadius: 10, display: 'flex', alignItems: 'flex-start', gap: 10,
|
||||
}}>
|
||||
<Terminal size={15} style={{ color: '#92400e', marginTop: 1, flexShrink: 0 }} />
|
||||
<Terminal size={15} className="text-[#92400e]" style={{ marginTop: 1, flexShrink: 0 }} />
|
||||
<p style={{ fontSize: 12.5, color: '#92400e', lineHeight: 1.5, margin: 0 }}>
|
||||
{t('login.forgotPasswordSmtpHintOff')}
|
||||
</p>
|
||||
@@ -122,7 +93,7 @@ const ForgotPasswordPage: React.FC = () => {
|
||||
{t('common.email')}
|
||||
</label>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<Mail size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
|
||||
<Mail size={15} className="text-[#9ca3af]" style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
|
||||
<input
|
||||
type="email" value={email}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)}
|
||||
|
||||
@@ -1,66 +1,35 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import React from 'react'
|
||||
import { Bell, CheckCheck, Trash2 } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { useInAppNotificationStore } from '../store/inAppNotificationStore.ts'
|
||||
import { useSettingsStore } from '../store/settingsStore'
|
||||
import Navbar from '../components/Layout/Navbar'
|
||||
import PageShell from '../components/Layout/PageShell'
|
||||
import { Spinner } from '../components/shared/Spinner'
|
||||
import InAppNotificationItem from '../components/Notifications/InAppNotificationItem.tsx'
|
||||
import { useInAppNotifications } from './inAppNotifications/useInAppNotifications'
|
||||
|
||||
export default function InAppNotificationsPage(): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const { settings } = useSettingsStore()
|
||||
const darkMode = settings.dark_mode
|
||||
const dark = darkMode === true || darkMode === 'dark' || (darkMode === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)
|
||||
|
||||
const { notifications, unreadCount, total, isLoading, hasMore, fetchNotifications, markAllRead, deleteAll } = useInAppNotificationStore()
|
||||
const [unreadOnly, setUnreadOnly] = useState(false)
|
||||
const loaderRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
fetchNotifications(true)
|
||||
}, [])
|
||||
|
||||
// Reload when filter changes
|
||||
useEffect(() => {
|
||||
// We need to fetch with the unreadOnly filter — re-fetch from scratch
|
||||
// The store fetchNotifications doesn't take a filter param directly,
|
||||
// so we use the API directly for filtered view via a side channel.
|
||||
// For now, reset and fetch — store always loads all, filter is client-side.
|
||||
fetchNotifications(true)
|
||||
}, [unreadOnly])
|
||||
|
||||
// Infinite scroll
|
||||
useEffect(() => {
|
||||
if (!loaderRef.current) return
|
||||
const observer = new IntersectionObserver(entries => {
|
||||
if (entries[0].isIntersecting && hasMore && !isLoading) {
|
||||
fetchNotifications(false)
|
||||
}
|
||||
}, { threshold: 0.1 })
|
||||
observer.observe(loaderRef.current)
|
||||
return () => observer.disconnect()
|
||||
}, [hasMore, isLoading])
|
||||
|
||||
const displayed = unreadOnly ? notifications.filter(n => !n.is_read) : notifications
|
||||
// Page = wiring container: store, filter, fetch + infinite scroll live in the hook.
|
||||
const {
|
||||
notifications, unreadCount, total, isLoading, hasMore,
|
||||
unreadOnly, setUnreadOnly, loaderRef, displayed,
|
||||
markAllRead, deleteAll,
|
||||
} = useInAppNotifications()
|
||||
|
||||
return (
|
||||
<div className="min-h-screen" style={{ background: 'var(--bg-primary)' }}>
|
||||
<Navbar />
|
||||
<div style={{ paddingTop: 'var(--nav-h)' }}>
|
||||
<div className="max-w-2xl mx-auto px-4 py-8">
|
||||
<PageShell background="var(--bg-primary)">
|
||||
<div className="max-w-2xl mx-auto px-4 py-8">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold" style={{ color: 'var(--text-primary)' }}>
|
||||
<h1 className="text-xl font-semibold text-content">
|
||||
{t('notifications.title')}
|
||||
{unreadCount > 0 && (
|
||||
<span className="ml-2 px-2 py-0.5 rounded-full text-xs font-medium align-middle inline-flex items-center justify-center"
|
||||
style={{ background: 'var(--text-primary)', color: 'var(--bg-primary)' }}>
|
||||
<span className="ml-2 px-2 py-0.5 rounded-full text-xs font-medium align-middle inline-flex items-center justify-center bg-content text-surface">
|
||||
{unreadCount}
|
||||
</span>
|
||||
)}
|
||||
</h1>
|
||||
<p className="text-sm mt-0.5" style={{ color: 'var(--text-muted)' }}>
|
||||
<p className="text-sm mt-0.5 text-content-muted">
|
||||
{total} {total === 1 ? 'notification' : 'notifications'}
|
||||
</p>
|
||||
</div>
|
||||
@@ -70,8 +39,7 @@ export default function InAppNotificationsPage(): React.ReactElement {
|
||||
{unreadCount > 0 && (
|
||||
<button
|
||||
onClick={markAllRead}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-colors"
|
||||
style={{ background: 'var(--bg-hover)', color: 'var(--text-secondary)' }}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-colors text-content-secondary bg-surface-hover"
|
||||
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-tertiary)'}
|
||||
onMouseLeave={e => e.currentTarget.style.background = 'var(--bg-hover)'}
|
||||
>
|
||||
@@ -95,40 +63,29 @@ export default function InAppNotificationsPage(): React.ReactElement {
|
||||
<div className="flex gap-2 mb-4">
|
||||
<button
|
||||
onClick={() => setUnreadOnly(false)}
|
||||
className="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors"
|
||||
style={{
|
||||
background: !unreadOnly ? 'var(--text-primary)' : 'var(--bg-hover)',
|
||||
color: !unreadOnly ? 'var(--bg-primary)' : 'var(--text-secondary)',
|
||||
}}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${!unreadOnly ? 'bg-content text-surface' : 'bg-surface-hover text-content-secondary'}`}
|
||||
>
|
||||
{t('notifications.all')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setUnreadOnly(true)}
|
||||
className="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors"
|
||||
style={{
|
||||
background: unreadOnly ? 'var(--text-primary)' : 'var(--bg-hover)',
|
||||
color: unreadOnly ? 'var(--bg-primary)' : 'var(--text-secondary)',
|
||||
}}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${unreadOnly ? 'bg-content text-surface' : 'bg-surface-hover text-content-secondary'}`}
|
||||
>
|
||||
{t('notifications.unreadOnly')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Notification list */}
|
||||
<div
|
||||
className="rounded-xl border overflow-hidden"
|
||||
style={{ borderColor: 'var(--border-primary)', background: 'var(--bg-card)' }}
|
||||
>
|
||||
<div className="rounded-xl border overflow-hidden border-edge bg-surface-card">
|
||||
{isLoading && displayed.length === 0 ? (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<div className="w-6 h-6 border-2 border-slate-200 border-t-current rounded-full animate-spin" />
|
||||
<Spinner className="w-6 h-6 border-2 border-slate-200 border-t-current" />
|
||||
</div>
|
||||
) : displayed.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-16 px-4 text-center gap-3">
|
||||
<Bell className="w-12 h-12" style={{ color: 'var(--text-faint)' }} />
|
||||
<p className="text-base font-medium" style={{ color: 'var(--text-muted)' }}>{t('notifications.empty')}</p>
|
||||
<p className="text-sm" style={{ color: 'var(--text-faint)' }}>{t('notifications.emptyDescription')}</p>
|
||||
<Bell className="w-12 h-12 text-content-faint" />
|
||||
<p className="text-base font-medium text-content-muted">{t('notifications.empty')}</p>
|
||||
<p className="text-sm text-content-faint">{t('notifications.emptyDescription')}</p>
|
||||
</div>
|
||||
) : (
|
||||
displayed.map(n => (
|
||||
@@ -139,12 +96,11 @@ export default function InAppNotificationsPage(): React.ReactElement {
|
||||
{/* Infinite scroll trigger */}
|
||||
{hasMore && (
|
||||
<div ref={loaderRef} className="flex items-center justify-center py-4">
|
||||
{isLoading && <div className="w-5 h-5 border-2 border-slate-200 border-t-current rounded-full animate-spin" />}
|
||||
{isLoading && <Spinner className="w-5 h-5 border-2 border-slate-200 border-t-current" />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PageShell>
|
||||
)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -194,6 +194,40 @@ describe('JourneyPage', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// FE-PAGE-JOURNEY-007b — XSS regression: the suggestion banner interpolates
|
||||
// a user-controlled trip title into an HTML template that is later passed to
|
||||
// dangerouslySetInnerHTML. The sanitiser in @trek/shared must drop any script
|
||||
// payload, otherwise renaming a trip is a one-click XSS for anyone visiting
|
||||
// the Journey page.
|
||||
it('FE-PAGE-JOURNEY-007b: sanitises script payloads in suggestion title', async () => {
|
||||
const malicious = {
|
||||
id: 1337,
|
||||
title: '<img src=x onerror=alert(1)><script>window.__pwned=true</script>',
|
||||
start_date: '2026-03-01',
|
||||
end_date: '2026-04-01',
|
||||
place_count: 3,
|
||||
};
|
||||
server.use(
|
||||
http.get('/api/journeys', () =>
|
||||
HttpResponse.json({ journeys: [] })
|
||||
),
|
||||
http.get('/api/journeys/suggestions', () =>
|
||||
HttpResponse.json({ trips: [malicious] })
|
||||
),
|
||||
);
|
||||
|
||||
render(<JourneyPage />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Trip just ended/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// The script tag must not survive the sanitiser anywhere in the rendered DOM.
|
||||
expect(document.querySelector('script')).toBeNull();
|
||||
expect(document.querySelector('img[onerror]')).toBeNull();
|
||||
// And the side effect would only fire if onerror executed.
|
||||
expect((window as unknown as { __pwned?: boolean }).__pwned).toBeUndefined();
|
||||
});
|
||||
|
||||
// FE-PAGE-JOURNEY-008
|
||||
it('FE-PAGE-JOURNEY-008: shows active journey hero when active journey exists', async () => {
|
||||
const active = buildJourneyListItem({ id: 10, title: 'Active Trip', status: 'active', trip_date_min: '2020-01-01', trip_date_max: '2099-12-31' });
|
||||
|
||||
@@ -1,16 +1,12 @@
|
||||
import { useEffect, useState, useMemo, useRef } from 'react'
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { useJourneyStore } from '../store/journeyStore'
|
||||
import { journeyApi } from '../api/client'
|
||||
import Navbar from '../components/Layout/Navbar'
|
||||
import { useToast } from '../components/shared/Toast'
|
||||
import { useTranslation } from '../i18n'
|
||||
import PageShell from '../components/Layout/PageShell'
|
||||
import { useTranslation, TransHtml } from '../i18n'
|
||||
import {
|
||||
Plus, Search, Sparkles, Calendar, MapPin, BookOpen, Camera,
|
||||
Check, X, ChevronRight, RefreshCw, Users,
|
||||
} from 'lucide-react'
|
||||
import type { Journey } from '../store/journeyStore'
|
||||
import { computeJourneyLifecycle } from '../utils/journeyLifecycle'
|
||||
import { useJourney } from './journey/useJourney'
|
||||
|
||||
const GRADIENTS = [
|
||||
'linear-gradient(135deg, #0F172A 0%, #6366F1 45%, #EC4899 100%)',
|
||||
@@ -35,92 +31,20 @@ function timeAgo(timestamp: number, t: (k: string, p?: any) => string): string {
|
||||
}
|
||||
|
||||
export default function JourneyPage() {
|
||||
const navigate = useNavigate()
|
||||
const toast = useToast()
|
||||
const { t } = useTranslation()
|
||||
const { journeys, loading, loadJourneys, createJourney } = useJourneyStore()
|
||||
|
||||
const [showCreate, setShowCreate] = useState(false)
|
||||
const [newTitle, setNewTitle] = useState('')
|
||||
const [availableTrips, setAvailableTrips] = useState<any[]>([])
|
||||
const [selectedTripIds, setSelectedTripIds] = useState<Set<number>>(new Set())
|
||||
const [searchOpen, setSearchOpen] = useState(false)
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const searchInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// suggestion
|
||||
const [suggestions, setSuggestions] = useState<any[]>([])
|
||||
const [dismissedSuggestions, setDismissedSuggestions] = useState<Set<number>>(new Set())
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
|
||||
useEffect(() => {
|
||||
loadJourneys()
|
||||
journeyApi.suggestions().then(d => setSuggestions(d.trips || [])).catch(() => {})
|
||||
}, [])
|
||||
|
||||
// The bottom-nav "+" opens the new-journey modal via ?create=1.
|
||||
useEffect(() => {
|
||||
if (searchParams.get('create') === '1') {
|
||||
openCreateModal()
|
||||
setSearchParams(p => { p.delete('create'); return p }, { replace: true })
|
||||
}
|
||||
}, [searchParams])
|
||||
|
||||
const activeSuggestion = suggestions.find(s => !dismissedSuggestions.has(s.id))
|
||||
|
||||
const activeJourney = useMemo(() => {
|
||||
if (searchQuery.trim()) return null
|
||||
return journeys.find(j => {
|
||||
const j2 = j as any
|
||||
return computeJourneyLifecycle(j.status, j2.trip_date_min, j2.trip_date_max) === 'live'
|
||||
}) || null
|
||||
}, [journeys, searchQuery])
|
||||
|
||||
const filteredJourneys = useMemo(() => {
|
||||
const q = searchQuery.trim().toLowerCase()
|
||||
if (!q) return journeys.filter(j => j.id !== activeJourney?.id)
|
||||
return journeys.filter(j => {
|
||||
const inTitle = j.title.toLowerCase().includes(q)
|
||||
const inSubtitle = j.subtitle?.toLowerCase().includes(q) ?? false
|
||||
return inTitle || inSubtitle
|
||||
})
|
||||
}, [journeys, activeJourney, searchQuery])
|
||||
|
||||
const openCreateModal = async (preSelectedTripId?: number) => {
|
||||
setShowCreate(true)
|
||||
setNewTitle('')
|
||||
const initial = new Set<number>()
|
||||
if (preSelectedTripId) initial.add(preSelectedTripId)
|
||||
setSelectedTripIds(initial)
|
||||
try {
|
||||
const data = await journeyApi.availableTrips()
|
||||
setAvailableTrips(data.trips || [])
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!newTitle.trim()) return
|
||||
try {
|
||||
const j = await createJourney({
|
||||
title: newTitle.trim(),
|
||||
trip_ids: [...selectedTripIds],
|
||||
})
|
||||
setShowCreate(false)
|
||||
navigate(`/journey/${j.id}`)
|
||||
} catch {
|
||||
toast.error(t('journey.createError'))
|
||||
}
|
||||
}
|
||||
|
||||
const totalPlaces = useMemo(() => {
|
||||
return availableTrips.filter(t => selectedTripIds.has(t.id)).reduce((sum: number, t: any) => sum + (t.place_count || 0), 0)
|
||||
}, [availableTrips, selectedTripIds])
|
||||
// Page = wiring container: store load, create modal, search + suggestions in the hook.
|
||||
const {
|
||||
navigate, journeys, loading,
|
||||
showCreate, setShowCreate, newTitle, setNewTitle,
|
||||
availableTrips, selectedTripIds, setSelectedTripIds,
|
||||
searchOpen, setSearchOpen, searchQuery, setSearchQuery, searchInputRef,
|
||||
activeSuggestion, setDismissedSuggestions,
|
||||
activeJourney, filteredJourneys,
|
||||
openCreateModal, handleCreate, totalPlaces,
|
||||
} = useJourney()
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-zinc-50 dark:bg-zinc-950">
|
||||
<Navbar />
|
||||
<div style={{ paddingTop: 'var(--nav-h, 56px)' }}>
|
||||
<PageShell className="bg-zinc-50 dark:bg-zinc-950" navOffset="var(--nav-h, 56px)">
|
||||
<div className="max-w-[1440px] mx-auto">
|
||||
|
||||
{/* Header — mobile */}
|
||||
@@ -162,29 +86,29 @@ export default function JourneyPage() {
|
||||
|
||||
{/* Header — desktop (unified toolbar) */}
|
||||
<div className="hidden md:block px-8 pt-10 pb-7">
|
||||
<div style={{
|
||||
background: 'var(--bg-tertiary)', borderRadius: 18,
|
||||
border: '1px solid var(--border-primary)',
|
||||
<div className="bg-surface-tertiary border border-edge" style={{
|
||||
borderRadius: 18,
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.06), 0 1px 2px rgba(0,0,0,0.04)',
|
||||
padding: '14px 16px 14px 22px',
|
||||
display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap',
|
||||
}}>
|
||||
<h2 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: 'var(--text-primary)', letterSpacing: '-0.01em', flexShrink: 0 }}>
|
||||
<h2 className="text-content" style={{ margin: 0, fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em', flexShrink: 0 }}>
|
||||
{t('journey.title')}
|
||||
</h2>
|
||||
<div style={{ width: 1, height: 22, background: 'var(--border-faint)', flexShrink: 0 }} />
|
||||
<span style={{ fontSize: 13, color: 'var(--text-muted)' }}>
|
||||
<div className="bg-edge-faint" style={{ width: 1, height: 22, flexShrink: 0 }} />
|
||||
<span className="text-content-muted" style={{ fontSize: 13 }}>
|
||||
{t('journey.frontpage.subtitle')}
|
||||
</span>
|
||||
|
||||
<div style={{ display: 'inline-flex', gap: 6, alignItems: 'center', marginLeft: 'auto', flexShrink: 0 }}>
|
||||
<button
|
||||
onClick={() => openCreateModal()}
|
||||
className="bg-accent text-accent-text"
|
||||
style={{
|
||||
appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
padding: '9px 14px', borderRadius: 10, fontSize: 13, fontWeight: 500,
|
||||
background: 'var(--accent)', color: 'var(--accent-text)', flexShrink: 0,
|
||||
flexShrink: 0,
|
||||
marginLeft: 2,
|
||||
transition: 'opacity 0.15s ease',
|
||||
}}
|
||||
@@ -213,7 +137,7 @@ export default function JourneyPage() {
|
||||
<div>
|
||||
<div className="text-[10px] font-semibold tracking-[0.12em] uppercase opacity-70">{t("journey.frontpage.suggestionLabel")}</div>
|
||||
<div className="text-[13px] mt-0.5">
|
||||
<span dangerouslySetInnerHTML={{ __html: t('journey.frontpage.suggestionText', { title: activeSuggestion.title }) }} />
|
||||
<TransHtml html="journey.frontpage.suggestionText" params={{ title: activeSuggestion.title }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -355,7 +279,6 @@ export default function JourneyPage() {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Create Modal */}
|
||||
{showCreate && (
|
||||
@@ -463,7 +386,7 @@ export default function JourneyPage() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PageShell>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import { useEffect, useState, useMemo, useRef, useCallback } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { journeyApi } from '../api/client'
|
||||
import { useTranslation, SUPPORTED_LANGUAGES } from '../i18n'
|
||||
import { useSettingsStore } from '../store/settingsStore'
|
||||
import {
|
||||
@@ -10,51 +7,13 @@ import {
|
||||
ThumbsUp, ThumbsDown,
|
||||
} from 'lucide-react'
|
||||
import JourneyMap from '../components/Journey/JourneyMap'
|
||||
import type { JourneyMapHandle } from '../components/Journey/JourneyMap'
|
||||
import JournalBody from '../components/Journey/JournalBody'
|
||||
import PhotoLightbox from '../components/Journey/PhotoLightbox'
|
||||
import MobileMapTimeline from '../components/Journey/MobileMapTimeline'
|
||||
import MobileEntryView from '../components/Journey/MobileEntryView'
|
||||
import { useIsMobile } from '../hooks/useIsMobile'
|
||||
import { formatLocationName } from '../utils/formatters'
|
||||
import { DAY_COLORS } from '../components/Journey/dayColors'
|
||||
|
||||
interface PublicEntry {
|
||||
id: number
|
||||
title?: string | null
|
||||
story?: string | null
|
||||
entry_date: string
|
||||
entry_time?: string | null
|
||||
location_name?: string | null
|
||||
location_lat?: number | null
|
||||
location_lng?: number | null
|
||||
mood?: string | null
|
||||
weather?: string | null
|
||||
pros_cons?: { pros: string[]; cons: string[] } | null
|
||||
photos: PublicPhoto[]
|
||||
}
|
||||
|
||||
interface PublicPhoto {
|
||||
id: number
|
||||
entry_id: number
|
||||
photo_id: number
|
||||
provider?: string
|
||||
asset_id?: string | null
|
||||
owner_id?: number | null
|
||||
file_path?: string | null
|
||||
caption?: string | null
|
||||
}
|
||||
|
||||
interface PublicGalleryPhoto {
|
||||
id: number
|
||||
journey_id: number
|
||||
photo_id: number
|
||||
provider?: string
|
||||
asset_id?: string | null
|
||||
owner_id?: number | null
|
||||
file_path?: string | null
|
||||
caption?: string | null
|
||||
}
|
||||
import { useJourneyPublic } from './journeyPublic/useJourneyPublic'
|
||||
|
||||
const MOOD_CONFIG: Record<string, { icon: typeof Smile; label: string; bg: string; text: string }> = {
|
||||
amazing: { icon: Laugh, label: 'Amazing', bg: 'bg-pink-50 dark:bg-pink-900/20', text: 'text-pink-600 dark:text-pink-400' },
|
||||
@@ -85,97 +44,18 @@ function formatDate(d: string, locale?: string): { weekday: string; month: strin
|
||||
}
|
||||
}
|
||||
|
||||
function groupByDate(entries: PublicEntry[]): Map<string, PublicEntry[]> {
|
||||
const groups = new Map<string, PublicEntry[]>()
|
||||
for (const e of entries) {
|
||||
const d = e.entry_date
|
||||
if (!groups.has(d)) groups.set(d, [])
|
||||
groups.get(d)!.push(e)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
export default function JourneyPublicPage() {
|
||||
const { token } = useParams()
|
||||
const [data, setData] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(false)
|
||||
const isMobile = useIsMobile()
|
||||
const [view, setView] = useState<'timeline' | 'gallery' | 'map'>('timeline')
|
||||
const [lightbox, setLightbox] = useState<{ photos: { id: string; src: string; caption?: string | null }[]; index: number } | null>(null)
|
||||
const { t } = useTranslation()
|
||||
const [showLangPicker, setShowLangPicker] = useState(false)
|
||||
const locale = useSettingsStore(s => s.settings.language) || 'en'
|
||||
const mapRef = useRef<JourneyMapHandle>(null)
|
||||
const [activeEntryId, setActiveEntryId] = useState<string | null>(null)
|
||||
const [viewingEntry, setViewingEntry] = useState<PublicEntry | null>(null)
|
||||
|
||||
const handleMarkerClick = useCallback((entryId: string) => {
|
||||
setActiveEntryId(entryId)
|
||||
mapRef.current?.highlightMarker(entryId)
|
||||
document.querySelector(`[data-entry-id="${entryId}"]`)
|
||||
?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return
|
||||
journeyApi.getPublicJourney(token)
|
||||
.then(d => setData(d))
|
||||
.catch(() => setError(true))
|
||||
.finally(() => setLoading(false))
|
||||
}, [token])
|
||||
|
||||
const entries = (data?.entries || []) as PublicEntry[]
|
||||
const gallery = (data?.gallery || []) as PublicGalleryPhoto[]
|
||||
const perms = data?.permissions || {}
|
||||
const journey = data?.journey || {}
|
||||
const stats = data?.stats || {}
|
||||
|
||||
const timelineEntries = useMemo(() => entries, [entries])
|
||||
const groupedEntries = useMemo(() => groupByDate(timelineEntries), [timelineEntries])
|
||||
const sortedDates = useMemo(() => [...groupedEntries.keys()].sort(), [groupedEntries])
|
||||
const mapEntries = useMemo(
|
||||
() => timelineEntries.filter(e => e.location_lat && e.location_lng),
|
||||
[timelineEntries],
|
||||
)
|
||||
const allPhotos = gallery
|
||||
|
||||
// Map entries with day color/label for colored markers.
|
||||
// dayIdx is derived from sortedDates (ALL timeline dates) so marker colors
|
||||
// stay in sync with the timeline day headers even when some days have no locations.
|
||||
const sidebarMapItems = useMemo(() => {
|
||||
const counters = new Map<string, number>()
|
||||
return mapEntries.map(e => {
|
||||
const dayIdx = sortedDates.indexOf(e.entry_date)
|
||||
const dayLabel = (counters.get(e.entry_date) ?? 0) + 1
|
||||
counters.set(e.entry_date, dayLabel)
|
||||
return {
|
||||
id: String(e.id),
|
||||
lat: e.location_lat!,
|
||||
lng: e.location_lng!,
|
||||
title: e.title || '',
|
||||
mood: e.mood,
|
||||
created_at: e.entry_date,
|
||||
entry_date: e.entry_date,
|
||||
dayColor: DAY_COLORS[dayIdx % DAY_COLORS.length],
|
||||
dayLabel,
|
||||
}
|
||||
})
|
||||
}, [mapEntries, sortedDates])
|
||||
|
||||
// Two-column desktop layout: timeline feed left + sticky map right
|
||||
const desktopTwoColumn = !isMobile && perms.share_timeline && perms.share_map
|
||||
|
||||
// Set default view based on permissions
|
||||
useEffect(() => {
|
||||
if (!perms.share_timeline && perms.share_gallery) setView('gallery')
|
||||
else if (!perms.share_timeline && !perms.share_gallery && perms.share_map) setView('map')
|
||||
}, [perms])
|
||||
|
||||
// When switching to desktop two-column, 'map' standalone tab no longer exists
|
||||
useEffect(() => {
|
||||
if (desktopTwoColumn && view === 'map') setView('timeline')
|
||||
}, [desktopTwoColumn, view])
|
||||
// Page = wiring container: the share fetch, view state and all timeline/map
|
||||
// derivations live in the hook; the render helpers below stay next to the JSX.
|
||||
const {
|
||||
token, data, loading, error, isMobile, locale,
|
||||
view, setView, lightbox, setLightbox, showLangPicker, setShowLangPicker,
|
||||
mapRef, activeEntryId, setActiveEntryId, viewingEntry, setViewingEntry, handleMarkerClick,
|
||||
perms, journey, stats,
|
||||
timelineEntries, groupedEntries, sortedDates, sidebarMapItems, allPhotos,
|
||||
desktopTwoColumn,
|
||||
} = useJourneyPublic()
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
|
||||
+21
-259
@@ -1,260 +1,22 @@
|
||||
import React, { useState, useEffect, useMemo, useRef } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import { useAuthStore } from '../store/authStore'
|
||||
import { useSettingsStore } from '../store/settingsStore'
|
||||
import { SUPPORTED_LANGUAGES, useTranslation, detectBrowserLanguage } from '../i18n'
|
||||
import { authApi, configApi } from '../api/client'
|
||||
import { hasStoredLanguage } from '../store/settingsStore'
|
||||
import { getApiErrorMessage } from '../types'
|
||||
import React from 'react'
|
||||
import { SUPPORTED_LANGUAGES, useTranslation } from '../i18n'
|
||||
import { Plane, Eye, EyeOff, Mail, Lock, MapPin, Calendar, Package, User, Globe, Zap, Users, Wallet, Map, CheckSquare, BookMarked, FolderOpen, Route, Shield, KeyRound, ChevronDown } from 'lucide-react'
|
||||
|
||||
interface AppConfig {
|
||||
has_users: boolean
|
||||
allow_registration: boolean
|
||||
setup_complete: boolean
|
||||
demo_mode: boolean
|
||||
oidc_configured: boolean
|
||||
oidc_display_name?: string
|
||||
oidc_only_mode: boolean
|
||||
password_login: boolean
|
||||
password_registration: boolean
|
||||
oidc_login: boolean
|
||||
oidc_registration: boolean
|
||||
env_override_oidc_only: boolean
|
||||
}
|
||||
import { useLogin } from './login/useLogin'
|
||||
|
||||
export default function LoginPage(): React.ReactElement {
|
||||
const { t, language } = useTranslation()
|
||||
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 [inviteToken, setInviteToken] = useState<string>('')
|
||||
const [inviteValid, setInviteValid] = useState<boolean>(false)
|
||||
const exchangeInitiated = useRef(false)
|
||||
|
||||
const [langDropdownOpen, setLangDropdownOpen] = useState<boolean>(false)
|
||||
|
||||
const { login, register, demoLogin, completeMfaLogin, loadUser } = useAuthStore()
|
||||
const { setLanguageLocal, setLanguageTransient } = useSettingsStore()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const noRedirect = !!(location.state as { noRedirect?: boolean } | null)?.noRedirect
|
||||
|
||||
const redirectTarget = useMemo(() => {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const redirect = params.get('redirect')
|
||||
// Only allow relative paths starting with / to prevent open redirect attacks
|
||||
if (redirect && redirect.startsWith('/') && !redirect.startsWith('//') && !redirect.startsWith('/\\')) {
|
||||
return redirect
|
||||
}
|
||||
return '/dashboard'
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (redirectTarget !== '/dashboard') {
|
||||
sessionStorage.setItem('oidc_redirect', redirectTarget)
|
||||
}
|
||||
}, [redirectTarget])
|
||||
|
||||
useEffect(() => {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
|
||||
const invite = params.get('invite')
|
||||
const oidcCode = params.get('oidc_code')
|
||||
const oidcError = params.get('oidc_error')
|
||||
|
||||
if (invite) {
|
||||
setInviteToken(invite)
|
||||
setMode('register')
|
||||
authApi.validateInvite(invite).then(() => {
|
||||
setInviteValid(true)
|
||||
}).catch(() => {
|
||||
setError(t('login.invalidInviteLink'))
|
||||
})
|
||||
window.history.replaceState({}, '', window.location.pathname)
|
||||
}
|
||||
|
||||
if (oidcCode) {
|
||||
if (exchangeInitiated.current) return
|
||||
exchangeInitiated.current = true
|
||||
setIsLoading(true)
|
||||
fetch('/api/auth/oidc/exchange?code=' + encodeURIComponent(oidcCode), { credentials: 'include' })
|
||||
.then(r => r.json())
|
||||
.then(async data => {
|
||||
window.history.replaceState({}, '', '/login')
|
||||
if (data.token) {
|
||||
await loadUser()
|
||||
const savedRedirect = sessionStorage.getItem('oidc_redirect') || '/dashboard'
|
||||
sessionStorage.removeItem('oidc_redirect')
|
||||
navigate(savedRedirect, { replace: true })
|
||||
} else {
|
||||
setError(data.error || t('login.oidcFailed'))
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
window.history.replaceState({}, '', '/login')
|
||||
setError(t('login.oidcFailed'))
|
||||
})
|
||||
.finally(() => setIsLoading(false))
|
||||
return
|
||||
}
|
||||
|
||||
if (oidcError) {
|
||||
const errorMessages: Record<string, string> = {
|
||||
registration_disabled: t('login.oidc.registrationDisabled'),
|
||||
no_email: t('login.oidc.noEmail'),
|
||||
token_failed: t('login.oidc.tokenFailed'),
|
||||
invalid_state: t('login.oidc.invalidState'),
|
||||
}
|
||||
setError(errorMessages[oidcError] || oidcError)
|
||||
sessionStorage.removeItem('oidc_redirect')
|
||||
window.history.replaceState({}, '', '/login')
|
||||
return
|
||||
}
|
||||
|
||||
const CONFIG_CACHE_KEY = 'trek_app_config_cache'
|
||||
authApi.getAppConfig?.()
|
||||
.then((config: AppConfig) => {
|
||||
try { localStorage.setItem(CONFIG_CACHE_KEY, JSON.stringify(config)) } catch { /* ignore quota errors */ }
|
||||
return { config, fromCache: false }
|
||||
})
|
||||
.catch(() => {
|
||||
try {
|
||||
const raw = localStorage.getItem(CONFIG_CACHE_KEY)
|
||||
return raw ? { config: JSON.parse(raw) as AppConfig, fromCache: true } : { config: null as AppConfig | null, fromCache: false }
|
||||
} catch { return { config: null as AppConfig | null, fromCache: false } }
|
||||
})
|
||||
.then(({ config, fromCache }) => {
|
||||
if (config) {
|
||||
setAppConfig(config)
|
||||
if (!config.has_users) setMode('register')
|
||||
// Skip auto-redirect when config is from cache — network is unreliable
|
||||
// and auto-redirecting to the IdP could loop if the proxy changed.
|
||||
if (!fromCache && !config.password_login && config.oidc_login && config.oidc_configured && config.has_users && !invite && !noRedirect) {
|
||||
window.location.href = '/api/auth/oidc/login'
|
||||
}
|
||||
}
|
||||
})
|
||||
}, [navigate, t, noRedirect])
|
||||
|
||||
// Language detection chain (runs once on mount, only if user has no saved preference):
|
||||
// 1. localStorage → already in store initial state, skip
|
||||
// 2. Browser/OS language (navigator.languages)
|
||||
// 3. Server default (DEFAULT_LANGUAGE env var)
|
||||
// 4. 'en' → hardcoded fallback already in store
|
||||
useEffect(() => {
|
||||
if (hasStoredLanguage()) return
|
||||
|
||||
const detected = detectBrowserLanguage()
|
||||
if (detected) {
|
||||
setLanguageTransient(detected)
|
||||
return
|
||||
}
|
||||
|
||||
configApi.getPublicConfig()
|
||||
.then(({ defaultLanguage }) => { if (defaultLanguage) setLanguageTransient(defaultLanguage) })
|
||||
.catch((err) => console.warn('Failed to fetch default language config:', err))
|
||||
}, [setLanguageTransient])
|
||||
|
||||
useEffect(() => {
|
||||
if (!langDropdownOpen) return
|
||||
const close = () => setLangDropdownOpen(false)
|
||||
document.addEventListener('click', close)
|
||||
return () => document.removeEventListener('click', close)
|
||||
}, [langDropdownOpen])
|
||||
|
||||
const handleDemoLogin = async (): Promise<void> => {
|
||||
setError('')
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await demoLogin()
|
||||
setShowTakeoff(true)
|
||||
setTimeout(() => navigate(redirectTarget), 2600)
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : t('login.demoFailed'))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const [showTakeoff, setShowTakeoff] = useState<boolean>(false)
|
||||
const [mfaStep, setMfaStep] = useState(false)
|
||||
const [mfaToken, setMfaToken] = useState('')
|
||||
const [mfaCode, setMfaCode] = useState('')
|
||||
const [passwordChangeStep, setPasswordChangeStep] = useState(false)
|
||||
const [savedLoginPassword, setSavedLoginPassword] = useState('')
|
||||
const [newPassword, setNewPassword] = useState('')
|
||||
const [confirmPassword, setConfirmPassword] = useState('')
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>): Promise<void> => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setIsLoading(true)
|
||||
try {
|
||||
if (passwordChangeStep) {
|
||||
if (!newPassword) { setError(t('settings.passwordRequired')); setIsLoading(false); return }
|
||||
if (newPassword.length < 8) { setError(t('settings.passwordTooShort')); setIsLoading(false); return }
|
||||
if (newPassword !== confirmPassword) { setError(t('settings.passwordMismatch')); setIsLoading(false); return }
|
||||
await authApi.changePassword({ current_password: savedLoginPassword, new_password: newPassword })
|
||||
await loadUser({ silent: true })
|
||||
setShowTakeoff(true)
|
||||
setTimeout(() => navigate(redirectTarget), 2600)
|
||||
return
|
||||
}
|
||||
if (mode === 'login' && mfaStep) {
|
||||
if (!mfaCode.trim()) {
|
||||
setError(t('login.mfaCodeRequired'))
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
const mfaResult = await completeMfaLogin(mfaToken, mfaCode)
|
||||
if ('user' in mfaResult && mfaResult.user?.must_change_password) {
|
||||
setSavedLoginPassword(password)
|
||||
setPasswordChangeStep(true)
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
setShowTakeoff(true)
|
||||
setTimeout(() => navigate(redirectTarget), 2600)
|
||||
return
|
||||
}
|
||||
if (mode === 'register') {
|
||||
if (!username.trim()) { setError(t('login.usernameRequired')); setIsLoading(false); return }
|
||||
if (password.length < 8) { setError(t('login.passwordMinLength')); setIsLoading(false); return }
|
||||
await register(username, email, password, inviteToken || undefined)
|
||||
} else {
|
||||
const result = await login(email, password)
|
||||
if ('mfa_required' in result && result.mfa_required && 'mfa_token' in result) {
|
||||
setMfaToken(result.mfa_token)
|
||||
setMfaStep(true)
|
||||
setMfaCode('')
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
if ('user' in result && result.user?.must_change_password) {
|
||||
setSavedLoginPassword(password)
|
||||
setPasswordChangeStep(true)
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
setShowTakeoff(true)
|
||||
setTimeout(() => navigate(redirectTarget), 2600)
|
||||
} catch (err: unknown) {
|
||||
setError(getApiErrorMessage(err, t('login.error')))
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const showRegisterOption = (appConfig?.password_registration || !appConfig?.has_users || inviteValid) && (appConfig?.setup_complete !== false || !appConfig?.has_users)
|
||||
|
||||
// In OIDC-only mode, show a minimal page that redirects directly to the IdP
|
||||
const oidcOnly = !appConfig?.password_login && appConfig?.oidc_login && appConfig?.oidc_configured
|
||||
// Page = wiring container: the whole auth surface lives in the useLogin hook.
|
||||
const {
|
||||
navigate,
|
||||
mode, setMode,
|
||||
username, setUsername, email, setEmail, password, setPassword, showPassword, setShowPassword,
|
||||
isLoading, error, setError, appConfig, inviteToken,
|
||||
langDropdownOpen, setLangDropdownOpen, setLanguageLocal,
|
||||
showTakeoff, mfaStep, setMfaStep, mfaToken, setMfaToken, mfaCode, setMfaCode,
|
||||
passwordChangeStep, newPassword, setNewPassword, confirmPassword, setConfirmPassword,
|
||||
noRedirect, showRegisterOption, oidcOnly,
|
||||
handleDemoLogin, handleSubmit,
|
||||
} = useLogin()
|
||||
|
||||
const inputBase: React.CSSProperties = {
|
||||
width: '100%', padding: '11px 12px 11px 40px', border: '1px solid #e5e7eb',
|
||||
@@ -688,7 +450,7 @@ export default function LoginPage(): React.ReactElement {
|
||||
<div>
|
||||
<label style={{ display: 'block', fontSize: 12.5, fontWeight: 600, color: '#374151', marginBottom: 6 }}>{t('settings.newPassword')}</label>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<Lock size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
|
||||
<Lock size={15} className="text-[#9ca3af]" style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
|
||||
<input
|
||||
type="password" value={newPassword} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNewPassword(e.target.value)} required
|
||||
placeholder={t('settings.newPassword')} style={inputBase}
|
||||
@@ -700,7 +462,7 @@ export default function LoginPage(): React.ReactElement {
|
||||
<div>
|
||||
<label style={{ display: 'block', fontSize: 12.5, fontWeight: 600, color: '#374151', marginBottom: 6 }}>{t('settings.confirmPassword')}</label>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<Lock size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
|
||||
<Lock size={15} className="text-[#9ca3af]" style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
|
||||
<input
|
||||
type="password" value={confirmPassword} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setConfirmPassword(e.target.value)} required
|
||||
placeholder={t('settings.confirmPassword')} style={inputBase}
|
||||
@@ -716,7 +478,7 @@ export default function LoginPage(): React.ReactElement {
|
||||
<div>
|
||||
<label style={{ display: 'block', fontSize: 12.5, fontWeight: 600, color: '#374151', marginBottom: 6 }}>{t('login.mfaCodeLabel')}</label>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<KeyRound size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
|
||||
<KeyRound size={15} className="text-[#9ca3af]" style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
|
||||
<input
|
||||
type="text"
|
||||
inputMode="text"
|
||||
@@ -746,7 +508,7 @@ export default function LoginPage(): React.ReactElement {
|
||||
<div>
|
||||
<label style={{ display: 'block', fontSize: 12.5, fontWeight: 600, color: '#374151', marginBottom: 6 }}>{t('login.username')}</label>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<User size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
|
||||
<User size={15} className="text-[#9ca3af]" style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
|
||||
<input
|
||||
type="text" value={username} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setUsername(e.target.value)} required
|
||||
placeholder="admin" style={inputBase}
|
||||
@@ -762,7 +524,7 @@ export default function LoginPage(): React.ReactElement {
|
||||
<div>
|
||||
<label style={{ display: 'block', fontSize: 12.5, fontWeight: 600, color: '#374151', marginBottom: 6 }}>{t('common.email')}</label>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<Mail size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
|
||||
<Mail size={15} className="text-[#9ca3af]" style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
|
||||
<input
|
||||
type="email" value={email} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)} required
|
||||
placeholder={t('login.emailPlaceholder')} style={inputBase}
|
||||
@@ -778,7 +540,7 @@ export default function LoginPage(): React.ReactElement {
|
||||
<div>
|
||||
<label style={{ display: 'block', fontSize: 12.5, fontWeight: 600, color: '#374151', marginBottom: 6 }}>{t('common.password')}</label>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<Lock size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
|
||||
<Lock size={15} className="text-[#9ca3af]" style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
|
||||
<input
|
||||
type={showPassword ? 'text' : 'password'} value={password} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)} required
|
||||
placeholder="••••••••" style={{ ...inputBase, paddingRight: 44 }}
|
||||
|
||||
@@ -1,148 +1,16 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useAuthStore } from '../store/authStore'
|
||||
import { oauthApi } from '../api/client'
|
||||
import React from 'react'
|
||||
import { SCOPE_GROUPS } from '../api/oauthScopes'
|
||||
import { Lock, ShieldCheck, AlertTriangle, Loader2, LogIn } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
|
||||
interface ValidateResult {
|
||||
valid: boolean
|
||||
error?: string
|
||||
error_description?: string
|
||||
client?: { name: string; allowed_scopes: string[] }
|
||||
scopes?: string[]
|
||||
consentRequired?: boolean
|
||||
loginRequired?: boolean
|
||||
scopeSelectable?: boolean
|
||||
}
|
||||
|
||||
type PageState = 'loading' | 'login_required' | 'consent' | 'auto_approving' | 'error' | 'done'
|
||||
import { useOAuthAuthorize } from './oauthAuthorize/useOAuthAuthorize'
|
||||
|
||||
export default function OAuthAuthorizePage(): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const { isAuthenticated, isLoading: authLoading, loadUser } = useAuthStore()
|
||||
const [pageState, setPageState] = useState<PageState>('loading')
|
||||
const [validation, setValidation] = useState<ValidateResult | null>(null)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null)
|
||||
const [selectedScopes, setSelectedScopes] = useState<string[]>([])
|
||||
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const clientId = params.get('client_id') || ''
|
||||
const redirectUri = params.get('redirect_uri') || ''
|
||||
const scope = params.get('scope') || ''
|
||||
const state = params.get('state') || ''
|
||||
const codeChallenge = params.get('code_challenge') || ''
|
||||
const ccMethod = params.get('code_challenge_method') || ''
|
||||
const resource = params.get('resource') || undefined
|
||||
|
||||
// Load auth state once, then validate
|
||||
useEffect(() => {
|
||||
loadUser({ silent: true }).catch(() => {})
|
||||
}, [loadUser])
|
||||
|
||||
useEffect(() => {
|
||||
if (authLoading) return
|
||||
validateRequest()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [authLoading, isAuthenticated])
|
||||
|
||||
async function validateRequest() {
|
||||
setPageState('loading')
|
||||
try {
|
||||
const result = await oauthApi.validate({
|
||||
client_id: clientId,
|
||||
redirect_uri: redirectUri,
|
||||
scope,
|
||||
state,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: ccMethod,
|
||||
response_type: 'code',
|
||||
resource,
|
||||
})
|
||||
setValidation(result)
|
||||
|
||||
if (!result.valid) {
|
||||
setPageState('error')
|
||||
setErrorMsg(result.error_description || result.error || 'Invalid authorization request')
|
||||
return
|
||||
}
|
||||
|
||||
if (result.loginRequired) {
|
||||
setPageState('login_required')
|
||||
return
|
||||
}
|
||||
|
||||
if (!result.consentRequired) {
|
||||
// Consent already on record — auto-approve silently with the full validated scope
|
||||
setPageState('auto_approving')
|
||||
await submitConsent(true, result.scopes ?? [])
|
||||
return
|
||||
}
|
||||
|
||||
// Pre-select all scopes the client is requesting — user can deselect
|
||||
setSelectedScopes(result.scopes ?? [])
|
||||
setPageState('consent')
|
||||
} catch (err: unknown) {
|
||||
setPageState('error')
|
||||
setErrorMsg('Failed to validate authorization request. Please try again.')
|
||||
}
|
||||
}
|
||||
|
||||
async function submitConsent(approved: boolean, scopes: string[] = selectedScopes) {
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const result = await oauthApi.authorize({
|
||||
client_id: clientId,
|
||||
redirect_uri: redirectUri,
|
||||
// When approving, send only the scopes the user selected; deny uses original scope
|
||||
scope: approved ? scopes.join(' ') : scope,
|
||||
state,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: ccMethod,
|
||||
approved,
|
||||
resource,
|
||||
})
|
||||
setPageState('done')
|
||||
window.location.href = result.redirect
|
||||
} catch {
|
||||
setPageState('error')
|
||||
setErrorMsg('Authorization failed. Please try again.')
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
function toggleScope(s: string) {
|
||||
setSelectedScopes(prev =>
|
||||
prev.includes(s) ? prev.filter(x => x !== s) : [...prev, s]
|
||||
)
|
||||
}
|
||||
|
||||
function toggleGroup(groupScopes: string[], allSelected: boolean) {
|
||||
setSelectedScopes(prev =>
|
||||
allSelected
|
||||
? prev.filter(s => !groupScopes.includes(s))
|
||||
: [...new Set([...prev, ...groupScopes])]
|
||||
)
|
||||
}
|
||||
|
||||
function handleLoginRedirect() {
|
||||
const next = '/oauth/consent?' + params.toString() + window.location.hash
|
||||
window.location.href = '/login?redirect=' + encodeURIComponent(next)
|
||||
}
|
||||
|
||||
// Group requested scopes by their translated group name
|
||||
const scopesByGroup = React.useMemo(() => {
|
||||
const requested = validation?.scopes || []
|
||||
const groups: Record<string, string[]> = {}
|
||||
for (const s of requested) {
|
||||
const keys = SCOPE_GROUPS[s]
|
||||
const group = keys ? t(keys.groupKey) : 'Other'
|
||||
if (!groups[group]) groups[group] = []
|
||||
groups[group].push(s)
|
||||
}
|
||||
return groups
|
||||
}, [validation, t])
|
||||
// Page = wiring container: the validate→consent state machine lives in the hook.
|
||||
const {
|
||||
pageState, validation, submitting, errorMsg, selectedScopes, clientId,
|
||||
scopesByGroup, submitConsent, toggleScope, toggleGroup, handleLoginRedirect,
|
||||
} = useOAuthAuthorize()
|
||||
|
||||
// ---- Render states ----
|
||||
|
||||
@@ -152,7 +20,7 @@ export default function OAuthAuthorizePage(): React.ReactElement {
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--accent-primary, #4f46e5)' }} />
|
||||
<p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
|
||||
{pageState === 'auto_approving' ? 'Authorizing…' : 'Loading…'}
|
||||
{pageState === 'auto_approving' ? t('oauth.authorize.authorizing') : t('oauth.authorize.loading')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -164,7 +32,7 @@ export default function OAuthAuthorizePage(): React.ReactElement {
|
||||
<div className="min-h-screen flex items-center justify-center p-4" style={{ background: 'var(--bg-primary)' }}>
|
||||
<div className="w-full max-w-sm rounded-xl shadow-lg p-8 space-y-4 text-center" style={{ background: 'var(--bg-card)' }}>
|
||||
<AlertTriangle className="w-10 h-10 mx-auto text-red-500" />
|
||||
<h1 className="text-xl font-semibold" style={{ color: 'var(--text-primary)' }}>Authorization Error</h1>
|
||||
<h1 className="text-xl font-semibold" style={{ color: 'var(--text-primary)' }}>{t('oauth.authorize.errorTitle')}</h1>
|
||||
<p className="text-sm" style={{ color: 'var(--text-secondary)' }}>{errorMsg}</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -177,9 +45,9 @@ export default function OAuthAuthorizePage(): React.ReactElement {
|
||||
<div className="w-full max-w-sm rounded-xl shadow-lg p-8 space-y-5" style={{ background: 'var(--bg-card)' }}>
|
||||
<div className="text-center space-y-2">
|
||||
<Lock className="w-10 h-10 mx-auto" style={{ color: 'var(--accent-primary, #4f46e5)' }} />
|
||||
<h1 className="text-xl font-semibold" style={{ color: 'var(--text-primary)' }}>Sign in to continue</h1>
|
||||
<h1 className="text-xl font-semibold" style={{ color: 'var(--text-primary)' }}>{t('oauth.authorize.loginTitle')}</h1>
|
||||
<p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
|
||||
<strong>{validation?.client?.name || clientId}</strong> wants access to your TREK account. Please sign in first.
|
||||
{t('oauth.authorize.loginDescription', { client: validation?.client?.name || clientId })}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
@@ -187,7 +55,7 @@ export default function OAuthAuthorizePage(): React.ReactElement {
|
||||
className="w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium text-white"
|
||||
style={{ background: 'var(--accent-primary, #4f46e5)' }}>
|
||||
<LogIn className="w-4 h-4" />
|
||||
Sign in to TREK
|
||||
{t('oauth.authorize.loginButton')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -206,19 +74,19 @@ export default function OAuthAuthorizePage(): React.ReactElement {
|
||||
<ShieldCheck className="w-6 h-6" style={{ color: 'var(--accent-primary, #4f46e5)' }} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-wide mb-1" style={{ color: 'var(--text-tertiary)' }}>Authorization Request</p>
|
||||
<p className="text-xs font-medium uppercase tracking-wide mb-1" style={{ color: 'var(--text-tertiary)' }}>{t('oauth.authorize.requestLabel')}</p>
|
||||
<h1 className="text-lg font-semibold leading-snug" style={{ color: 'var(--text-primary)' }}>
|
||||
{validation?.client?.name || clientId}
|
||||
</h1>
|
||||
<p className="text-sm mt-2" style={{ color: 'var(--text-secondary)' }}>
|
||||
This application is requesting access to your TREK account.
|
||||
{t('oauth.authorize.requestDescription')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 space-y-2">
|
||||
<p className="text-xs mb-3" style={{ color: 'var(--text-tertiary)' }}>
|
||||
Only grant access to applications you trust. Your data stays on your server.
|
||||
{t('oauth.authorize.trustNote')}
|
||||
</p>
|
||||
<button
|
||||
onClick={() => submitConsent(true)}
|
||||
@@ -226,19 +94,24 @@ export default function OAuthAuthorizePage(): React.ReactElement {
|
||||
className="w-full px-4 py-2.5 rounded-lg text-sm font-medium text-white disabled:opacity-60 transition-opacity"
|
||||
style={{ background: 'var(--accent-primary, #4f46e5)' }}>
|
||||
{submitting
|
||||
? 'Authorizing…'
|
||||
? t('oauth.authorize.authorizing')
|
||||
: validation?.scopeSelectable && selectedScopes.length === 0
|
||||
? 'Select at least one scope'
|
||||
? t('oauth.authorize.selectScope')
|
||||
: validation?.scopeSelectable
|
||||
? `Approve (${selectedScopes.length} scope${selectedScopes.length !== 1 ? 's' : ''})`
|
||||
: 'Approve Access'}
|
||||
? t(
|
||||
selectedScopes.length !== 1
|
||||
? 'oauth.authorize.approveManyScopes'
|
||||
: 'oauth.authorize.approveOneScope',
|
||||
{ count: selectedScopes.length },
|
||||
)
|
||||
: t('oauth.authorize.approveAccess')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => submitConsent(false)}
|
||||
disabled={submitting}
|
||||
className="w-full px-4 py-2.5 rounded-lg text-sm font-medium border transition-colors hover:bg-slate-50 dark:hover:bg-slate-800 disabled:opacity-60"
|
||||
style={{ borderColor: 'var(--border-primary)', color: 'var(--text-secondary)' }}>
|
||||
Deny
|
||||
{t('oauth.authorize.deny')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -249,7 +122,7 @@ export default function OAuthAuthorizePage(): React.ReactElement {
|
||||
{Object.keys(scopesByGroup).length > 0 && (
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-wide mb-4" style={{ color: 'var(--text-tertiary)' }}>
|
||||
{validation?.scopeSelectable ? 'Choose which permissions to grant' : 'Permissions requested'}
|
||||
{validation?.scopeSelectable ? t('oauth.authorize.choosePermissions') : t('oauth.authorize.permissionsRequested')}
|
||||
</p>
|
||||
|
||||
{validation?.scopeSelectable ? (
|
||||
@@ -333,12 +206,12 @@ export default function OAuthAuthorizePage(): React.ReactElement {
|
||||
{/* Always-available tools — granted regardless of scopes */}
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-wide mb-3" style={{ color: 'var(--text-tertiary)' }}>
|
||||
Always included
|
||||
{t('oauth.authorize.alwaysIncluded')}
|
||||
</p>
|
||||
<div className="space-y-1.5">
|
||||
{[
|
||||
{ name: 'list_trips', desc: 'List your trips so the AI can discover trip IDs' },
|
||||
{ name: 'get_trip_summary', desc: 'Read a trip overview needed to use any other tool' },
|
||||
{ name: 'list_trips', desc: t('oauth.authorize.alwaysTool.listTrips') },
|
||||
{ name: 'get_trip_summary', desc: t('oauth.authorize.alwaysTool.getTripSummary') },
|
||||
].map(({ name, desc }) => (
|
||||
<div key={name} className="flex items-start gap-2.5 px-3 py-2 rounded-lg" style={{ background: 'var(--bg-secondary)' }}>
|
||||
<span className="mt-0.5 text-base leading-none flex-shrink-0">👁️</span>
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# Page pattern: wiring container + data hook
|
||||
|
||||
Every page under `src/pages` follows the same shape: the exported `*Page`
|
||||
component is a thin **wiring container** and all of its state, effects, data
|
||||
loading and event handlers live in a co-located **`use<Page>()` hook**.
|
||||
|
||||
```
|
||||
src/pages/
|
||||
DashboardPage.tsx ← container: reads the hook, renders JSX
|
||||
dashboard/
|
||||
useDashboard.ts ← state, effects, API calls, handlers
|
||||
dashboardModel.ts ← (optional) pure types + helpers, no React
|
||||
```
|
||||
|
||||
## What goes where
|
||||
|
||||
**The hook (`use<Page>.ts`)** owns everything stateful:
|
||||
|
||||
- `useState` / `useReducer` / `useRef`
|
||||
- `useEffect` / `useLayoutEffect`
|
||||
- `useMemo` / `useCallback`
|
||||
- store selectors, API calls, WebSocket listeners, handlers
|
||||
- derived values
|
||||
|
||||
It returns a single object the page destructures.
|
||||
|
||||
**The page (`*Page.tsx`)** is presentation only:
|
||||
|
||||
- `const { ... } = use<Page>()`
|
||||
- `useTranslation()` for `t`/`locale` (a context hook, not state — allowed)
|
||||
- JSX, and `t`-dependent display arrays like the tab list
|
||||
- presentational sub-components and pure helpers may live in the same file,
|
||||
before or after the default export
|
||||
|
||||
```tsx
|
||||
export default function DashboardPage() {
|
||||
const { t } = useTranslation()
|
||||
const { trips, isLoading, handleCreate } = useDashboard()
|
||||
if (isLoading) return <Spinner />
|
||||
return <Grid trips={trips} onCreate={handleCreate} />
|
||||
}
|
||||
```
|
||||
|
||||
## Why
|
||||
|
||||
- **Testable** — page tests render JSX; hook logic is isolated and mockable.
|
||||
- **Readable** — the container reads top-to-bottom as "what the page shows".
|
||||
- **Diffable** — logic changes touch the hook, layout changes touch the page.
|
||||
|
||||
## Notes
|
||||
|
||||
- A `<page>Model.ts` is optional — use it for pure types and helpers shared
|
||||
between the hook and the page (no React imports). See `atlas/atlasModel.ts`
|
||||
for a mutable-lookup-table example and `admin/adminModel.ts` for types only.
|
||||
- The post-guard derivations that depend on a now-narrowed value (e.g. after
|
||||
`if (!current) return`) may stay in the page next to the JSX that uses them.
|
||||
- Keep the rendered JSX byte-identical when extracting — this is a refactor of
|
||||
where logic lives, not a redesign.
|
||||
|
||||
## Enforcement
|
||||
|
||||
`npm run lint:pages` (`scripts/check-page-pattern.mjs`) scans each `*Page.tsx`
|
||||
default-export body and fails if it calls `useState`, `useReducer`, `useEffect`,
|
||||
`useLayoutEffect`, `useMemo`, `useCallback` or `useRef` directly. Move that logic
|
||||
into the page's hook. Sub-components and helper hooks in the same file are not
|
||||
flagged.
|
||||
@@ -1,230 +0,0 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { render, screen, waitFor, act } from '../../tests/helpers/render';
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../tests/helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../tests/helpers/store';
|
||||
import { buildUser, buildTrip } from '../../tests/helpers/factories';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { useTripStore } from '../store/tripStore';
|
||||
import PhotosPage from './PhotosPage';
|
||||
import type { Photo } from '../types';
|
||||
|
||||
vi.mock('../components/Photos/PhotoGallery', () => ({
|
||||
default: ({ photos }: { photos: Photo[]; onUpload: unknown; onDelete: unknown; onUpdate: unknown; places: unknown[]; days: unknown[]; tripId: unknown }) =>
|
||||
React.createElement('div', { 'data-testid': 'photo-gallery' }, `${photos.length} photos`),
|
||||
}));
|
||||
|
||||
vi.mock('../components/Layout/Navbar', () => ({
|
||||
default: ({ tripTitle }: { tripTitle?: string }) =>
|
||||
React.createElement('nav', { 'data-testid': 'navbar' }, tripTitle),
|
||||
}));
|
||||
|
||||
function buildPhoto(overrides: Partial<Photo> = {}): Photo {
|
||||
return {
|
||||
id: 1,
|
||||
trip_id: 1,
|
||||
filename: 'photo1.jpg',
|
||||
original_name: 'photo1.jpg',
|
||||
mime_type: 'image/jpeg',
|
||||
size: 12345,
|
||||
caption: null,
|
||||
place_id: null,
|
||||
day_id: null,
|
||||
created_at: '2025-01-01T00:00:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function renderPhotosPage(tripId: number | string = 1) {
|
||||
return render(
|
||||
<Routes>
|
||||
<Route path="/trips/:id/photos" element={<PhotosPage />} />
|
||||
</Routes>,
|
||||
{ initialEntries: [`/trips/${tripId}/photos`] },
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() });
|
||||
seedStore(useTripStore, {
|
||||
photos: [],
|
||||
loadPhotos: vi.fn().mockResolvedValue(undefined),
|
||||
addPhoto: vi.fn().mockResolvedValue(undefined),
|
||||
deletePhoto: vi.fn().mockResolvedValue(undefined),
|
||||
updatePhoto: vi.fn().mockResolvedValue(undefined),
|
||||
} as any);
|
||||
});
|
||||
|
||||
describe('PhotosPage', () => {
|
||||
describe('FE-PAGE-PHOTOS-001: Loading spinner shown while data fetches', () => {
|
||||
it('shows a spinner while data is loading', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips/:id', async () => {
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
const trip = buildTrip({ id: 1 });
|
||||
return HttpResponse.json({ trip });
|
||||
}),
|
||||
);
|
||||
|
||||
renderPhotosPage(1);
|
||||
|
||||
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('FE-PAGE-PHOTOS-002: Trip name in Navbar after load', () => {
|
||||
it('passes the trip name to Navbar after data loads', async () => {
|
||||
const trip = buildTrip({ id: 1, name: 'Venice Trip' });
|
||||
server.use(
|
||||
http.get('/api/trips/:id', () => HttpResponse.json({ trip })),
|
||||
);
|
||||
|
||||
renderPhotosPage(1);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('navbar')).toHaveTextContent('Venice Trip');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('FE-PAGE-PHOTOS-003: PhotoGallery renders after load', () => {
|
||||
it('renders the PhotoGallery after data loads', async () => {
|
||||
renderPhotosPage(1);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('photo-gallery')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('FE-PAGE-PHOTOS-004: Photo count shown in header', () => {
|
||||
it('shows the correct photo count in the header', async () => {
|
||||
const photo = buildPhoto({ id: 1, trip_id: 1 });
|
||||
seedStore(useTripStore, {
|
||||
photos: [photo],
|
||||
loadPhotos: vi.fn().mockResolvedValue(undefined),
|
||||
addPhoto: vi.fn().mockResolvedValue(undefined),
|
||||
deletePhoto: vi.fn().mockResolvedValue(undefined),
|
||||
updatePhoto: vi.fn().mockResolvedValue(undefined),
|
||||
} as any);
|
||||
|
||||
renderPhotosPage(1);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('photo-gallery')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText(/1 photos for/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('FE-PAGE-PHOTOS-005: Back link navigates to trip planner', () => {
|
||||
it('back link points to the trip planner page', async () => {
|
||||
renderPhotosPage(1);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('photo-gallery')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const backLink = screen.getByRole('link', { name: /back to planning/i });
|
||||
expect(backLink.getAttribute('href')).toContain('/trips/1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('FE-PAGE-PHOTOS-006: loadPhotos called with trip ID on mount', () => {
|
||||
it('calls tripStore.loadPhotos with the trip ID from the URL', async () => {
|
||||
const mockLoadPhotos = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useTripStore, {
|
||||
photos: [],
|
||||
loadPhotos: mockLoadPhotos,
|
||||
addPhoto: vi.fn().mockResolvedValue(undefined),
|
||||
deletePhoto: vi.fn().mockResolvedValue(undefined),
|
||||
updatePhoto: vi.fn().mockResolvedValue(undefined),
|
||||
} as any);
|
||||
|
||||
renderPhotosPage(1);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockLoadPhotos).toHaveBeenCalledWith('1');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('FE-PAGE-PHOTOS-007: Navigation to /dashboard on fetch error', () => {
|
||||
it('navigates to /dashboard when trip fetch fails', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips/:id', () =>
|
||||
HttpResponse.json({ error: 'Not found' }, { status: 404 }),
|
||||
),
|
||||
);
|
||||
|
||||
render(
|
||||
<Routes>
|
||||
<Route path="/trips/:id/photos" element={<PhotosPage />} />
|
||||
<Route path="/dashboard" element={<div data-testid="dashboard">Dashboard</div>} />
|
||||
</Routes>,
|
||||
{ initialEntries: ['/trips/1/photos'] },
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('dashboard')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('FE-PAGE-PHOTOS-008: Photos sync from tripStore to local state', () => {
|
||||
it('PhotoGallery re-renders when store photos change', async () => {
|
||||
seedStore(useTripStore, {
|
||||
photos: [],
|
||||
loadPhotos: vi.fn().mockResolvedValue(undefined),
|
||||
addPhoto: vi.fn().mockResolvedValue(undefined),
|
||||
deletePhoto: vi.fn().mockResolvedValue(undefined),
|
||||
updatePhoto: vi.fn().mockResolvedValue(undefined),
|
||||
} as any);
|
||||
|
||||
renderPhotosPage(1);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('photo-gallery')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('photo-gallery')).toHaveTextContent('0 photos');
|
||||
|
||||
act(() => {
|
||||
useTripStore.setState({ photos: [buildPhoto({ id: 99 })] } as any);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('photo-gallery')).toHaveTextContent('1 photos');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('FE-PAGE-PHOTOS-009: Empty photo list renders gallery with 0 photos', () => {
|
||||
it('renders PhotoGallery with 0 photos when photos array is empty', async () => {
|
||||
renderPhotosPage(1);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('photo-gallery')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('photo-gallery')).toHaveTextContent('0 photos');
|
||||
});
|
||||
});
|
||||
|
||||
describe('FE-PAGE-PHOTOS-010: Page heading present', () => {
|
||||
it('renders the "Fotos" heading', async () => {
|
||||
renderPhotosPage(1);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('photo-gallery')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByRole('heading', { name: /photos/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,110 +0,0 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useParams, useNavigate, Link } from 'react-router-dom'
|
||||
import { useTripStore } from '../store/tripStore'
|
||||
import { tripsApi, daysApi, placesApi } from '../api/client'
|
||||
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(): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const { id: tripId } = useParams<{ id: string }>()
|
||||
const navigate = useNavigate()
|
||||
const tripStore = useTripStore()
|
||||
|
||||
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 (): Promise<void> => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const [tripData, daysData, placesData] = await Promise.all([
|
||||
tripsApi.get(tripId),
|
||||
daysApi.list(tripId),
|
||||
placesApi.list(tripId),
|
||||
])
|
||||
setTrip(tripData.trip)
|
||||
setDays(daysData.days)
|
||||
setPlaces(placesData.places)
|
||||
|
||||
// Load photos
|
||||
await tripStore.loadPhotos(tripId)
|
||||
} catch (err: unknown) {
|
||||
navigate('/dashboard')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Sync photos from store
|
||||
useEffect(() => {
|
||||
setPhotos(tripStore.photos)
|
||||
}, [tripStore.photos])
|
||||
|
||||
const handleUpload = async (formData: FormData): Promise<void> => {
|
||||
await tripStore.addPhoto(tripId, formData)
|
||||
}
|
||||
|
||||
const handleDelete = async (photoId: number): Promise<void> => {
|
||||
await tripStore.deletePhoto(tripId, photoId)
|
||||
}
|
||||
|
||||
const handleUpdate = async (photoId: number, data: Record<string, string | number | null>): Promise<void> => {
|
||||
await tripStore.updatePhoto(tripId, photoId, data)
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50">
|
||||
<div className="w-10 h-10 border-4 border-slate-200 border-t-slate-700 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50">
|
||||
<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">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<Link
|
||||
to={`/trips/${tripId}`}
|
||||
className="flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
{t('common.backToPlanning')}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">{t('photos.title')}</h1>
|
||||
<p className="text-gray-500 text-sm">{t('photos.subtitle', { count: photos.length, trip: trip?.name })}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PhotoGallery
|
||||
photos={photos}
|
||||
onUpload={handleUpload}
|
||||
onDelete={handleDelete}
|
||||
onUpdate={handleUpdate}
|
||||
places={places}
|
||||
days={days}
|
||||
tripId={tripId}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,46 +1,17 @@
|
||||
import React, { useState } from 'react'
|
||||
import { Link, useNavigate } from 'react-router-dom'
|
||||
import { useAuthStore } from '../store/authStore'
|
||||
import React from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { Map, Eye, EyeOff, Mail, Lock, User } from 'lucide-react'
|
||||
import { useRegister } from './register/useRegister'
|
||||
|
||||
export default function RegisterPage(): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
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: React.FormEvent<HTMLFormElement>): Promise<void> => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
setError(t('register.passwordMismatch'))
|
||||
return
|
||||
}
|
||||
|
||||
if (password.length < 8) {
|
||||
setError(t('register.passwordTooShort'))
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await register(username, email, password)
|
||||
navigate('/dashboard')
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : t('register.failed'))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
// Page = wiring container: form state, validation + register flow live in the hook.
|
||||
const {
|
||||
username, setUsername, email, setEmail, password, setPassword,
|
||||
confirmPassword, setConfirmPassword, showPassword, setShowPassword,
|
||||
isLoading, error, handleSubmit,
|
||||
} = useRegister()
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex">
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import React, { useState, useEffect, FormEvent, ChangeEvent } from 'react'
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import React, { ChangeEvent } from 'react'
|
||||
import { Lock, KeyRound, CheckCircle2, AlertTriangle, Eye, EyeOff } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { authApi } from '../api/client'
|
||||
import { getApiErrorMessage } from '../types'
|
||||
import { useResetPassword } from './resetPassword/useResetPassword'
|
||||
|
||||
const inputBase: React.CSSProperties = {
|
||||
width: '100%', padding: '11px 44px 11px 38px', borderRadius: 12,
|
||||
@@ -14,50 +12,13 @@ const inputBase: React.CSSProperties = {
|
||||
|
||||
const ResetPasswordPage: React.FC = () => {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const [params] = useSearchParams()
|
||||
const token = params.get('token') || ''
|
||||
|
||||
const [pw, setPw] = useState('')
|
||||
const [pw2, setPw2] = useState('')
|
||||
const [showPw, setShowPw] = useState(false)
|
||||
const [mfaCode, setMfaCode] = useState('')
|
||||
const [mfaRequired, setMfaRequired] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [success, setSuccess] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) setError(t('login.resetPasswordInvalidLink'))
|
||||
}, [token, t])
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (isLoading) return
|
||||
setError('')
|
||||
if (!token) return
|
||||
if (pw.length < 8) { setError(t('login.passwordMinLength')); return }
|
||||
if (pw !== pw2) { setError(t('login.passwordsDontMatch')); return }
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const res = await authApi.resetPassword({
|
||||
token,
|
||||
new_password: pw,
|
||||
...(mfaRequired && mfaCode ? { mfa_code: mfaCode.trim() } : {}),
|
||||
})
|
||||
if (res.mfa_required) {
|
||||
setMfaRequired(true)
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
if (res.success) {
|
||||
setSuccess(true)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(getApiErrorMessage(err, t('login.resetPasswordFailed')))
|
||||
}
|
||||
setIsLoading(false)
|
||||
}
|
||||
// Page = wiring container: token, form state, validation + submit live in the hook.
|
||||
const {
|
||||
navigate, token,
|
||||
pw, setPw, pw2, setPw2, showPw, setShowPw,
|
||||
mfaCode, setMfaCode, mfaRequired, error, success, isLoading,
|
||||
handleSubmit,
|
||||
} = useResetPassword()
|
||||
|
||||
const shell = (inner: React.ReactNode) => (
|
||||
<div style={{
|
||||
@@ -140,7 +101,7 @@ const ResetPasswordPage: React.FC = () => {
|
||||
{t('login.newPassword')}
|
||||
</label>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<Lock size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
|
||||
<Lock size={15} className="text-[#9ca3af]" style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
|
||||
<input
|
||||
type={showPw ? 'text' : 'password'} value={pw}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setPw(e.target.value)}
|
||||
@@ -159,7 +120,7 @@ const ResetPasswordPage: React.FC = () => {
|
||||
{t('login.confirmPassword')}
|
||||
</label>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<Lock size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
|
||||
<Lock size={15} className="text-[#9ca3af]" style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
|
||||
<input
|
||||
type={showPw ? 'text' : 'password'} value={pw2}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setPw2(e.target.value)}
|
||||
@@ -177,7 +138,7 @@ const ResetPasswordPage: React.FC = () => {
|
||||
{t('login.mfaCode')}
|
||||
</label>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<KeyRound size={15} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: '#9ca3af', pointerEvents: 'none' }} />
|
||||
<KeyRound size={15} className="text-[#9ca3af]" style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
|
||||
<input
|
||||
type="text" inputMode="numeric" value={mfaCode}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setMfaCode(e.target.value)}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
import React from 'react'
|
||||
import { Settings, Palette, Map, Bell, Plug, CloudOff, User, Info } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { authApi } from '../api/client'
|
||||
import { useAddonStore } from '../store/addonStore'
|
||||
import Navbar from '../components/Layout/Navbar'
|
||||
import PageShell from '../components/Layout/PageShell'
|
||||
import PageSidebar, { type PageSidebarTab } from '../components/Layout/PageSidebar'
|
||||
import DisplaySettingsTab from '../components/Settings/DisplaySettingsTab'
|
||||
import MapSettingsTab from '../components/Settings/MapSettingsTab'
|
||||
@@ -13,30 +10,12 @@ import IntegrationsTab from '../components/Settings/IntegrationsTab'
|
||||
import AccountTab from '../components/Settings/AccountTab'
|
||||
import AboutTab from '../components/Settings/AboutTab'
|
||||
import OfflineTab from '../components/Settings/OfflineTab'
|
||||
import { useSettings } from './settings/useSettings'
|
||||
|
||||
export default function SettingsPage(): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const [searchParams] = useSearchParams()
|
||||
const { isEnabled: addonEnabled, loadAddons } = useAddonStore()
|
||||
|
||||
const memoriesEnabled = addonEnabled('memories')
|
||||
const mcpEnabled = addonEnabled('mcp')
|
||||
const hasIntegrations = memoriesEnabled || mcpEnabled
|
||||
|
||||
const [appVersion, setAppVersion] = useState<string | null>(null)
|
||||
const [activeTab, setActiveTab] = useState('display')
|
||||
|
||||
useEffect(() => {
|
||||
loadAddons()
|
||||
authApi.getAppConfig?.().then(c => setAppVersion(c?.version)).catch(() => {})
|
||||
}, [])
|
||||
|
||||
// Auto-switch to account tab when MFA is required
|
||||
useEffect(() => {
|
||||
if (searchParams.get('mfa') === 'required') {
|
||||
setActiveTab('account')
|
||||
}
|
||||
}, [searchParams])
|
||||
// Page = wiring container: addon/version loading + active-tab state in the hook.
|
||||
const { hasIntegrations, appVersion, activeTab, setActiveTab } = useSettings()
|
||||
|
||||
const tabs: PageSidebarTab[] = [
|
||||
{ id: 'display', label: t('settings.tabs.display'), icon: Palette },
|
||||
@@ -53,19 +32,16 @@ export default function SettingsPage(): React.ReactElement {
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="min-h-screen" style={{ background: 'var(--bg-secondary)' }}>
|
||||
<Navbar />
|
||||
|
||||
<div style={{ paddingTop: 'var(--nav-h)' }}>
|
||||
<div className="w-full px-4 sm:px-6 lg:px-8 py-8">
|
||||
<PageShell background="var(--bg-secondary)">
|
||||
<div className="w-full px-4 sm:px-6 lg:px-8 py-8">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: 'var(--bg-tertiary)' }}>
|
||||
<Settings className="w-5 h-5" style={{ color: 'var(--text-secondary)' }} />
|
||||
<div className="w-10 h-10 rounded-xl flex items-center justify-center bg-surface-tertiary">
|
||||
<Settings className="w-5 h-5 text-content-secondary" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold" style={{ color: 'var(--text-primary)' }}>{t('settings.title')}</h1>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('settings.subtitle')}</p>
|
||||
<h1 className="text-2xl font-bold text-content">{t('settings.title')}</h1>
|
||||
<p className="text-sm text-content-muted">{t('settings.subtitle')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -86,7 +62,6 @@ export default function SettingsPage(): React.ReactElement {
|
||||
{activeTab === 'about' && appVersion && <AboutTab appVersion={appVersion} />}
|
||||
</PageSidebar>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PageShell>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { useEffect } from 'react'
|
||||
import { MapContainer, TileLayer, Marker, Tooltip, useMap } from 'react-leaflet'
|
||||
import L from 'leaflet'
|
||||
import { useTranslation, SUPPORTED_LANGUAGES } from '../i18n'
|
||||
import { useSettingsStore } from '../store/settingsStore'
|
||||
import { getLocaleForLanguage } from '../i18n'
|
||||
import { shareApi } from '../api/client'
|
||||
import { useSharedTrip } from './sharedTrip/useSharedTrip'
|
||||
import { getCategoryIcon } from '../components/shared/categoryIcons'
|
||||
import { createElement } from 'react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
@@ -40,31 +39,22 @@ function FitBoundsToPlaces({ places }: { places: any[] }) {
|
||||
}
|
||||
|
||||
export default function SharedTripPage() {
|
||||
const { token } = useParams<{ token: string }>()
|
||||
const { t, locale } = useTranslation()
|
||||
const [data, setData] = useState<any>(null)
|
||||
const [error, setError] = useState(false)
|
||||
const [selectedDay, setSelectedDay] = useState<number | null>(null)
|
||||
const [activeTab, setActiveTab] = useState('plan')
|
||||
const [showLangPicker, setShowLangPicker] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return
|
||||
shareApi.getSharedTrip(token).then(setData).catch(() => setError(true))
|
||||
}, [token])
|
||||
// Page = wiring container: share fetch + view state live in the hook.
|
||||
const { data, error, selectedDay, setSelectedDay, activeTab, setActiveTab, showLangPicker, setShowLangPicker } = useSharedTrip()
|
||||
|
||||
if (error) return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', background: '#f3f4f6' }}>
|
||||
<div className="bg-[#f3f4f6]" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh' }}>
|
||||
<div style={{ textAlign: 'center', padding: 40 }}>
|
||||
<div style={{ fontSize: 48, marginBottom: 16 }}>🔒</div>
|
||||
<h1 style={{ fontSize: 20, fontWeight: 700, color: '#111827' }}>{t('shared.expired')}</h1>
|
||||
<p style={{ color: '#6b7280', marginTop: 8 }}>{t('shared.expiredHint')}</p>
|
||||
<h1 className="text-[#111827]" style={{ fontSize: 20, fontWeight: 700 }}>{t('shared.expired')}</h1>
|
||||
<p className="text-[#6b7280]" style={{ marginTop: 8 }}>{t('shared.expiredHint')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
if (!data) return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', background: '#f3f4f6' }}>
|
||||
<div className="bg-[#f3f4f6]" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh' }}>
|
||||
<div style={{ width: 32, height: 32, border: '3px solid #e5e7eb', borderTopColor: '#111827', borderRadius: '50%', animation: 'spin 0.6s linear infinite' }} />
|
||||
<style>{`@keyframes spin { to { transform: rotate(360deg) } }`}</style>
|
||||
</div>
|
||||
@@ -81,19 +71,19 @@ export default function SharedTripPage() {
|
||||
const center = mapPlaces.length > 0 ? [mapPlaces[0].lat, mapPlaces[0].lng] : [48.85, 2.35]
|
||||
|
||||
return (
|
||||
<div style={{ minHeight: '100vh', background: 'var(--bg-secondary, #f3f4f6)', fontFamily: "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif" }}>
|
||||
<div className="bg-surface-secondary" style={{ minHeight: '100vh', fontFamily: "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif" }}>
|
||||
{/* Header */}
|
||||
<div style={{ background: 'linear-gradient(135deg, #000 0%, #0f172a 50%, #1e293b 100%)', color: 'white', padding: '32px 20px 28px', textAlign: 'center', position: 'relative' }}>
|
||||
<div className="text-white" style={{ background: 'linear-gradient(135deg, #000 0%, #0f172a 50%, #1e293b 100%)', padding: '32px 20px 28px', textAlign: 'center', position: 'relative' }}>
|
||||
{/* Cover image background */}
|
||||
{trip.cover_image && (
|
||||
<div style={{ position: 'absolute', inset: 0, backgroundImage: `url(${trip.cover_image.startsWith('http') ? trip.cover_image : trip.cover_image.startsWith('/') ? trip.cover_image : '/uploads/' + trip.cover_image})`, backgroundSize: 'cover', backgroundPosition: 'center', opacity: 0.15 }} />
|
||||
)}
|
||||
{/* Background decoration */}
|
||||
<div style={{ position: 'absolute', top: -60, right: -60, width: 200, height: 200, borderRadius: '50%', background: 'rgba(255,255,255,0.03)' }} />
|
||||
<div style={{ position: 'absolute', bottom: -40, left: -40, width: 150, height: 150, borderRadius: '50%', background: 'rgba(255,255,255,0.02)' }} />
|
||||
<div className="bg-[rgba(255,255,255,0.03)]" style={{ position: 'absolute', top: -60, right: -60, width: 200, height: 200, borderRadius: '50%' }} />
|
||||
<div className="bg-[rgba(255,255,255,0.02)]" style={{ position: 'absolute', bottom: -40, left: -40, width: 150, height: 150, borderRadius: '50%' }} />
|
||||
|
||||
{/* Logo */}
|
||||
<div style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 44, height: 44, borderRadius: 12, background: 'rgba(255,255,255,0.08)', backdropFilter: 'blur(8px)', marginBottom: 12, border: '1px solid rgba(255,255,255,0.1)' }}>
|
||||
<div className="bg-[rgba(255,255,255,0.08)]" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 44, height: 44, borderRadius: 12, backdropFilter: 'blur(8px)', marginBottom: 12, border: '1px solid rgba(255,255,255,0.1)' }}>
|
||||
<img src="/icons/icon-white.svg" alt="TREK" width="26" height="26" />
|
||||
</div>
|
||||
|
||||
@@ -106,7 +96,7 @@ export default function SharedTripPage() {
|
||||
)}
|
||||
|
||||
{(trip.start_date || trip.end_date) && (
|
||||
<div style={{ marginTop: 10, display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 14px', borderRadius: 20, background: 'rgba(255,255,255,0.08)', backdropFilter: 'blur(4px)', border: '1px solid rgba(255,255,255,0.08)' }}>
|
||||
<div className="bg-[rgba(255,255,255,0.08)]" style={{ marginTop: 10, display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 14px', borderRadius: 20, backdropFilter: 'blur(4px)', border: '1px solid rgba(255,255,255,0.08)' }}>
|
||||
<span style={{ fontSize: 12, fontWeight: 500, opacity: 0.8 }}>
|
||||
{[trip.start_date, trip.end_date].filter(Boolean).map((d: string) => new Date(d + 'T00:00:00Z').toLocaleDateString(locale, { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' })).join(' — ')}
|
||||
</span>
|
||||
@@ -119,22 +109,25 @@ export default function SharedTripPage() {
|
||||
|
||||
{/* Language picker - top right */}
|
||||
<div style={{ position: 'absolute', top: 12, right: 12, zIndex: 10 }}>
|
||||
<button onClick={() => setShowLangPicker(v => !v)} style={{
|
||||
<button onClick={() => setShowLangPicker(v => !v)}
|
||||
className="bg-[rgba(255,255,255,0.1)] text-[rgba(255,255,255,0.7)]"
|
||||
style={{
|
||||
padding: '5px 12px', borderRadius: 20, border: '1px solid rgba(255,255,255,0.15)',
|
||||
background: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(8px)',
|
||||
color: 'rgba(255,255,255,0.7)', fontSize: 11, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
|
||||
backdropFilter: 'blur(8px)',
|
||||
fontSize: 11, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
|
||||
}}>
|
||||
{SUPPORTED_LANGUAGES.find(l => l.value === (locale?.split('-')[0] || 'en'))?.label || 'Language'}
|
||||
</button>
|
||||
{showLangPicker && (
|
||||
<div style={{ position: 'absolute', top: '100%', right: 0, marginTop: 6, background: 'white', borderRadius: 10, boxShadow: '0 4px 16px rgba(0,0,0,0.2)', padding: 4, zIndex: 50, minWidth: 150 }}>
|
||||
<div className="bg-white" style={{ position: 'absolute', top: '100%', right: 0, marginTop: 6, borderRadius: 10, boxShadow: '0 4px 16px rgba(0,0,0,0.2)', padding: 4, zIndex: 50, minWidth: 150 }}>
|
||||
{SUPPORTED_LANGUAGES.map(lang => (
|
||||
<button key={lang.value} onClick={() => {
|
||||
// Set language locally without API call (shared page has no auth)
|
||||
useSettingsStore.setState(s => ({ settings: { ...s.settings, language: lang.value } }))
|
||||
setShowLangPicker(false)
|
||||
}}
|
||||
style={{ display: 'block', width: '100%', padding: '6px 12px', border: 'none', background: 'none', textAlign: 'left', cursor: 'pointer', fontSize: 12, color: '#374151', borderRadius: 6, fontFamily: 'inherit' }}
|
||||
className="text-[#374151]"
|
||||
style={{ display: 'block', width: '100%', padding: '6px 12px', border: 'none', background: 'none', textAlign: 'left', cursor: 'pointer', fontSize: 12, borderRadius: 6, fontFamily: 'inherit' }}
|
||||
onMouseEnter={e => e.currentTarget.style.background = '#f3f4f6'}
|
||||
onMouseLeave={e => e.currentTarget.style.background = 'none'}
|
||||
>{lang.label}</button>
|
||||
@@ -154,13 +147,13 @@ export default function SharedTripPage() {
|
||||
...(permissions?.share_budget ? [{ id: 'budget', label: t('shared.tabBudget'), Icon: Wallet }] : []),
|
||||
...(permissions?.share_collab ? [{ id: 'collab', label: t('shared.tabChat'), Icon: MessageCircle }] : []),
|
||||
].map(tab => (
|
||||
<button key={tab.id} onClick={() => setActiveTab(tab.id)} style={{
|
||||
<button key={tab.id} onClick={() => setActiveTab(tab.id)}
|
||||
className={activeTab === tab.id ? 'bg-[#111827] text-white' : 'bg-surface-card text-[#6b7280]'}
|
||||
style={{
|
||||
padding: '8px 18px', borderRadius: 12, border: '1.5px solid', cursor: 'pointer',
|
||||
fontSize: 12, fontWeight: 600, fontFamily: 'inherit', transition: 'all 0.15s', whiteSpace: 'nowrap',
|
||||
display: 'flex', alignItems: 'center', gap: 6,
|
||||
background: activeTab === tab.id ? '#111827' : 'var(--bg-card, white)',
|
||||
borderColor: activeTab === tab.id ? '#111827' : 'var(--border-faint, #e5e7eb)',
|
||||
color: activeTab === tab.id ? 'white' : '#6b7280',
|
||||
boxShadow: activeTab === tab.id ? '0 2px 8px rgba(0,0,0,0.15)' : '0 1px 3px rgba(0,0,0,0.04)',
|
||||
}}><tab.Icon size={13} /><span className="hidden sm:inline">{tab.label}</span></button>
|
||||
))}
|
||||
@@ -197,20 +190,20 @@ export default function SharedTripPage() {
|
||||
})
|
||||
|
||||
return (
|
||||
<div key={day.id} style={{ background: 'var(--bg-card, white)', borderRadius: 14, overflow: 'hidden', border: '1px solid var(--border-faint, #e5e7eb)' }}>
|
||||
<div key={day.id} className="bg-surface-card border border-edge-faint" style={{ borderRadius: 14, overflow: 'hidden' }}>
|
||||
<div onClick={() => setSelectedDay(selectedDay === day.id ? null : day.id)}
|
||||
style={{ padding: '12px 16px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
<div style={{ width: 28, height: 28, borderRadius: '50%', background: selectedDay === day.id ? '#111827' : '#f3f4f6', color: selectedDay === day.id ? 'white' : '#6b7280', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, flexShrink: 0 }}>{di + 1}</div>
|
||||
<div className={selectedDay === day.id ? 'bg-[#111827] text-white' : 'bg-[#f3f4f6] text-[#6b7280]'} style={{ width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, flexShrink: 0 }}>{di + 1}</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 600, color: '#111827' }}>{day.title || `Day ${day.day_number}`}</div>
|
||||
{day.date && <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 1 }}>{new Date(day.date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' })}</div>}
|
||||
<div className="text-[#111827]" style={{ fontSize: 14, fontWeight: 600 }}>{day.title || `Day ${day.day_number}`}</div>
|
||||
{day.date && <div className="text-[#9ca3af]" style={{ fontSize: 11, marginTop: 1 }}>{new Date(day.date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' })}</div>}
|
||||
</div>
|
||||
{dayAccs.map((acc: any) => (
|
||||
<span key={acc.id} style={{ fontSize: 9, padding: '2px 6px', borderRadius: 4, background: '#f3f4f6', color: '#6b7280', display: 'flex', alignItems: 'center', gap: 3 }}>
|
||||
<span key={acc.id} className="bg-[#f3f4f6] text-[#6b7280]" style={{ fontSize: 9, padding: '2px 6px', borderRadius: 4, display: 'flex', alignItems: 'center', gap: 3 }}>
|
||||
<Hotel size={8} /> {acc.place_name}
|
||||
</span>
|
||||
))}
|
||||
<span style={{ fontSize: 11, color: '#9ca3af' }}>{da.length} {t('shared.places')}</span>
|
||||
<span className="text-[#9ca3af]" style={{ fontSize: 11 }}>{da.length} {t('shared.places')}</span>
|
||||
</div>
|
||||
|
||||
{selectedDay === day.id && merged.length > 0 && (
|
||||
@@ -225,24 +218,24 @@ export default function SharedTripPage() {
|
||||
if (r.type === 'flight') sub = [meta.airline, meta.flight_number, meta.departure_airport && meta.arrival_airport ? `${meta.departure_airport} → ${meta.arrival_airport}` : ''].filter(Boolean).join(' · ')
|
||||
else if (r.type === 'train') sub = [meta.train_number, meta.platform ? `Gl. ${meta.platform}` : ''].filter(Boolean).join(' · ')
|
||||
return (
|
||||
<div key={`t-${r.id}`} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 8px', borderRadius: 6, background: 'rgba(59,130,246,0.06)', border: '1px solid rgba(59,130,246,0.15)' }}>
|
||||
<div style={{ width: 24, height: 24, borderRadius: '50%', background: 'rgba(59,130,246,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
|
||||
<div key={`t-${r.id}`} className="bg-[rgba(59,130,246,0.06)]" style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 8px', borderRadius: 6, border: '1px solid rgba(59,130,246,0.15)' }}>
|
||||
<div className="bg-[rgba(59,130,246,0.12)]" style={{ width: 24, height: 24, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
|
||||
<TIcon size={12} color="#3b82f6" />
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 500, color: '#111827' }}>{r.title}{time ? ` · ${time}` : ''}</div>
|
||||
{sub && <div style={{ fontSize: 10, color: '#6b7280' }}>{sub}</div>}
|
||||
<div className="text-[#111827]" style={{ fontSize: 12, fontWeight: 500 }}>{r.title}{time ? ` · ${time}` : ''}</div>
|
||||
{sub && <div className="text-[#6b7280]" style={{ fontSize: 10 }}>{sub}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (item.type === 'note') {
|
||||
return (
|
||||
<div key={`n-${item.data.id}`} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 8px', borderRadius: 6, background: '#f9fafb', border: '1px solid #f3f4f6' }}>
|
||||
<div key={`n-${item.data.id}`} className="bg-[#f9fafb]" style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 8px', borderRadius: 6, border: '1px solid #f3f4f6' }}>
|
||||
<FileText size={12} color="#9ca3af" />
|
||||
<div>
|
||||
<div style={{ fontSize: 12, color: '#374151' }}>{item.data.text}</div>
|
||||
{item.data.time && <div style={{ fontSize: 10, color: '#9ca3af' }}>{item.data.time}</div>}
|
||||
<div className="text-[#374151]" style={{ fontSize: 12 }}>{item.data.text}</div>
|
||||
{item.data.time && <div className="text-[#9ca3af]" style={{ fontSize: 10 }}>{item.data.time}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -256,10 +249,10 @@ export default function SharedTripPage() {
|
||||
{place.image_url ? <img src={place.image_url} style={{ width: 28, height: 28, borderRadius: '50%', objectFit: 'cover' }} /> : <MapPin size={13} color="white" />}
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontSize: 12.5, fontWeight: 500, color: '#111827' }}>{place.name}</div>
|
||||
{(place.address || place.description) && <div style={{ fontSize: 10, color: '#9ca3af', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{place.address || place.description}</div>}
|
||||
<div className="text-[#111827]" style={{ fontSize: 12.5, fontWeight: 500 }}>{place.name}</div>
|
||||
{(place.address || place.description) && <div className="text-[#9ca3af]" style={{ fontSize: 10, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{place.address || place.description}</div>}
|
||||
</div>
|
||||
{place.place_time && <span style={{ fontSize: 10, color: '#6b7280', display: 'flex', alignItems: 'center', gap: 3, flexShrink: 0 }}><Clock size={9} />{place.place_time}{place.end_time ? ` – ${place.end_time}` : ''}</span>}
|
||||
{place.place_time && <span className="text-[#6b7280]" style={{ fontSize: 10, display: 'flex', alignItems: 'center', gap: 3, flexShrink: 0 }}><Clock size={9} />{place.place_time}{place.end_time ? ` – ${place.end_time}` : ''}</span>}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
@@ -281,13 +274,13 @@ export default function SharedTripPage() {
|
||||
const time = rTime ?? ''
|
||||
const date = rDate ? new Date(rDate + 'T00:00:00Z').toLocaleDateString(locale, { day: 'numeric', month: 'short', timeZone: 'UTC' }) : ''
|
||||
return (
|
||||
<div key={r.id} style={{ background: 'var(--bg-card, white)', borderRadius: 10, padding: '12px 16px', border: '1px solid var(--border-faint, #e5e7eb)', display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<div style={{ width: 32, height: 32, borderRadius: '50%', background: '#f3f4f6', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
|
||||
<div key={r.id} className="bg-surface-card border border-edge-faint" style={{ borderRadius: 10, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<div className="bg-[#f3f4f6]" style={{ width: 32, height: 32, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
|
||||
<TIcon size={15} color="#6b7280" />
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 600, color: '#111827' }}>{r.title}</div>
|
||||
<div style={{ fontSize: 11, color: '#9ca3af', display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 2 }}>
|
||||
<div className="text-[#111827]" style={{ fontSize: 13, fontWeight: 600 }}>{r.title}</div>
|
||||
<div className="text-[#9ca3af]" style={{ fontSize: 11, display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 2 }}>
|
||||
{date && <span>{date}</span>}
|
||||
{time && <span>{time}</span>}
|
||||
{r.location && <span>{r.location}</span>}
|
||||
@@ -295,7 +288,7 @@ export default function SharedTripPage() {
|
||||
{meta.train_number && <span>{meta.train_number}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<span style={{ fontSize: 10, padding: '2px 8px', borderRadius: 20, fontWeight: 600, background: r.status === 'confirmed' ? 'rgba(22,163,74,0.1)' : 'rgba(217,119,6,0.1)', color: r.status === 'confirmed' ? '#16a34a' : '#d97706' }}>
|
||||
<span className={r.status === 'confirmed' ? 'bg-[rgba(22,163,74,0.1)] text-[#16a34a]' : 'bg-[rgba(217,119,6,0.1)] text-[#d97706]'} style={{ fontSize: 10, padding: '2px 8px', borderRadius: 20, fontWeight: 600 }}>
|
||||
{r.status === 'confirmed' ? t('shared.confirmed') : t('shared.pending')}
|
||||
</span>
|
||||
</div>
|
||||
@@ -306,13 +299,13 @@ export default function SharedTripPage() {
|
||||
|
||||
{/* Packing */}
|
||||
{activeTab === 'packing' && (packing || []).length > 0 && (
|
||||
<div style={{ background: 'var(--bg-card, white)', borderRadius: 14, border: '1px solid var(--border-faint, #e5e7eb)', overflow: 'hidden' }}>
|
||||
<div className="bg-surface-card border border-edge-faint" style={{ borderRadius: 14, overflow: 'hidden' }}>
|
||||
{Object.entries((packing || []).reduce((g: any, i: any) => { const c = i.category || t('shared.other'); (g[c] = g[c] || []).push(i); return g }, {})).map(([cat, items]: [string, any]) => (
|
||||
<div key={cat}>
|
||||
<div style={{ padding: '8px 16px', background: '#f9fafb', fontSize: 11, fontWeight: 700, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.05em', borderBottom: '1px solid #f3f4f6' }}>{cat}</div>
|
||||
<div className="bg-[#f9fafb] text-[#6b7280]" style={{ padding: '8px 16px', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', borderBottom: '1px solid #f3f4f6' }}>{cat}</div>
|
||||
{items.map((item: any) => (
|
||||
<div key={item.id} style={{ padding: '6px 16px', display: 'flex', alignItems: 'center', gap: 8, borderBottom: '1px solid #f9fafb' }}>
|
||||
<span style={{ fontSize: 13, color: item.checked ? '#9ca3af' : '#111827', textDecoration: item.checked ? 'line-through' : 'none' }}>{item.name}</span>
|
||||
<span className={item.checked ? 'text-[#9ca3af]' : 'text-[#111827]'} style={{ fontSize: 13, textDecoration: item.checked ? 'line-through' : 'none' }}>{item.name}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -327,21 +320,21 @@ export default function SharedTripPage() {
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
{/* Total card */}
|
||||
<div style={{ background: 'linear-gradient(135deg, #000 0%, #1a1a2e 100%)', borderRadius: 14, padding: '20px 24px', color: 'white' }}>
|
||||
<div className="text-white" style={{ background: 'linear-gradient(135deg, #000 0%, #1a1a2e 100%)', borderRadius: 14, padding: '20px 24px' }}>
|
||||
<div style={{ fontSize: 10, fontWeight: 500, letterSpacing: 1, textTransform: 'uppercase', opacity: 0.5 }}>{t('shared.totalBudget')}</div>
|
||||
<div style={{ fontSize: 28, fontWeight: 700, marginTop: 4 }}>{total.toLocaleString(locale, { minimumFractionDigits: 2 })} {trip.currency || 'EUR'}</div>
|
||||
</div>
|
||||
{/* By category */}
|
||||
{Object.entries(grouped).map(([cat, items]: [string, any]) => (
|
||||
<div key={cat} style={{ background: 'var(--bg-card, white)', borderRadius: 12, border: '1px solid var(--border-faint, #e5e7eb)', overflow: 'hidden' }}>
|
||||
<div style={{ padding: '10px 16px', background: '#f9fafb', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #f3f4f6' }}>
|
||||
<span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>{cat}</span>
|
||||
<span style={{ fontSize: 12, fontWeight: 600, color: '#6b7280' }}>{items.reduce((s: number, i: any) => s + (parseFloat(i.total_price) || 0), 0).toLocaleString(locale, { minimumFractionDigits: 2 })} {trip.currency || ''}</span>
|
||||
<div key={cat} className="bg-surface-card border border-edge-faint" style={{ borderRadius: 12, overflow: 'hidden' }}>
|
||||
<div className="bg-[#f9fafb]" style={{ padding: '10px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #f3f4f6' }}>
|
||||
<span className="text-[#374151]" style={{ fontSize: 12, fontWeight: 700 }}>{cat}</span>
|
||||
<span className="text-[#6b7280]" style={{ fontSize: 12, fontWeight: 600 }}>{items.reduce((s: number, i: any) => s + (parseFloat(i.total_price) || 0), 0).toLocaleString(locale, { minimumFractionDigits: 2 })} {trip.currency || ''}</span>
|
||||
</div>
|
||||
{items.map((item: any) => (
|
||||
<div key={item.id} style={{ padding: '8px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #fafafa' }}>
|
||||
<span style={{ fontSize: 13, color: '#111827' }}>{item.name}</span>
|
||||
<span style={{ fontSize: 13, fontWeight: 600, color: '#111827' }}>{item.total_price ? Number(item.total_price).toLocaleString(locale, { minimumFractionDigits: 2 }) : '—'}</span>
|
||||
<span className="text-[#111827]" style={{ fontSize: 13 }}>{item.name}</span>
|
||||
<span className="text-[#111827]" style={{ fontSize: 13, fontWeight: 600 }}>{item.total_price ? Number(item.total_price).toLocaleString(locale, { minimumFractionDigits: 2 }) : '—'}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -352,10 +345,10 @@ export default function SharedTripPage() {
|
||||
|
||||
{/* Collab Chat */}
|
||||
{activeTab === 'collab' && (collab || []).length > 0 && (
|
||||
<div style={{ background: 'var(--bg-card, white)', borderRadius: 14, border: '1px solid var(--border-faint, #e5e7eb)', overflow: 'hidden' }}>
|
||||
<div style={{ padding: '12px 16px', background: '#f9fafb', borderBottom: '1px solid #f3f4f6', display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<div className="bg-surface-card border border-edge-faint" style={{ borderRadius: 14, overflow: 'hidden' }}>
|
||||
<div className="bg-[#f9fafb]" style={{ padding: '12px 16px', borderBottom: '1px solid #f3f4f6', display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<MessageCircle size={14} color="#6b7280" />
|
||||
<span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>{t('shared.tabChat')} · {(collab || []).length} {t('shared.messages')}</span>
|
||||
<span className="text-[#374151]" style={{ fontSize: 12, fontWeight: 700 }}>{t('shared.tabChat')} · {(collab || []).length} {t('shared.messages')}</span>
|
||||
</div>
|
||||
<div style={{ maxHeight: 500, overflowY: 'auto', padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
{(collab || []).map((msg: any, i: number) => {
|
||||
@@ -364,20 +357,20 @@ export default function SharedTripPage() {
|
||||
return (
|
||||
<div key={msg.id}>
|
||||
{showDate && (
|
||||
<div style={{ textAlign: 'center', margin: '8px 0', fontSize: 10, fontWeight: 600, color: '#9ca3af' }}>
|
||||
<div className="text-[#9ca3af]" style={{ textAlign: 'center', margin: '8px 0', fontSize: 10, fontWeight: 600 }}>
|
||||
{new Date(msg.created_at).toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short' })}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'flex', gap: 10 }}>
|
||||
<div style={{ width: 32, height: 32, borderRadius: '50%', background: '#e5e7eb', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, color: '#6b7280', flexShrink: 0, overflow: 'hidden' }}>
|
||||
<div className="bg-[#e5e7eb] text-[#6b7280]" style={{ width: 32, height: 32, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, flexShrink: 0, overflow: 'hidden' }}>
|
||||
{msg.avatar ? <img src={`/uploads/avatars/${msg.avatar}`} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : (msg.username || '?')[0].toUpperCase()}
|
||||
</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
|
||||
<span style={{ fontSize: 12, fontWeight: 600, color: '#111827' }}>{msg.username}</span>
|
||||
<span style={{ fontSize: 10, color: '#9ca3af' }}>{new Date(msg.created_at).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' })}</span>
|
||||
<span className="text-[#111827]" style={{ fontSize: 12, fontWeight: 600 }}>{msg.username}</span>
|
||||
<span className="text-[#9ca3af]" style={{ fontSize: 10 }}>{new Date(msg.created_at).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' })}</span>
|
||||
</div>
|
||||
<div style={{ fontSize: 13, color: '#374151', marginTop: 3, lineHeight: 1.5, whiteSpace: 'pre-wrap' }}>{msg.text}</div>
|
||||
<div className="text-[#374151]" style={{ fontSize: 13, marginTop: 3, lineHeight: 1.5, whiteSpace: 'pre-wrap' }}>{msg.text}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -389,11 +382,11 @@ export default function SharedTripPage() {
|
||||
|
||||
{/* Footer */}
|
||||
<div style={{ textAlign: 'center', padding: '40px 0 20px' }}>
|
||||
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '8px 16px', borderRadius: 20, background: 'var(--bg-card, white)', border: '1px solid var(--border-faint, #e5e7eb)', boxShadow: '0 1px 3px rgba(0,0,0,0.04)' }}>
|
||||
<div className="bg-surface-card border border-edge-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '8px 16px', borderRadius: 20, boxShadow: '0 1px 3px rgba(0,0,0,0.04)' }}>
|
||||
<img src="/icons/icon.svg" alt="TREK" width="18" height="18" style={{ borderRadius: 4 }} />
|
||||
<span style={{ fontSize: 11, color: '#9ca3af' }}>{t('shared.sharedVia')} <strong style={{ color: '#6b7280' }}>TREK</strong></span>
|
||||
<span className="text-[#9ca3af]" style={{ fontSize: 11 }}>{t('shared.sharedVia')} <strong className="text-[#6b7280]">TREK</strong></span>
|
||||
</div>
|
||||
<div style={{ marginTop: 8, fontSize: 10, color: '#d1d5db' }}>Made with <span style={{ color: '#ef4444' }}>♥</span> by Maurice · <a href="https://github.com/mauriceboe/TREK" style={{ color: '#9ca3af', textDecoration: 'none' }}>GitHub</a></div>
|
||||
<div className="text-[#d1d5db]" style={{ marginTop: 8, fontSize: 10 }}>Made with <span className="text-[#ef4444]">♥</span> by Maurice · <a href="https://github.com/mauriceboe/TREK" className="text-[#9ca3af]" style={{ textDecoration: 'none' }}>GitHub</a></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -252,7 +252,7 @@ describe('TripPlannerPage', () => {
|
||||
renderPlannerPage(42);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockLoadTrip).toHaveBeenCalledWith('42');
|
||||
expect(mockLoadTrip).toHaveBeenCalledWith(42);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -298,7 +298,7 @@ describe('TripPlannerPage', () => {
|
||||
renderPlannerPage(999);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockLoadTrip).toHaveBeenCalledWith('999');
|
||||
expect(mockLoadTrip).toHaveBeenCalledWith(999);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -359,13 +359,13 @@ describe('TripPlannerPage', () => {
|
||||
});
|
||||
|
||||
describe('FE-PAGE-PLANNER-008: WebSocket hook mounted', () => {
|
||||
it('calls useTripWebSocket with the trip ID string', async () => {
|
||||
it('calls useTripWebSocket with the trip ID from URL params', async () => {
|
||||
seedTripStore({ id: 15 });
|
||||
|
||||
renderPlannerPage(15);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockUseTripWebSocket).toHaveBeenCalledWith('15');
|
||||
expect(mockUseTripWebSocket).toHaveBeenCalledWith(15);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -40,6 +40,7 @@ import { usePlaceSelection } from '../hooks/usePlaceSelection'
|
||||
import { usePlannerHistory } from '../hooks/usePlannerHistory'
|
||||
import type { Accommodation, TripMember, Day, Place, Reservation, PackingItem, TodoItem } from '../types'
|
||||
import { ListTodo, Upload, Plus, Trash2, FolderPlus } from 'lucide-react'
|
||||
import { useTripPlanner } from './tripPlanner/useTripPlanner'
|
||||
|
||||
function ListsContainer({ tripId, packingItems, todoItems }: { tripId: number; packingItems: PackingItem[]; todoItems: TodoItem[] }) {
|
||||
const [subTab, setSubTab] = useState<'packing' | 'todo'>(() => {
|
||||
@@ -60,38 +61,35 @@ function ListsContainer({ tripId, packingItems, todoItems }: { tripId: number; p
|
||||
return (
|
||||
<div>
|
||||
<div style={{ padding: '24px 28px 0' }} className="max-md:!px-4 max-md:!pt-4">
|
||||
<div style={{
|
||||
background: 'var(--bg-tertiary)', borderRadius: 18,
|
||||
<div className="bg-surface-tertiary" style={{
|
||||
borderRadius: 18,
|
||||
padding: '14px 16px 14px 22px',
|
||||
display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap',
|
||||
}}>
|
||||
<h2 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: 'var(--text-primary)', letterSpacing: '-0.01em', flexShrink: 0 }}>
|
||||
<h2 className="text-content" style={{ margin: 0, fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em', flexShrink: 0 }}>
|
||||
{t('trip.tabs.lists')}
|
||||
</h2>
|
||||
<div className="hidden md:block" style={{ width: 1, height: 22, background: 'var(--border-faint)', flexShrink: 0 }} />
|
||||
<div className="hidden md:block bg-edge-faint" style={{ width: 1, height: 22, flexShrink: 0 }} />
|
||||
<div style={{ display: 'inline-flex', gap: 4, flexWrap: 'wrap', flex: 1, minWidth: 0 }}>
|
||||
{tabs.map(tab => {
|
||||
const active = subTab === tab.id
|
||||
const Icon = tab.icon
|
||||
return (
|
||||
<button key={tab.id} onClick={() => setSubTabPersist(tab.id)}
|
||||
className={active ? 'bg-surface-card text-content' : 'bg-transparent text-content-muted'}
|
||||
style={{
|
||||
appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
padding: '6px 12px', borderRadius: 99, fontSize: 13, whiteSpace: 'nowrap',
|
||||
background: active ? 'var(--bg-card)' : 'transparent',
|
||||
color: active ? 'var(--text-primary)' : 'var(--text-muted)',
|
||||
fontWeight: active ? 500 : 400,
|
||||
boxShadow: active ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
|
||||
transition: 'background 180ms cubic-bezier(0.23,1,0.32,1), color 180ms cubic-bezier(0.23,1,0.32,1), box-shadow 180ms cubic-bezier(0.23,1,0.32,1)',
|
||||
}}
|
||||
>
|
||||
<Icon size={13} style={{ color: active ? 'var(--text-primary)' : 'var(--text-faint)' }} />
|
||||
<Icon size={13} className={active ? 'text-content' : 'text-content-faint'} />
|
||||
<span className="hidden sm:inline">{tab.label}</span>
|
||||
<span style={{
|
||||
<span className={`text-content-faint ${active ? 'bg-surface-tertiary' : 'bg-[rgba(0,0,0,0.06)]'}`} style={{
|
||||
fontSize: 10, fontWeight: 600,
|
||||
background: active ? 'var(--bg-tertiary)' : 'rgba(0,0,0,0.06)',
|
||||
color: 'var(--text-faint)',
|
||||
padding: '1px 6px', borderRadius: 99, minWidth: 16, textAlign: 'center',
|
||||
}}>{tab.count}</span>
|
||||
</button>
|
||||
@@ -110,8 +108,8 @@ function ListsContainer({ tripId, packingItems, todoItems }: { tripId: number; p
|
||||
<div style={{ display: 'flex', gap: 6, flexShrink: 0, marginLeft: 'auto', flexWrap: 'wrap' }}>
|
||||
{packingAbgehakt > 0 && (
|
||||
<button onClick={() => setClearCheckedSignal(s => s + 1)}
|
||||
className={`hidden sm:inline-flex items-center gap-1.5 px-[14px] py-[9px] hover:opacity-[0.88]`}
|
||||
style={{ ...sharedBtnStyle, background: 'rgba(239,68,68,0.14)', color: '#ef4444' }}
|
||||
className={`hidden sm:inline-flex items-center gap-1.5 px-[14px] py-[9px] hover:opacity-[0.88] bg-[rgba(239,68,68,0.14)] text-[#ef4444]`}
|
||||
style={sharedBtnStyle}
|
||||
>
|
||||
<Trash2 size={14} strokeWidth={2.5} />
|
||||
<span>{t('packing.clearChecked', { count: packingAbgehakt })}</span>
|
||||
@@ -119,21 +117,21 @@ function ListsContainer({ tripId, packingItems, todoItems }: { tripId: number; p
|
||||
)}
|
||||
<ApplyTemplateButton
|
||||
tripId={tripId}
|
||||
className={sharedBtnClass}
|
||||
style={{ ...sharedBtnStyle, background: 'var(--accent)', color: 'var(--accent-text)' }}
|
||||
className={`${sharedBtnClass} bg-accent text-accent-text`}
|
||||
style={sharedBtnStyle}
|
||||
/>
|
||||
{packingItems.length > 0 && (
|
||||
<button onClick={() => setSaveTemplateSignal(s => s + 1)}
|
||||
className={sharedBtnClass}
|
||||
style={{ ...sharedBtnStyle, background: 'var(--accent)', color: 'var(--accent-text)' }}
|
||||
className={`${sharedBtnClass} bg-accent text-accent-text`}
|
||||
style={sharedBtnStyle}
|
||||
>
|
||||
<FolderPlus size={14} strokeWidth={2.5} />
|
||||
<span className="hidden sm:inline">{t('packing.saveAsTemplate')}</span>
|
||||
</button>
|
||||
)}
|
||||
<button onClick={() => setImportPackingSignal(s => s + 1)}
|
||||
className={sharedBtnClass}
|
||||
style={{ ...sharedBtnStyle, background: 'var(--accent)', color: 'var(--accent-text)' }}
|
||||
className={`${sharedBtnClass} bg-accent text-accent-text`}
|
||||
style={sharedBtnStyle}
|
||||
>
|
||||
<Upload size={14} strokeWidth={2.5} />
|
||||
<span className="hidden sm:inline">{t('packing.import')}</span>
|
||||
@@ -143,12 +141,12 @@ function ListsContainer({ tripId, packingItems, todoItems }: { tripId: number; p
|
||||
})()}
|
||||
{subTab === 'todo' && (
|
||||
<button onClick={() => setAddTodoSignal(s => s + 1)}
|
||||
className="hover:opacity-[0.88]"
|
||||
className="hover:opacity-[0.88] bg-accent text-accent-text"
|
||||
style={{
|
||||
appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
padding: '9px 14px', borderRadius: 10, fontSize: 13, fontWeight: 500,
|
||||
background: 'var(--accent)', color: 'var(--accent-text)', flexShrink: 0,
|
||||
flexShrink: 0,
|
||||
marginLeft: 'auto',
|
||||
}}
|
||||
>
|
||||
@@ -167,590 +165,46 @@ function ListsContainer({ tripId, packingItems, todoItems }: { tripId: number; p
|
||||
}
|
||||
|
||||
export default function TripPlannerPage(): React.ReactElement | null {
|
||||
const { id: tripId } = useParams<{ id: string }>()
|
||||
const navigate = useNavigate()
|
||||
const toast = useToast()
|
||||
const { t, language } = useTranslation()
|
||||
const { settings } = useSettingsStore()
|
||||
const placesPhotosEnabled = useAuthStore(s => s.placesPhotosEnabled)
|
||||
const trip = useTripStore(s => s.trip)
|
||||
const days = useTripStore(s => s.days)
|
||||
const places = useTripStore(s => s.places)
|
||||
const assignments = useTripStore(s => s.assignments)
|
||||
const packingItems = useTripStore(s => s.packingItems)
|
||||
const todoItems = useTripStore(s => s.todoItems)
|
||||
const categories = useTripStore(s => s.categories)
|
||||
const reservations = useTripStore(s => s.reservations)
|
||||
const budgetItems = useTripStore(s => s.budgetItems)
|
||||
const files = useTripStore(s => s.files)
|
||||
const selectedDayId = useTripStore(s => s.selectedDayId)
|
||||
const isLoading = useTripStore(s => s.isLoading)
|
||||
// Actions — stable references, don't cause re-renders
|
||||
const tripActions = useRef(useTripStore.getState()).current
|
||||
const can = useCanDo()
|
||||
const canUploadFiles = can('file_upload', trip)
|
||||
const { pushUndo, undo, canUndo, lastActionLabel } = usePlannerHistory()
|
||||
|
||||
const handleUndo = useCallback(async () => {
|
||||
const label = lastActionLabel
|
||||
await undo()
|
||||
toast.info(t('undo.done', { action: label ?? '' }))
|
||||
}, [undo, lastActionLabel, toast])
|
||||
|
||||
const [enabledAddons, setEnabledAddons] = useState<Record<string, boolean>>({ packing: true, budget: true, documents: true, collab: false })
|
||||
const [collabFeatures, setCollabFeatures] = useState<{ chat: boolean; notes: boolean; polls: boolean; whatsnext: boolean }>({ chat: true, notes: true, polls: true, whatsnext: true })
|
||||
const [tripAccommodations, setTripAccommodations] = useState<Accommodation[]>([])
|
||||
const [allowedFileTypes, setAllowedFileTypes] = useState<string | null>(null)
|
||||
const [tripMembers, setTripMembers] = useState<TripMember[]>([])
|
||||
|
||||
const loadAccommodations = useCallback(() => {
|
||||
if (tripId) {
|
||||
accommodationRepo.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {})
|
||||
tripActions.loadReservations(tripId)
|
||||
}
|
||||
}, [tripId])
|
||||
|
||||
useEffect(() => {
|
||||
addonsApi.enabled().then(data => {
|
||||
const map = {}
|
||||
data.addons.forEach(a => { map[a.id] = true })
|
||||
setEnabledAddons({ packing: !!map.packing, budget: !!map.budget, documents: !!map.documents, collab: !!map.collab })
|
||||
if (data.collabFeatures) setCollabFeatures(data.collabFeatures)
|
||||
}).catch(() => {})
|
||||
authApi.getAppConfig().then(config => {
|
||||
if (config.allowed_file_types) setAllowedFileTypes(config.allowed_file_types)
|
||||
}).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const TRANSPORT_TYPES = new Set(['flight', 'train', 'car', 'cruise', 'bus'])
|
||||
|
||||
const TRIP_TABS = [
|
||||
{ id: 'plan', label: t('trip.tabs.plan'), icon: Map },
|
||||
{ id: 'transports', label: t('trip.tabs.transports'), icon: Train },
|
||||
{ id: 'buchungen', label: t('trip.tabs.reservations'), shortLabel: t('trip.tabs.reservationsShort'), icon: Ticket },
|
||||
...(enabledAddons.packing ? [{ id: 'listen', label: t('trip.tabs.lists'), shortLabel: t('trip.tabs.listsShort'), icon: PackageCheck }] : []),
|
||||
...(enabledAddons.budget ? [{ id: 'finanzplan', label: t('trip.tabs.budget'), icon: Wallet }] : []),
|
||||
...(enabledAddons.documents ? [{ id: 'dateien', label: t('trip.tabs.files'), icon: FolderOpen }] : []),
|
||||
...(enabledAddons.collab ? [{ id: 'collab', label: t('admin.addons.catalog.collab.name'), icon: Users }] : []),
|
||||
]
|
||||
|
||||
const [activeTab, setActiveTab] = useState<string>(() => {
|
||||
const saved = sessionStorage.getItem(`trip-tab-${tripId}`)
|
||||
return saved || 'plan'
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
const validTabIds = TRIP_TABS.map(t => t.id)
|
||||
if (!validTabIds.includes(activeTab)) {
|
||||
setActiveTab('plan')
|
||||
sessionStorage.setItem(`trip-tab-${tripId}`, 'plan')
|
||||
}
|
||||
}, [enabledAddons])
|
||||
|
||||
const handleTabChange = (tabId: string): void => {
|
||||
setActiveTab(tabId)
|
||||
sessionStorage.setItem(`trip-tab-${tripId}`, tabId)
|
||||
if (tabId === 'finanzplan') tripActions.loadBudgetItems?.(tripId)
|
||||
if (tabId === 'dateien' && (!files || files.length === 0)) tripActions.loadFiles?.(tripId)
|
||||
}
|
||||
const { leftWidth, rightWidth, leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed, startResizeLeft, startResizeRight } = useResizablePanels()
|
||||
const { selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment } = usePlaceSelection()
|
||||
const [showDayDetail, setShowDayDetail] = useState<Day | null>(null)
|
||||
const [dayDetailCollapsed, setDayDetailCollapsed] = useState(false)
|
||||
const [showPlaceForm, setShowPlaceForm] = useState<boolean>(false)
|
||||
const [editingPlace, setEditingPlace] = useState<Place | null>(null)
|
||||
const [prefillCoords, setPrefillCoords] = useState<{ lat: number; lng: number; name?: string; address?: string } | null>(null)
|
||||
const [editingAssignmentId, setEditingAssignmentId] = useState<number | null>(null)
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
|
||||
// The bottom-nav "+" opens the new-place form via ?create=place.
|
||||
useEffect(() => {
|
||||
if (searchParams.get('create') === 'place') {
|
||||
setEditingPlace(null); setEditingAssignmentId(null); setShowPlaceForm(true)
|
||||
setSearchParams(p => { p.delete('create'); return p }, { replace: true })
|
||||
}
|
||||
}, [searchParams])
|
||||
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 [bookingForAssignmentId, setBookingForAssignmentId] = useState<number | null>(null)
|
||||
const [showTransportModal, setShowTransportModal] = useState<boolean>(false)
|
||||
const [editingTransport, setEditingTransport] = useState<Reservation | null>(null)
|
||||
const [transportModalDayId, setTransportModalDayId] = useState<number | null>(null)
|
||||
// Manual route planning: off by default, toggled from the day-plan footer. Mode
|
||||
// (driving/walking) is per-session and selects which travel time the connectors show.
|
||||
const [routeShown, setRouteShown] = useState(false)
|
||||
const [routeProfile, setRouteProfile] = useState<'driving' | 'walking'>('driving')
|
||||
const [fitKey, setFitKey] = useState<number>(0)
|
||||
const initialFitTripId = useRef<number | null>(null)
|
||||
const [mobileSidebarOpen, setMobileSidebarOpen] = useState<'left' | 'right' | null>(null)
|
||||
const mobilePlanScrollTopRef = useRef<number>(0)
|
||||
const mobilePlacesScrollTopRef = useRef<number>(0)
|
||||
const [deletePlaceId, setDeletePlaceId] = useState<number | null>(null)
|
||||
const [deletePlaceIds, setDeletePlaceIds] = useState<number[] | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!trip) return
|
||||
if (initialFitTripId.current === trip.id) return
|
||||
const hasGeoPlaces = places.some(p => p.lat != null && p.lng != null)
|
||||
if (!hasGeoPlaces) return
|
||||
initialFitTripId.current = trip.id
|
||||
setFitKey(k => k + 1)
|
||||
}, [trip, places])
|
||||
|
||||
const connectionsStorageKey = tripId ? `trek:visible-connections:${tripId}` : null
|
||||
const [visibleConnections, setVisibleConnections] = useState<number[]>(() => {
|
||||
if (typeof window === 'undefined' || !connectionsStorageKey) return []
|
||||
try {
|
||||
const stored = window.localStorage.getItem(connectionsStorageKey)
|
||||
return stored ? JSON.parse(stored) as number[] : []
|
||||
} catch { return [] }
|
||||
})
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined' || !connectionsStorageKey) return
|
||||
window.localStorage.setItem(connectionsStorageKey, JSON.stringify(visibleConnections))
|
||||
}, [connectionsStorageKey, visibleConnections])
|
||||
const toggleConnection = useCallback((id: number) => {
|
||||
setVisibleConnections(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
|
||||
}, [])
|
||||
const [mapTransportDetail, setMapTransportDetail] = useState<Reservation | null>(null)
|
||||
|
||||
const [isMobile, setIsMobile] = useState(() => window.innerWidth < 768)
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia('(max-width: 767px)')
|
||||
const handler = (e: MediaQueryListEvent) => setIsMobile(e.matches)
|
||||
mq.addEventListener('change', handler)
|
||||
return () => mq.removeEventListener('change', handler)
|
||||
}, [])
|
||||
|
||||
// Start photo fetches during splash screen so images are ready when map mounts
|
||||
useEffect(() => {
|
||||
if (isLoading || !places || places.length === 0 || !placesPhotosEnabled) return
|
||||
for (const p of places) {
|
||||
if (p.image_url) continue
|
||||
const cacheKey = p.google_place_id || p.osm_id || `${p.lat},${p.lng}`
|
||||
if (!cacheKey || getCached(cacheKey)) continue
|
||||
const photoId = p.google_place_id || p.osm_id
|
||||
if (photoId || (p.lat && p.lng)) {
|
||||
fetchPhoto(cacheKey, photoId || `coords:${p.lat}:${p.lng}`, p.lat, p.lng, p.name)
|
||||
}
|
||||
}
|
||||
}, [isLoading, places])
|
||||
|
||||
// Load trip + files (needed for place inspector file section)
|
||||
useEffect(() => {
|
||||
if (tripId) {
|
||||
tripActions.loadTrip(tripId).catch(() => { toast.error(t('trip.toast.loadError')); navigate('/dashboard') })
|
||||
tripActions.loadFiles(tripId)
|
||||
loadAccommodations()
|
||||
if (!navigator.onLine) {
|
||||
offlineDb.tripMembers.where('tripId').equals(Number(tripId)).toArray()
|
||||
.then(rows => setTripMembers(rows))
|
||||
.catch(() => {})
|
||||
} else {
|
||||
tripsApi.getMembers(tripId).then(d => {
|
||||
const all = [d.owner, ...(d.members || [])].filter(Boolean)
|
||||
setTripMembers(all)
|
||||
}).catch(() => {})
|
||||
}
|
||||
}
|
||||
}, [tripId])
|
||||
|
||||
useEffect(() => {
|
||||
if (tripId) {
|
||||
tripActions.loadReservations(tripId)
|
||||
tripActions.loadBudgetItems?.(tripId)
|
||||
}
|
||||
}, [tripId])
|
||||
|
||||
useTripWebSocket(tripId)
|
||||
|
||||
const [mapCategoryFilter, setMapCategoryFilter] = useState<Set<string>>(new Set())
|
||||
const [mapPlacesFilter, setMapPlacesFilter] = useState<string>('all')
|
||||
|
||||
const [expandedDayIds, setExpandedDayIds] = useState<Set<number> | null>(null)
|
||||
|
||||
const mapPlaces = useMemo(() => {
|
||||
// Build set of place IDs assigned to collapsed days
|
||||
const hiddenPlaceIds = new Set<number>()
|
||||
if (expandedDayIds) {
|
||||
for (const [dayId, dayAssignments] of Object.entries(assignments)) {
|
||||
if (!expandedDayIds.has(Number(dayId))) {
|
||||
for (const a of dayAssignments) {
|
||||
if (a.place?.id) hiddenPlaceIds.add(a.place.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Don't hide places that are also assigned to an expanded day
|
||||
for (const [dayId, dayAssignments] of Object.entries(assignments)) {
|
||||
if (expandedDayIds.has(Number(dayId))) {
|
||||
for (const a of dayAssignments) {
|
||||
hiddenPlaceIds.delete(a.place?.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build set of planned place IDs for unplanned filter
|
||||
const plannedIds = mapPlacesFilter === 'unplanned'
|
||||
? new Set(Object.values(assignments).flatMap(da => da.map(a => a.place?.id).filter(Boolean)))
|
||||
: null
|
||||
|
||||
return places.filter(p => {
|
||||
if (!p.lat || !p.lng) return false
|
||||
if (mapPlacesFilter === 'tracks' && !p.route_geometry) return false
|
||||
if (mapCategoryFilter.size > 0) {
|
||||
if (p.category_id == null) {
|
||||
if (!mapCategoryFilter.has('uncategorized')) return false
|
||||
} else if (!mapCategoryFilter.has(String(p.category_id))) return false
|
||||
}
|
||||
if (hiddenPlaceIds.has(p.id)) return false
|
||||
if (plannedIds && plannedIds.has(p.id)) return false
|
||||
return true
|
||||
})
|
||||
}, [places, mapCategoryFilter, mapPlacesFilter, assignments, expandedDayIds])
|
||||
|
||||
const { route, routeSegments, routeInfo, setRoute, setRouteInfo, updateRouteForDay } = useRouteCalculation({ assignments } as any, selectedDayId, routeShown, routeProfile)
|
||||
|
||||
const handleSelectDay = useCallback((dayId, skipFit) => {
|
||||
const changed = dayId !== selectedDayId
|
||||
tripActions.setSelectedDay(dayId)
|
||||
if (changed && !skipFit) setFitKey(k => k + 1)
|
||||
setMobileSidebarOpen(null)
|
||||
updateRouteForDay(dayId)
|
||||
}, [updateRouteForDay, selectedDayId])
|
||||
|
||||
const handlePlaceClick = useCallback((placeId, assignmentId) => {
|
||||
if (assignmentId) {
|
||||
selectAssignment(assignmentId, placeId)
|
||||
} else {
|
||||
setSelectedPlaceId(placeId)
|
||||
}
|
||||
if (placeId) { setShowDayDetail(null); setLeftCollapsed(false); setRightCollapsed(false) }
|
||||
}, [selectAssignment, setSelectedPlaceId])
|
||||
|
||||
const handleMarkerClick = useCallback((placeId) => {
|
||||
if (placeId === undefined) {
|
||||
setSelectedPlaceId(null)
|
||||
return
|
||||
}
|
||||
// Find every assignment for this place (same place can sit on several
|
||||
// days / be planned twice in one day). Cycle through them on repeated
|
||||
// marker clicks so the sidebar highlight jumps to the next occurrence
|
||||
// instead of leaving the user confused.
|
||||
const allAssignments = Object.values(useTripStore.getState().assignments || {}).flat()
|
||||
const matching = allAssignments.filter(a => a?.place?.id === placeId)
|
||||
|
||||
if (matching.length === 0) {
|
||||
setSelectedPlaceId(prev => prev === placeId ? null : placeId)
|
||||
} else if (matching.length === 1) {
|
||||
const only = matching[0]
|
||||
if (selectedAssignmentId === only.id) {
|
||||
setSelectedPlaceId(null)
|
||||
} else {
|
||||
selectAssignment(only.id, placeId)
|
||||
}
|
||||
} else {
|
||||
const currentIdx = matching.findIndex(a => a.id === selectedAssignmentId)
|
||||
const nextIdx = currentIdx === -1 ? 0 : currentIdx + 1
|
||||
if (nextIdx >= matching.length) {
|
||||
// cycled past the last occurrence — clear selection so the next
|
||||
// click starts fresh at occurrence 0.
|
||||
setSelectedPlaceId(null)
|
||||
} else {
|
||||
selectAssignment(matching[nextIdx].id, placeId)
|
||||
}
|
||||
}
|
||||
setLeftCollapsed(false); setRightCollapsed(false)
|
||||
}, [selectAssignment, selectedAssignmentId, setSelectedPlaceId])
|
||||
|
||||
const handleMapClick = useCallback(() => {
|
||||
setSelectedPlaceId(null)
|
||||
}, [])
|
||||
|
||||
const handleMapContextMenu = useCallback(async (e) => {
|
||||
if (!can('place_edit', trip)) return
|
||||
e.originalEvent?.preventDefault()
|
||||
const { lat, lng } = e.latlng
|
||||
setPrefillCoords({ lat, lng })
|
||||
setEditingPlace(null)
|
||||
setEditingAssignmentId(null)
|
||||
setShowPlaceForm(true)
|
||||
try {
|
||||
const { mapsApi } = await import('../api/client')
|
||||
const data = await mapsApi.reverse(lat, lng, language)
|
||||
if (data.name || data.address) {
|
||||
setPrefillCoords(prev => prev ? { ...prev, name: data.name || '', address: data.address || '' } : prev)
|
||||
}
|
||||
} catch { /* best effort */ }
|
||||
}, [language])
|
||||
|
||||
const handleSavePlace = useCallback(async (data) => {
|
||||
const pendingFiles = data._pendingFiles
|
||||
delete data._pendingFiles
|
||||
if (editingPlace) {
|
||||
// Always strip time fields from place update — time is per-assignment only
|
||||
const { place_time, end_time, ...placeData } = data
|
||||
await tripActions.updatePlace(tripId, editingPlace.id, placeData)
|
||||
// If editing from assignment context, save time per-assignment
|
||||
if (editingAssignmentId) {
|
||||
await assignmentsApi.updateTime(tripId, editingAssignmentId, { place_time: place_time || null, end_time: end_time || null })
|
||||
await tripActions.refreshDays(tripId)
|
||||
}
|
||||
// Upload pending files with place_id
|
||||
if (pendingFiles?.length > 0) {
|
||||
for (const file of pendingFiles) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
fd.append('place_id', editingPlace.id)
|
||||
try { await tripActions.addFile(tripId, fd) } catch {}
|
||||
}
|
||||
}
|
||||
toast.success(t('trip.toast.placeUpdated'))
|
||||
} else {
|
||||
const place = await tripActions.addPlace(tripId, data)
|
||||
if (pendingFiles?.length > 0 && place?.id) {
|
||||
for (const file of pendingFiles) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
fd.append('place_id', place.id)
|
||||
try { await tripActions.addFile(tripId, fd) } catch {}
|
||||
}
|
||||
}
|
||||
toast.success(t('trip.toast.placeAdded'))
|
||||
if (place?.id) {
|
||||
const capturedId = place.id
|
||||
pushUndo(t('undo.addPlace'), async () => {
|
||||
await tripActions.deletePlace(tripId, capturedId)
|
||||
})
|
||||
}
|
||||
}
|
||||
}, [editingPlace, editingAssignmentId, tripId, toast, pushUndo])
|
||||
|
||||
const handleDeletePlace = useCallback((placeId) => {
|
||||
setDeletePlaceId(placeId)
|
||||
}, [])
|
||||
|
||||
const confirmDeletePlace = useCallback(async () => {
|
||||
if (!deletePlaceId) return
|
||||
const state = useTripStore.getState()
|
||||
const capturedPlace = state.places.find(p => p.id === deletePlaceId)
|
||||
const capturedAssignments = Object.entries(state.assignments).flatMap(([dayId, as]) =>
|
||||
as.filter(a => a.place?.id === deletePlaceId).map(a => ({ dayId: Number(dayId), orderIndex: a.order_index }))
|
||||
)
|
||||
try {
|
||||
await tripActions.deletePlace(tripId, deletePlaceId)
|
||||
if (selectedPlaceId === deletePlaceId) setSelectedPlaceId(null)
|
||||
updateRouteForDay(selectedDayId)
|
||||
toast.success(t('trip.toast.placeDeleted'))
|
||||
if (capturedPlace) {
|
||||
pushUndo(t('undo.deletePlace'), async () => {
|
||||
const newPlace = await tripActions.addPlace(tripId, {
|
||||
name: capturedPlace.name,
|
||||
description: capturedPlace.description,
|
||||
lat: capturedPlace.lat,
|
||||
lng: capturedPlace.lng,
|
||||
address: capturedPlace.address,
|
||||
category_id: capturedPlace.category_id,
|
||||
icon: capturedPlace.icon,
|
||||
price: capturedPlace.price,
|
||||
})
|
||||
for (const { dayId, orderIndex } of capturedAssignments) {
|
||||
await tripActions.assignPlaceToDay(tripId, dayId, newPlace.id, orderIndex)
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}, [deletePlaceId, tripId, toast, selectedPlaceId, selectedDayId, updateRouteForDay, pushUndo])
|
||||
|
||||
const confirmDeletePlaces = useCallback(async (ids?: number[]) => {
|
||||
const targetIds = ids ?? deletePlaceIds
|
||||
if (!targetIds?.length) return
|
||||
const state = useTripStore.getState()
|
||||
const capturedPlaces = state.places.filter(p => targetIds.includes(p.id))
|
||||
const capturedAssignments = Object.entries(state.assignments).flatMap(([dayId, as]) =>
|
||||
as.filter(a => a.place?.id != null && targetIds.includes(a.place.id)).map(a => ({ dayId: Number(dayId), placeId: a.place!.id, orderIndex: a.order_index }))
|
||||
)
|
||||
try {
|
||||
await tripActions.deletePlacesMany(tripId, targetIds)
|
||||
if (selectedPlaceId != null && targetIds.includes(selectedPlaceId)) setSelectedPlaceId(null)
|
||||
if (!ids) setDeletePlaceIds(null)
|
||||
updateRouteForDay(selectedDayId)
|
||||
toast.success(t('trip.toast.placesDeleted', { count: capturedPlaces.length }))
|
||||
if (capturedPlaces.length > 0) {
|
||||
pushUndo(t('undo.deletePlaces'), async () => {
|
||||
for (const place of capturedPlaces) {
|
||||
const newPlace = await tripActions.addPlace(tripId, {
|
||||
name: place.name, description: place.description,
|
||||
lat: place.lat, lng: place.lng, address: place.address,
|
||||
category_id: place.category_id, icon: place.icon, price: place.price,
|
||||
})
|
||||
for (const a of capturedAssignments.filter(x => x.placeId === place.id)) {
|
||||
await tripActions.assignPlaceToDay(tripId, a.dayId, newPlace.id, a.orderIndex)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}, [deletePlaceIds, tripId, toast, selectedPlaceId, selectedDayId, updateRouteForDay, pushUndo])
|
||||
|
||||
const handleAssignToDay = useCallback(async (placeId, dayId, position) => {
|
||||
const target = dayId || selectedDayId
|
||||
if (!target) { toast.error(t('trip.toast.selectDay')); return }
|
||||
try {
|
||||
const assignment = await tripActions.assignPlaceToDay(tripId, target, placeId, position)
|
||||
toast.success(t('trip.toast.assignedToDay'))
|
||||
updateRouteForDay(target)
|
||||
if (assignment?.id) {
|
||||
const capturedAssignmentId = assignment.id
|
||||
const capturedTarget = target
|
||||
pushUndo(t('undo.assignPlace'), async () => {
|
||||
await tripActions.removeAssignment(tripId, capturedTarget, capturedAssignmentId)
|
||||
})
|
||||
}
|
||||
} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}, [selectedDayId, tripId, toast, updateRouteForDay, pushUndo])
|
||||
|
||||
const handleRemoveAssignment = useCallback(async (dayId, assignmentId) => {
|
||||
const state = useTripStore.getState()
|
||||
const capturedAssignment = (state.assignments[String(dayId)] || []).find(a => a.id === assignmentId)
|
||||
const capturedPlaceId = capturedAssignment?.place?.id
|
||||
const capturedOrderIndex = capturedAssignment?.order_index ?? 0
|
||||
try {
|
||||
await tripActions.removeAssignment(tripId, dayId, assignmentId)
|
||||
updateRouteForDay(dayId)
|
||||
if (capturedPlaceId != null) {
|
||||
const capturedDayId = dayId
|
||||
const capturedPos = capturedOrderIndex
|
||||
pushUndo(t('undo.removeAssignment'), async () => {
|
||||
await tripActions.assignPlaceToDay(tripId, capturedDayId, capturedPlaceId, capturedPos)
|
||||
})
|
||||
}
|
||||
}
|
||||
catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}, [tripId, toast, updateRouteForDay, pushUndo])
|
||||
|
||||
const handleReorder = useCallback((dayId, orderedIds) => {
|
||||
const prevIds = (useTripStore.getState().assignments[String(dayId)] || [])
|
||||
.slice().sort((a, b) => a.order_index - b.order_index).map(a => a.id)
|
||||
try {
|
||||
tripActions.reorderAssignments(tripId, dayId, orderedIds)
|
||||
.then(() => {
|
||||
const capturedDayId = dayId
|
||||
const capturedPrevIds = prevIds
|
||||
pushUndo(t('undo.reorder'), async () => {
|
||||
await tripActions.reorderAssignments(tripId, capturedDayId, capturedPrevIds)
|
||||
})
|
||||
})
|
||||
.catch(err => toast.error(err instanceof Error ? err.message : t('trip.toast.reorderError')))
|
||||
updateRouteForDay(dayId)
|
||||
}
|
||||
catch { toast.error(t('trip.toast.reorderError')) }
|
||||
}, [tripId, toast, pushUndo, updateRouteForDay])
|
||||
|
||||
const handleUpdateDayTitle = useCallback(async (dayId, title) => {
|
||||
try { await tripActions.updateDayTitle(tripId, dayId, title) }
|
||||
catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}, [tripId, toast])
|
||||
|
||||
const handleSaveReservation = async (data) => {
|
||||
try {
|
||||
if (editingReservation) {
|
||||
const r = await tripActions.updateReservation(tripId, editingReservation.id, { ...data, day_id: selectedDayId || null })
|
||||
toast.success(t('trip.toast.reservationUpdated'))
|
||||
setShowReservationModal(false)
|
||||
setEditingReservation(null)
|
||||
if (data.type === 'hotel') {
|
||||
accommodationsApi.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {})
|
||||
}
|
||||
return r
|
||||
} else {
|
||||
const r = await tripActions.addReservation(tripId, { ...data, day_id: selectedDayId || null })
|
||||
toast.success(t('trip.toast.reservationAdded'))
|
||||
setShowReservationModal(false)
|
||||
// Refresh accommodations if hotel was created
|
||||
if (data.type === 'hotel') {
|
||||
accommodationsApi.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {})
|
||||
}
|
||||
return r
|
||||
}
|
||||
} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}
|
||||
|
||||
const handleSaveTransport = async (data) => {
|
||||
try {
|
||||
if (editingTransport) {
|
||||
const r = await tripActions.updateReservation(tripId, editingTransport.id, data)
|
||||
toast.success(t('trip.toast.reservationUpdated'))
|
||||
setShowTransportModal(false)
|
||||
setEditingTransport(null)
|
||||
setTransportModalDayId(null)
|
||||
return r
|
||||
} else {
|
||||
const r = await tripActions.addReservation(tripId, data)
|
||||
toast.success(t('trip.toast.reservationAdded'))
|
||||
setShowTransportModal(false)
|
||||
setEditingTransport(null)
|
||||
setTransportModalDayId(null)
|
||||
return r
|
||||
}
|
||||
} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}
|
||||
|
||||
const handleDeleteReservation = async (id) => {
|
||||
try {
|
||||
await tripActions.deleteReservation(tripId, id)
|
||||
toast.success(t('trip.toast.deleted'))
|
||||
// Refresh accommodations in case a hotel booking was deleted
|
||||
accommodationsApi.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {})
|
||||
}
|
||||
catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}
|
||||
|
||||
const selectedPlace = selectedPlaceId ? places.find(p => p.id === selectedPlaceId) : null
|
||||
|
||||
// Build placeId → order-number map from the selected day's assignments
|
||||
const dayOrderMap = useMemo(() => {
|
||||
if (!selectedDayId) return {}
|
||||
const da = assignments[String(selectedDayId)] || []
|
||||
const sorted = [...da].sort((a, b) => a.order_index - b.order_index)
|
||||
const map = {}
|
||||
sorted.forEach((a, i) => {
|
||||
if (!a.place?.id) return
|
||||
if (!map[a.place.id]) map[a.place.id] = []
|
||||
map[a.place.id].push(i + 1)
|
||||
})
|
||||
return map
|
||||
}, [selectedDayId, assignments])
|
||||
|
||||
// Places assigned to selected day (with coords) — used for map fitting
|
||||
const dayPlaces = useMemo(() => {
|
||||
if (!selectedDayId) return []
|
||||
const da = assignments[String(selectedDayId)] || []
|
||||
return da.map(a => a.place).filter(p => p?.lat && p?.lng)
|
||||
}, [selectedDayId, assignments])
|
||||
|
||||
const mapTileUrl = settings.map_tile_url || 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png'
|
||||
const defaultCenter = [settings.default_lat || 48.8566, settings.default_lng || 2.3522]
|
||||
const defaultZoom = settings.default_zoom || 10
|
||||
|
||||
const fontStyle = { fontFamily: "-apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Segoe UI', system-ui, sans-serif" }
|
||||
|
||||
// Splash screen — show for initial load + a brief moment for photos to start loading
|
||||
const [splashDone, setSplashDone] = useState(false)
|
||||
useEffect(() => {
|
||||
if (!isLoading && trip) {
|
||||
const timer = setTimeout(() => setSplashDone(true), 1500)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [isLoading, trip])
|
||||
// Page = wiring container: the entire planner state machine (store, tabs,
|
||||
// selection, CRUD handlers with undo, map filters, splash) lives in the hook.
|
||||
const {
|
||||
tripId, navigate, toast, t, language, settings, placesPhotosEnabled,
|
||||
trip, days, places, assignments, packingItems, todoItems, categories, reservations, budgetItems, files,
|
||||
selectedDayId, isLoading, tripActions, can, canUploadFiles,
|
||||
pushUndo, undo, canUndo, lastActionLabel, handleUndo,
|
||||
enabledAddons, collabFeatures, tripAccommodations, setTripAccommodations,
|
||||
allowedFileTypes, tripMembers, setTripMembers, loadAccommodations,
|
||||
TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange,
|
||||
leftWidth, rightWidth, leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed, startResizeLeft, startResizeRight,
|
||||
selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment,
|
||||
showDayDetail, setShowDayDetail, dayDetailCollapsed, setDayDetailCollapsed,
|
||||
showPlaceForm, setShowPlaceForm, editingPlace, setEditingPlace,
|
||||
prefillCoords, setPrefillCoords, editingAssignmentId, setEditingAssignmentId,
|
||||
showTripForm, setShowTripForm, showMembersModal, setShowMembersModal,
|
||||
showReservationModal, setShowReservationModal, editingReservation, setEditingReservation,
|
||||
bookingForAssignmentId, setBookingForAssignmentId,
|
||||
showTransportModal, setShowTransportModal, editingTransport, setEditingTransport,
|
||||
transportModalDayId, setTransportModalDayId,
|
||||
routeShown, setRouteShown, routeProfile, setRouteProfile, fitKey, setFitKey,
|
||||
mobileSidebarOpen, setMobileSidebarOpen, mobilePlanScrollTopRef, mobilePlacesScrollTopRef,
|
||||
deletePlaceId, setDeletePlaceId, deletePlaceIds, setDeletePlaceIds,
|
||||
visibleConnections, setVisibleConnections, toggleConnection, mapTransportDetail, setMapTransportDetail,
|
||||
isMobile, mapCategoryFilter, setMapCategoryFilter, mapPlacesFilter, setMapPlacesFilter,
|
||||
expandedDayIds, setExpandedDayIds, mapPlaces,
|
||||
route, routeSegments, routeInfo, setRoute, setRouteInfo, updateRouteForDay,
|
||||
handleSelectDay, handlePlaceClick, handleMarkerClick, handleMapClick, handleMapContextMenu,
|
||||
handleSavePlace, handleDeletePlace, confirmDeletePlace, confirmDeletePlaces,
|
||||
handleAssignToDay, handleRemoveAssignment, handleReorder, handleUpdateDayTitle,
|
||||
handleSaveReservation, handleSaveTransport, handleDeleteReservation,
|
||||
selectedPlace, dayOrderMap, dayPlaces,
|
||||
mapTileUrl, defaultCenter, defaultZoom, fontStyle, splashDone,
|
||||
} = useTripPlanner()
|
||||
|
||||
if (isLoading || !splashDone) {
|
||||
return (
|
||||
<div style={{
|
||||
<div className="bg-surface" style={{
|
||||
minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
|
||||
background: 'var(--bg-primary)', ...fontStyle,
|
||||
...fontStyle,
|
||||
}}>
|
||||
<style>{`
|
||||
@keyframes dotPulse {
|
||||
@@ -770,16 +224,16 @@ export default function TripPlannerPage(): React.ReactElement | null {
|
||||
height={64}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ fontSize: 20, fontWeight: 700, color: 'var(--text-primary)', letterSpacing: '-0.3px', marginBottom: 6, animation: 'fadeInUp 0.5s ease-out' }}>
|
||||
<div className="text-content" style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-0.3px', marginBottom: 6, animation: 'fadeInUp 0.5s ease-out' }}>
|
||||
{trip?.title || 'TREK'}
|
||||
</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--text-faint)', fontWeight: 500, letterSpacing: '2px', textTransform: 'uppercase', marginBottom: 32, animation: 'fadeInUp 0.5s ease-out 0.1s both' }}>
|
||||
<div className="text-content-faint" style={{ fontSize: 12, fontWeight: 500, letterSpacing: '2px', textTransform: 'uppercase', marginBottom: 32, animation: 'fadeInUp 0.5s ease-out 0.1s both' }}>
|
||||
{t('trip.loadingPhotos')}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
{[0, 1, 2].map(i => (
|
||||
<div key={i} style={{
|
||||
width: 8, height: 8, borderRadius: '50%', background: 'var(--text-muted)',
|
||||
<div key={i} className="bg-content-muted" style={{
|
||||
width: 8, height: 8, borderRadius: '50%',
|
||||
animation: `dotPulse 1.4s ease-in-out ${i * 0.2}s infinite`,
|
||||
}} />
|
||||
))}
|
||||
@@ -793,14 +247,12 @@ export default function TripPlannerPage(): React.ReactElement | null {
|
||||
<div style={{ position: 'fixed', inset: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden', ...fontStyle }}>
|
||||
<Navbar tripTitle={trip.title} tripId={tripId} showBack onBack={() => navigate('/dashboard')} onShare={() => setShowMembersModal(true)} />
|
||||
|
||||
<div style={{
|
||||
<div className="bg-surface-elevated border-b border-edge-faint" style={{
|
||||
position: 'fixed', top: 'var(--nav-h)', left: 0, right: 0, zIndex: 40,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
padding: '0 12px',
|
||||
background: 'var(--bg-elevated)',
|
||||
backdropFilter: 'blur(16px)',
|
||||
WebkitBackdropFilter: 'blur(16px)',
|
||||
borderBottom: '1px solid var(--border-faint)',
|
||||
height: 44,
|
||||
}}>
|
||||
<SlidingTabs
|
||||
@@ -889,7 +341,7 @@ export default function TripPlannerPage(): React.ReactElement | null {
|
||||
onReorder={handleReorder}
|
||||
onUpdateDayTitle={handleUpdateDayTitle}
|
||||
onAssignToDay={handleAssignToDay}
|
||||
onRouteCalculated={(r) => { if (r) { setRoute([r.coordinates]); setRouteInfo({ distance: r.distanceText, duration: r.durationText, walkingText: r.walkingText, drivingText: r.drivingText }) } else { setRoute(null); setRouteInfo(null) } }}
|
||||
onRouteCalculated={(r) => { if (r) { setRoute([r.coordinates]); setRouteInfo(r) } else { setRoute(null); setRouteInfo(null) } }}
|
||||
reservations={reservations}
|
||||
visibleConnectionIds={visibleConnections}
|
||||
onToggleConnection={toggleConnection}
|
||||
@@ -979,6 +431,8 @@ export default function TripPlannerPage(): React.ReactElement | null {
|
||||
onCategoryFilterChange={setMapCategoryFilter}
|
||||
onPlacesFilterChange={setMapPlacesFilter}
|
||||
pushUndo={pushUndo}
|
||||
days={days}
|
||||
isMobile={false}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -988,11 +442,13 @@ export default function TripPlannerPage(): React.ReactElement | null {
|
||||
{activeTab === 'plan' && !mobileSidebarOpen && !showPlaceForm && !showMembersModal && !showReservationModal && ReactDOM.createPortal(
|
||||
<div className="flex md:hidden" style={{ position: 'fixed', top: 'calc(var(--nav-h) + 44px + 12px)', left: 12, right: 12, justifyContent: 'space-between', zIndex: 100, pointerEvents: 'none' }}>
|
||||
<button onClick={() => setMobileSidebarOpen('left')}
|
||||
style={{ pointerEvents: 'auto', background: 'var(--bg-card)', color: 'var(--text-primary)', backdropFilter: 'blur(12px)', border: '1px solid var(--border-primary)', borderRadius: 24, padding: '11px 24px', fontSize: 15, fontWeight: 600, cursor: 'pointer', boxShadow: '0 2px 12px rgba(0,0,0,0.15)', minHeight: 44, fontFamily: 'inherit', touchAction: 'manipulation' }}>
|
||||
className="bg-surface-card text-content border border-edge"
|
||||
style={{ pointerEvents: 'auto', backdropFilter: 'blur(12px)', borderRadius: 24, padding: '11px 24px', fontSize: 15, fontWeight: 600, cursor: 'pointer', boxShadow: '0 2px 12px rgba(0,0,0,0.15)', minHeight: 44, fontFamily: 'inherit', touchAction: 'manipulation' }}>
|
||||
{t('trip.mobilePlan')}
|
||||
</button>
|
||||
<button onClick={() => setMobileSidebarOpen('right')}
|
||||
style={{ pointerEvents: 'auto', background: 'var(--bg-card)', color: 'var(--text-primary)', backdropFilter: 'blur(12px)', border: '1px solid var(--border-primary)', borderRadius: 24, padding: '11px 24px', fontSize: 15, fontWeight: 600, cursor: 'pointer', boxShadow: '0 2px 12px rgba(0,0,0,0.15)', minHeight: 44, fontFamily: 'inherit', touchAction: 'manipulation' }}>
|
||||
className="bg-surface-card text-content border border-edge"
|
||||
style={{ pointerEvents: 'auto', backdropFilter: 'blur(12px)', borderRadius: 24, padding: '11px 24px', fontSize: 15, fontWeight: 600, cursor: 'pointer', boxShadow: '0 2px 12px rgba(0,0,0,0.15)', minHeight: 44, fontFamily: 'inherit', touchAction: 'manipulation' }}>
|
||||
{t('trip.mobilePlaces')}
|
||||
</button>
|
||||
</div>,
|
||||
@@ -1063,7 +519,7 @@ export default function TripPlannerPage(): React.ReactElement | null {
|
||||
),
|
||||
}
|
||||
}))
|
||||
} catch {}
|
||||
} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}}
|
||||
onUpdatePlace={async (placeId, data) => { try { await tripActions.updatePlace(tripId, placeId, data) } catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) } }}
|
||||
leftWidth={(isMobile || window.innerWidth < 900) ? 0 : (leftCollapsed ? 0 : leftWidth)}
|
||||
@@ -1072,7 +528,7 @@ export default function TripPlannerPage(): React.ReactElement | null {
|
||||
)}
|
||||
|
||||
{selectedPlace && isMobile && ReactDOM.createPortal(
|
||||
<div style={{ position: 'fixed', inset: 0, zIndex: 9999, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', background: 'rgba(0,0,0,0.3)', paddingBottom: 'var(--bottom-nav-h)' }} onClick={() => setSelectedPlaceId(null)}>
|
||||
<div className="bg-[rgba(0,0,0,0.3)]" style={{ position: 'fixed', inset: 0, zIndex: 9999, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: 'var(--bottom-nav-h)' }} onClick={() => setSelectedPlaceId(null)}>
|
||||
<div style={{ width: '100%', maxHeight: '85vh' }} onClick={e => e.stopPropagation()}>
|
||||
<PlaceInspector
|
||||
place={selectedPlace}
|
||||
@@ -1112,7 +568,7 @@ export default function TripPlannerPage(): React.ReactElement | null {
|
||||
),
|
||||
}
|
||||
}))
|
||||
} catch {}
|
||||
} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}}
|
||||
onUpdatePlace={async (placeId, data) => { try { await tripActions.updatePlace(tripId, placeId, data) } catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) } }}
|
||||
leftWidth={0}
|
||||
@@ -1124,17 +580,17 @@ export default function TripPlannerPage(): React.ReactElement | null {
|
||||
)}
|
||||
|
||||
{mobileSidebarOpen && ReactDOM.createPortal(
|
||||
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.3)', zIndex: 9999 }} onClick={() => setMobileSidebarOpen(null)}>
|
||||
<div style={{ position: 'absolute', top: 'var(--nav-h)', left: 0, right: 0, bottom: 0, background: 'var(--bg-card)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }} onClick={e => e.stopPropagation()}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px', borderBottom: '1px solid var(--border-secondary)' }}>
|
||||
<span style={{ fontWeight: 600, fontSize: 14, color: 'var(--text-primary)' }}>{mobileSidebarOpen === 'left' ? t('trip.mobilePlan') : t('trip.mobilePlaces')}</span>
|
||||
<button onClick={() => setMobileSidebarOpen(null)} style={{ background: 'var(--bg-tertiary)', border: 'none', borderRadius: '50%', width: 28, height: 28, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-primary)' }}>
|
||||
<div className="bg-[rgba(0,0,0,0.3)]" style={{ position: 'fixed', inset: 0, zIndex: 9999 }} onClick={() => setMobileSidebarOpen(null)}>
|
||||
<div className="bg-surface-card" style={{ position: 'absolute', top: 'var(--nav-h)', left: 0, right: 0, bottom: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }} onClick={e => e.stopPropagation()}>
|
||||
<div className="border-b border-edge-secondary" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px' }}>
|
||||
<span className="text-content" style={{ fontWeight: 600, fontSize: 14 }}>{mobileSidebarOpen === 'left' ? t('trip.mobilePlan') : t('trip.mobilePlaces')}</span>
|
||||
<button onClick={() => setMobileSidebarOpen(null)} className="bg-surface-tertiary text-content" style={{ border: 'none', borderRadius: '50%', width: 28, height: 28, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ flex: 1, overflow: 'auto' }}>
|
||||
{mobileSidebarOpen === 'left'
|
||||
? <DayPlanSidebar tripId={tripId} trip={trip} days={days} places={places} categories={categories} assignments={assignments} selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} selectedAssignmentId={selectedAssignmentId} onSelectDay={(id) => { handleSelectDay(id); setMobileSidebarOpen(null) }} onPlaceClick={(placeId, assignmentId) => { handlePlaceClick(placeId, assignmentId) }} onReorder={handleReorder} onUpdateDayTitle={handleUpdateDayTitle} onAssignToDay={handleAssignToDay} onRouteCalculated={(r) => { if (r) { setRoute(r.coordinates); setRouteInfo({ distance: r.distanceText, duration: r.durationText }) } }} reservations={reservations} visibleConnectionIds={visibleConnections} onToggleConnection={toggleConnection} onAddReservation={(dayId) => { setEditingReservation(null); tripActions.setSelectedDay(dayId); setShowReservationModal(true); setMobileSidebarOpen(null) }} onAddTransport={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onAddPlace={() => { setEditingPlace(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null) }} accommodations={tripAccommodations} routeShown={routeShown} routeProfile={routeProfile} onToggleRoute={() => setRouteShown(v => !v)} onSetRouteProfile={setRouteProfile} onNavigateToFiles={() => { setMobileSidebarOpen(null); handleTabChange('dateien') }} onExpandedDaysChange={setExpandedDayIds} pushUndo={pushUndo} canUndo={canUndo} lastActionLabel={lastActionLabel} onUndo={handleUndo} onEditTransport={can('day_edit', trip) ? (reservation) => { setEditingTransport(reservation); setTransportModalDayId(reservation.day_id ?? null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true); setMobileSidebarOpen(null) } : undefined} initialScrollTop={mobilePlanScrollTopRef.current} onScrollTopChange={(top) => { mobilePlanScrollTopRef.current = top }} />
|
||||
? <DayPlanSidebar tripId={tripId} trip={trip} days={days} places={places} categories={categories} assignments={assignments} selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} selectedAssignmentId={selectedAssignmentId} onSelectDay={(id) => { handleSelectDay(id); setMobileSidebarOpen(null) }} onPlaceClick={(placeId, assignmentId) => { handlePlaceClick(placeId, assignmentId) }} onReorder={handleReorder} onUpdateDayTitle={handleUpdateDayTitle} onAssignToDay={handleAssignToDay} onRouteCalculated={(r) => { if (r) { setRoute([r.coordinates]); setRouteInfo(r) } }} reservations={reservations} visibleConnectionIds={visibleConnections} onToggleConnection={toggleConnection} onAddReservation={(dayId) => { setEditingReservation(null); tripActions.setSelectedDay(dayId); setShowReservationModal(true); setMobileSidebarOpen(null) }} onAddTransport={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onAddPlace={() => { setEditingPlace(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null) }} onRemoveAssignment={handleRemoveAssignment} onEditPlace={(place, assignmentId) => { setEditingPlace(place); setEditingAssignmentId(assignmentId || null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} accommodations={tripAccommodations} routeShown={routeShown} routeProfile={routeProfile} onToggleRoute={() => setRouteShown(v => !v)} onSetRouteProfile={setRouteProfile} onNavigateToFiles={() => { setMobileSidebarOpen(null); handleTabChange('dateien') }} onExpandedDaysChange={setExpandedDayIds} pushUndo={pushUndo} canUndo={canUndo} lastActionLabel={lastActionLabel} onUndo={handleUndo} onEditTransport={can('day_edit', trip) ? (reservation) => { setEditingTransport(reservation); setTransportModalDayId(reservation.day_id ?? null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true); setMobileSidebarOpen(null) } : undefined} initialScrollTop={mobilePlanScrollTopRef.current} onScrollTopChange={(top) => { mobilePlanScrollTopRef.current = top }} />
|
||||
: <PlacesSidebar tripId={tripId} places={places} categories={categories} assignments={assignments} selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} onPlaceClick={(placeId) => { handlePlaceClick(placeId); setMobileSidebarOpen(null) }} onAddPlace={() => { setEditingPlace(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onAssignToDay={handleAssignToDay} onEditPlace={(place) => { setEditingPlace(place); setEditingAssignmentId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} onBulkDeletePlaces={(ids) => setDeletePlaceIds(ids)} onBulkDeleteConfirm={(ids) => confirmDeletePlaces(ids)} days={days} isMobile onCategoryFilterChange={setMapCategoryFilter} onPlacesFilterChange={setMapPlacesFilter} pushUndo={pushUndo} initialScrollTop={mobilePlacesScrollTopRef.current} onScrollTopChange={(top) => { mobilePlacesScrollTopRef.current = top }} />
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -152,7 +152,7 @@ describe('VacayPage', () => {
|
||||
// FE-PAGE-VACAY-009
|
||||
it('shows incoming invite overlay with username and action buttons', async () => {
|
||||
seedStore(useVacayStore, makeVacayState({
|
||||
incomingInvites: [{ id: 1, plan_id: 99, username: 'bob' }],
|
||||
incomingInvites: [{ plan_id: 99, owner_username: 'bob' }],
|
||||
}) as any);
|
||||
render(<VacayPage />);
|
||||
await waitFor(() => {
|
||||
@@ -166,7 +166,7 @@ describe('VacayPage', () => {
|
||||
it('calls acceptInvite with plan_id on accept button click', async () => {
|
||||
const mockAcceptInvite = vi.fn();
|
||||
seedStore(useVacayStore, makeVacayState({
|
||||
incomingInvites: [{ id: 1, plan_id: 99, username: 'bob' }],
|
||||
incomingInvites: [{ plan_id: 99, owner_username: 'bob' }],
|
||||
acceptInvite: mockAcceptInvite,
|
||||
}) as any);
|
||||
render(<VacayPage />);
|
||||
@@ -181,7 +181,7 @@ describe('VacayPage', () => {
|
||||
it('calls declineInvite with plan_id on decline button click', async () => {
|
||||
const mockDeclineInvite = vi.fn();
|
||||
seedStore(useVacayStore, makeVacayState({
|
||||
incomingInvites: [{ id: 1, plan_id: 99, username: 'bob' }],
|
||||
incomingInvites: [{ plan_id: 99, owner_username: 'bob' }],
|
||||
declineInvite: mockDeclineInvite,
|
||||
}) as any);
|
||||
render(<VacayPage />);
|
||||
|
||||
+61
-108
@@ -1,64 +1,31 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react'
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { useVacayStore } from '../store/vacayStore'
|
||||
import { addListener, removeListener } from '../api/websocket'
|
||||
import Navbar from '../components/Layout/Navbar'
|
||||
import PageShell from '../components/Layout/PageShell'
|
||||
import VacayCalendar from '../components/Vacay/VacayCalendar'
|
||||
import VacayPersons from '../components/Vacay/VacayPersons'
|
||||
import VacayStats from '../components/Vacay/VacayStats'
|
||||
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'
|
||||
import { useVacay } from './vacay/useVacay'
|
||||
|
||||
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<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: { type: string }) => {
|
||||
if (msg.type === 'vacay:update' || msg.type === 'vacay:settings') {
|
||||
loadPlan()
|
||||
loadEntries(selectedYear)
|
||||
loadStats(selectedYear)
|
||||
if (msg.type === 'vacay:settings') loadAll()
|
||||
}
|
||||
if (msg.type === 'vacay:invite' || msg.type === 'vacay:accepted' || msg.type === 'vacay:declined' || msg.type === 'vacay:cancelled' || msg.type === 'vacay:dissolved') {
|
||||
loadAll()
|
||||
}
|
||||
}, [selectedYear])
|
||||
|
||||
useEffect(() => {
|
||||
addListener(handleWsMessage)
|
||||
return () => removeListener(handleWsMessage)
|
||||
}, [handleWsMessage])
|
||||
useEffect(() => {
|
||||
if (selectedYear) { loadEntries(selectedYear); loadStats(selectedYear); loadHolidays(selectedYear) }
|
||||
}, [selectedYear])
|
||||
|
||||
const handleAddNextYear = () => {
|
||||
const nextYear = years.length > 0 ? Math.max(...years) + 1 : new Date().getFullYear()
|
||||
addYear(nextYear)
|
||||
}
|
||||
|
||||
const handleAddPrevYear = () => {
|
||||
const prevYear = years.length > 0 ? Math.min(...years) - 1 : new Date().getFullYear()
|
||||
addYear(prevYear)
|
||||
}
|
||||
// Page = wiring container: vacay store, live sync + UI state live in the hook.
|
||||
const {
|
||||
years, selectedYear, setSelectedYear, removeYear, loading,
|
||||
incomingInvites, acceptInvite, declineInvite, plan,
|
||||
showSettings, setShowSettings, deleteYear, setDeleteYear,
|
||||
showMobileSidebar, setShowMobileSidebar,
|
||||
handleAddNextYear, handleAddPrevYear,
|
||||
} = useVacay()
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen" style={{ background: 'var(--bg-primary)' }}>
|
||||
<Navbar />
|
||||
<div className="flex items-center justify-center" style={{ paddingTop: 'var(--nav-h)', minHeight: 'calc(100vh - var(--nav-h))' }}>
|
||||
<div className="w-8 h-8 border-2 rounded-full animate-spin" style={{ borderColor: 'var(--border-primary)', borderTopColor: 'var(--text-primary)' }} />
|
||||
</div>
|
||||
</div>
|
||||
<PageShell background="var(--bg-primary)" contentClassName="flex items-center justify-center" contentStyle={{ minHeight: 'calc(100vh - var(--nav-h))' }}>
|
||||
<div className="w-8 h-8 border-2 rounded-full animate-spin border-edge border-t-content" />
|
||||
</PageShell>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -66,25 +33,25 @@ export default function VacayPage(): React.ReactElement {
|
||||
const sidebarContent = (
|
||||
<>
|
||||
{/* Year Selector */}
|
||||
<div className="rounded-xl border p-3" style={{ background: 'var(--bg-card)', borderColor: 'var(--border-primary)' }}>
|
||||
<div className="rounded-xl border p-3 bg-surface-card border-edge">
|
||||
<div className="flex items-center mb-2">
|
||||
<span className="text-[11px] font-medium uppercase tracking-wider" style={{ color: 'var(--text-faint)' }}>{t('vacay.year')}</span>
|
||||
<span className="text-[11px] font-medium uppercase tracking-wider text-content-faint">{t('vacay.year')}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="flex items-center gap-1">
|
||||
<button onClick={handleAddPrevYear} className="p-0.5 rounded transition-colors" style={{ color: 'var(--text-faint)' }} title={t('vacay.addPrevYear')}>
|
||||
<button onClick={handleAddPrevYear} className="p-0.5 rounded transition-colors text-content-faint" title={t('vacay.addPrevYear')}>
|
||||
<Plus size={14} />
|
||||
</button>
|
||||
<button onClick={() => { const idx = years.indexOf(selectedYear); if (idx > 0) setSelectedYear(years[idx - 1]) }} disabled={years.indexOf(selectedYear) <= 0} className="p-1 rounded-lg disabled:opacity-20 transition-colors" style={{ background: 'var(--bg-secondary)' }}>
|
||||
<ChevronLeft size={16} style={{ color: 'var(--text-muted)' }} />
|
||||
<button onClick={() => { const idx = years.indexOf(selectedYear); if (idx > 0) setSelectedYear(years[idx - 1]) }} disabled={years.indexOf(selectedYear) <= 0} className="p-1 rounded-lg disabled:opacity-20 transition-colors bg-surface-secondary">
|
||||
<ChevronLeft size={16} className="text-content-muted" />
|
||||
</button>
|
||||
</div>
|
||||
<span className="text-xl font-bold tabular-nums" style={{ color: 'var(--text-primary)' }}>{selectedYear}</span>
|
||||
<span className="text-xl font-bold tabular-nums text-content">{selectedYear}</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<button onClick={() => { const idx = years.indexOf(selectedYear); if (idx < years.length - 1) setSelectedYear(years[idx + 1]) }} disabled={years.indexOf(selectedYear) >= years.length - 1} className="p-1 rounded-lg disabled:opacity-20 transition-colors" style={{ background: 'var(--bg-secondary)' }}>
|
||||
<ChevronRight size={16} style={{ color: 'var(--text-muted)' }} />
|
||||
<button onClick={() => { const idx = years.indexOf(selectedYear); if (idx < years.length - 1) setSelectedYear(years[idx + 1]) }} disabled={years.indexOf(selectedYear) >= years.length - 1} className="p-1 rounded-lg disabled:opacity-20 transition-colors bg-surface-secondary">
|
||||
<ChevronRight size={16} className="text-content-muted" />
|
||||
</button>
|
||||
<button onClick={handleAddNextYear} className="p-0.5 rounded transition-colors" style={{ color: 'var(--text-faint)' }} title={t('vacay.addYear')}>
|
||||
<button onClick={handleAddNextYear} className="p-0.5 rounded transition-colors text-content-faint" title={t('vacay.addYear')}>
|
||||
<Plus size={14} />
|
||||
</button>
|
||||
</div>
|
||||
@@ -92,11 +59,7 @@ export default function VacayPage(): React.ReactElement {
|
||||
<div className="grid grid-cols-4 gap-1">
|
||||
{years.map(y => (
|
||||
<div key={y} onClick={() => setSelectedYear(y)}
|
||||
className="group relative py-1.5 rounded-lg text-xs font-medium transition-[background-color,color] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] text-center cursor-pointer"
|
||||
style={{
|
||||
background: y === selectedYear ? 'var(--text-primary)' : 'var(--bg-secondary)',
|
||||
color: y === selectedYear ? 'var(--bg-card)' : 'var(--text-muted)',
|
||||
}}>
|
||||
className={`group relative py-1.5 rounded-lg text-xs font-medium transition-[background-color,color] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] text-center cursor-pointer ${y === selectedYear ? 'bg-content text-surface-card' : 'bg-surface-secondary text-content-muted'}`}>
|
||||
{y}
|
||||
{years.length > 1 && (
|
||||
<span onClick={e => { e.stopPropagation(); setDeleteYear(y); setShowMobileSidebar(false) }}
|
||||
@@ -113,8 +76,8 @@ export default function VacayPage(): React.ReactElement {
|
||||
|
||||
{/* Legend */}
|
||||
{(plan?.holidays_enabled || plan?.company_holidays_enabled || plan?.block_weekends) && (
|
||||
<div className="rounded-xl border p-3" style={{ background: 'var(--bg-card)', borderColor: 'var(--border-primary)' }}>
|
||||
<span className="text-[11px] font-medium uppercase tracking-wider" style={{ color: 'var(--text-faint)' }}>{t('vacay.legend')}</span>
|
||||
<div className="rounded-xl border p-3 bg-surface-card border-edge">
|
||||
<span className="text-[11px] font-medium uppercase tracking-wider text-content-faint">{t('vacay.legend')}</span>
|
||||
<div className="mt-2 flex flex-wrap gap-x-3 gap-y-1.5">
|
||||
{plan?.holidays_enabled && (plan?.holiday_calendars ?? []).length === 0 && (
|
||||
<LegendItem color="#fecaca" label={t('vacay.publicHoliday')} />
|
||||
@@ -133,31 +96,26 @@ export default function VacayPage(): React.ReactElement {
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen" style={{ background: 'var(--bg-primary)' }}>
|
||||
<Navbar />
|
||||
|
||||
<div style={{ paddingTop: 'var(--nav-h)' }}>
|
||||
<PageShell background="var(--bg-primary)">
|
||||
<div className="max-w-[1800px] mx-auto px-3 sm:px-4 py-4 sm:py-6">
|
||||
{/* Mobile + tablet header (filter toggle lives here) */}
|
||||
<div className="lg:hidden flex items-center justify-between mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ background: 'var(--bg-secondary)' }}>
|
||||
<CalendarDays size={18} style={{ color: 'var(--text-primary)' }} />
|
||||
<div className="w-9 h-9 rounded-xl flex items-center justify-center bg-surface-secondary">
|
||||
<CalendarDays size={18} className="text-content" />
|
||||
</div>
|
||||
<h1 className="text-lg font-bold" style={{ color: 'var(--text-primary)' }}>{t('admin.addons.catalog.vacay.name')}</h1>
|
||||
<h1 className="text-lg font-bold text-content">{t('admin.addons.catalog.vacay.name')}</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setShowMobileSidebar(true)}
|
||||
className="lg:hidden flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-colors"
|
||||
style={{ background: 'var(--bg-secondary)', color: 'var(--text-muted)' }}
|
||||
className="lg:hidden flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-colors bg-surface-secondary text-content-muted"
|
||||
>
|
||||
<SlidersHorizontal size={14} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowSettings(true)}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-colors"
|
||||
style={{ background: 'var(--bg-secondary)', color: 'var(--text-muted)' }}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-colors bg-surface-secondary text-content-muted"
|
||||
>
|
||||
<Settings size={14} />
|
||||
</button>
|
||||
@@ -166,28 +124,28 @@ export default function VacayPage(): React.ReactElement {
|
||||
|
||||
{/* Desktop header — unified toolbar (sidebar is always visible at this width) */}
|
||||
<div className="hidden lg:block" style={{ marginBottom: 20 }}>
|
||||
<div style={{
|
||||
background: 'var(--bg-tertiary)', borderRadius: 18,
|
||||
border: '1px solid var(--border-primary)',
|
||||
<div className="bg-surface-tertiary border border-edge" style={{
|
||||
borderRadius: 18,
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.06), 0 1px 2px rgba(0,0,0,0.04)',
|
||||
padding: '14px 16px 14px 22px',
|
||||
display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap',
|
||||
}}>
|
||||
<h2 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: 'var(--text-primary)', letterSpacing: '-0.01em', flexShrink: 0 }}>
|
||||
<h2 className="text-content" style={{ margin: 0, fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em', flexShrink: 0 }}>
|
||||
{t('admin.addons.catalog.vacay.name')}
|
||||
</h2>
|
||||
<div style={{ width: 1, height: 22, background: 'var(--border-faint)', flexShrink: 0 }} />
|
||||
<span style={{ fontSize: 13, color: 'var(--text-muted)' }}>
|
||||
<div className="bg-edge-faint" style={{ width: 1, height: 22, flexShrink: 0 }} />
|
||||
<span className="text-content-muted" style={{ fontSize: 13 }}>
|
||||
{t('vacay.subtitle')}
|
||||
</span>
|
||||
<div style={{ display: 'inline-flex', gap: 6, alignItems: 'center', marginLeft: 'auto', flexShrink: 0 }}>
|
||||
<button
|
||||
onClick={() => setShowSettings(true)}
|
||||
className="bg-accent text-accent-text"
|
||||
style={{
|
||||
appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
padding: '9px 14px', borderRadius: 10, fontSize: 13, fontWeight: 500,
|
||||
background: 'var(--accent)', color: 'var(--accent-text)', flexShrink: 0,
|
||||
flexShrink: 0,
|
||||
marginLeft: 2,
|
||||
transition: 'opacity 0.15s ease',
|
||||
}}
|
||||
@@ -213,14 +171,13 @@ export default function VacayPage(): React.ReactElement {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mobile Sidebar Drawer */}
|
||||
{showMobileSidebar && ReactDOM.createPortal(
|
||||
<div className="fixed inset-0 lg:hidden" style={{ zIndex: 99980 }}>
|
||||
<div className="absolute inset-0" style={{ background: 'rgba(0,0,0,0.4)' }} onClick={() => setShowMobileSidebar(false)} />
|
||||
<div className="absolute left-0 top-0 bottom-0 w-[280px] overflow-y-auto p-3 flex flex-col gap-3"
|
||||
style={{ background: 'var(--bg-primary)', boxShadow: '4px 0 24px rgba(0,0,0,0.15)', animation: 'slideInLeft 0.2s ease-out' }}>
|
||||
<div className="absolute inset-0 bg-[rgba(0,0,0,0.4)]" onClick={() => setShowMobileSidebar(false)} />
|
||||
<div className="absolute left-0 top-0 bottom-0 w-[280px] overflow-y-auto p-3 flex flex-col gap-3 bg-surface"
|
||||
style={{ boxShadow: '4px 0 24px rgba(0,0,0,0.15)', animation: 'slideInLeft 0.2s ease-out' }}>
|
||||
{sidebarContent}
|
||||
</div>
|
||||
</div>,
|
||||
@@ -235,19 +192,19 @@ export default function VacayPage(): React.ReactElement {
|
||||
{/* Delete Year Modal */}
|
||||
<Modal isOpen={deleteYear !== null} onClose={() => setDeleteYear(null)} title={t('vacay.removeYear')} size="sm">
|
||||
<div className="space-y-4">
|
||||
<div className="flex gap-3 p-3 rounded-lg" style={{ background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.15)' }}>
|
||||
<div className="flex gap-3 p-3 rounded-lg bg-[rgba(239,68,68,0.08)] border border-[rgba(239,68,68,0.15)]">
|
||||
<AlertTriangle size={18} className="text-red-500 shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text-primary)' }}>
|
||||
<p className="text-sm font-medium text-content">
|
||||
{t('vacay.removeYearConfirm', { year: deleteYear })}
|
||||
</p>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
<p className="text-xs mt-1 text-content-muted">
|
||||
{t('vacay.removeYearHint')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3 justify-end">
|
||||
<button onClick={() => setDeleteYear(null)} className="px-4 py-2 text-sm rounded-lg transition-colors" style={{ color: 'var(--text-muted)', border: '1px solid var(--border-primary)' }}>
|
||||
<button onClick={() => setDeleteYear(null)} className="px-4 py-2 text-sm rounded-lg transition-colors border text-content-muted border-edge">
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button onClick={async () => { await removeYear(deleteYear); setDeleteYear(null) }} className="px-4 py-2 text-sm bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors">
|
||||
@@ -259,21 +216,19 @@ export default function VacayPage(): React.ReactElement {
|
||||
|
||||
{/* Incoming invite — forced fullscreen modal */}
|
||||
{incomingInvites.length > 0 && ReactDOM.createPortal(
|
||||
<div className="fixed inset-0 flex items-center justify-center px-4"
|
||||
style={{ zIndex: 99995, backgroundColor: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)' }}>
|
||||
<div className="fixed inset-0 flex items-center justify-center px-4 bg-[rgba(0,0,0,0.7)]"
|
||||
style={{ zIndex: 99995, backdropFilter: 'blur(8px)' }}>
|
||||
{incomingInvites.map(inv => (
|
||||
<div key={inv.id} className="trek-modal-enter w-full max-w-md rounded-2xl shadow-2xl overflow-hidden"
|
||||
style={{ background: 'var(--bg-card)' }}>
|
||||
<div key={inv.plan_id} className="trek-modal-enter w-full max-w-md rounded-2xl shadow-2xl overflow-hidden bg-surface-card">
|
||||
<div className="px-6 pt-6 pb-4 text-center">
|
||||
<div className="w-14 h-14 rounded-full mx-auto mb-4 flex items-center justify-center text-lg font-bold"
|
||||
style={{ background: 'var(--bg-secondary)', color: 'var(--text-primary)' }}>
|
||||
{inv.username?.[0]?.toUpperCase()}
|
||||
<div className="w-14 h-14 rounded-full mx-auto mb-4 flex items-center justify-center text-lg font-bold bg-surface-secondary text-content">
|
||||
{inv.owner_username?.[0]?.toUpperCase()}
|
||||
</div>
|
||||
<h2 className="text-lg font-bold mb-1" style={{ color: 'var(--text-primary)' }}>
|
||||
<h2 className="text-lg font-bold mb-1 text-content">
|
||||
{t('vacay.inviteTitle')}
|
||||
</h2>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="font-semibold" style={{ color: 'var(--text-primary)' }}>{inv.username}</span> {t('vacay.inviteWantsToFuse')}
|
||||
<p className="text-sm text-content-muted">
|
||||
<span className="font-semibold text-content">{inv.owner_username}</span> {t('vacay.inviteWantsToFuse')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="px-6 pb-4 space-y-2">
|
||||
@@ -285,13 +240,11 @@ export default function VacayPage(): React.ReactElement {
|
||||
</div>
|
||||
<div className="px-6 pb-6 flex gap-3">
|
||||
<button onClick={() => declineInvite(inv.plan_id)}
|
||||
className="flex-1 px-4 py-2.5 text-sm font-medium rounded-xl transition-colors"
|
||||
style={{ color: 'var(--text-muted)', border: '1px solid var(--border-primary)' }}>
|
||||
className="flex-1 px-4 py-2.5 text-sm font-medium rounded-xl transition-colors border text-content-muted border-edge">
|
||||
{t('vacay.decline')}
|
||||
</button>
|
||||
<button onClick={() => acceptInvite(inv.plan_id)}
|
||||
className="flex-1 px-4 py-2.5 text-sm font-medium rounded-xl transition-colors"
|
||||
style={{ background: 'var(--text-primary)', color: 'var(--bg-card)' }}>
|
||||
className="flex-1 px-4 py-2.5 text-sm font-medium rounded-xl transition-colors bg-content text-surface-card">
|
||||
{t('vacay.acceptFusion')}
|
||||
</button>
|
||||
</div>
|
||||
@@ -307,15 +260,15 @@ export default function VacayPage(): React.ReactElement {
|
||||
to { transform: translateX(0); }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
</PageShell>
|
||||
)
|
||||
}
|
||||
|
||||
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)' }} />
|
||||
<span className="text-xs" style={{ color: 'var(--text-primary)' }}>{text}</span>
|
||||
<div className="flex items-start gap-3 px-3 py-2 rounded-lg bg-surface-secondary">
|
||||
<Icon size={15} className="shrink-0 mt-0.5 text-content-muted" />
|
||||
<span className="text-xs text-content">{text}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -324,7 +277,7 @@ function LegendItem({ color, label }: { color: string; label: string }): React.R
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="w-4 h-3 rounded" style={{ background: color, border: `1px solid ${color}` }} />
|
||||
<span className="text-[11px]" style={{ color: 'var(--text-muted)' }}>{label}</span>
|
||||
<span className="text-[11px] text-content-muted">{label}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { adminApi } from '../../api/client'
|
||||
import { useToast } from '../../components/shared/Toast'
|
||||
import { ADMIN_EVENT_LABEL_KEYS, ADMIN_CHANNEL_LABEL_KEYS } from './AdminPage.constants'
|
||||
|
||||
// Per-event × per-channel admin notification preference matrix.
|
||||
// Loads its own data and auto-saves each toggle. Markup identical to AdminPage.
|
||||
export default function AdminNotificationsPanel({ t, toast }: { t: (k: string) => string; toast: ReturnType<typeof useToast> }) {
|
||||
const [matrix, setMatrix] = useState<any>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
adminApi.getNotificationPreferences().then((data: any) => setMatrix(data)).catch(() => {})
|
||||
}, [])
|
||||
|
||||
if (!matrix) return <p className="text-content-faint" style={{ fontSize: 12, fontStyle: 'italic', padding: 16 }}>Loading…</p>
|
||||
|
||||
const visibleChannels = (['inapp', 'email', 'webhook', 'ntfy'] as const).filter(ch => {
|
||||
if (!matrix.available_channels[ch]) return false
|
||||
return matrix.event_types.some((evt: string) => matrix.implemented_combos[evt]?.includes(ch))
|
||||
})
|
||||
|
||||
const toggle = async (eventType: string, channel: string) => {
|
||||
const current = matrix.preferences[eventType]?.[channel] ?? true
|
||||
const updated = { ...matrix.preferences, [eventType]: { ...matrix.preferences[eventType], [channel]: !current } }
|
||||
setMatrix((m: any) => m ? { ...m, preferences: updated } : m)
|
||||
setSaving(true)
|
||||
try {
|
||||
await adminApi.updateNotificationPreferences(updated)
|
||||
} catch {
|
||||
setMatrix((m: any) => m ? { ...m, preferences: matrix.preferences } : m)
|
||||
toast.error(t('common.error'))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (matrix.event_types.length === 0) {
|
||||
return (
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<p className="text-content-faint" style={{ fontSize: 13 }}>{t('settings.notificationPreferences.noChannels')}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-slate-100">
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.tabs.notifications')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.notifications.adminNotificationsHint')}</p>
|
||||
</div>
|
||||
<div className="p-6">
|
||||
{saving && <p className="text-content-faint" style={{ fontSize: 11, marginBottom: 8 }}>Saving…</p>}
|
||||
{/* Header row */}
|
||||
<div className="border-b border-edge" style={{ display: 'grid', gridTemplateColumns: `1fr ${visibleChannels.map(() => '80px').join(' ')}`, gap: 4, paddingBottom: 6, marginBottom: 4 }}>
|
||||
<span />
|
||||
{visibleChannels.map(ch => (
|
||||
<span key={ch} className="text-content-faint" style={{ fontSize: 11, fontWeight: 600, textAlign: 'center', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
|
||||
{t(ADMIN_CHANNEL_LABEL_KEYS[ch]) || ch}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{/* Event rows */}
|
||||
{matrix.event_types.map((eventType: string) => {
|
||||
const implementedForEvent = matrix.implemented_combos[eventType] ?? []
|
||||
return (
|
||||
<div key={eventType} className="border-b border-edge" style={{ display: 'grid', gridTemplateColumns: `1fr ${visibleChannels.map(() => '80px').join(' ')}`, gap: 4, alignItems: 'center', padding: '8px 0' }}>
|
||||
<span className="text-content" style={{ fontSize: 13 }}>
|
||||
{t(ADMIN_EVENT_LABEL_KEYS[eventType]) || eventType}
|
||||
</span>
|
||||
{visibleChannels.map(ch => {
|
||||
if (!implementedForEvent.includes(ch)) {
|
||||
return <span key={ch} className="text-content-faint" style={{ textAlign: 'center', fontSize: 14 }}>—</span>
|
||||
}
|
||||
const isOn = matrix.preferences[eventType]?.[ch] ?? true
|
||||
return (
|
||||
<div key={ch} style={{ display: 'flex', justifyContent: 'center' }}>
|
||||
<button
|
||||
onClick={() => toggle(eventType, ch)}
|
||||
className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors flex-shrink-0 ${isOn ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span className="absolute left-0.5 h-4 w-4 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: isOn ? 'translateX(16px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
import React from 'react'
|
||||
import { authApi, notificationsApi } from '../../api/client'
|
||||
import { Save } from 'lucide-react'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import type { useAdmin } from './useAdmin'
|
||||
import AdminNotificationsPanel from './AdminNotificationsPanel'
|
||||
|
||||
interface AdminNotificationsTabProps {
|
||||
admin: ReturnType<typeof useAdmin>
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
// "Notifications" admin tab: email/webhook/ntfy channel toggles, SMTP credentials,
|
||||
// trip reminders, admin webhook + ntfy targets, and the per-event preference matrix.
|
||||
// Derives channel state from smtpValues exactly as the original inline IIFE did.
|
||||
export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTabProps): React.ReactElement {
|
||||
const { toast, smtpValues, setSmtpValues, smtpLoaded, setTripRemindersEnabled } = admin
|
||||
|
||||
// Derive active channels from smtpValues.notification_channels (plural)
|
||||
// with fallback to notification_channel (singular) for existing installs
|
||||
const rawChannels = smtpValues.notification_channels ?? smtpValues.notification_channel ?? 'none'
|
||||
const activeChans = rawChannels === 'none' ? [] : rawChannels.split(',').map((c: string) => c.trim())
|
||||
const emailActive = activeChans.includes('email')
|
||||
const webhookActive = activeChans.includes('webhook')
|
||||
const ntfyActive = activeChans.includes('ntfy')
|
||||
const tripRemindersActive = smtpValues.notify_trip_reminder !== 'false'
|
||||
|
||||
const setChannels = async (email: boolean, webhook: boolean, ntfy: boolean) => {
|
||||
const chans = [email && 'email', webhook && 'webhook', ntfy && 'ntfy'].filter(Boolean).join(',') || 'none'
|
||||
setSmtpValues(prev => ({ ...prev, notification_channels: chans }))
|
||||
try {
|
||||
await authApi.updateAppSettings({ notification_channels: chans })
|
||||
} catch {
|
||||
// Revert state on failure
|
||||
const reverted = [emailActive && 'email', webhookActive && 'webhook', ntfyActive && 'ntfy'].filter(Boolean).join(',') || 'none'
|
||||
setSmtpValues(prev => ({ ...prev, notification_channels: reverted }))
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const smtpConfigured = !!(smtpValues.smtp_host?.trim())
|
||||
const saveNotifications = async () => {
|
||||
// Saves credentials only — channel activation is auto-saved by the toggle
|
||||
const notifKeys = ['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_skip_tls_verify']
|
||||
const payload: Record<string, string> = {}
|
||||
for (const k of notifKeys) { if (smtpValues[k] !== undefined) payload[k] = smtpValues[k] }
|
||||
try {
|
||||
await authApi.updateAppSettings(payload)
|
||||
toast.success(t('admin.notifications.saved'))
|
||||
authApi.getAppConfig().then((c: { trip_reminders_enabled?: boolean }) => {
|
||||
if (c?.trip_reminders_enabled !== undefined) setTripRemindersEnabled(c.trip_reminders_enabled)
|
||||
}).catch(() => {})
|
||||
} catch { toast.error(t('common.error')) }
|
||||
}
|
||||
|
||||
return (<>
|
||||
<div className="space-y-4">
|
||||
{/* Email Panel */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.notifications.emailPanel.title')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.smtp.hint')}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setChannels(!emailActive, webhookActive, ntfyActive)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${emailActive ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: emailActive ? 'translateX(20px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
</div>
|
||||
<div className={`p-6 space-y-3 ${!emailActive ? 'opacity-50 pointer-events-none' : ''}`}>
|
||||
{smtpLoaded && [
|
||||
{ key: 'smtp_host', label: 'SMTP Host', placeholder: 'mail.example.com' },
|
||||
{ key: 'smtp_port', label: 'SMTP Port', placeholder: '587' },
|
||||
{ key: 'smtp_user', label: 'SMTP User', placeholder: 'trek@example.com' },
|
||||
{ key: 'smtp_pass', label: 'SMTP Password', placeholder: '••••••••', type: 'password' },
|
||||
{ key: 'smtp_from', label: 'From Address', placeholder: 'trek@example.com' },
|
||||
].map(field => (
|
||||
<div key={field.key}>
|
||||
<label className="block text-xs font-medium text-slate-500 mb-1">{field.label}</label>
|
||||
<input
|
||||
type={field.type || 'text'}
|
||||
value={smtpValues[field.key] || ''}
|
||||
onChange={e => setSmtpValues(prev => ({ ...prev, [field.key]: e.target.value }))}
|
||||
placeholder={field.placeholder}
|
||||
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>
|
||||
))}
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 0' }}>
|
||||
<div>
|
||||
<span className="text-xs font-medium text-slate-500">Skip TLS certificate check</span>
|
||||
<p className="text-[10px] text-slate-400 mt-0.5">Enable for self-signed certificates on local mail servers</p>
|
||||
</div>
|
||||
<button onClick={() => {
|
||||
const newVal = smtpValues.smtp_skip_tls_verify === 'true' ? 'false' : 'true'
|
||||
setSmtpValues(prev => ({ ...prev, smtp_skip_tls_verify: newVal }))
|
||||
}}
|
||||
className={`relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors ${smtpValues.smtp_skip_tls_verify === 'true' ? 'bg-content' : 'bg-edge'}`}>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: smtpValues.smtp_skip_tls_verify === 'true' ? 'translateX(20px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-6 pb-4 flex items-center gap-2 border-t border-slate-100 pt-4">
|
||||
<button onClick={saveNotifications}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-slate-900 text-white rounded-lg text-sm font-medium hover:bg-slate-800 transition-colors">
|
||||
<Save className="w-4 h-4" />{t('common.save')}
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
const smtpKeys = ['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_skip_tls_verify']
|
||||
const payload: Record<string, string> = {}
|
||||
for (const k of smtpKeys) { if (smtpValues[k] !== undefined) payload[k] = smtpValues[k] }
|
||||
await authApi.updateAppSettings(payload).catch(() => {})
|
||||
try {
|
||||
const result = await notificationsApi.testSmtp()
|
||||
if (result.success) toast.success(t('admin.smtp.testSuccess'))
|
||||
else toast.error(result.error || t('admin.smtp.testFailed'))
|
||||
} catch { toast.error(t('admin.smtp.testFailed')) }
|
||||
}}
|
||||
disabled={!smtpConfigured}
|
||||
className="px-4 py-2 border border-slate-300 text-slate-700 rounded-lg text-sm font-medium hover:bg-slate-50 transition-colors disabled:opacity-40"
|
||||
>
|
||||
{t('admin.smtp.testButton')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Webhook Panel */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.notifications.webhookPanel.title')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.webhook.hint')}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setChannels(emailActive, !webhookActive, ntfyActive)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${webhookActive ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: webhookActive ? 'translateX(20px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Ntfy Panel */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.notifications.ntfy')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.ntfy.hint') || 'Allow users to configure their own ntfy topics for push notifications.'}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setChannels(emailActive, webhookActive, !ntfyActive)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${ntfyActive ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: ntfyActive ? 'translateX(20px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* In-App Panel */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.notifications.inappPanel.title')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.notifications.inappPanel.hint')}</p>
|
||||
</div>
|
||||
<div className="relative inline-flex h-6 w-11 items-center rounded-full flex-shrink-0 bg-content"
|
||||
style={{ opacity: 0.5, cursor: 'not-allowed' }}>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: 'translateX(20px)' }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Trip Reminders Toggle */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.notifications.tripReminders.title')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.notifications.tripReminders.hint')}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={async () => {
|
||||
const next = !tripRemindersActive
|
||||
setSmtpValues(prev => ({ ...prev, notify_trip_reminder: next ? 'true' : 'false' }))
|
||||
try {
|
||||
await authApi.updateAppSettings({ notify_trip_reminder: next ? 'true' : 'false' })
|
||||
toast.success(next ? t('admin.notifications.tripReminders.enabled') : t('admin.notifications.tripReminders.disabled'))
|
||||
authApi.getAppConfig().then((c: { trip_reminders_enabled?: boolean }) => {
|
||||
if (c?.trip_reminders_enabled !== undefined) setTripRemindersEnabled(c.trip_reminders_enabled)
|
||||
}).catch(() => {})
|
||||
} catch {
|
||||
setSmtpValues(prev => ({ ...prev, notify_trip_reminder: tripRemindersActive ? 'true' : 'false' }))
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${tripRemindersActive ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: tripRemindersActive ? 'translateX(20px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Admin Webhook Panel */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-slate-100">
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.notifications.adminWebhookPanel.title')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.notifications.adminWebhookPanel.hint')}</p>
|
||||
</div>
|
||||
<div className="p-6 space-y-3">
|
||||
{smtpLoaded && (
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-500 mb-1">{t('admin.notifications.adminWebhookPanel.title')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={smtpValues.admin_webhook_url === '••••••••' ? '' : smtpValues.admin_webhook_url || ''}
|
||||
onChange={e => setSmtpValues(prev => ({ ...prev, admin_webhook_url: e.target.value }))}
|
||||
placeholder={smtpValues.admin_webhook_url === '••••••••' ? '••••••••' : 'https://discord.com/api/webhooks/...'}
|
||||
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>
|
||||
)}
|
||||
</div>
|
||||
<div className="px-6 pb-4 flex items-center gap-2 border-t border-slate-100 pt-4">
|
||||
<button
|
||||
onClick={async () => {
|
||||
try {
|
||||
await authApi.updateAppSettings({ admin_webhook_url: smtpValues.admin_webhook_url || '' })
|
||||
toast.success(t('admin.notifications.adminWebhookPanel.saved'))
|
||||
} catch { toast.error(t('common.error')) }
|
||||
}}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-slate-900 text-white rounded-lg text-sm font-medium hover:bg-slate-800 transition-colors">
|
||||
<Save className="w-4 h-4" />{t('common.save')}
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
const url = smtpValues.admin_webhook_url === '••••••••' ? undefined : smtpValues.admin_webhook_url
|
||||
if (!url && smtpValues.admin_webhook_url !== '••••••••') return
|
||||
try {
|
||||
if (url) await authApi.updateAppSettings({ admin_webhook_url: url }).catch(() => {})
|
||||
const result = await notificationsApi.testWebhook(url)
|
||||
if (result.success) toast.success(t('admin.notifications.adminWebhookPanel.testSuccess'))
|
||||
else toast.error(result.error || t('admin.notifications.adminWebhookPanel.testFailed'))
|
||||
} catch { toast.error(t('admin.notifications.adminWebhookPanel.testFailed')) }
|
||||
}}
|
||||
disabled={!smtpValues.admin_webhook_url?.trim()}
|
||||
className="px-4 py-2 border border-slate-300 text-slate-700 rounded-lg text-sm font-medium hover:bg-slate-50 transition-colors disabled:opacity-40"
|
||||
>
|
||||
{t('admin.notifications.testWebhook')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Admin Ntfy Panel */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-slate-100">
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.notifications.adminNtfyPanel.title')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.notifications.adminNtfyPanel.hint')}</p>
|
||||
</div>
|
||||
<div className="p-6 space-y-3">
|
||||
{smtpLoaded && (
|
||||
<>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-500 mb-1">{t('admin.notifications.adminNtfyPanel.serverLabel')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={smtpValues.admin_ntfy_server || ''}
|
||||
onChange={e => setSmtpValues(prev => ({ ...prev, admin_ntfy_server: e.target.value }))}
|
||||
placeholder={t('admin.notifications.adminNtfyPanel.serverPlaceholder')}
|
||||
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"
|
||||
/>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.notifications.adminNtfyPanel.serverHint')}</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-500 mb-1">{t('admin.notifications.adminNtfyPanel.topicLabel')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={smtpValues.admin_ntfy_topic || ''}
|
||||
onChange={e => setSmtpValues(prev => ({ ...prev, admin_ntfy_topic: e.target.value }))}
|
||||
placeholder={t('admin.notifications.adminNtfyPanel.topicPlaceholder')}
|
||||
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>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-500 mb-1">{t('admin.notifications.adminNtfyPanel.tokenLabel')}</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="password"
|
||||
value={smtpValues.admin_ntfy_token === '••••••••' ? '' : smtpValues.admin_ntfy_token || ''}
|
||||
onChange={e => setSmtpValues(prev => ({ ...prev, admin_ntfy_token: e.target.value }))}
|
||||
placeholder={smtpValues.admin_ntfy_token === '••••••••' ? '••••••••' : ''}
|
||||
className="flex-1 px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
|
||||
/>
|
||||
{smtpValues.admin_ntfy_token === '••••••••' && (
|
||||
<button
|
||||
onClick={async () => {
|
||||
try {
|
||||
await authApi.updateAppSettings({ admin_ntfy_token: '' })
|
||||
setSmtpValues(prev => ({ ...prev, admin_ntfy_token: '' }))
|
||||
toast.success(t('admin.notifications.adminNtfyPanel.tokenCleared'))
|
||||
} catch { toast.error(t('common.error')) }
|
||||
}}
|
||||
className="px-3 py-2 border border-red-300 text-red-600 rounded-lg text-sm font-medium hover:bg-red-50 transition-colors"
|
||||
>
|
||||
{t('common.clear')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="px-6 pb-4 flex items-center gap-2 border-t border-slate-100 pt-4">
|
||||
<button
|
||||
onClick={async () => {
|
||||
try {
|
||||
await authApi.updateAppSettings({
|
||||
admin_ntfy_server: smtpValues.admin_ntfy_server || '',
|
||||
admin_ntfy_topic: smtpValues.admin_ntfy_topic || '',
|
||||
...(smtpValues.admin_ntfy_token && smtpValues.admin_ntfy_token !== '••••••••'
|
||||
? { admin_ntfy_token: smtpValues.admin_ntfy_token }
|
||||
: {}),
|
||||
})
|
||||
toast.success(t('admin.notifications.adminNtfyPanel.saved'))
|
||||
} catch { toast.error(t('common.error')) }
|
||||
}}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-slate-900 text-white rounded-lg text-sm font-medium hover:bg-slate-800 transition-colors">
|
||||
<Save className="w-4 h-4" />{t('common.save')}
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
const topic = smtpValues.admin_ntfy_topic?.trim()
|
||||
if (!topic) return
|
||||
try {
|
||||
const token = smtpValues.admin_ntfy_token && smtpValues.admin_ntfy_token !== '••••••••'
|
||||
? smtpValues.admin_ntfy_token : null
|
||||
const result = await notificationsApi.testNtfy({
|
||||
topic,
|
||||
server: smtpValues.admin_ntfy_server || null,
|
||||
token,
|
||||
})
|
||||
if (result.success) toast.success(t('admin.notifications.adminNtfyPanel.testSuccess'))
|
||||
else toast.error(result.error || t('admin.notifications.adminNtfyPanel.testFailed'))
|
||||
} catch { toast.error(t('admin.notifications.adminNtfyPanel.testFailed')) }
|
||||
}}
|
||||
disabled={!smtpValues.admin_ntfy_topic?.trim()}
|
||||
className="px-4 py-2 border border-slate-300 text-slate-700 rounded-lg text-sm font-medium hover:bg-slate-50 transition-colors disabled:opacity-40"
|
||||
>
|
||||
{t('admin.notifications.adminNtfyPanel.test')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<AdminNotificationsPanel t={t} toast={toast} />
|
||||
</div>
|
||||
</>)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/** Static label-key maps for the admin notification matrix. No React, no side effects. */
|
||||
|
||||
export const ADMIN_EVENT_LABEL_KEYS: Record<string, string> = {
|
||||
version_available: 'settings.notifyVersionAvailable',
|
||||
}
|
||||
|
||||
export const ADMIN_CHANNEL_LABEL_KEYS: Record<string, string> = {
|
||||
inapp: 'settings.notificationPreferences.inapp',
|
||||
email: 'settings.notificationPreferences.email',
|
||||
webhook: 'settings.notificationPreferences.webhook',
|
||||
ntfy: 'settings.notificationPreferences.ntfy',
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
import React from 'react'
|
||||
import { adminApi, authApi } from '../../api/client'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import { Eye, EyeOff, Save, CheckCircle, XCircle, Loader2, Sun, RefreshCw, AlertTriangle } from 'lucide-react'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import type { useAdmin } from './useAdmin'
|
||||
|
||||
interface AdminSettingsTabProps {
|
||||
admin: ReturnType<typeof useAdmin>
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
// "Settings" admin tab: auth methods, require-MFA, allowed file types, API keys,
|
||||
// OIDC config and the danger zone. Pure layout around the useAdmin hook.
|
||||
export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): React.ReactElement {
|
||||
const {
|
||||
toast,
|
||||
setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled,
|
||||
placesPhotosEnabled, setPlacesPhotosEnabledState,
|
||||
placesAutocompleteEnabled, setPlacesAutocompleteEnabledState,
|
||||
placesDetailsEnabled, setPlacesDetailsEnabledState,
|
||||
oidcConfig, setOidcConfig, savingOidc, setSavingOidc,
|
||||
passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration,
|
||||
oidcLogin, setOidcLogin, oidcRegistration, setOidcRegistration,
|
||||
envOverrideOidcOnly, oidcConfigured, requireMfa,
|
||||
allowedFileTypes, setAllowedFileTypes, savingFileTypes, setSavingFileTypes,
|
||||
mapsKey, setMapsKey, showKeys, savingKeys, validating, validation,
|
||||
setShowRotateJwtModal,
|
||||
handleToggleAuthSetting, handleToggleRequireMfa,
|
||||
toggleKey, handleSaveApiKeys, handleValidateKey,
|
||||
} = admin
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Authentication Methods */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-slate-100">
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.authMethods')}</h2>
|
||||
</div>
|
||||
<div className="p-6 space-y-5">
|
||||
{envOverrideOidcOnly && (
|
||||
<p className="text-xs text-amber-600 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
|
||||
{t('admin.envOverrideHint')}
|
||||
</p>
|
||||
)}
|
||||
{/* Password Login */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-700">{t('admin.passwordLogin')}</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">{t('admin.passwordLoginHint')}</p>
|
||||
</div>
|
||||
<button
|
||||
disabled={envOverrideOidcOnly || (!passwordLogin && !oidcLogin)}
|
||||
onClick={() => handleToggleAuthSetting('password_login', !passwordLogin, setPasswordLogin)}
|
||||
title={!passwordLogin && !oidcLogin ? t('admin.lockoutWarning') : undefined}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors disabled:opacity-50 ${passwordLogin ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span
|
||||
className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: passwordLogin ? 'translateX(20px)' : 'translateX(0)' }}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
{/* Password Registration */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-700">{t('admin.passwordRegistration')}</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">{t('admin.passwordRegistrationHint')}</p>
|
||||
</div>
|
||||
<button
|
||||
disabled={envOverrideOidcOnly}
|
||||
onClick={() => handleToggleAuthSetting('password_registration', !passwordRegistration, setPasswordRegistration)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors disabled:opacity-50 ${passwordRegistration ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span
|
||||
className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: passwordRegistration ? 'translateX(20px)' : 'translateX(0)' }}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
{/* SSO Login (only when OIDC configured) */}
|
||||
{oidcConfigured && (
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-700">{t('admin.oidcLogin')}</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">{t('admin.oidcLoginHint')}</p>
|
||||
</div>
|
||||
<button
|
||||
disabled={!passwordLogin && oidcLogin}
|
||||
onClick={() => handleToggleAuthSetting('oidc_login', !oidcLogin, setOidcLogin)}
|
||||
title={!passwordLogin && oidcLogin ? t('admin.lockoutWarning') : undefined}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors disabled:opacity-50 ${oidcLogin ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span
|
||||
className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: oidcLogin ? 'translateX(20px)' : 'translateX(0)' }}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{/* SSO Registration (only when OIDC configured) */}
|
||||
{oidcConfigured && (
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-700">{t('admin.oidcRegistration')}</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">{t('admin.oidcRegistrationHint')}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleToggleAuthSetting('oidc_registration', !oidcRegistration, setOidcRegistration)}
|
||||
className={`relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors ${oidcRegistration ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span
|
||||
className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: oidcRegistration ? 'translateX(20px)' : 'translateX(0)' }}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Require 2FA for all users */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-slate-100">
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.requireMfa')}</h2>
|
||||
</div>
|
||||
<div className="p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-700">{t('admin.requireMfa')}</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">{t('admin.requireMfaHint')}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleToggleRequireMfa(!requireMfa)}
|
||||
className={`relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors ${requireMfa ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span
|
||||
className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: requireMfa ? 'translateX(20px)' : 'translateX(0)' }}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Allowed File Types */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-slate-100">
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.fileTypes')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.fileTypesHint')}</p>
|
||||
</div>
|
||||
<div className="p-6">
|
||||
<input
|
||||
type="text"
|
||||
value={allowedFileTypes}
|
||||
onChange={e => setAllowedFileTypes(e.target.value)}
|
||||
placeholder="jpg,png,pdf,doc,docx,xls,xlsx,txt,csv"
|
||||
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"
|
||||
/>
|
||||
<p className="text-xs text-slate-400 mt-2">{t('admin.fileTypesFormat')}</p>
|
||||
<button
|
||||
onClick={async () => {
|
||||
setSavingFileTypes(true)
|
||||
try {
|
||||
await authApi.updateAppSettings({ allowed_file_types: allowedFileTypes })
|
||||
toast.success(t('admin.fileTypesSaved'))
|
||||
} catch { toast.error(t('common.error')) }
|
||||
finally { setSavingFileTypes(false) }
|
||||
}}
|
||||
disabled={savingFileTypes}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-slate-900 text-white rounded-lg text-sm hover:bg-slate-700 disabled:bg-slate-400 mt-3"
|
||||
>
|
||||
{savingFileTypes ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
{t('common.save')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* API Keys */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-slate-100">
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.apiKeys')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.apiKeysHint')}</p>
|
||||
</div>
|
||||
<div className="p-6 space-y-4">
|
||||
{/* Google Maps Key */}
|
||||
<div>
|
||||
<label className="flex items-center gap-2 text-sm font-medium text-slate-700 mb-1.5">
|
||||
{t('admin.mapsKey')}
|
||||
<span className="text-[9px] font-medium px-1.5 py-px rounded-full bg-emerald-200 dark:bg-emerald-800 text-emerald-800 dark:text-emerald-200">{t('admin.recommended')}</span>
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<input
|
||||
type={showKeys.maps ? 'text' : 'password'}
|
||||
value={mapsKey}
|
||||
onChange={e => setMapsKey(e.target.value)}
|
||||
placeholder={t('settings.keyPlaceholder')}
|
||||
className="w-full pr-10 px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleKey('maps')}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
|
||||
>
|
||||
{showKeys.maps ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleValidateKey('maps')}
|
||||
disabled={!mapsKey || validating.maps}
|
||||
className="px-3 py-2 text-sm border border-slate-300 rounded-lg hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed flex items-center gap-1.5"
|
||||
>
|
||||
{validating.maps ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : validation.maps === true ? (
|
||||
<CheckCircle className="w-4 h-4 text-emerald-500" />
|
||||
) : validation.maps === false ? (
|
||||
<XCircle className="w-4 h-4 text-red-500" />
|
||||
) : null}
|
||||
{t('admin.validateKey')}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.mapsKeyHintLong')}</p>
|
||||
{validation.maps === true && (
|
||||
<p className="text-xs text-emerald-600 mt-1 flex items-center gap-1">
|
||||
<span className="w-2 h-2 bg-emerald-500 rounded-full inline-block"></span>
|
||||
{t('admin.keyValid')}
|
||||
</p>
|
||||
)}
|
||||
{validation.maps === false && (
|
||||
<p className="text-xs text-red-500 mt-1 flex items-center gap-1">
|
||||
<span className="w-2 h-2 bg-red-500 rounded-full inline-block"></span>
|
||||
{t('admin.keyInvalid')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Place Photos Toggle */}
|
||||
<div className="flex items-center justify-between gap-4 py-3 border-t border-slate-100">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-700">{t('admin.placesPhotos.title')}</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">{t('admin.placesPhotos.subtitle')}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={async () => {
|
||||
const next = !placesPhotosEnabled
|
||||
setPlacesPhotosEnabledState(next)
|
||||
setPlacesPhotosEnabled(next)
|
||||
try { await adminApi.updatePlacesPhotos(next) } catch { setPlacesPhotosEnabledState(!next); setPlacesPhotosEnabled(!next) }
|
||||
}}
|
||||
className={`relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors ${placesPhotosEnabled ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200" style={{ transform: placesPhotosEnabled ? 'translateX(20px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Place Autocomplete Toggle */}
|
||||
<div className="flex items-center justify-between gap-4 py-3 border-t border-slate-100">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-700">{t('admin.placesAutocomplete.title')}</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">{t('admin.placesAutocomplete.subtitle')}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={async () => {
|
||||
const next = !placesAutocompleteEnabled
|
||||
setPlacesAutocompleteEnabledState(next)
|
||||
setPlacesAutocompleteEnabled(next)
|
||||
try { await adminApi.updatePlacesAutocomplete(next) } catch { setPlacesAutocompleteEnabledState(!next); setPlacesAutocompleteEnabled(!next) }
|
||||
}}
|
||||
className={`relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors ${placesAutocompleteEnabled ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200" style={{ transform: placesAutocompleteEnabled ? 'translateX(20px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Place Details Toggle */}
|
||||
<div className="flex items-center justify-between gap-4 py-3 border-t border-slate-100">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-700">{t('admin.placesDetails.title')}</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">{t('admin.placesDetails.subtitle')}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={async () => {
|
||||
const next = !placesDetailsEnabled
|
||||
setPlacesDetailsEnabledState(next)
|
||||
setPlacesDetailsEnabled(next)
|
||||
try { await adminApi.updatePlacesDetails(next) } catch { setPlacesDetailsEnabledState(!next); setPlacesDetailsEnabled(!next) }
|
||||
}}
|
||||
className={`relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors ${placesDetailsEnabled ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200" style={{ transform: placesDetailsEnabled ? 'translateX(20px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Open-Meteo Weather Info */}
|
||||
<div className="rounded-lg border border-emerald-200 bg-emerald-50 dark:bg-emerald-950/30 dark:border-emerald-800 overflow-hidden">
|
||||
<div className="px-4 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-7 h-7 rounded-lg bg-emerald-500 flex items-center justify-center flex-shrink-0">
|
||||
<Sun className="w-3.5 h-3.5 text-white" />
|
||||
</div>
|
||||
<span className="text-sm font-semibold text-emerald-900 dark:text-emerald-200">{t('admin.weather.title')}</span>
|
||||
</div>
|
||||
<span className="text-[10px] font-medium px-2 py-0.5 rounded-full bg-emerald-200 dark:bg-emerald-800 text-emerald-800 dark:text-emerald-200">{t('admin.weather.badge')}</span>
|
||||
</div>
|
||||
<div className="px-4 pb-3">
|
||||
<p className="text-xs text-emerald-800 dark:text-emerald-300 leading-relaxed">{t('admin.weather.description')}</p>
|
||||
<p className="text-[11px] text-emerald-600 dark:text-emerald-400 mt-1.5 leading-relaxed">{t('admin.weather.locationHint')}</p>
|
||||
<div className="mt-3 grid grid-cols-1 sm:grid-cols-3 gap-2">
|
||||
<div className="rounded-md bg-white dark:bg-emerald-900/40 px-3 py-2 border border-emerald-100 dark:border-emerald-800">
|
||||
<p className="text-xs font-semibold text-emerald-900 dark:text-emerald-200">{t('admin.weather.forecast')}</p>
|
||||
<p className="text-[11px] text-emerald-600 dark:text-emerald-400 mt-0.5">{t('admin.weather.forecastDesc')}</p>
|
||||
</div>
|
||||
<div className="rounded-md bg-white dark:bg-emerald-900/40 px-3 py-2 border border-emerald-100 dark:border-emerald-800">
|
||||
<p className="text-xs font-semibold text-emerald-900 dark:text-emerald-200">{t('admin.weather.climate')}</p>
|
||||
<p className="text-[11px] text-emerald-600 dark:text-emerald-400 mt-0.5">{t('admin.weather.climateDesc')}</p>
|
||||
</div>
|
||||
<div className="rounded-md bg-white dark:bg-emerald-900/40 px-3 py-2 border border-emerald-100 dark:border-emerald-800">
|
||||
<p className="text-xs font-semibold text-emerald-900 dark:text-emerald-200">{t('admin.weather.requests')}</p>
|
||||
<p className="text-[11px] text-emerald-600 dark:text-emerald-400 mt-0.5">{t('admin.weather.requestsDesc')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleSaveApiKeys}
|
||||
disabled={savingKeys}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-slate-900 text-white rounded-lg text-sm hover:bg-slate-700 disabled:bg-slate-400"
|
||||
>
|
||||
{savingKeys ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
{t('common.save')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* OIDC / SSO Configuration */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-slate-100">
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.oidcTitle')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.oidcSubtitle')}</p>
|
||||
</div>
|
||||
<div className="p-6 space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('admin.oidcDisplayName')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={oidcConfig.display_name}
|
||||
onChange={e => setOidcConfig(c => ({ ...c, display_name: e.target.value }))}
|
||||
placeholder='z.B. Google, Authentik, Keycloak'
|
||||
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>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('admin.oidcIssuer')}</label>
|
||||
<input
|
||||
type="url"
|
||||
value={oidcConfig.issuer}
|
||||
onChange={e => setOidcConfig(c => ({ ...c, issuer: e.target.value }))}
|
||||
placeholder='https://accounts.google.com'
|
||||
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"
|
||||
/>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.oidcIssuerHint')}</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">Discovery URL <span className="text-slate-400 font-normal">(optional)</span></label>
|
||||
<input
|
||||
type="url"
|
||||
value={oidcConfig.discovery_url}
|
||||
onChange={e => setOidcConfig(c => ({ ...c, discovery_url: e.target.value }))}
|
||||
placeholder='https://auth.example.com/application/o/trek/.well-known/openid-configuration'
|
||||
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"
|
||||
/>
|
||||
<p className="text-xs text-slate-400 mt-1">Override the auto-constructed discovery URL. Required for providers like Authentik where the endpoint is not at <code className="bg-slate-100 px-1 rounded">{'<issuer>/.well-known/openid-configuration'}</code>.</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">Client ID</label>
|
||||
<input
|
||||
type="text"
|
||||
value={oidcConfig.client_id}
|
||||
onChange={e => setOidcConfig(c => ({ ...c, client_id: 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>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">Client Secret</label>
|
||||
<input
|
||||
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>
|
||||
<button
|
||||
onClick={async () => {
|
||||
setSavingOidc(true)
|
||||
try {
|
||||
const payload: Record<string, unknown> = { issuer: oidcConfig.issuer, client_id: oidcConfig.client_id, display_name: oidcConfig.display_name, discovery_url: oidcConfig.discovery_url }
|
||||
if (oidcConfig.client_secret) payload.client_secret = oidcConfig.client_secret
|
||||
await adminApi.updateOidc(payload)
|
||||
toast.success(t('admin.oidcSaved'))
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
} finally {
|
||||
setSavingOidc(false)
|
||||
}
|
||||
}}
|
||||
disabled={savingOidc}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-slate-900 text-white rounded-lg text-sm hover:bg-slate-700 disabled:bg-slate-400"
|
||||
>
|
||||
{savingOidc ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
{t('common.save')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/* Danger Zone */}
|
||||
<div className="bg-white rounded-xl border border-red-200 overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-red-100 bg-red-50">
|
||||
<h2 className="font-semibold text-red-700 flex items-center gap-2">
|
||||
<AlertTriangle className="w-4 h-4" />
|
||||
Danger Zone
|
||||
</h2>
|
||||
</div>
|
||||
<div className="p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-700">Rotate JWT Secret</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">Generate a new JWT signing secret. All active sessions will be invalidated immediately.</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setShowRotateJwtModal(true)}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium transition-colors"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
Rotate
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import React from 'react'
|
||||
import { useCountUp } from '../../hooks/useCountUp'
|
||||
|
||||
// Single animated metric card in the admin stats grid. Presentational.
|
||||
export default function AdminStatCard({ label, value, icon: Icon }: { label: string; value: number; icon: React.ComponentType<{ className?: string; style?: React.CSSProperties }> }): React.ReactElement {
|
||||
const animated = useCountUp(value, 900)
|
||||
return (
|
||||
<div className="rounded-xl border p-4 bg-surface-card border-edge">
|
||||
<div className="flex items-center gap-4">
|
||||
<Icon className="w-5 h-5 text-content" />
|
||||
<div>
|
||||
<p className="text-xl font-bold tabular-nums text-content">{animated}</p>
|
||||
<p className="text-xs text-content-muted">{label}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import React from 'react'
|
||||
import { ArrowUpCircle, ExternalLink, Download } from 'lucide-react'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import type { UpdateInfo } from './adminModel'
|
||||
|
||||
interface AdminUpdateBannerProps {
|
||||
updateInfo: UpdateInfo
|
||||
t: TranslationFn
|
||||
onHowTo: () => void
|
||||
}
|
||||
|
||||
// The "new version available" banner shown at the top of the admin page.
|
||||
// Purely presentational — extracted from AdminPage with identical markup.
|
||||
export default function AdminUpdateBanner({ updateInfo, t, onHowTo }: AdminUpdateBannerProps): React.ReactElement {
|
||||
return (
|
||||
<div className="mb-6 p-4 rounded-xl border flex flex-col sm:flex-row items-start sm:items-center gap-4 bg-amber-50 dark:bg-amber-950/40 border-amber-300 dark:border-amber-700">
|
||||
<div className="flex items-center gap-4 flex-1 min-w-0">
|
||||
<div className="flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center bg-amber-500 dark:bg-amber-600">
|
||||
<ArrowUpCircle className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-amber-900 dark:text-amber-200">{t('admin.update.available')}</p>
|
||||
<p className="text-xs text-amber-700 dark:text-amber-400 mt-0.5">
|
||||
{t('admin.update.text').replace('{version}', `v${updateInfo.latest}`).replace('{current}', `v${updateInfo.current}`)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
{updateInfo.release_url && (
|
||||
<a
|
||||
href={updateInfo.release_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors text-amber-800 dark:text-amber-300 border border-amber-300 dark:border-amber-600 hover:bg-amber-100 dark:hover:bg-amber-900/50"
|
||||
>
|
||||
<ExternalLink className="w-3.5 h-3.5" />
|
||||
{t('admin.update.button')}
|
||||
</a>
|
||||
)}
|
||||
<button
|
||||
onClick={onHowTo}
|
||||
className="flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-semibold transition-colors bg-slate-900 dark:bg-white text-white dark:text-slate-900 hover:bg-slate-700 dark:hover:bg-gray-200"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('admin.update.howTo')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
import React from 'react'
|
||||
import { adminApi } from '../../api/client'
|
||||
import Modal from '../../components/shared/Modal'
|
||||
import CustomSelect from '../../components/shared/CustomSelect'
|
||||
import { CheckCircle, ArrowUpCircle, ExternalLink, RefreshCw, AlertTriangle } from 'lucide-react'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import type { useAdmin } from './useAdmin'
|
||||
|
||||
interface AdminUserModalsProps {
|
||||
admin: ReturnType<typeof useAdmin>
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
// The admin page's modal layer: create-user, edit-user, the "how to update"
|
||||
// popup and the rotate-JWT confirmation. Pure layout around the useAdmin hook.
|
||||
export default function AdminUserModals({ admin, t }: AdminUserModalsProps): React.ReactElement {
|
||||
const {
|
||||
logout, navigate, toast,
|
||||
editingUser, setEditingUser, editForm, setEditForm,
|
||||
showCreateUser, setShowCreateUser, createForm, setCreateForm,
|
||||
updateInfo, showUpdateModal, setShowUpdateModal,
|
||||
showRotateJwtModal, setShowRotateJwtModal, rotatingJwt, setRotatingJwt,
|
||||
handleCreateUser, handleSaveUser,
|
||||
} = admin
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Create user modal */}
|
||||
<Modal
|
||||
isOpen={showCreateUser}
|
||||
onClose={() => setShowCreateUser(false)}
|
||||
title={t('admin.createUser')}
|
||||
size="sm"
|
||||
footer={
|
||||
<div className="flex gap-3 justify-end">
|
||||
<button
|
||||
onClick={() => setShowCreateUser(false)}
|
||||
className="px-4 py-2 text-sm text-slate-600 border border-slate-200 rounded-lg hover:bg-slate-50"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCreateUser}
|
||||
className="px-4 py-2 text-sm bg-slate-900 hover:bg-slate-700 text-white rounded-lg"
|
||||
>
|
||||
{t('admin.createUser')}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('settings.username')} *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={createForm.username}
|
||||
onChange={e => setCreateForm(f => ({ ...f, username: e.target.value }))}
|
||||
placeholder={t('settings.username')}
|
||||
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 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('common.email')} *</label>
|
||||
<input
|
||||
type="email"
|
||||
value={createForm.email}
|
||||
onChange={e => setCreateForm(f => ({ ...f, email: e.target.value }))}
|
||||
placeholder={t('common.email')}
|
||||
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 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('common.password')} *</label>
|
||||
<input
|
||||
type="password"
|
||||
value={createForm.password}
|
||||
onChange={e => setCreateForm(f => ({ ...f, password: e.target.value }))}
|
||||
placeholder={t('common.password')}
|
||||
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 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('settings.role')}</label>
|
||||
<CustomSelect
|
||||
value={createForm.role}
|
||||
onChange={value => setCreateForm(f => ({ ...f, role: String(value) }))}
|
||||
options={[
|
||||
{ value: 'user', label: t('settings.roleUser') },
|
||||
{ value: 'admin', label: t('settings.roleAdmin') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
{/* Edit user modal */}
|
||||
<Modal
|
||||
isOpen={!!editingUser}
|
||||
onClose={() => setEditingUser(null)}
|
||||
title={t('admin.editUser')}
|
||||
size="sm"
|
||||
footer={
|
||||
<div className="flex gap-3 justify-end">
|
||||
<button
|
||||
onClick={() => setEditingUser(null)}
|
||||
className="px-4 py-2 text-sm text-slate-600 border border-slate-200 rounded-lg hover:bg-slate-50"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSaveUser}
|
||||
className="px-4 py-2 text-sm bg-slate-900 hover:bg-slate-700 text-white rounded-lg"
|
||||
>
|
||||
{t('common.save')}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{editingUser && (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('settings.username')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={editForm.username}
|
||||
onChange={e => setEditForm(f => ({ ...f, username: 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 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('common.email')}</label>
|
||||
<input
|
||||
type="email"
|
||||
value={editForm.email}
|
||||
onChange={e => setEditForm(f => ({ ...f, email: 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 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('admin.newPassword')} <span className="text-slate-400 font-normal">({t('admin.newPasswordHint')})</span></label>
|
||||
<input
|
||||
type="password"
|
||||
value={editForm.password}
|
||||
onChange={e => setEditForm(f => ({ ...f, password: e.target.value }))}
|
||||
placeholder={t('admin.newPasswordPlaceholder')}
|
||||
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 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('settings.role')}</label>
|
||||
<CustomSelect
|
||||
value={editForm.role}
|
||||
onChange={value => setEditForm(f => ({ ...f, role: String(value) }))}
|
||||
options={[
|
||||
{ value: 'user', label: t('settings.roleUser') },
|
||||
{ value: 'admin', label: t('settings.roleAdmin') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
{/* Update instructions popup */}
|
||||
{showUpdateModal && (
|
||||
<div
|
||||
style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}
|
||||
onClick={() => setShowUpdateModal(false)}
|
||||
>
|
||||
<div
|
||||
onClick={e => e.stopPropagation()}
|
||||
style={{ width: '100%', maxWidth: 440, borderRadius: 16, overflow: 'hidden' }}
|
||||
className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700"
|
||||
>
|
||||
<div style={{ background: 'linear-gradient(135deg, #0f172a, #1e293b)', padding: '20px 24px', display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<div className="bg-[rgba(255,255,255,0.2)]" style={{ width: 40, height: 40, borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
|
||||
<ArrowUpCircle size={20} className="text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-white" style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>{t('admin.update.howTo')}</h3>
|
||||
<p className="text-[rgba(255,255,255,0.8)]" style={{ margin: '2px 0 0', fontSize: 12 }}>
|
||||
v{updateInfo?.current} → v{updateInfo?.latest}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ padding: '20px 24px' }}>
|
||||
<p className="text-gray-700 dark:text-gray-300" style={{ fontSize: 13, lineHeight: 1.6, margin: 0 }}>
|
||||
{t('admin.update.dockerText').replace('{version}', `v${updateInfo?.latest ?? ''}`)}
|
||||
</p>
|
||||
|
||||
<div style={{ marginTop: 14, padding: '12px 14px', borderRadius: 10, fontSize: 12, lineHeight: 1.8, fontFamily: 'monospace', whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}
|
||||
className="bg-gray-900 dark:bg-gray-950 text-gray-100 border border-gray-700"
|
||||
>
|
||||
{`docker pull mauriceboe/trek:latest
|
||||
docker stop trek && docker rm trek
|
||||
docker run -d --name trek \\
|
||||
-p 3000:3000 \\
|
||||
-v /opt/trek/data:/app/data \\
|
||||
-v /opt/trek/uploads:/app/uploads \\
|
||||
--restart unless-stopped \\
|
||||
mauriceboe/trek:latest`}
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: 10, padding: '10px 12px', borderRadius: 10, fontSize: 12, lineHeight: 1.5 }}
|
||||
className="bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 border border-emerald-200 dark:border-emerald-800"
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<CheckCircle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
|
||||
<span>{t('admin.update.dataInfo')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{updateInfo?.release_url && (
|
||||
<div style={{ marginTop: 10, padding: '10px 12px', borderRadius: 10, fontSize: 12, lineHeight: 1.5 }}
|
||||
className="bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-800"
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<ExternalLink className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
|
||||
<span>
|
||||
<a href={updateInfo.release_url} target="_blank" rel="noopener noreferrer" className="underline font-semibold">
|
||||
{t('admin.update.button')}
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={{ padding: '0 24px 20px', display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<button
|
||||
onClick={() => setShowUpdateModal(false)}
|
||||
className="bg-slate-900 dark:bg-white text-white dark:text-slate-900 hover:bg-slate-700 dark:hover:bg-gray-200"
|
||||
style={{ padding: '9px 20px', borderRadius: 10, fontSize: 13, fontWeight: 600, border: 'none', cursor: 'pointer', fontFamily: 'inherit' }}
|
||||
>
|
||||
{t('common.close')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Rotate JWT Secret confirmation modal */}
|
||||
<Modal
|
||||
isOpen={showRotateJwtModal}
|
||||
onClose={() => setShowRotateJwtModal(false)}
|
||||
title="Rotate JWT Secret"
|
||||
size="sm"
|
||||
footer={
|
||||
<div className="flex gap-3 justify-end">
|
||||
<button
|
||||
onClick={() => setShowRotateJwtModal(false)}
|
||||
disabled={rotatingJwt}
|
||||
className="px-4 py-2 text-sm text-slate-600 border border-slate-200 rounded-lg hover:bg-slate-50 disabled:opacity-50"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
setRotatingJwt(true)
|
||||
try {
|
||||
await adminApi.rotateJwtSecret()
|
||||
setShowRotateJwtModal(false)
|
||||
logout()
|
||||
navigate('/login', { state: { noRedirect: true } })
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
setRotatingJwt(false)
|
||||
}
|
||||
}}
|
||||
disabled={rotatingJwt}
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm bg-red-600 hover:bg-red-700 disabled:bg-red-300 text-white rounded-lg font-medium"
|
||||
>
|
||||
{rotatingJwt ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <RefreshCw className="w-4 h-4" />}
|
||||
Rotate & Log out
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex gap-3">
|
||||
<div className="flex-shrink-0 w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
|
||||
<AlertTriangle className="w-5 h-5 text-red-600" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-900 mb-1">Warning, this will invalidate all sessions and log you out.</p>
|
||||
<p className="text-xs text-slate-500">A new JWT secret will be generated immediately. Every logged-in user — including you — will be signed out and will need to log in again.</p>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import React from 'react'
|
||||
import { Shield, Trash2, Edit2, UserPlus, Link2, Copy, Plus } from 'lucide-react'
|
||||
import Modal from '../../components/shared/Modal'
|
||||
import PermissionsPanel from '../../components/Admin/PermissionsPanel'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import type { useAdmin } from './useAdmin'
|
||||
|
||||
interface AdminUsersTabProps {
|
||||
admin: ReturnType<typeof useAdmin>
|
||||
t: TranslationFn
|
||||
locale: string
|
||||
}
|
||||
|
||||
// "Users" admin tab: user table, invite links, permissions panel + the
|
||||
// create-invite modal. Pure layout around the useAdmin hook — no logic of its own.
|
||||
export default function AdminUsersTab({ admin, t, locale }: AdminUsersTabProps): React.ReactElement {
|
||||
const {
|
||||
serverTimezone, hour12, currentUser,
|
||||
users, isLoading,
|
||||
setShowCreateUser,
|
||||
invites, showCreateInvite, setShowCreateInvite, inviteForm, setInviteForm,
|
||||
copyInviteLink, handleCreateInvite, handleDeleteInvite,
|
||||
handleEditUser, handleDeleteUser,
|
||||
} = admin
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="p-5 border-b border-slate-100 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.tabs.users')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{users.length} {t('admin.stats.users')}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setShowCreateUser(true)}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 text-sm bg-slate-900 text-white rounded-lg hover:bg-slate-700 transition-colors"
|
||||
>
|
||||
<UserPlus className="w-4 h-4" />
|
||||
{t('admin.createUser')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="p-8 text-center">
|
||||
<div className="w-8 h-8 border-2 border-slate-200 border-t-slate-900 rounded-full animate-spin mx-auto"></div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="text-left text-xs font-medium text-slate-500 uppercase tracking-wider border-b border-slate-100 bg-slate-50">
|
||||
<th className="px-5 py-3">{t('admin.table.user')}</th>
|
||||
<th className="px-5 py-3">{t('admin.table.email')}</th>
|
||||
<th className="px-5 py-3">{t('admin.table.role')}</th>
|
||||
<th className="px-5 py-3">{t('admin.table.created')}</th>
|
||||
<th className="px-5 py-3">{t('admin.table.lastLogin')}</th>
|
||||
<th className="px-5 py-3 text-right">{t('admin.table.actions')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100 trek-stagger">
|
||||
{users.map(u => (
|
||||
<tr key={u.id} className={`hover:bg-slate-50 transition-colors ${u.id === currentUser?.id ? 'bg-slate-50/60' : ''}`}>
|
||||
<td className="px-5 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative">
|
||||
{u.avatar_url ? (
|
||||
<img src={u.avatar_url} alt={u.username} className="w-8 h-8 rounded-full object-cover" />
|
||||
) : (
|
||||
<div className="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center text-sm font-medium text-slate-700">
|
||||
{u.username.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<span className={`absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-surface-card ${u.online ? 'bg-[#22c55e]' : 'bg-[#94a3b8]'}`} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-900">{u.username}</p>
|
||||
{u.id === currentUser?.id && (
|
||||
<span className="text-xs text-slate-500">{t('admin.you')}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-5 py-3 text-sm text-slate-600">{u.email}</td>
|
||||
<td className="px-5 py-3">
|
||||
<span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-0.5 rounded-full ${
|
||||
u.role === 'admin'
|
||||
? 'bg-slate-900 text-white'
|
||||
: 'bg-slate-100 text-slate-600'
|
||||
}`}>
|
||||
{u.role === 'admin' && <Shield className="w-3 h-3" />}
|
||||
{u.role === 'admin' ? t('settings.roleAdmin') : t('settings.roleUser')}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-5 py-3 text-sm text-slate-500">
|
||||
{new Date(u.created_at).toLocaleDateString(locale, { timeZone: serverTimezone })}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-sm text-slate-500">
|
||||
{u.last_login ? new Date(u.last_login).toLocaleDateString(locale, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', hour12, timeZone: serverTimezone }) : '—'}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<div className="flex items-center gap-2 justify-end">
|
||||
<button
|
||||
onClick={() => handleEditUser(u)}
|
||||
className="p-1.5 text-slate-400 hover:text-slate-900 hover:bg-slate-100 rounded-lg transition-colors"
|
||||
title={t('admin.editUser')}
|
||||
>
|
||||
<Edit2 className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDeleteUser(u)}
|
||||
disabled={u.id === currentUser?.id}
|
||||
className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
|
||||
title={t('admin.deleteUserTitle')}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Invite Links (inside users tab) */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden mt-6">
|
||||
<div className="p-5 border-b border-slate-100 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.invite.title')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.invite.subtitle')}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setShowCreateInvite(true)}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 text-sm bg-slate-900 text-white rounded-lg hover:bg-slate-700 transition-colors"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
{t('admin.invite.create')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{invites.length === 0 ? (
|
||||
<div className="p-8 text-center text-sm text-slate-400">{t('admin.invite.empty')}</div>
|
||||
) : (
|
||||
<div className="divide-y divide-slate-100">
|
||||
{invites.map(inv => {
|
||||
const isExpired = inv.expires_at && new Date(inv.expires_at) < new Date()
|
||||
const isUsedUp = inv.max_uses > 0 && inv.used_count >= inv.max_uses
|
||||
const isActive = !isExpired && !isUsedUp
|
||||
return (
|
||||
<div key={inv.id} className="px-5 py-3 flex items-center gap-4">
|
||||
<Link2 className={`w-4 h-4 flex-shrink-0 ${isActive ? 'text-content' : 'text-[#d1d5db]'}`} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="text-xs font-mono text-slate-600 truncate">{inv.token.slice(0, 12)}...</code>
|
||||
<span className={`text-xs px-1.5 py-0.5 rounded-full font-medium ${
|
||||
isActive ? 'bg-green-50 text-green-700' : 'bg-slate-100 text-slate-400'
|
||||
}`}>
|
||||
{isUsedUp ? t('admin.invite.usedUp') : isExpired ? t('admin.invite.expired') : t('admin.invite.active')}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-slate-400 mt-0.5">
|
||||
{inv.used_count}/{inv.max_uses === 0 ? '∞' : inv.max_uses} {t('admin.invite.uses')}
|
||||
{inv.expires_at && ` · ${t('admin.invite.expiresAt')} ${new Date(inv.expires_at).toLocaleDateString(locale, { timeZone: serverTimezone })}`}
|
||||
{` · ${t('admin.invite.createdBy')} ${inv.created_by_name}`}
|
||||
</div>
|
||||
</div>
|
||||
{isActive && (
|
||||
<button onClick={() => copyInviteLink(inv.token)} title={t('admin.invite.copyLink')}
|
||||
className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-400 hover:text-slate-700 transition-colors">
|
||||
<Copy className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
<button onClick={() => handleDeleteInvite(inv.id)} title={t('common.delete')}
|
||||
className="p-1.5 rounded-lg hover:bg-red-50 text-slate-400 hover:text-red-500 transition-colors">
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-6"><PermissionsPanel /></div>
|
||||
|
||||
{/* Create Invite Modal */}
|
||||
<Modal isOpen={showCreateInvite} onClose={() => setShowCreateInvite(false)} title={t('admin.invite.create')} size="sm">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">{t('admin.invite.maxUses')}</label>
|
||||
<div className="flex gap-2">
|
||||
{[1, 2, 3, 4, 5, 0].map(n => (
|
||||
<button key={n} type="button" onClick={() => setInviteForm(f => ({ ...f, max_uses: n }))}
|
||||
className={`flex-1 py-2 rounded-lg text-sm font-semibold border transition-colors ${
|
||||
inviteForm.max_uses === n ? 'bg-slate-900 text-white border-slate-900' : 'bg-white text-slate-600 border-slate-200 hover:border-slate-400'
|
||||
}`}>
|
||||
{n === 0 ? '∞' : `${n}×`}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">{t('admin.invite.expiry')}</label>
|
||||
<div className="flex gap-2">
|
||||
{[
|
||||
{ value: 1, label: '1d' },
|
||||
{ value: 3, label: '3d' },
|
||||
{ value: 7, label: '7d' },
|
||||
{ value: 14, label: '14d' },
|
||||
{ value: '', label: '∞' },
|
||||
].map(opt => (
|
||||
<button key={String(opt.value)} type="button" onClick={() => setInviteForm(f => ({ ...f, expires_in_days: opt.value as number | '' }))}
|
||||
className={`flex-1 py-2 rounded-lg text-sm font-semibold border transition-colors ${
|
||||
inviteForm.expires_in_days === opt.value ? 'bg-slate-900 text-white border-slate-900' : 'bg-white text-slate-600 border-slate-200 hover:border-slate-400'
|
||||
}`}>
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2 border-t border-slate-100">
|
||||
<button onClick={() => setShowCreateInvite(false)} className="px-4 py-2 text-sm text-slate-500 hover:text-slate-700">{t('common.cancel')}</button>
|
||||
<button onClick={handleCreateInvite} className="px-4 py-2 text-sm bg-slate-900 text-white rounded-lg hover:bg-slate-700">{t('admin.invite.createAndCopy')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/** Shared types for the admin page + its data hook. No React, no side effects. */
|
||||
|
||||
export interface AdminUser {
|
||||
id: number
|
||||
username: string
|
||||
email: string
|
||||
role: 'admin' | 'user'
|
||||
created_at: string
|
||||
last_login?: string | null
|
||||
online?: boolean
|
||||
oidc_issuer?: string | null
|
||||
avatar_url?: string | null
|
||||
}
|
||||
|
||||
export interface AdminStats {
|
||||
totalUsers: number
|
||||
totalTrips: number
|
||||
totalPlaces: number
|
||||
totalFiles: number
|
||||
}
|
||||
|
||||
export interface OidcConfig {
|
||||
issuer: string
|
||||
client_id: string
|
||||
client_secret: string
|
||||
client_secret_set: boolean
|
||||
display_name: string
|
||||
discovery_url: string
|
||||
}
|
||||
|
||||
export interface UpdateInfo {
|
||||
update_available: boolean
|
||||
latest: string
|
||||
current: string
|
||||
release_url?: string
|
||||
is_docker?: boolean
|
||||
is_prerelease?: boolean
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import apiClient, { adminApi, authApi } from '../../api/client'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import { useToast } from '../../components/shared/Toast'
|
||||
import type { AdminUser, AdminStats, OidcConfig, UpdateInfo } from './adminModel'
|
||||
|
||||
/**
|
||||
* Admin page logic — owns every admin data slice (users, stats, invites, auth
|
||||
* toggles, OIDC, feature flags, API keys, SMTP, version/update) plus the CRUD
|
||||
* and toggle handlers. AdminPage stays a wiring container that builds the
|
||||
* (t-dependent) tab list and renders the tab panels around this state.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useAdmin() {
|
||||
const { demoMode, serverTimezone } = useAuthStore()
|
||||
const { t } = useTranslation()
|
||||
const hour12 = useSettingsStore(s => s.settings.time_format) === '12h'
|
||||
const mcpEnabled = useAddonStore(s => s.isEnabled('mcp'))
|
||||
const devMode = useAuthStore(s => s.devMode)
|
||||
|
||||
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' })
|
||||
|
||||
// Bag tracking
|
||||
const [bagTrackingEnabled, setBagTrackingEnabled] = useState<boolean>(false)
|
||||
useEffect(() => { adminApi.getBagTracking().then(d => setBagTrackingEnabled(d.enabled)).catch(() => {}) }, [])
|
||||
|
||||
// Places photos
|
||||
const [placesPhotosEnabled, setPlacesPhotosEnabledState] = useState<boolean>(true)
|
||||
useEffect(() => { adminApi.getPlacesPhotos().then(d => setPlacesPhotosEnabledState(d.enabled)).catch(() => {}) }, [])
|
||||
|
||||
// Places autocomplete
|
||||
const [placesAutocompleteEnabled, setPlacesAutocompleteEnabledState] = useState<boolean>(true)
|
||||
useEffect(() => { adminApi.getPlacesAutocomplete().then(d => setPlacesAutocompleteEnabledState(d.enabled)).catch(() => {}) }, [])
|
||||
|
||||
// Places details
|
||||
const [placesDetailsEnabled, setPlacesDetailsEnabledState] = useState<boolean>(true)
|
||||
useEffect(() => { adminApi.getPlacesDetails().then(d => setPlacesDetailsEnabledState(d.enabled)).catch(() => {}) }, [])
|
||||
|
||||
// Collab features
|
||||
const [collabFeatures, setCollabFeatures] = useState<{ chat: boolean; notes: boolean; polls: boolean; whatsnext: boolean }>({ chat: true, notes: true, polls: true, whatsnext: true })
|
||||
useEffect(() => { adminApi.getCollabFeatures().then(d => setCollabFeatures(d)).catch(() => {}) }, [])
|
||||
|
||||
// OIDC config
|
||||
const [oidcConfig, setOidcConfig] = useState<OidcConfig>({ issuer: '', client_id: '', client_secret: '', client_secret_set: false, display_name: '', discovery_url: '' })
|
||||
const [savingOidc, setSavingOidc] = useState<boolean>(false)
|
||||
|
||||
// Auth toggles
|
||||
const [passwordLogin, setPasswordLogin] = useState<boolean>(true)
|
||||
const [passwordRegistration, setPasswordRegistration] = useState<boolean>(true)
|
||||
const [oidcLogin, setOidcLogin] = useState<boolean>(true)
|
||||
const [oidcRegistration, setOidcRegistration] = useState<boolean>(true)
|
||||
const [envOverrideOidcOnly, setEnvOverrideOidcOnly] = useState<boolean>(false)
|
||||
const [oidcConfigured, setOidcConfigured] = useState<boolean>(false)
|
||||
const [requireMfa, setRequireMfa] = useState<boolean>(false)
|
||||
|
||||
// Invite links
|
||||
const [invites, setInvites] = useState<any[]>([])
|
||||
const [showCreateInvite, setShowCreateInvite] = useState<boolean>(false)
|
||||
const [inviteForm, setInviteForm] = useState<{ max_uses: number; expires_in_days: number | '' }>({ max_uses: 1, expires_in_days: 7 })
|
||||
|
||||
// File types
|
||||
const [allowedFileTypes, setAllowedFileTypes] = useState<string>('jpg,jpeg,png,gif,webp,heic,pdf,doc,docx,xls,xlsx,txt,csv')
|
||||
const [savingFileTypes, setSavingFileTypes] = useState<boolean>(false)
|
||||
|
||||
// SMTP settings
|
||||
const [smtpValues, setSmtpValues] = useState<Record<string, string>>({})
|
||||
const [smtpLoaded, setSmtpLoaded] = useState(false)
|
||||
useEffect(() => {
|
||||
apiClient.get('/auth/app-settings').then(r => {
|
||||
setSmtpValues(r.data || {})
|
||||
setSmtpLoaded(true)
|
||||
}).catch(() => setSmtpLoaded(true))
|
||||
}, [])
|
||||
|
||||
// API Keys
|
||||
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<UpdateInfo | null>(null)
|
||||
const [showUpdateModal, setShowUpdateModal] = useState<boolean>(false)
|
||||
|
||||
const { user: currentUser, updateApiKeys, setAppRequireMfa, setTripRemindersEnabled, setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled, logout } = useAuthStore()
|
||||
const navigate = useNavigate()
|
||||
const toast = useToast()
|
||||
|
||||
const [showRotateJwtModal, setShowRotateJwtModal] = useState<boolean>(false)
|
||||
const [rotatingJwt, setRotatingJwt] = useState<boolean>(false)
|
||||
|
||||
useEffect(() => {
|
||||
loadData()
|
||||
loadAppConfig()
|
||||
loadApiKeys()
|
||||
adminApi.getOidc().then(setOidcConfig).catch(() => {})
|
||||
adminApi.checkVersion().then(data => {
|
||||
if (data.update_available) setUpdateInfo(data)
|
||||
}).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const loadData = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const [usersData, statsData, invitesData] = await Promise.all([
|
||||
adminApi.users(),
|
||||
adminApi.stats(),
|
||||
adminApi.listInvites().catch(() => ({ invites: [] })),
|
||||
])
|
||||
setUsers(usersData.users)
|
||||
setStats(statsData)
|
||||
setInvites(invitesData.invites || [])
|
||||
} catch (err: unknown) {
|
||||
toast.error(t('admin.toast.loadError'))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadAppConfig = async () => {
|
||||
try {
|
||||
const config = await authApi.getAppConfig()
|
||||
setPasswordLogin(config.password_login ?? true)
|
||||
setPasswordRegistration(config.password_registration ?? config.allow_registration ?? true)
|
||||
setOidcLogin(config.oidc_login ?? true)
|
||||
setOidcRegistration(config.oidc_registration ?? config.allow_registration ?? true)
|
||||
setEnvOverrideOidcOnly(config.env_override_oidc_only ?? false)
|
||||
setOidcConfigured(config.oidc_configured ?? false)
|
||||
if (config.require_mfa !== undefined) setRequireMfa(!!config.require_mfa)
|
||||
if (config.allowed_file_types) setAllowedFileTypes(config.allowed_file_types)
|
||||
} catch (err: unknown) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
const loadApiKeys = async () => {
|
||||
try {
|
||||
const data = await authApi.getSettings()
|
||||
setMapsKey(data.settings?.maps_api_key || '')
|
||||
setWeatherKey(data.settings?.openweather_api_key || '')
|
||||
} catch (err: unknown) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggleAuthSetting = async (key: string, value: boolean, setter: (v: boolean) => void) => {
|
||||
setter(value)
|
||||
try {
|
||||
await authApi.updateAppSettings({ [key]: value })
|
||||
} catch (err: unknown) {
|
||||
setter(!value)
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggleRequireMfa = async (value: boolean) => {
|
||||
setRequireMfa(value)
|
||||
try {
|
||||
await authApi.updateAppSettings({ require_mfa: value })
|
||||
setAppRequireMfa(value)
|
||||
toast.success(t('common.saved'))
|
||||
} catch (err: unknown) {
|
||||
setRequireMfa(!value)
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
}
|
||||
}
|
||||
|
||||
const toggleKey = (key) => {
|
||||
setShowKeys(prev => ({ ...prev, [key]: !prev[key] }))
|
||||
}
|
||||
|
||||
const handleSaveApiKeys = async () => {
|
||||
setSavingKeys(true)
|
||||
try {
|
||||
await updateApiKeys({
|
||||
maps_api_key: mapsKey,
|
||||
openweather_api_key: weatherKey,
|
||||
})
|
||||
toast.success(t('admin.keySaved'))
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : 'Unknown error')
|
||||
} finally {
|
||||
setSavingKeys(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleValidateKeys = async () => {
|
||||
setValidating({ maps: true, weather: true })
|
||||
try {
|
||||
// Save first so validation uses the current values
|
||||
await updateApiKeys({ maps_api_key: mapsKey, openweather_api_key: weatherKey })
|
||||
const result = await authApi.validateKeys()
|
||||
setValidation(result)
|
||||
} catch (err: unknown) {
|
||||
toast.error(t('common.error'))
|
||||
} finally {
|
||||
setValidating({})
|
||||
}
|
||||
}
|
||||
|
||||
const handleValidateKey = async (keyType) => {
|
||||
setValidating(prev => ({ ...prev, [keyType]: true }))
|
||||
try {
|
||||
// Save first so validation uses the current values
|
||||
await updateApiKeys({ maps_api_key: mapsKey, openweather_api_key: weatherKey })
|
||||
const result = await authApi.validateKeys()
|
||||
setValidation(prev => ({ ...prev, [keyType]: result[keyType] }))
|
||||
} catch (err: unknown) {
|
||||
toast.error(t('common.error'))
|
||||
} finally {
|
||||
setValidating(prev => ({ ...prev, [keyType]: false }))
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreateUser = async () => {
|
||||
if (!createForm.username.trim() || !createForm.email.trim() || !createForm.password.trim()) {
|
||||
toast.error(t('admin.toast.fieldsRequired'))
|
||||
return
|
||||
}
|
||||
if (createForm.password.trim().length < 8) {
|
||||
toast.error(t('settings.passwordTooShort'))
|
||||
return
|
||||
}
|
||||
try {
|
||||
const data = await adminApi.createUser(createForm)
|
||||
setUsers(prev => [data.user, ...prev])
|
||||
setShowCreateUser(false)
|
||||
setCreateForm({ username: '', email: '', password: '', role: 'user' })
|
||||
toast.success(t('admin.toast.userCreated'))
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('admin.toast.createError')))
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreateInvite = async () => {
|
||||
try {
|
||||
const data = await adminApi.createInvite({
|
||||
max_uses: inviteForm.max_uses,
|
||||
expires_in_days: inviteForm.expires_in_days || undefined,
|
||||
})
|
||||
setInvites(prev => [data.invite, ...prev])
|
||||
setShowCreateInvite(false)
|
||||
setInviteForm({ max_uses: 1, expires_in_days: 7 })
|
||||
// Copy link to clipboard
|
||||
const link = `${window.location.origin}/register?invite=${data.invite.token}`
|
||||
navigator.clipboard.writeText(link).then(() => toast.success(t('admin.invite.copied')))
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('admin.invite.createError')))
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteInvite = async (id: number) => {
|
||||
try {
|
||||
await adminApi.deleteInvite(id)
|
||||
setInvites(prev => prev.filter(i => i.id !== id))
|
||||
toast.success(t('admin.invite.deleted'))
|
||||
} catch {
|
||||
toast.error(t('admin.invite.deleteError'))
|
||||
}
|
||||
}
|
||||
|
||||
const copyInviteLink = (token: string) => {
|
||||
const link = `${window.location.origin}/register?invite=${token}`
|
||||
navigator.clipboard.writeText(link).then(() => toast.success(t('admin.invite.copied')))
|
||||
}
|
||||
|
||||
const handleEditUser = (user) => {
|
||||
setEditingUser(user)
|
||||
setEditForm({ username: user.username, email: user.email, role: user.role, password: '' })
|
||||
}
|
||||
|
||||
const handleSaveUser = async () => {
|
||||
try {
|
||||
const payload: { username?: string; email?: string; role: string; password?: string } = {
|
||||
username: editForm.username.trim() || undefined,
|
||||
email: editForm.email.trim() || undefined,
|
||||
role: editForm.role,
|
||||
}
|
||||
if (editForm.password.trim()) {
|
||||
if (editForm.password.trim().length < 8) {
|
||||
toast.error(t('settings.passwordTooShort'))
|
||||
return
|
||||
}
|
||||
payload.password = editForm.password.trim()
|
||||
}
|
||||
const data = await adminApi.updateUser(editingUser.id, payload)
|
||||
setUsers(prev => prev.map(u => u.id === editingUser.id ? data.user : u))
|
||||
setEditingUser(null)
|
||||
toast.success(t('admin.toast.userUpdated'))
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('admin.toast.updateError')))
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteUser = async (user) => {
|
||||
if (user.id === currentUser?.id) {
|
||||
toast.error(t('admin.toast.cannotDeleteSelf'))
|
||||
return
|
||||
}
|
||||
if (!confirm(t('admin.deleteUser', { name: user.username }))) return
|
||||
try {
|
||||
await adminApi.deleteUser(user.id)
|
||||
setUsers(prev => prev.filter(u => u.id !== user.id))
|
||||
toast.success(t('admin.toast.userDeleted'))
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('admin.toast.deleteError')))
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
// store-derived
|
||||
demoMode, serverTimezone, hour12, mcpEnabled, devMode, currentUser,
|
||||
updateApiKeys, setAppRequireMfa, setTripRemindersEnabled,
|
||||
setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled, logout,
|
||||
navigate, toast,
|
||||
// state + setters
|
||||
activeTab, setActiveTab, users, setUsers, stats, isLoading,
|
||||
editingUser, setEditingUser, editForm, setEditForm,
|
||||
showCreateUser, setShowCreateUser, createForm, setCreateForm,
|
||||
bagTrackingEnabled, setBagTrackingEnabled,
|
||||
placesPhotosEnabled, setPlacesPhotosEnabledState,
|
||||
placesAutocompleteEnabled, setPlacesAutocompleteEnabledState,
|
||||
placesDetailsEnabled, setPlacesDetailsEnabledState,
|
||||
collabFeatures, setCollabFeatures,
|
||||
oidcConfig, setOidcConfig, savingOidc, setSavingOidc,
|
||||
passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration,
|
||||
oidcLogin, setOidcLogin, oidcRegistration, setOidcRegistration,
|
||||
envOverrideOidcOnly, setEnvOverrideOidcOnly, oidcConfigured, setOidcConfigured,
|
||||
requireMfa, setRequireMfa,
|
||||
invites, setInvites, showCreateInvite, setShowCreateInvite, inviteForm, setInviteForm,
|
||||
allowedFileTypes, setAllowedFileTypes, savingFileTypes, setSavingFileTypes,
|
||||
smtpValues, setSmtpValues, smtpLoaded,
|
||||
mapsKey, setMapsKey, weatherKey, setWeatherKey,
|
||||
showKeys, setShowKeys, savingKeys, validating, validation,
|
||||
updateInfo, setUpdateInfo, showUpdateModal, setShowUpdateModal,
|
||||
showRotateJwtModal, setShowRotateJwtModal, rotatingJwt, setRotatingJwt,
|
||||
// handlers
|
||||
loadData, loadAppConfig, loadApiKeys, handleToggleAuthSetting, handleToggleRequireMfa,
|
||||
toggleKey, handleSaveApiKeys, handleValidateKeys, handleValidateKey,
|
||||
handleCreateUser, handleCreateInvite, handleDeleteInvite, copyInviteLink,
|
||||
handleEditUser, handleSaveUser, handleDeleteUser,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import React from 'react'
|
||||
import { Search, X, ChevronRight } from 'lucide-react'
|
||||
import type { TranslationFn } from '../../types'
|
||||
|
||||
type CountryOption = { code: string; label: string }
|
||||
|
||||
interface AtlasCountrySearchProps {
|
||||
dark: boolean
|
||||
t: TranslationFn
|
||||
search: string
|
||||
setSearch: (v: string) => void
|
||||
results: CountryOption[]
|
||||
setResults: (v: CountryOption[]) => void
|
||||
open: boolean
|
||||
setOpen: (v: boolean) => void
|
||||
options: CountryOption[]
|
||||
onSelect: (code: string) => void
|
||||
}
|
||||
|
||||
// The floating country search box that overlays the globe (search input + results
|
||||
// dropdown). Extracted from AtlasPage as a presentational sibling — behaviour and
|
||||
// markup are byte-identical to the inline version it replaced.
|
||||
export default function AtlasCountrySearch({
|
||||
dark, t, search, setSearch, results, setResults, open, setOpen, options, onSelect,
|
||||
}: AtlasCountrySearchProps): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
className="absolute z-20 flex justify-center"
|
||||
style={{ top: 'calc(env(safe-area-inset-top, 0px) + 14px)', left: 0, right: 0, pointerEvents: 'none' }}
|
||||
>
|
||||
<div style={{ width: 'min(520px, calc(100vw - 28px))', pointerEvents: 'auto' }}>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
padding: '10px 12px',
|
||||
borderRadius: 16,
|
||||
border: '1px solid ' + (dark ? 'rgba(255,255,255,0.10)' : 'rgba(0,0,0,0.08)'),
|
||||
background: dark ? 'rgba(10,10,15,0.55)' : 'rgba(255,255,255,0.55)',
|
||||
backdropFilter: 'blur(18px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(18px) saturate(180%)',
|
||||
boxShadow: dark ? '0 8px 26px rgba(0,0,0,0.25)' : '0 8px 26px rgba(0,0,0,0.10)',
|
||||
}}>
|
||||
<Search size={16} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<input
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value
|
||||
setSearch(raw)
|
||||
const q = raw.trim().toLowerCase()
|
||||
if (!q) {
|
||||
setResults([])
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
const next = options
|
||||
.filter(o => o.label.toLowerCase().includes(q) || o.code.toLowerCase() === q)
|
||||
.slice(0, 8)
|
||||
setResults(next)
|
||||
setOpen(true)
|
||||
}}
|
||||
onFocus={() => {
|
||||
if (results.length > 0) setOpen(true)
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') {
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Enter') {
|
||||
const first = results[0]
|
||||
if (first) onSelect(first.code)
|
||||
}
|
||||
}}
|
||||
placeholder={t('atlas.searchCountry')}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
className="text-content"
|
||||
style={{
|
||||
flex: 1,
|
||||
border: 'none',
|
||||
outline: 'none',
|
||||
background: 'transparent',
|
||||
fontSize: 13,
|
||||
fontFamily: 'inherit',
|
||||
}}
|
||||
/>
|
||||
{search.trim() && (
|
||||
<button
|
||||
onClick={() => {
|
||||
setSearch('')
|
||||
setResults([])
|
||||
setOpen(false)
|
||||
}}
|
||||
className="text-content-faint"
|
||||
style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 2, display: 'flex' }}
|
||||
aria-label="Clear"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{open && results.length > 0 && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: 8,
|
||||
borderRadius: 14,
|
||||
overflow: 'hidden',
|
||||
border: '1px solid ' + (dark ? 'rgba(255,255,255,0.10)' : 'rgba(0,0,0,0.08)'),
|
||||
background: dark ? 'rgba(10,10,15,0.75)' : 'rgba(255,255,255,0.75)',
|
||||
backdropFilter: 'blur(18px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(18px) saturate(180%)',
|
||||
boxShadow: dark ? '0 12px 30px rgba(0,0,0,0.35)' : '0 12px 30px rgba(0,0,0,0.12)',
|
||||
}}
|
||||
onMouseLeave={() => setOpen(false)}
|
||||
>
|
||||
{results.map((r) => (
|
||||
<button
|
||||
key={r.code}
|
||||
onClick={() => onSelect(r.code)}
|
||||
style={{
|
||||
width: '100%',
|
||||
border: 'none',
|
||||
background: 'transparent',
|
||||
cursor: 'pointer',
|
||||
padding: '10px 12px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
fontFamily: 'inherit',
|
||||
textAlign: 'left',
|
||||
borderBottom: '1px solid ' + (dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.06)'),
|
||||
}}
|
||||
onMouseEnter={(e) => { (e.currentTarget as HTMLButtonElement).style.background = dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)' }}
|
||||
onMouseLeave={(e) => { (e.currentTarget as HTMLButtonElement).style.background = 'transparent' }}
|
||||
>
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
|
||||
<img src={`https://flagcdn.com/w40/${r.code.toLowerCase()}.png`} alt={r.code} style={{ width: 28, height: 20, borderRadius: 4, objectFit: 'cover' }} />
|
||||
<span className="text-content" style={{ fontSize: 13, fontWeight: 650, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{r.label}
|
||||
</span>
|
||||
</span>
|
||||
<ChevronRight size={16} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Shared types + pure helpers for the Atlas page. No React, no side effects.
|
||||
* A2_TO_A3 is deliberately a mutable module-level object: the geoData load
|
||||
* effect in useAtlas augments it at runtime, and both the hook (visited-country
|
||||
* colouring) and the page's SidebarContent read it — they must share one
|
||||
* reference, so it lives here rather than inside either consumer.
|
||||
*/
|
||||
|
||||
export interface AtlasCountry {
|
||||
code: string
|
||||
tripCount: number
|
||||
placeCount: number
|
||||
firstVisit?: string | null
|
||||
lastVisit?: string | null
|
||||
}
|
||||
|
||||
export interface AtlasStats {
|
||||
totalTrips: number
|
||||
totalPlaces: number
|
||||
totalCountries: number
|
||||
totalDays: number
|
||||
totalCities?: number
|
||||
}
|
||||
|
||||
export 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
|
||||
}
|
||||
|
||||
export interface CountryDetail {
|
||||
places: import('../../types').AtlasPlace[]
|
||||
trips: { id: number; title: string }[]
|
||||
manually_marked?: boolean
|
||||
}
|
||||
|
||||
export interface BucketItem {
|
||||
id: number
|
||||
name: string
|
||||
lat: number | null
|
||||
lng: number | null
|
||||
country_code: string | null
|
||||
notes: string | null
|
||||
target_date: string | null
|
||||
}
|
||||
|
||||
// Convert country code to flag emoji
|
||||
export function countryCodeToFlag(code: string): string {
|
||||
if (!code || code.length !== 2) return ''
|
||||
return String.fromCodePoint(...[...code.toUpperCase()].map(c => 0x1F1E6 + c.charCodeAt(0) - 65))
|
||||
}
|
||||
|
||||
// ISO-3166-1 alpha-2 → alpha-3 mapping. Two sources feed this table:
|
||||
// 1. Hardcoded entries below — REQUIRED for any country whose Natural Earth GeoJSON record
|
||||
// has ISO_A2='-99' (e.g. France=FRA, Norway=NOR). The runtime augmentation loop
|
||||
// (see geoData useEffect below) skips '-99' features, so those countries MUST be
|
||||
// listed here or the atlas_country_options A3-fallback will silently fail.
|
||||
// 2. Runtime augmentation — the geoData load effect adds entries for every feature
|
||||
// that has a valid ISO_A2, covering territories not present below.
|
||||
export const A2_TO_A3: Record<string, string> = {"AF":"AFG","AL":"ALB","DZ":"DZA","AD":"AND","AO":"AGO","AG":"ATG","AR":"ARG","AM":"ARM","AU":"AUS","AT":"AUT","AZ":"AZE","BS":"BHS","BH":"BHR","BD":"BGD","BB":"BRB","BY":"BLR","BE":"BEL","BZ":"BLZ","BJ":"BEN","BT":"BTN","BO":"BOL","BA":"BIH","BW":"BWA","BR":"BRA","BN":"BRN","BG":"BGR","BF":"BFA","BI":"BDI","CV":"CPV","KH":"KHM","CM":"CMR","CA":"CAN","CF":"CAF","TD":"TCD","CL":"CHL","CN":"CHN","CO":"COL","KM":"COM","CG":"COG","CD":"COD","CR":"CRI","CI":"CIV","HR":"HRV","CU":"CUB","CY":"CYP","CZ":"CZE","DK":"DNK","DJ":"DJI","DM":"DMA","DO":"DOM","EC":"ECU","EG":"EGY","SV":"SLV","GQ":"GNQ","ER":"ERI","EE":"EST","SZ":"SWZ","ET":"ETH","FJ":"FJI","FI":"FIN","FR":"FRA","GA":"GAB","GM":"GMB","GE":"GEO","DE":"DEU","GH":"GHA","GR":"GRC","GD":"GRD","GT":"GTM","GN":"GIN","GW":"GNB","GY":"GUY","HT":"HTI","HN":"HND","HU":"HUN","IS":"ISL","IN":"IND","ID":"IDN","IR":"IRN","IQ":"IRQ","IE":"IRL","IL":"ISR","IT":"ITA","JM":"JAM","JP":"JPN","JO":"JOR","KZ":"KAZ","KE":"KEN","KI":"KIR","KP":"PRK","KR":"KOR","KW":"KWT","KG":"KGZ","LA":"LAO","LV":"LVA","LB":"LBN","LS":"LSO","LR":"LBR","LY":"LBY","LI":"LIE","LT":"LTU","LU":"LUX","MG":"MDG","MW":"MWI","MY":"MYS","MV":"MDV","ML":"MLI","MT":"MLT","MR":"MRT","MU":"MUS","MX":"MEX","MD":"MDA","MN":"MNG","ME":"MNE","MA":"MAR","MZ":"MOZ","MM":"MMR","NA":"NAM","NP":"NPL","NL":"NLD","NZ":"NZL","NI":"NIC","NE":"NER","NG":"NGA","MK":"MKD","NO":"NOR","OM":"OMN","PK":"PAK","PA":"PAN","PG":"PNG","PY":"PRY","PE":"PER","PH":"PHL","PL":"POL","PT":"PRT","QA":"QAT","RO":"ROU","RU":"RUS","RW":"RWA","SA":"SAU","SN":"SEN","RS":"SRB","SL":"SLE","SG":"SGP","SK":"SVK","SI":"SVN","SB":"SLB","SO":"SOM","ZA":"ZAF","SS":"SSD","ES":"ESP","LK":"LKA","SD":"SDN","SR":"SUR","SE":"SWE","CH":"CHE","SY":"SYR","TW":"TWN","TJ":"TJK","TZ":"TZA","TH":"THA","TL":"TLS","TG":"TGO","TT":"TTO","TN":"TUN","TR":"TUR","TM":"TKM","UG":"UGA","UA":"UKR","AE":"ARE","GB":"GBR","US":"USA","UY":"URY","UZ":"UZB","VU":"VUT","VE":"VEN","VN":"VNM","YE":"YEM","ZM":"ZMB","ZW":"ZWE"}
|
||||
@@ -0,0 +1,691 @@
|
||||
import React, { useEffect, useMemo, useState, useRef } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { getIntlLanguage, getLocaleForLanguage, useTranslation } from '../../i18n'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import apiClient, { mapsApi } from '../../api/client'
|
||||
import L from 'leaflet'
|
||||
import type { GeoJsonFeatureCollection } from '../../types'
|
||||
import { A2_TO_A3, type AtlasData, type CountryDetail, type BucketItem } from './atlasModel'
|
||||
|
||||
function useCountryNames(language: string): (code: string) => string {
|
||||
const [resolver, setResolver] = useState<(code: string) => string>(() => (code: string) => code)
|
||||
useEffect(() => {
|
||||
try {
|
||||
const dn = new Intl.DisplayNames([getIntlLanguage(language)], { type: 'region' })
|
||||
setResolver(() => (code: string) => { try { return dn.of(code) || code } catch { return code } })
|
||||
} catch { /* */ }
|
||||
}, [language])
|
||||
return resolver
|
||||
}
|
||||
|
||||
/**
|
||||
* Atlas page logic — the whole interactive globe lives here: atlas/bucket-list
|
||||
* loading, the Leaflet map lifecycle (country + sub-national region layers,
|
||||
* bucket markers, viewport-driven region fetching), country/region mark/unmark
|
||||
* flows and the country search. AtlasPage stays a wiring container that renders
|
||||
* the returned state via its presentational SidebarContent/MobileStats helpers.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useAtlas() {
|
||||
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<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 country_layer_by_a2_ref = useRef<Record<string, any>>({})
|
||||
|
||||
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
|
||||
const y = e.clientY - rect.top
|
||||
// Subtle inner glow
|
||||
glareRef.current.style.background = `radial-gradient(circle 300px at ${x}px ${y}px, ${dark ? 'rgba(255,255,255,0.025)' : 'rgba(255,255,255,0.25)'} 0%, transparent 70%)`
|
||||
glareRef.current.style.opacity = '1'
|
||||
// Border glow that follows cursor
|
||||
borderGlareRef.current.style.opacity = '1'
|
||||
borderGlareRef.current.style.maskImage = `radial-gradient(circle 150px at ${x}px ${y}px, black 0%, transparent 100%)`
|
||||
borderGlareRef.current.style.webkitMaskImage = `radial-gradient(circle 150px at ${x}px ${y}px, black 0%, transparent 100%)`
|
||||
}
|
||||
const handlePanelMouseLeave = () => {
|
||||
if (glareRef.current) glareRef.current.style.opacity = '0'
|
||||
if (borderGlareRef.current) borderGlareRef.current.style.opacity = '0'
|
||||
}
|
||||
|
||||
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)
|
||||
const [visitedRegions, setVisitedRegions] = useState<Record<string, { code: string; name: string; placeCount: number; manuallyMarked?: boolean }[]>>({})
|
||||
const regionLayerRef = useRef<L.GeoJSON | null>(null)
|
||||
const regionGeoCache = useRef<Record<string, GeoJsonFeatureCollection>>({})
|
||||
const [showRegions, setShowRegions] = useState(false)
|
||||
const [regionGeoLoaded, setRegionGeoLoaded] = useState(0)
|
||||
const regionTooltipRef = useRef<HTMLDivElement>(null)
|
||||
const loadCountryDetailRef = useRef<(code: string) => void>(() => {})
|
||||
const handleMarkCountryRef = useRef<(code: string, name: string) => void>(() => {})
|
||||
const setConfirmActionRef = useRef<typeof setConfirmAction>(() => {})
|
||||
const [confirmAction, setConfirmAction] = useState<{ type: 'mark' | 'unmark' | 'choose' | 'bucket' | 'choose-region' | 'unmark-region'; code: string; name: string; regionCode?: string; countryName?: string } | null>(null)
|
||||
const [bucketMonth, setBucketMonth] = useState(0)
|
||||
const [bucketYear, setBucketYear] = useState(0)
|
||||
|
||||
// Bucket list
|
||||
const [bucketList, setBucketList] = useState<BucketItem[]>([])
|
||||
const [showBucketAdd, setShowBucketAdd] = useState(false)
|
||||
const [bucketForm, setBucketForm] = useState({ name: '', notes: '', lat: '', lng: '', target_date: '' })
|
||||
const [bucketSearch, setBucketSearch] = useState('')
|
||||
const [bucketSearchResults, setBucketSearchResults] = useState<any[]>([])
|
||||
const [bucketSearching, setBucketSearching] = useState(false)
|
||||
const [bucketPoiMonth, setBucketPoiMonth] = useState(0)
|
||||
const [bucketPoiYear, setBucketPoiYear] = useState(0)
|
||||
const [bucketTab, setBucketTab] = useState<'stats' | 'bucket'>('stats')
|
||||
const bucketMarkersRef = useRef<any>(null)
|
||||
|
||||
const [atlas_country_search, set_atlas_country_search] = useState('')
|
||||
const [atlas_country_results, set_atlas_country_results] = useState<{ code: string; label: string }[]>([])
|
||||
const [atlas_country_open, set_atlas_country_open] = useState(false)
|
||||
|
||||
const atlas_country_options = useMemo(() => {
|
||||
if (!geoData) return []
|
||||
// Precompute A3 → A2 reverse lookup once per geoData change instead of
|
||||
// scanning A2_TO_A3 for every feature that needs the fallback.
|
||||
const a3ToA2 = new Map<string, string>()
|
||||
for (const [a2Key, a3Val] of Object.entries(A2_TO_A3)) a3ToA2.set(a3Val, a2Key)
|
||||
|
||||
const opts: { code: string; label: string }[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const f of (geoData as any).features || []) {
|
||||
const rawA2 = f?.properties?.ISO_A2
|
||||
let resolvedA2: string | null = (typeof rawA2 === 'string' && rawA2.length === 2 && rawA2 !== '-99') ? rawA2 : null
|
||||
if (!resolvedA2) {
|
||||
const a3 = f?.properties?.ADM0_A3 || f?.properties?.ISO_A3 || f?.properties?.['ISO3166-1-Alpha-3'] || null
|
||||
if (a3 && a3 !== '-99') resolvedA2 = a3ToA2.get(a3) ?? null
|
||||
}
|
||||
if (!resolvedA2 || seen.has(resolvedA2)) continue
|
||||
seen.add(resolvedA2)
|
||||
const label = String(resolveName(resolvedA2) || f?.properties?.NAME || f?.properties?.ADMIN || resolvedA2)
|
||||
opts.push({ code: resolvedA2, label })
|
||||
}
|
||||
opts.sort((a, b) => a.label.localeCompare(b.label))
|
||||
return opts
|
||||
}, [geoData, resolveName])
|
||||
|
||||
// Load atlas data + bucket list
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
apiClient.get('/addons/atlas/stats'),
|
||||
apiClient.get('/addons/atlas/bucket-list'),
|
||||
]).then(([statsRes, bucketRes]) => {
|
||||
setData(statsRes.data)
|
||||
setBucketList(bucketRes.data.items || [])
|
||||
setLoading(false)
|
||||
}).catch(() => setLoading(false))
|
||||
}, [])
|
||||
|
||||
// Load GeoJSON world data (direct GeoJSON, no conversion needed)
|
||||
useEffect(() => {
|
||||
fetch('https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_50m_admin_0_countries.geojson')
|
||||
.then(r => r.json())
|
||||
.then(geo => {
|
||||
// Dynamically build A2→A3 mapping from GeoJSON
|
||||
for (const f of geo.features) {
|
||||
const a2 = f.properties?.ISO_A2
|
||||
const a3 = f.properties?.ADM0_A3 || f.properties?.ISO_A3
|
||||
if (a2 && a3 && a2 !== '-99' && a3 !== '-99' && !A2_TO_A3[a2]) {
|
||||
A2_TO_A3[a2] = a3
|
||||
}
|
||||
}
|
||||
setGeoData(geo)
|
||||
})
|
||||
.catch(() => {})
|
||||
}, [])
|
||||
|
||||
// Load visited regions (geocoded from places/trips) — once on mount
|
||||
useEffect(() => {
|
||||
apiClient.get(`/addons/atlas/regions?_t=${Date.now()}`)
|
||||
.then(r => setVisitedRegions(r.data?.regions || {}))
|
||||
.catch(() => {})
|
||||
}, [])
|
||||
|
||||
// Load admin-1 GeoJSON for countries visible in the current viewport
|
||||
const loadRegionsForViewportRef = useRef<() => void>(() => {})
|
||||
const loadRegionsForViewport = (): void => {
|
||||
if (!mapInstance.current) return
|
||||
const bounds = mapInstance.current.getBounds()
|
||||
const toLoad: string[] = []
|
||||
for (const [code, layer] of Object.entries(country_layer_by_a2_ref.current)) {
|
||||
if (regionGeoCache.current[code]) continue
|
||||
try {
|
||||
if (bounds.intersects((layer as any).getBounds())) toLoad.push(code)
|
||||
} catch {}
|
||||
}
|
||||
if (!toLoad.length) return
|
||||
apiClient.get(`/addons/atlas/regions/geo?countries=${toLoad.join(',')}`)
|
||||
.then(geoRes => {
|
||||
const geo = geoRes.data
|
||||
if (!geo?.features) return
|
||||
let added = false
|
||||
for (const c of toLoad) {
|
||||
const features = geo.features.filter((f: any) => f.properties?.iso_a2?.toUpperCase() === c)
|
||||
if (features.length > 0) { regionGeoCache.current[c] = { type: 'FeatureCollection', features }; added = true }
|
||||
}
|
||||
if (added) setRegionGeoLoaded(v => v + 1)
|
||||
})
|
||||
.catch(() => {})
|
||||
}
|
||||
loadRegionsForViewportRef.current = loadRegionsForViewport
|
||||
|
||||
// Initialize map — runs after loading is done and mapRef is available
|
||||
useEffect(() => {
|
||||
if (loading || !mapRef.current) return
|
||||
if (mapInstance.current) { mapInstance.current.remove(); mapInstance.current = null }
|
||||
|
||||
const map = L.map(mapRef.current, {
|
||||
center: [25, 0],
|
||||
zoom: 3,
|
||||
minZoom: 3,
|
||||
maxZoom: 10,
|
||||
zoomControl: false,
|
||||
attributionControl: false,
|
||||
maxBounds: [[-90, -220], [90, 220]],
|
||||
maxBoundsViscosity: 1.0,
|
||||
fadeAnimation: false,
|
||||
preferCanvas: true,
|
||||
})
|
||||
|
||||
L.control.zoom({ position: 'bottomright' }).addTo(map)
|
||||
|
||||
const tileUrl = dark
|
||||
? 'https://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}{r}.png'
|
||||
: 'https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png'
|
||||
|
||||
L.tileLayer(tileUrl, {
|
||||
maxZoom: 10,
|
||||
keepBuffer: 25,
|
||||
updateWhenZooming: true,
|
||||
updateWhenIdle: false,
|
||||
tileSize: 256,
|
||||
zoomOffset: 0,
|
||||
crossOrigin: true,
|
||||
referrerPolicy: 'strict-origin-when-cross-origin',
|
||||
} as any).addTo(map)
|
||||
|
||||
// Preload adjacent zoom level tiles
|
||||
L.tileLayer(tileUrl, {
|
||||
maxZoom: 10,
|
||||
keepBuffer: 10,
|
||||
opacity: 0,
|
||||
tileSize: 256,
|
||||
crossOrigin: true,
|
||||
referrerPolicy: 'strict-origin-when-cross-origin',
|
||||
}).addTo(map)
|
||||
|
||||
// Custom pane for region layer — above overlay (z-index 400)
|
||||
map.createPane('regionPane')
|
||||
map.getPane('regionPane')!.style.zIndex = '401'
|
||||
|
||||
mapInstance.current = map
|
||||
|
||||
// Zoom-based region switching
|
||||
map.on('zoomend', () => {
|
||||
const z = map.getZoom()
|
||||
const shouldShow = z >= 5
|
||||
setShowRegions(shouldShow)
|
||||
const overlayPane = map.getPane('overlayPane')
|
||||
if (overlayPane) {
|
||||
overlayPane.style.opacity = shouldShow ? '0.35' : '1'
|
||||
overlayPane.style.pointerEvents = shouldShow ? 'none' : 'auto'
|
||||
}
|
||||
if (shouldShow) {
|
||||
// Re-add region layer if it was removed while zoomed out
|
||||
if (regionLayerRef.current && !map.hasLayer(regionLayerRef.current)) {
|
||||
regionLayerRef.current.addTo(map)
|
||||
}
|
||||
loadRegionsForViewportRef.current()
|
||||
} else {
|
||||
// Physically remove region layer so its SVG paths can't intercept events
|
||||
if (regionTooltipRef.current) regionTooltipRef.current.style.display = 'none'
|
||||
if (regionLayerRef.current && map.hasLayer(regionLayerRef.current)) {
|
||||
regionLayerRef.current.resetStyle()
|
||||
regionLayerRef.current.removeFrom(map)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
map.on('moveend', () => {
|
||||
if (map.getZoom() >= 6) loadRegionsForViewportRef.current()
|
||||
})
|
||||
|
||||
return () => { map.remove(); mapInstance.current = null }
|
||||
}, [dark, loading])
|
||||
|
||||
// Render GeoJSON countries
|
||||
useEffect(() => {
|
||||
if (!mapInstance.current || !geoData || !data) return
|
||||
|
||||
const visitedA3 = new Set(data.countries.map(c => A2_TO_A3[c.code]).filter(Boolean))
|
||||
const countryMap = {}
|
||||
data.countries.forEach(c => { if (A2_TO_A3[c.code]) countryMap[A2_TO_A3[c.code]] = c })
|
||||
|
||||
// Preserve current map view
|
||||
const currentCenter = mapInstance.current.getCenter()
|
||||
const currentZoom = mapInstance.current.getZoom()
|
||||
|
||||
if (geoLayerRef.current) {
|
||||
mapInstance.current.removeLayer(geoLayerRef.current)
|
||||
}
|
||||
|
||||
// Generate deterministic color per country code
|
||||
const VISITED_COLORS = ['#6366f1','#ec4899','#14b8a6','#f97316','#8b5cf6','#ef4444','#3b82f6','#22c55e','#06b6d4','#f43f5e','#a855f7','#10b981','#0ea5e9','#e11d48','#0d9488','#7c3aed','#2563eb','#dc2626','#059669','#d946ef']
|
||||
// Assign colors in order of visit (by index in countries array) so no two neighbors share a color easily
|
||||
const visitedA3List = [...visitedA3]
|
||||
const colorMap = {}
|
||||
visitedA3List.forEach((a3, i) => { colorMap[a3] = VISITED_COLORS[i % VISITED_COLORS.length] })
|
||||
const colorForCode = (a3) => colorMap[a3] || VISITED_COLORS[0]
|
||||
|
||||
const canvasRenderer = L.canvas({ padding: 0.5, tolerance: 5 })
|
||||
|
||||
geoLayerRef.current = L.geoJSON(geoData, {
|
||||
renderer: canvasRenderer,
|
||||
interactive: true,
|
||||
bubblingMouseEvents: false,
|
||||
style: (feature) => {
|
||||
const a3 = feature.properties?.ADM0_A3 || feature.properties?.ISO_A3 || feature.properties?.['ISO3166-1-Alpha-3'] || feature.id
|
||||
const visited = visitedA3.has(a3)
|
||||
return {
|
||||
fillColor: visited ? colorForCode(a3) : (dark ? '#1e1e2e' : '#e2e8f0'),
|
||||
fillOpacity: visited ? 0.7 : 0.3,
|
||||
color: dark ? '#333' : '#cbd5e1',
|
||||
weight: 0.5,
|
||||
}
|
||||
},
|
||||
onEachFeature: (feature, layer) => {
|
||||
const a3 = feature.properties?.ADM0_A3 || feature.properties?.ISO_A3 || feature.properties?.['ISO3166-1-Alpha-3'] || feature.id
|
||||
const c = countryMap[a3]
|
||||
if (c) {
|
||||
country_layer_by_a2_ref.current[c.code] = layer
|
||||
const name = resolveName(c.code)
|
||||
const formatDate = (d) => { if (!d) return '—'; const dt = new Date(d); return dt.toLocaleDateString(getLocaleForLanguage(language), { month: 'short', year: 'numeric' }) }
|
||||
const tooltipHtml = `
|
||||
<div style="display:flex;flex-direction:column;gap:8px;min-width:160px">
|
||||
<div style="font-size:13px;font-weight:600;text-transform:uppercase;letter-spacing:0.1em;padding-bottom:6px;border-bottom:1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)'}">${name}</div>
|
||||
<div style="display:flex;gap:14px">
|
||||
<div><span style="font-size:16px;font-weight:800">${c.tripCount}</span> <span style="font-size:10px;opacity:0.5;text-transform:uppercase;letter-spacing:0.05em">${c.tripCount === 1 ? t('atlas.tripSingular') : t('atlas.tripPlural')}</span></div>
|
||||
<div><span style="font-size:16px;font-weight:800">${c.placeCount}</span> <span style="font-size:10px;opacity:0.5;text-transform:uppercase;letter-spacing:0.05em">${c.placeCount === 1 ? t('atlas.placeVisited') : t('atlas.placesVisited')}</span></div>
|
||||
</div>
|
||||
<div style="display:flex;gap:2px;border-top:1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)'};padding-top:8px">
|
||||
<div style="flex:1;display:flex;flex-direction:column;gap:2px">
|
||||
<span style="font-size:9px;text-transform:uppercase;letter-spacing:0.08em;opacity:0.4">${t('atlas.firstVisit')}</span>
|
||||
<span style="font-size:12px;font-weight:700">${formatDate(c.firstVisit)}</span>
|
||||
</div>
|
||||
<div style="flex:1;display:flex;flex-direction:column;gap:2px">
|
||||
<span style="font-size:9px;text-transform:uppercase;letter-spacing:0.08em;opacity:0.4">${t('atlas.lastVisitLabel')}</span>
|
||||
<span style="font-size:12px;font-weight:700">${formatDate(c.lastVisit)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>`
|
||||
layer.bindTooltip(tooltipHtml, {
|
||||
sticky: false, permanent: false, className: 'atlas-tooltip', direction: 'top', offset: [0, -10], opacity: 1
|
||||
})
|
||||
layer.on('click', () => {
|
||||
if (c.placeCount === 0 && c.tripCount === 0) {
|
||||
handleUnmarkCountry(c.code)
|
||||
}
|
||||
})
|
||||
layer.on('mouseover', (e) => {
|
||||
e.target.setStyle({ fillOpacity: 0.9, weight: 2, color: dark ? '#818cf8' : '#4f46e5' })
|
||||
})
|
||||
layer.on('mouseout', (e) => {
|
||||
geoLayerRef.current.resetStyle(e.target)
|
||||
})
|
||||
} else {
|
||||
// Unvisited country — allow clicking to mark as visited
|
||||
// Reverse lookup: find A2 code from A3, or use A3 directly
|
||||
const a3ToA2Entry = Object.entries(A2_TO_A3).find(([, v]) => v === a3)
|
||||
const isoA2 = feature.properties?.ISO_A2
|
||||
const countryCode = a3ToA2Entry ? a3ToA2Entry[0] : (isoA2 && isoA2 !== '-99' ? isoA2 : null)
|
||||
if (countryCode && countryCode !== '-99') {
|
||||
country_layer_by_a2_ref.current[countryCode] = layer
|
||||
const name = feature.properties?.NAME || feature.properties?.ADMIN || resolveName(countryCode)
|
||||
layer.bindTooltip(`<div style="font-size:12px;font-weight:600">${name}</div>`, {
|
||||
sticky: false, className: 'atlas-tooltip', direction: 'top', offset: [0, -10], opacity: 1
|
||||
})
|
||||
layer.on('click', () => handleMarkCountry(countryCode, name))
|
||||
layer.on('mouseover', (e) => {
|
||||
e.target.setStyle({ fillOpacity: 0.5, weight: 1.5, color: dark ? '#555' : '#94a3b8' })
|
||||
})
|
||||
layer.on('mouseout', (e) => {
|
||||
geoLayerRef.current.resetStyle(e.target)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
} as L.GeoJSONOptions & { renderer?: L.Renderer }).addTo(mapInstance.current)
|
||||
|
||||
// Restore map view after re-render
|
||||
mapInstance.current.setView(currentCenter, currentZoom, { animate: false })
|
||||
}, [geoData, data, dark])
|
||||
|
||||
// Render sub-national region layer (zoom >= 5)
|
||||
useEffect(() => {
|
||||
if (!mapInstance.current) return
|
||||
|
||||
// Remove existing region layer
|
||||
if (regionLayerRef.current) {
|
||||
mapInstance.current.removeLayer(regionLayerRef.current)
|
||||
regionLayerRef.current = null
|
||||
}
|
||||
|
||||
if (Object.keys(regionGeoCache.current).length === 0) return
|
||||
|
||||
// Build set of visited region codes and per-country name sets
|
||||
const visitedRegionCodes = new Set<string>()
|
||||
const visitedRegionNamesByCountry = new Map<string, Set<string>>()
|
||||
const regionPlaceCounts: Record<string, number> = {}
|
||||
for (const [countryCode, regions] of Object.entries(visitedRegions)) {
|
||||
const names = new Set<string>()
|
||||
for (const r of regions) {
|
||||
visitedRegionCodes.add(r.code)
|
||||
names.add(r.name.toLowerCase())
|
||||
regionPlaceCounts[r.code] = r.placeCount
|
||||
regionPlaceCounts[`${countryCode}:${r.name.toLowerCase()}`] = r.placeCount
|
||||
}
|
||||
visitedRegionNamesByCountry.set(countryCode, names)
|
||||
}
|
||||
|
||||
// Match feature by ISO code OR region name scoped to the feature's country
|
||||
const isVisitedFeature = (f: any) => {
|
||||
if (visitedRegionCodes.has(f.properties?.iso_3166_2)) return true
|
||||
const countryA2 = (f.properties?.iso_a2 || '').toUpperCase()
|
||||
const countryNames = visitedRegionNamesByCountry.get(countryA2)
|
||||
if (!countryNames) return false
|
||||
const name = (f.properties?.name || '').toLowerCase()
|
||||
if (countryNames.has(name)) return true
|
||||
const nameEn = (f.properties?.name_en || '').toLowerCase()
|
||||
if (nameEn && countryNames.has(nameEn)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
// Include ALL region features — visited ones get colored fill, unvisited get outline only
|
||||
const allFeatures: any[] = []
|
||||
for (const geo of Object.values(regionGeoCache.current)) {
|
||||
for (const f of geo.features) {
|
||||
allFeatures.push(f)
|
||||
}
|
||||
}
|
||||
if (allFeatures.length === 0) return
|
||||
|
||||
// Use same colors as country layer
|
||||
const VISITED_COLORS = ['#6366f1','#ec4899','#14b8a6','#f97316','#8b5cf6','#ef4444','#3b82f6','#22c55e','#06b6d4','#f43f5e','#a855f7','#10b981','#0ea5e9','#e11d48','#0d9488','#7c3aed','#2563eb','#dc2626','#059669','#d946ef']
|
||||
const countryA3Set = data ? data.countries.map(c => A2_TO_A3[c.code]).filter(Boolean) : []
|
||||
const countryColorMap: Record<string, string> = {}
|
||||
countryA3Set.forEach((a3, i) => { countryColorMap[a3] = VISITED_COLORS[i % VISITED_COLORS.length] })
|
||||
// Map country A2 code to country color
|
||||
const a2ColorMap: Record<string, string> = {}
|
||||
if (data) data.countries.forEach(c => { if (A2_TO_A3[c.code] && countryColorMap[A2_TO_A3[c.code]]) a2ColorMap[c.code] = countryColorMap[A2_TO_A3[c.code]] })
|
||||
|
||||
const mergedGeo = { type: 'FeatureCollection', features: allFeatures }
|
||||
|
||||
const svgRenderer = L.svg({ pane: 'regionPane' })
|
||||
|
||||
regionLayerRef.current = L.geoJSON(mergedGeo as any, {
|
||||
renderer: svgRenderer,
|
||||
interactive: true,
|
||||
pane: 'regionPane',
|
||||
style: (feature) => {
|
||||
const countryA2 = (feature?.properties?.iso_a2 || '').toUpperCase()
|
||||
const visited = isVisitedFeature(feature)
|
||||
return visited ? {
|
||||
fillColor: a2ColorMap[countryA2] || '#6366f1',
|
||||
fillOpacity: 0.85,
|
||||
color: dark ? '#888' : '#64748b',
|
||||
weight: 1.2,
|
||||
} : {
|
||||
fillColor: dark ? '#ffffff' : '#000000',
|
||||
fillOpacity: 0.03,
|
||||
color: dark ? '#555' : '#94a3b8',
|
||||
weight: 1,
|
||||
}
|
||||
},
|
||||
onEachFeature: (feature, layer) => {
|
||||
const regionName = feature?.properties?.name || ''
|
||||
const regionNameEn = feature?.properties?.name_en || ''
|
||||
const countryName = feature?.properties?.admin || ''
|
||||
const regionCode = feature?.properties?.iso_3166_2 || ''
|
||||
const countryA2 = (feature?.properties?.iso_a2 || '').toUpperCase()
|
||||
const visited = isVisitedFeature(feature)
|
||||
const count = regionPlaceCounts[regionCode] || regionPlaceCounts[`${countryA2}:${regionName.toLowerCase()}`] || regionPlaceCounts[`${countryA2}:${regionNameEn.toLowerCase()}`] || 0
|
||||
layer.on('click', () => {
|
||||
if (!countryA2) return
|
||||
if (visited) {
|
||||
const regionEntry = visitedRegions[countryA2]?.find(r => r.code === regionCode || r.name.toLowerCase() === regionNameEn.toLowerCase())
|
||||
if (regionEntry?.manuallyMarked) {
|
||||
setConfirmActionRef.current({
|
||||
type: 'unmark-region',
|
||||
code: countryA2,
|
||||
name: regionName,
|
||||
regionCode,
|
||||
countryName,
|
||||
})
|
||||
} else {
|
||||
loadCountryDetailRef.current(countryA2)
|
||||
}
|
||||
} else {
|
||||
setConfirmActionRef.current({
|
||||
type: 'choose-region',
|
||||
code: countryA2, // country A2 code — used for flag display
|
||||
name: regionName, // region name — shown as heading
|
||||
regionCode,
|
||||
countryName,
|
||||
})
|
||||
}
|
||||
})
|
||||
layer.on('mouseover', (e: any) => {
|
||||
e.target.setStyle(visited
|
||||
? { fillOpacity: 0.95, weight: 2, color: dark ? '#818cf8' : '#4f46e5' }
|
||||
: { fillOpacity: 0.15, fillColor: dark ? '#818cf8' : '#4f46e5', weight: 1.5, color: dark ? '#818cf8' : '#4f46e5' }
|
||||
)
|
||||
const tt = regionTooltipRef.current
|
||||
if (tt) {
|
||||
tt.style.display = 'block'
|
||||
tt.style.left = e.originalEvent.clientX + 12 + 'px'
|
||||
tt.style.top = e.originalEvent.clientY - 10 + 'px'
|
||||
tt.innerHTML = visited
|
||||
? `<div style="font-weight:600;margin-bottom:3px">${regionName}</div><div style="opacity:0.5;font-size:10px">${countryName}</div><div style="margin-top:5px;font-size:11px"><b>${count}</b> ${count === 1 ? 'place' : 'places'}</div>`
|
||||
: `<div style="font-weight:600;margin-bottom:3px">${regionName}</div><div style="opacity:0.5;font-size:10px">${countryName}</div>`
|
||||
}
|
||||
})
|
||||
layer.on('mousemove', (e: any) => {
|
||||
const tt = regionTooltipRef.current
|
||||
if (tt) { tt.style.left = e.originalEvent.clientX + 12 + 'px'; tt.style.top = e.originalEvent.clientY - 10 + 'px' }
|
||||
})
|
||||
layer.on('mouseout', (e: any) => {
|
||||
regionLayerRef.current?.resetStyle(e.target)
|
||||
const tt = regionTooltipRef.current
|
||||
if (tt) tt.style.display = 'none'
|
||||
})
|
||||
},
|
||||
} as L.GeoJSONOptions & { renderer?: L.Renderer })
|
||||
// Only add to map if currently in region mode — otherwise hold it ready for when user zooms in
|
||||
if (mapInstance.current.getZoom() >= 6) {
|
||||
regionLayerRef.current.addTo(mapInstance.current)
|
||||
}
|
||||
}, [regionGeoLoaded, visitedRegions, dark, t])
|
||||
|
||||
const handleMarkCountry = (code: string, name: string): void => {
|
||||
setConfirmAction({ type: 'choose', code, name })
|
||||
}
|
||||
handleMarkCountryRef.current = handleMarkCountry
|
||||
setConfirmActionRef.current = setConfirmAction
|
||||
|
||||
const handleUnmarkCountry = (code: string): void => {
|
||||
const country = data?.countries.find(c => c.code === code)
|
||||
setConfirmAction({ type: 'unmark', code, name: resolveName(code) })
|
||||
}
|
||||
|
||||
const select_country_from_search = (country_code: string): void => {
|
||||
const country_label = resolveName(country_code)
|
||||
set_atlas_country_search(country_label)
|
||||
set_atlas_country_open(false)
|
||||
set_atlas_country_results([])
|
||||
|
||||
const layer = country_layer_by_a2_ref.current[country_code]
|
||||
try {
|
||||
if (layer?.getBounds && mapInstance.current) {
|
||||
mapInstance.current.fitBounds(layer.getBounds(), { padding: [24, 24], animate: true, maxZoom: 6 })
|
||||
}
|
||||
} catch (e ) {
|
||||
console.error('Error fitting bounds', e)
|
||||
}
|
||||
setConfirmAction({ type: 'choose', code: country_code, name: country_label })
|
||||
}
|
||||
|
||||
const executeConfirmAction = async (): Promise<void> => {
|
||||
if (!confirmAction) return
|
||||
const { type, code } = confirmAction
|
||||
setConfirmAction(null)
|
||||
|
||||
// Update local state immediately (no API reload = no map re-render flash)
|
||||
if (type === 'mark') {
|
||||
apiClient.post(`/addons/atlas/country/${code}/mark`).catch(() => {})
|
||||
setData(prev => {
|
||||
if (!prev || prev.countries.find(c => c.code === code)) return prev
|
||||
return {
|
||||
...prev,
|
||||
countries: [...prev.countries, { code, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null }],
|
||||
stats: { ...prev.stats, totalCountries: prev.stats.totalCountries + 1 },
|
||||
}
|
||||
})
|
||||
} else {
|
||||
apiClient.delete(`/addons/atlas/country/${code}/mark`).catch(() => {})
|
||||
setSelectedCountry(null)
|
||||
setCountryDetail(null)
|
||||
setData(prev => {
|
||||
if (!prev) return prev
|
||||
const c = prev.countries.find(c => c.code === code)
|
||||
if (!c || c.placeCount > 0 || c.tripCount > 0) return prev
|
||||
return {
|
||||
...prev,
|
||||
countries: prev.countries.filter(c => c.code !== code),
|
||||
stats: { ...prev.stats, totalCountries: Math.max(0, prev.stats.totalCountries - 1) },
|
||||
}
|
||||
})
|
||||
setVisitedRegions(prev => {
|
||||
if (!prev[code]) return prev
|
||||
const next = { ...prev }
|
||||
delete next[code]
|
||||
return next
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleAddBucketItem = async (): Promise<void> => {
|
||||
if (!bucketForm.name.trim()) return
|
||||
try {
|
||||
const data: Record<string, unknown> = { name: bucketForm.name.trim() }
|
||||
if (bucketForm.notes.trim()) data.notes = bucketForm.notes.trim()
|
||||
if (bucketForm.lat && bucketForm.lng) { data.lat = parseFloat(bucketForm.lat); data.lng = parseFloat(bucketForm.lng) }
|
||||
const targetDate = bucketForm.target_date || (bucketPoiMonth > 0 && bucketPoiYear > 0 ? `${bucketPoiYear}-${String(bucketPoiMonth).padStart(2, '0')}` : null)
|
||||
if (targetDate) data.target_date = targetDate
|
||||
const r = await apiClient.post('/addons/atlas/bucket-list', data)
|
||||
setBucketList(prev => [r.data.item, ...prev])
|
||||
setBucketForm({ name: '', notes: '', lat: '', lng: '', target_date: '' })
|
||||
setBucketSearch(''); setBucketSearchResults([]); setBucketPoiMonth(0); setBucketPoiYear(0)
|
||||
setShowBucketAdd(false)
|
||||
} catch { /* */ }
|
||||
}
|
||||
|
||||
const handleDeleteBucketItem = async (id: number): Promise<void> => {
|
||||
try {
|
||||
await apiClient.delete(`/addons/atlas/bucket-list/${id}`)
|
||||
setBucketList(prev => prev.filter(i => i.id !== id))
|
||||
} catch { /* */ }
|
||||
}
|
||||
|
||||
const handleBucketPoiSearch = async () => {
|
||||
if (!bucketSearch.trim()) return
|
||||
setBucketSearching(true)
|
||||
try {
|
||||
const result = await mapsApi.search(bucketSearch, language)
|
||||
setBucketSearchResults(result.places || [])
|
||||
} catch {} finally { setBucketSearching(false) }
|
||||
}
|
||||
|
||||
const handleSelectBucketPoi = (result: any) => {
|
||||
const targetDate = bucketPoiMonth > 0 && bucketPoiYear > 0 ? `${bucketPoiYear}-${String(bucketPoiMonth).padStart(2, '0')}` : null
|
||||
setBucketForm({
|
||||
name: result.name || bucketSearch,
|
||||
notes: '',
|
||||
lat: String(result.lat || ''),
|
||||
lng: String(result.lng || ''),
|
||||
target_date: targetDate || '',
|
||||
})
|
||||
setBucketSearchResults([])
|
||||
setBucketSearch('')
|
||||
}
|
||||
|
||||
// Render bucket list markers on map
|
||||
useEffect(() => {
|
||||
if (!mapInstance.current) return
|
||||
if (bucketMarkersRef.current) {
|
||||
mapInstance.current.removeLayer(bucketMarkersRef.current)
|
||||
}
|
||||
if (bucketList.length === 0) return
|
||||
const markers = bucketList.filter(b => b.lat && b.lng).map(b => {
|
||||
const icon = L.divIcon({
|
||||
className: '',
|
||||
html: `<div style="width:28px;height:28px;border-radius:50%;background:rgba(251,191,36,0.9);display:flex;align-items:center;justify-content:center;box-shadow:0 2px 8px rgba(0,0,0,0.3);border:2px solid white"><svg width="14" height="14" viewBox="0 0 24 24" fill="white" stroke="none"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg></div>`,
|
||||
iconSize: [28, 28],
|
||||
iconAnchor: [14, 14],
|
||||
})
|
||||
return L.marker([b.lat!, b.lng!], { icon }).bindTooltip(
|
||||
`<div style="font-size:12px;font-weight:600">${b.name}</div>${b.notes ? `<div style="font-size:10px;opacity:0.7;margin-top:2px">${b.notes}</div>` : ''}`,
|
||||
{ className: 'atlas-tooltip', direction: 'top', offset: [0, -14] }
|
||||
)
|
||||
})
|
||||
bucketMarkersRef.current = L.layerGroup(markers).addTo(mapInstance.current)
|
||||
}, [bucketList])
|
||||
|
||||
const loadCountryDetail = async (code: string): Promise<void> => {
|
||||
setSelectedCountry(code)
|
||||
try {
|
||||
const r = await apiClient.get(`/addons/atlas/country/${code}`)
|
||||
setCountryDetail(r.data)
|
||||
} catch { /* */ }
|
||||
}
|
||||
loadCountryDetailRef.current = loadCountryDetail
|
||||
|
||||
const stats = data?.stats || { totalTrips: 0, totalPlaces: 0, totalCountries: 0, totalDays: 0 }
|
||||
const countries = data?.countries || []
|
||||
|
||||
return {
|
||||
t, language, navigate, resolveName, dark, loading,
|
||||
mapRef, regionTooltipRef, panelRef, glareRef, borderGlareRef,
|
||||
handlePanelMouseMove, handlePanelMouseLeave,
|
||||
data, setData, stats, countries, selectedCountry, countryDetail,
|
||||
loadCountryDetail, handleUnmarkCountry, select_country_from_search,
|
||||
visitedRegions, setVisitedRegions,
|
||||
atlas_country_search, set_atlas_country_search,
|
||||
atlas_country_results, set_atlas_country_results,
|
||||
atlas_country_open, set_atlas_country_open, atlas_country_options,
|
||||
confirmAction, setConfirmAction, executeConfirmAction,
|
||||
bucketMonth, setBucketMonth, bucketYear, setBucketYear,
|
||||
bucketList, setBucketList, bucketTab, setBucketTab,
|
||||
showBucketAdd, setShowBucketAdd, bucketForm, setBucketForm,
|
||||
handleAddBucketItem, handleDeleteBucketItem, handleBucketPoiSearch, handleSelectBucketPoi,
|
||||
bucketSearchResults, setBucketSearchResults,
|
||||
bucketPoiMonth, setBucketPoiMonth, bucketPoiYear, setBucketPoiYear,
|
||||
bucketSearching, bucketSearch, setBucketSearch,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Dashboard data model + pure helpers — shared by the data hook (useDashboard)
|
||||
* and the presentational components in DashboardPage. Kept free of React/IO so
|
||||
* both sides can import it without a cycle. Part of the FE "page = wiring
|
||||
* container + data hook" convention (see dashboard/README.md).
|
||||
*/
|
||||
|
||||
import type { Trip } from '../../types'
|
||||
|
||||
// The dashboard works with the canonical Trip shape returned by the list/get
|
||||
// endpoints (it already carries the computed day_count/place_count/is_owner/
|
||||
// owner_username/shared_count fields). Kept as a named alias so the existing
|
||||
// imports stay stable.
|
||||
export type DashboardTrip = Trip
|
||||
|
||||
export interface Member { id: number; username: string; avatar_url?: string | null }
|
||||
export interface Place {
|
||||
id: number; name: string; image_url: string | null; lat: number | null; lng: number | null
|
||||
google_place_id: string | null; osm_id: string | null
|
||||
category_color?: string | null; category_icon?: string | null
|
||||
}
|
||||
export interface HeroBundle { members: Member[]; places: Place[] }
|
||||
export interface TravelStats { totalTrips?: number; totalDays?: number; totalPlaces?: number; totalDistanceKm?: number; countries?: string[] }
|
||||
export interface UpcomingReservation {
|
||||
id: number; trip_id: number; title: string; type: string
|
||||
reservation_time?: string | null; day_date?: string | null
|
||||
location?: string | null; place_name?: string | null; trip_title?: string | null
|
||||
}
|
||||
|
||||
export const MS_PER_DAY = 86400000
|
||||
|
||||
export 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.getTime() - today.getTime()) / MS_PER_DAY)
|
||||
}
|
||||
|
||||
export function getTripStatus(trip: DashboardTrip): 'ongoing' | 'today' | 'tomorrow' | 'future' | 'past' | 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)
|
||||
if (until === null) return null
|
||||
if (until === 0) return 'today'
|
||||
if (until === 1) return 'tomorrow'
|
||||
if (until > 1) return 'future'
|
||||
return 'past'
|
||||
}
|
||||
|
||||
export function sortTrips(trips: DashboardTrip[]): DashboardTrip[] {
|
||||
const today = new Date().toISOString().split('T')[0]
|
||||
const rank = (t: DashboardTrip) => {
|
||||
if (t.start_date && t.end_date && t.start_date <= today && t.end_date >= today) return 0
|
||||
if (t.start_date && t.start_date >= today) return 1
|
||||
return 2
|
||||
}
|
||||
return [...trips].sort((a, b) => {
|
||||
const ra = rank(a), rb = rank(b)
|
||||
if (ra !== rb) return ra - rb
|
||||
const ad = a.start_date || '', bd = b.start_date || ''
|
||||
if (ra <= 1) return ad.localeCompare(bd)
|
||||
return bd.localeCompare(ad)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { tripsApi, authApi, reservationsApi } from '../../api/client'
|
||||
import { tripRepo } from '../../repo/tripRepo'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../../components/shared/Toast'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import type { TripCreateRequest } from '@trek/shared'
|
||||
import {
|
||||
type DashboardTrip,
|
||||
type TravelStats,
|
||||
type UpcomingReservation,
|
||||
type HeroBundle,
|
||||
getTripStatus,
|
||||
sortTrips,
|
||||
} from './dashboardModel'
|
||||
|
||||
/**
|
||||
* Dashboard data hook — owns every bit of the page's state, data loading and
|
||||
* mutations (trip CRUD, archive/copy, travel stats, upcoming reservations,
|
||||
* the spotlight hero bundle) and exposes derived values + handlers. The
|
||||
* DashboardPage component is a pure wiring container that renders what this
|
||||
* returns. Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useDashboard() {
|
||||
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 [viewMode, setViewMode] = useState<'grid' | 'list'>(() => (localStorage.getItem('trek_dashboard_view') as 'grid' | 'list') || 'grid')
|
||||
const [deleteTrip, setDeleteTrip] = useState<DashboardTrip | null>(null)
|
||||
const [copyTrip, setCopyTrip] = useState<DashboardTrip | null>(null)
|
||||
const [tripFilter, setTripFilter] = useState<'planned' | 'archive' | 'completed'>('planned')
|
||||
|
||||
const [stats, setStats] = useState<TravelStats | null>(null)
|
||||
const [upcoming, setUpcoming] = useState<UpcomingReservation[]>([])
|
||||
const [heroBundle, setHeroBundle] = useState<HeroBundle | null>(null)
|
||||
|
||||
const navigate = useNavigate()
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const toast = useToast()
|
||||
const { t, locale } = useTranslation()
|
||||
const { demoMode } = useAuthStore()
|
||||
|
||||
const toggleViewMode = () => {
|
||||
setViewMode(prev => {
|
||||
const next = prev === 'grid' ? 'list' : 'grid'
|
||||
localStorage.setItem('trek_dashboard_view', next)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (searchParams.get('create') === '1') {
|
||||
setShowForm(true)
|
||||
setSearchParams({}, { replace: true })
|
||||
}
|
||||
}, [searchParams])
|
||||
|
||||
useEffect(() => { loadTrips() }, [])
|
||||
|
||||
// Travel stats + upcoming reservations power the atlas row and the sidebar.
|
||||
// Both are best-effort: a failure just leaves that section empty.
|
||||
useEffect(() => {
|
||||
authApi.travelStats().then(setStats).catch(() => {})
|
||||
reservationsApi.upcoming().then((r: { reservations: UpcomingReservation[] }) => setUpcoming(r.reservations || [])).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const loadTrips = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const { trips, archivedTrips } = await tripRepo.list()
|
||||
setTrips(sortTrips(trips))
|
||||
setArchivedTrips(sortTrips(archivedTrips))
|
||||
} catch {
|
||||
toast.error(t('dashboard.toast.loadError'))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const today = new Date().toISOString().split('T')[0]
|
||||
const spotlight = trips.find(t => t.start_date && t.end_date && t.start_date <= today && t.end_date >= today)
|
||||
|| trips.find(t => t.start_date && t.start_date >= today)
|
||||
|| trips[0]
|
||||
|| null
|
||||
const rest = spotlight ? trips.filter(t => t.id !== spotlight.id) : trips
|
||||
|
||||
// Pull the spotlight trip's members + places so the boarding pass can show
|
||||
// real buddies and place thumbnails instead of placeholders.
|
||||
useEffect(() => {
|
||||
if (!spotlight) { setHeroBundle(null); return }
|
||||
let cancelled = false
|
||||
tripsApi.bundle(spotlight.id)
|
||||
.then((b: HeroBundle) => { if (!cancelled) setHeroBundle({ members: b.members || [], places: b.places || [] }) })
|
||||
.catch(() => { if (!cancelled) setHeroBundle(null) })
|
||||
return () => { cancelled = true }
|
||||
}, [spotlight?.id])
|
||||
|
||||
const handleCreate = async (tripData: TripCreateRequest) => {
|
||||
try {
|
||||
const data = await tripsApi.create(tripData)
|
||||
setTrips(prev => sortTrips([data.trip, ...prev]))
|
||||
toast.success(t('dashboard.toast.created'))
|
||||
return data
|
||||
} catch (err: unknown) {
|
||||
throw new Error(getApiErrorMessage(err, t('dashboard.toast.createError')))
|
||||
}
|
||||
}
|
||||
|
||||
const handleUpdate = async (tripData: TripCreateRequest) => {
|
||||
if (!editingTrip) return
|
||||
try {
|
||||
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: unknown) {
|
||||
throw new Error(getApiErrorMessage(err, t('dashboard.toast.updateError')))
|
||||
}
|
||||
}
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!deleteTrip) return
|
||||
try {
|
||||
await tripsApi.delete(deleteTrip.id)
|
||||
setTrips(prev => prev.filter(t => t.id !== deleteTrip.id))
|
||||
setArchivedTrips(prev => prev.filter(t => t.id !== deleteTrip.id))
|
||||
toast.success(t('dashboard.toast.deleted'))
|
||||
} catch {
|
||||
toast.error(t('dashboard.toast.deleteError'))
|
||||
}
|
||||
setDeleteTrip(null)
|
||||
}
|
||||
|
||||
const handleArchive = async (id: number) => {
|
||||
try {
|
||||
const data = await tripsApi.archive(id)
|
||||
setTrips(prev => prev.filter(t => t.id !== id))
|
||||
setArchivedTrips(prev => sortTrips([data.trip, ...prev]))
|
||||
toast.success(t('dashboard.toast.archived'))
|
||||
} catch {
|
||||
toast.error(t('dashboard.toast.archiveError'))
|
||||
}
|
||||
}
|
||||
|
||||
const handleUnarchive = async (id: number) => {
|
||||
try {
|
||||
const data = await tripsApi.unarchive(id)
|
||||
setArchivedTrips(prev => prev.filter(t => t.id !== id))
|
||||
setTrips(prev => sortTrips([data.trip, ...prev]))
|
||||
toast.success(t('dashboard.toast.restored'))
|
||||
} catch {
|
||||
toast.error(t('dashboard.toast.restoreError'))
|
||||
}
|
||||
}
|
||||
|
||||
const confirmCopy = async () => {
|
||||
if (!copyTrip) return
|
||||
try {
|
||||
const data = await tripsApi.copy(copyTrip.id, { title: `${copyTrip.title} (${t('dashboard.copySuffix')})` })
|
||||
setTrips(prev => sortTrips([data.trip, ...prev]))
|
||||
toast.success(t('dashboard.toast.copied'))
|
||||
} catch {
|
||||
toast.error(t('dashboard.toast.copyError'))
|
||||
}
|
||||
setCopyTrip(null)
|
||||
}
|
||||
|
||||
const gridTrips = tripFilter === 'archive' ? archivedTrips
|
||||
: tripFilter === 'completed' ? rest.filter(t => getTripStatus(t) === 'past')
|
||||
: rest.filter(t => getTripStatus(t) !== 'past')
|
||||
|
||||
return {
|
||||
// cross-cutting
|
||||
demoMode, locale, t, navigate,
|
||||
// data + derived
|
||||
spotlight, heroBundle, stats, upcoming, gridTrips, isLoading,
|
||||
// ui state
|
||||
tripFilter, setTripFilter, viewMode, toggleViewMode,
|
||||
showForm, setShowForm, editingTrip, setEditingTrip,
|
||||
deleteTrip, setDeleteTrip, copyTrip, setCopyTrip, setTrips,
|
||||
// actions
|
||||
handleCreate, handleUpdate, confirmDelete, handleArchive, handleUnarchive, confirmCopy,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useParams, useNavigate } from 'react-router-dom'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { tripRepo } from '../../repo/tripRepo'
|
||||
import { placeRepo } from '../../repo/placeRepo'
|
||||
import type { Trip, Place, TripFile } from '../../types'
|
||||
|
||||
/**
|
||||
* Files page data hook — owns the trip/places load, the file sync from the trip
|
||||
* store and the upload/delete handlers. FilesPage is a pure wiring container.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useFiles() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const tripId = Number(id)
|
||||
const navigate = useNavigate()
|
||||
const tripStore = useTripStore()
|
||||
|
||||
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 (): Promise<void> => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const [tripData, placesData] = await Promise.all([
|
||||
tripRepo.get(tripId),
|
||||
placeRepo.list(tripId),
|
||||
])
|
||||
setTrip(tripData.trip)
|
||||
setPlaces(placesData.places)
|
||||
await tripStore.loadFiles(tripId)
|
||||
} catch (err: unknown) {
|
||||
navigate('/dashboard')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setFiles(tripStore.files)
|
||||
}, [tripStore.files])
|
||||
|
||||
const handleUpload = async (formData: FormData): Promise<void> => {
|
||||
await tripStore.addFile(tripId, formData)
|
||||
}
|
||||
|
||||
const handleDelete = async (fileId: number): Promise<void> => {
|
||||
await tripStore.deleteFile(tripId, fileId)
|
||||
}
|
||||
|
||||
return { tripId, navigate, trip, places, files, isLoading, handleUpload, handleDelete }
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useState, useEffect, type FormEvent } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { authApi } from '../../api/client'
|
||||
|
||||
/**
|
||||
* Forgot-password data hook — owns the form state, the SMTP-availability probe
|
||||
* and the enumeration-safe submit. ForgotPasswordPage is a pure wiring
|
||||
* container that renders what this returns. Behaviour is identical to the
|
||||
* previous in-component logic.
|
||||
*/
|
||||
export function useForgotPassword() {
|
||||
const navigate = useNavigate()
|
||||
const [email, setEmail] = useState('')
|
||||
const [submitted, setSubmitted] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [smtpConfigured, setSmtpConfigured] = useState<boolean | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Probe whether SMTP is configured so we can warn the user up-front that the
|
||||
// link will land in the server console instead of their inbox. Null while
|
||||
// pending — hint is hidden until we know.
|
||||
authApi.getAppConfig?.()
|
||||
.then((cfg: { available_channels?: { email?: boolean } } | null) => {
|
||||
setSmtpConfigured(!!cfg?.available_channels?.email)
|
||||
})
|
||||
.catch(() => setSmtpConfigured(null))
|
||||
}, [])
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (isLoading) return
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await authApi.forgotPassword({ email: email.trim() })
|
||||
} catch {
|
||||
// Enumeration-safe: success UX regardless of server outcome.
|
||||
}
|
||||
setSubmitted(true)
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit }
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useInAppNotificationStore } from '../../store/inAppNotificationStore.ts'
|
||||
|
||||
/**
|
||||
* In-app notifications data hook — owns the store wiring, the unread-only
|
||||
* filter, the initial + filter-change fetches and the infinite-scroll observer.
|
||||
* InAppNotificationsPage is a pure wiring container. Behaviour is identical to
|
||||
* the previous in-component logic.
|
||||
*/
|
||||
export function useInAppNotifications() {
|
||||
const { notifications, unreadCount, total, isLoading, hasMore, fetchNotifications, markAllRead, deleteAll } = useInAppNotificationStore()
|
||||
const [unreadOnly, setUnreadOnly] = useState(false)
|
||||
const loaderRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
fetchNotifications(true)
|
||||
}, [])
|
||||
|
||||
// Reload when filter changes
|
||||
useEffect(() => {
|
||||
// We need to fetch with the unreadOnly filter — re-fetch from scratch
|
||||
// The store fetchNotifications doesn't take a filter param directly,
|
||||
// so we use the API directly for filtered view via a side channel.
|
||||
// For now, reset and fetch — store always loads all, filter is client-side.
|
||||
fetchNotifications(true)
|
||||
}, [unreadOnly])
|
||||
|
||||
// Infinite scroll
|
||||
useEffect(() => {
|
||||
if (!loaderRef.current) return
|
||||
const observer = new IntersectionObserver(entries => {
|
||||
if (entries[0].isIntersecting && hasMore && !isLoading) {
|
||||
fetchNotifications(false)
|
||||
}
|
||||
}, { threshold: 0.1 })
|
||||
observer.observe(loaderRef.current)
|
||||
return () => observer.disconnect()
|
||||
}, [hasMore, isLoading])
|
||||
|
||||
const displayed = unreadOnly ? notifications.filter(n => !n.is_read) : notifications
|
||||
|
||||
return {
|
||||
notifications, unreadCount, total, isLoading, hasMore,
|
||||
unreadOnly, setUnreadOnly, loaderRef, displayed,
|
||||
markAllRead, deleteAll,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useEffect, useState, useMemo, useRef } from 'react'
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { useJourneyStore } from '../../store/journeyStore'
|
||||
import { journeyApi } from '../../api/client'
|
||||
import { useToast } from '../../components/shared/Toast'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { computeJourneyLifecycle } from '../../utils/journeyLifecycle'
|
||||
|
||||
/**
|
||||
* Journey list page logic — owns the journey store load, the create-journey
|
||||
* modal (title, available trips, selection), the search box, the trip
|
||||
* suggestion banner and the active/filtered journey derivations. JourneyPage
|
||||
* stays a wiring container around its hero/grid/modal JSX and JourneyCard.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useJourney() {
|
||||
const navigate = useNavigate()
|
||||
const toast = useToast()
|
||||
const { t } = useTranslation()
|
||||
const { journeys, loading, loadJourneys, createJourney } = useJourneyStore()
|
||||
|
||||
const [showCreate, setShowCreate] = useState(false)
|
||||
const [newTitle, setNewTitle] = useState('')
|
||||
const [availableTrips, setAvailableTrips] = useState<any[]>([])
|
||||
const [selectedTripIds, setSelectedTripIds] = useState<Set<number>>(new Set())
|
||||
const [searchOpen, setSearchOpen] = useState(false)
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const searchInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// suggestion
|
||||
const [suggestions, setSuggestions] = useState<any[]>([])
|
||||
const [dismissedSuggestions, setDismissedSuggestions] = useState<Set<number>>(new Set())
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
|
||||
useEffect(() => {
|
||||
loadJourneys()
|
||||
journeyApi.suggestions().then(d => setSuggestions(d.trips || [])).catch(() => {})
|
||||
}, [])
|
||||
|
||||
// The bottom-nav "+" opens the new-journey modal via ?create=1.
|
||||
useEffect(() => {
|
||||
if (searchParams.get('create') === '1') {
|
||||
openCreateModal()
|
||||
setSearchParams(p => { p.delete('create'); return p }, { replace: true })
|
||||
}
|
||||
}, [searchParams])
|
||||
|
||||
const activeSuggestion = suggestions.find(s => !dismissedSuggestions.has(s.id))
|
||||
|
||||
const activeJourney = useMemo(() => {
|
||||
if (searchQuery.trim()) return null
|
||||
return journeys.find(j => {
|
||||
const j2 = j as any
|
||||
return computeJourneyLifecycle(j.status, j2.trip_date_min, j2.trip_date_max) === 'live'
|
||||
}) || null
|
||||
}, [journeys, searchQuery])
|
||||
|
||||
const filteredJourneys = useMemo(() => {
|
||||
const q = searchQuery.trim().toLowerCase()
|
||||
if (!q) return journeys.filter(j => j.id !== activeJourney?.id)
|
||||
return journeys.filter(j => {
|
||||
const inTitle = j.title.toLowerCase().includes(q)
|
||||
const inSubtitle = j.subtitle?.toLowerCase().includes(q) ?? false
|
||||
return inTitle || inSubtitle
|
||||
})
|
||||
}, [journeys, activeJourney, searchQuery])
|
||||
|
||||
const openCreateModal = async (preSelectedTripId?: number) => {
|
||||
setShowCreate(true)
|
||||
setNewTitle('')
|
||||
const initial = new Set<number>()
|
||||
if (preSelectedTripId) initial.add(preSelectedTripId)
|
||||
setSelectedTripIds(initial)
|
||||
try {
|
||||
const data = await journeyApi.availableTrips()
|
||||
setAvailableTrips(data.trips || [])
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!newTitle.trim()) return
|
||||
try {
|
||||
const j = await createJourney({
|
||||
title: newTitle.trim(),
|
||||
trip_ids: [...selectedTripIds],
|
||||
})
|
||||
setShowCreate(false)
|
||||
navigate(`/journey/${j.id}`)
|
||||
} catch {
|
||||
toast.error(t('journey.createError'))
|
||||
}
|
||||
}
|
||||
|
||||
const totalPlaces = useMemo(() => {
|
||||
return availableTrips.filter(t => selectedTripIds.has(t.id)).reduce((sum: number, t: any) => sum + (t.place_count || 0), 0)
|
||||
}, [availableTrips, selectedTripIds])
|
||||
|
||||
return {
|
||||
navigate, journeys, loading,
|
||||
showCreate, setShowCreate, newTitle, setNewTitle,
|
||||
availableTrips, selectedTripIds, setSelectedTripIds,
|
||||
searchOpen, setSearchOpen, searchQuery, setSearchQuery, searchInputRef,
|
||||
activeSuggestion, setDismissedSuggestions,
|
||||
activeJourney, filteredJourneys,
|
||||
openCreateModal, handleCreate, totalPlaces,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
Laugh, Smile, Meh, Frown,
|
||||
Sun, CloudSun, Cloud, CloudRain, CloudLightning, Snowflake,
|
||||
} from 'lucide-react'
|
||||
|
||||
export const GRADIENTS = [
|
||||
'linear-gradient(135deg, #0F172A 0%, #6366F1 45%, #EC4899 100%)',
|
||||
'linear-gradient(135deg, #1E293B 0%, #7C3AED 50%, #F59E0B 100%)',
|
||||
'linear-gradient(135deg, #134E5E 0%, #71B280 100%)',
|
||||
'linear-gradient(135deg, #2D1B69 0%, #11998E 100%)',
|
||||
'linear-gradient(135deg, #4B134F 0%, #C94B4B 100%)',
|
||||
'linear-gradient(135deg, #373B44 0%, #4286F4 100%)',
|
||||
]
|
||||
|
||||
export const MOOD_CONFIG: Record<string, { bg: string; text: string; icon: typeof Laugh; label: string }> = {
|
||||
amazing: { bg: '#FDF2F8', text: '#BE185D', icon: Laugh, label: 'journey.mood.amazing' },
|
||||
good: { bg: '#FFFBEB', text: '#B45309', icon: Smile, label: 'journey.mood.good' },
|
||||
neutral: { bg: '#F4F4F5', text: '#3F3F46', icon: Meh, label: 'journey.mood.neutral' },
|
||||
rough: { bg: '#F5F3FF', text: '#6D28D9', icon: Frown, label: 'journey.mood.rough' },
|
||||
}
|
||||
|
||||
export const WEATHER_CONFIG: Record<string, { icon: typeof Sun; label: string }> = {
|
||||
sunny: { icon: Sun, label: 'journey.weather.sunny' },
|
||||
partly: { icon: CloudSun, label: 'journey.weather.partly' },
|
||||
cloudy: { icon: Cloud, label: 'journey.weather.cloudy' },
|
||||
rainy: { icon: CloudRain, label: 'journey.weather.rainy' },
|
||||
stormy: { icon: CloudLightning, label: 'journey.weather.stormy' },
|
||||
cold: { icon: Snowflake, label: 'journey.weather.cold' },
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { JourneyEntry } from '../../store/journeyStore'
|
||||
import { GRADIENTS } from './JourneyDetailPage.constants'
|
||||
|
||||
export function pickGradient(id: number): string {
|
||||
return GRADIENTS[id % GRADIENTS.length]
|
||||
}
|
||||
|
||||
export function groupByDate(entries: JourneyEntry[]): Map<string, JourneyEntry[]> {
|
||||
const groups = new Map<string, JourneyEntry[]>()
|
||||
for (const e of entries) {
|
||||
const d = e.entry_date
|
||||
if (!groups.has(d)) groups.set(d, [])
|
||||
groups.get(d)!.push(e)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
export function formatDate(d: string, locale?: string): { weekday: string; month: string; day: number } {
|
||||
const date = new Date(d + 'T00:00:00')
|
||||
// Pass the app's selected locale so weekday/month follow the UI language
|
||||
// instead of the browser's navigator.language.
|
||||
return {
|
||||
weekday: date.toLocaleDateString(locale, { weekday: 'long' }),
|
||||
month: date.toLocaleDateString(locale, { month: 'long' }),
|
||||
day: date.getDate(),
|
||||
}
|
||||
}
|
||||
|
||||
export function photoUrl(p: { photo_id: number }, size: 'thumbnail' | 'original' = 'thumbnail'): string {
|
||||
return `/api/photos/${p.photo_id}/${size}`
|
||||
}
|
||||
|
||||
export function groupPhotosByDate(photos: any[]): { date: string; label: string; assets: any[] }[] {
|
||||
const map = new Map<string, any[]>()
|
||||
for (const asset of photos) {
|
||||
const key = asset.takenAt ? asset.takenAt.slice(0, 10) : '__unknown__'
|
||||
if (!map.has(key)) map.set(key, [])
|
||||
map.get(key)!.push(asset)
|
||||
}
|
||||
return [...map.entries()].map(([date, assets]) => ({
|
||||
date,
|
||||
label: date === '__unknown__'
|
||||
? 'Unknown date'
|
||||
: new Date(date + 'T00:00:00').toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' }),
|
||||
assets,
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
import { useEffect, useState, useRef, useCallback, useMemo } from 'react'
|
||||
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { useJourneyStore } from '../../store/journeyStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { addListener, removeListener } from '../../api/websocket'
|
||||
import { DAY_COLORS } from '../../components/Journey/dayColors'
|
||||
import type { JourneyMapAutoHandle as JourneyMapHandle } from '../../components/Journey/JourneyMapAuto'
|
||||
import { useToast } from '../../components/shared/Toast'
|
||||
import { useIsMobile } from '../../hooks/useIsMobile'
|
||||
import type { JourneyEntry } from '../../store/journeyStore'
|
||||
|
||||
/**
|
||||
* Journey detail page logic — owns the journey load + WebSocket live sync, the
|
||||
* timeline/gallery view state, the entry editor/viewer/delete/lightbox dialogs,
|
||||
* the scroll-synced sticky map (marker click + located-entry tracking) and the
|
||||
* map/trip-date derivations. JourneyDetailPage stays a wiring container around
|
||||
* its large two-pane JSX and many presentational sub-components.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useJourneyDetail() {
|
||||
const { id } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const toast = useToast()
|
||||
const { t, locale } = useTranslation()
|
||||
const { current, loading, notFound, loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto } = useJourneyStore()
|
||||
const mapRef = useRef<JourneyMapHandle>(null)
|
||||
const fullMapRef = useRef<JourneyMapHandle>(null)
|
||||
const [activeLocationId, setActiveLocationId] = useState<string | null>(null)
|
||||
|
||||
const isMobile = useIsMobile()
|
||||
// Role-based permissions (server-provided via my_role). Fall back to
|
||||
// "owner" when the field isn't present yet (legacy responses) so behavior
|
||||
// matches the pre-permissions era.
|
||||
const myRole = (current as any)?.my_role ?? 'owner'
|
||||
const canEditEntries = myRole === 'owner' || myRole === 'editor'
|
||||
const canEditJourney = myRole === 'owner'
|
||||
const [view, setView] = useState<'timeline' | 'gallery'>('timeline')
|
||||
const [activeEntryId, setActiveEntryId] = useState<string | null>(null)
|
||||
const feedRef = useRef<HTMLDivElement>(null)
|
||||
const [viewingEntry, setViewingEntry] = useState<JourneyEntry | null>(null)
|
||||
const [editingEntry, setEditingEntry] = useState<JourneyEntry | null>(null)
|
||||
const [lightbox, setLightbox] = useState<{ photos: { id: number; src: string; caption?: string | null; provider?: string; asset_id?: string | null; owner_id?: number | null }[]; index: number } | null>(null)
|
||||
const [deleteTarget, setDeleteTarget] = useState<JourneyEntry | null>(null)
|
||||
const [showInvite, setShowInvite] = useState(false)
|
||||
const [showAddTrip, setShowAddTrip] = useState(false)
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
|
||||
// The bottom-nav "+" starts a new entry via ?create=entry.
|
||||
useEffect(() => {
|
||||
if (searchParams.get('create') === 'entry' && current && canEditEntries) {
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
setEditingEntry({ id: 0, journey_id: current.id, author_id: 0, type: 'entry', entry_date: today, visibility: 'private', sort_order: 0, photos: [], created_at: 0, updated_at: 0 } as JourneyEntry)
|
||||
setSearchParams(p => { p.delete('create'); return p }, { replace: true })
|
||||
}
|
||||
}, [searchParams, current, canEditEntries])
|
||||
const [unlinkTrip, setUnlinkTrip] = useState<{ trip_id: number; title: string } | null>(null)
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
const [hideSkeletons, setHideSkeletons] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (id) loadJourney(Number(id)).catch(() => {})
|
||||
}, [id])
|
||||
|
||||
useEffect(() => {
|
||||
if (current?.hide_skeletons !== undefined) setHideSkeletons(current.hide_skeletons)
|
||||
}, [current?.hide_skeletons])
|
||||
|
||||
useEffect(() => {
|
||||
if (notFound) {
|
||||
toast.error(t('journey.notFound'))
|
||||
navigate('/journey')
|
||||
}
|
||||
}, [notFound])
|
||||
|
||||
// WebSocket real-time updates
|
||||
useEffect(() => {
|
||||
if (!id) return
|
||||
const journeyId = Number(id)
|
||||
const handler = (event: Record<string, unknown>) => {
|
||||
const type = event.type as string
|
||||
if (!type?.startsWith('journey:')) return
|
||||
if (event.journeyId !== journeyId) return
|
||||
// reload journey data on any change from other contributors
|
||||
loadJourney(journeyId)
|
||||
}
|
||||
addListener(handler)
|
||||
return () => removeListener(handler)
|
||||
}, [id])
|
||||
|
||||
// scroll sync with map — the sticky map on the right follows whichever
|
||||
// entry the user is currently reading in the feed on the left. We use
|
||||
// scroll position (not IntersectionObserver) because short text-only
|
||||
// entries pass through any IO band too quickly to reliably register.
|
||||
const rafRef = useRef<number | null>(null)
|
||||
const scrollCleanupRef = useRef<(() => void) | null>(null)
|
||||
// Suppress scroll-sync updates while a programmatic smooth-scroll is
|
||||
// running (triggered by a marker click). The scroll-progress reference
|
||||
// line doesn't align with `scrollIntoView({ block: 'center' })`, so the
|
||||
// sync would otherwise pick random entries as the scroll animates past
|
||||
// them and end up nowhere near the clicked marker.
|
||||
const suppressScrollSyncRef = useRef(false)
|
||||
const suppressTimerRef = useRef<number | null>(null)
|
||||
const setupScrollSync = useCallback(() => {
|
||||
scrollCleanupRef.current?.()
|
||||
const feed = feedRef.current
|
||||
if (!feed) return
|
||||
|
||||
const commitWinner = () => {
|
||||
if (suppressScrollSyncRef.current) return
|
||||
const nodes = document.querySelectorAll('[data-entry-id]')
|
||||
if (nodes.length === 0) return
|
||||
const feedRect = feed.getBoundingClientRect()
|
||||
// Reference line tracks scroll progress — at the top of the feed
|
||||
// it sits at the top edge; at the bottom it sits at the bottom
|
||||
// edge. This keeps every entry passing through the line exactly
|
||||
// once even when they're too short to cross a static line before
|
||||
// the feed runs out of scroll.
|
||||
const maxScroll = feed.scrollHeight - feed.clientHeight
|
||||
const progress = maxScroll > 0 ? feed.scrollTop / maxScroll : 0
|
||||
const referenceY = feedRect.top + feedRect.height * progress
|
||||
let lastPast: { id: string; top: number } | null = null
|
||||
let firstAhead: { id: string; top: number } | null = null
|
||||
nodes.forEach(el => {
|
||||
const entryId = el.getAttribute('data-entry-id')
|
||||
if (!entryId) return
|
||||
const top = el.getBoundingClientRect().top
|
||||
if (top <= referenceY) {
|
||||
if (!lastPast || top > lastPast.top) lastPast = { id: entryId, top }
|
||||
} else {
|
||||
if (!firstAhead || top < firstAhead.top) firstAhead = { id: entryId, top }
|
||||
}
|
||||
})
|
||||
const winner = lastPast || firstAhead
|
||||
if (winner) {
|
||||
setActiveEntryId(winner.id)
|
||||
if (locatedEntryIdsRef.current.has(winner.id)) {
|
||||
mapRef.current?.highlightMarker(winner.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
const onScroll = () => {
|
||||
if (rafRef.current != null) return
|
||||
rafRef.current = window.requestAnimationFrame(() => {
|
||||
rafRef.current = null
|
||||
commitWinner()
|
||||
})
|
||||
}
|
||||
|
||||
feed.addEventListener('scroll', onScroll, { passive: true })
|
||||
window.addEventListener('scroll', onScroll, { passive: true })
|
||||
// prime once so the map syncs on initial load
|
||||
commitWinner()
|
||||
scrollCleanupRef.current = () => {
|
||||
feed.removeEventListener('scroll', onScroll)
|
||||
window.removeEventListener('scroll', onScroll)
|
||||
if (rafRef.current != null) {
|
||||
window.cancelAnimationFrame(rafRef.current)
|
||||
rafRef.current = null
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (current?.entries?.length) {
|
||||
const t = window.setTimeout(setupScrollSync, 300)
|
||||
return () => {
|
||||
window.clearTimeout(t)
|
||||
scrollCleanupRef.current?.()
|
||||
}
|
||||
}
|
||||
return () => scrollCleanupRef.current?.()
|
||||
}, [current?.entries, setupScrollSync])
|
||||
|
||||
const handleMarkerClick = useCallback((entryId: string) => {
|
||||
const el = document.querySelector(`[data-entry-id="${entryId}"]`)
|
||||
if (!el) return
|
||||
// Commit the choice immediately so the highlighted marker stays pinned
|
||||
// to the clicked entry even while smooth-scroll passes over others.
|
||||
suppressScrollSyncRef.current = true
|
||||
setActiveEntryId(entryId)
|
||||
mapRef.current?.highlightMarker(entryId)
|
||||
el.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
if (suppressTimerRef.current != null) window.clearTimeout(suppressTimerRef.current)
|
||||
// Smooth scroll typically finishes within ~500ms; 750ms gives a safety
|
||||
// buffer so the sync doesn't snap back to the wrong entry on the very
|
||||
// last frame.
|
||||
suppressTimerRef.current = window.setTimeout(() => {
|
||||
suppressScrollSyncRef.current = false
|
||||
suppressTimerRef.current = null
|
||||
}, 750)
|
||||
}, [])
|
||||
|
||||
useEffect(() => () => {
|
||||
if (suppressTimerRef.current != null) window.clearTimeout(suppressTimerRef.current)
|
||||
}, [])
|
||||
|
||||
const handleLocationClick = useCallback((id: string) => {
|
||||
setActiveLocationId(id)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
// give the sidebar map a chance to recalc its size when the view switches
|
||||
// (feed column width can shift slightly if the gallery vs timeline
|
||||
// renders with a different scrollbar state).
|
||||
requestAnimationFrame(() => mapRef.current?.invalidateSize())
|
||||
}, [view])
|
||||
|
||||
// On desktop we run a two-pane layout where only the feed column scrolls;
|
||||
// the body must not scroll underneath it. Restore on unmount.
|
||||
useEffect(() => {
|
||||
if (isMobile) return
|
||||
const prev = document.body.style.overflow
|
||||
document.body.style.overflow = 'hidden'
|
||||
return () => { document.body.style.overflow = prev }
|
||||
}, [isMobile])
|
||||
|
||||
// Map only shows real journal entries — skeletons are trip-derived
|
||||
// suggestions, not something the user actually journaled at that spot.
|
||||
const mapEntries = useMemo(
|
||||
() => (current?.entries || []).filter(e =>
|
||||
e.location_lat && e.location_lng &&
|
||||
e.title !== 'Gallery' &&
|
||||
e.title !== '[Trip Photos]' &&
|
||||
e.type !== 'skeleton'
|
||||
),
|
||||
[current?.entries]
|
||||
)
|
||||
|
||||
const sidebarMapItems = useMemo(() => {
|
||||
const allDates = [...new Set(
|
||||
(current?.entries || [])
|
||||
.filter(e => e.title !== 'Gallery' && e.title !== '[Trip Photos]')
|
||||
.map(e => e.entry_date)
|
||||
.sort()
|
||||
)]
|
||||
const sorted = [...mapEntries].sort((a, b) => a.entry_date.localeCompare(b.entry_date))
|
||||
const dayCounters = new Map<string, number>()
|
||||
return sorted.map(e => {
|
||||
const dayIdx = allDates.indexOf(e.entry_date)
|
||||
const dayLabel = (dayCounters.get(e.entry_date) ?? 0) + 1
|
||||
dayCounters.set(e.entry_date, dayLabel)
|
||||
return {
|
||||
id: String(e.id),
|
||||
lat: e.location_lat!,
|
||||
lng: e.location_lng!,
|
||||
title: e.title || '',
|
||||
location_name: e.location_name || '',
|
||||
mood: e.mood,
|
||||
created_at: e.entry_date,
|
||||
entry_date: e.entry_date,
|
||||
dayColor: DAY_COLORS[dayIdx % DAY_COLORS.length],
|
||||
dayLabel,
|
||||
}
|
||||
})
|
||||
}, [mapEntries, current?.entries])
|
||||
|
||||
const locatedEntryIdsRef = useRef(new Set<string>())
|
||||
useEffect(() => {
|
||||
locatedEntryIdsRef.current = new Set(sidebarMapItems.map(m => m.id))
|
||||
}, [sidebarMapItems])
|
||||
|
||||
const tripDates = useMemo(() => {
|
||||
const dates = new Set<string>()
|
||||
if (!current?.trips) return dates
|
||||
for (const trip of current.trips) {
|
||||
if (!trip.start_date || !trip.end_date) continue
|
||||
const start = new Date(trip.start_date + 'T00:00:00')
|
||||
const end = new Date(trip.end_date + 'T00:00:00')
|
||||
for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
|
||||
dates.add(d.toISOString().split('T')[0])
|
||||
}
|
||||
}
|
||||
return dates
|
||||
}, [current?.trips])
|
||||
|
||||
return {
|
||||
id, navigate, toast, t, locale,
|
||||
current, loading,
|
||||
canEditEntries, canEditJourney, myRole,
|
||||
view, setView, activeEntryId, setActiveEntryId, feedRef,
|
||||
viewingEntry, setViewingEntry, editingEntry, setEditingEntry,
|
||||
lightbox, setLightbox, deleteTarget, setDeleteTarget,
|
||||
showInvite, setShowInvite, showAddTrip, setShowAddTrip,
|
||||
unlinkTrip, setUnlinkTrip, showSettings, setShowSettings,
|
||||
hideSkeletons, setHideSkeletons,
|
||||
mapRef, fullMapRef, activeLocationId, handleMarkerClick, handleLocationClick,
|
||||
mapEntries, sidebarMapItems, tripDates, isMobile,
|
||||
loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Shared types + pure helpers for the public (read-only) journey share page.
|
||||
* No React, no side effects — safe to import from both the data hook and the
|
||||
* presentational page.
|
||||
*/
|
||||
|
||||
export interface PublicEntry {
|
||||
id: number
|
||||
title?: string | null
|
||||
story?: string | null
|
||||
entry_date: string
|
||||
entry_time?: string | null
|
||||
location_name?: string | null
|
||||
location_lat?: number | null
|
||||
location_lng?: number | null
|
||||
mood?: string | null
|
||||
weather?: string | null
|
||||
pros_cons?: { pros: string[]; cons: string[] } | null
|
||||
photos: PublicPhoto[]
|
||||
}
|
||||
|
||||
export interface PublicPhoto {
|
||||
id: number
|
||||
entry_id: number
|
||||
photo_id: number
|
||||
provider?: string
|
||||
asset_id?: string | null
|
||||
owner_id?: number | null
|
||||
file_path?: string | null
|
||||
caption?: string | null
|
||||
}
|
||||
|
||||
export interface PublicGalleryPhoto {
|
||||
id: number
|
||||
journey_id: number
|
||||
photo_id: number
|
||||
provider?: string
|
||||
asset_id?: string | null
|
||||
owner_id?: number | null
|
||||
file_path?: string | null
|
||||
caption?: string | null
|
||||
}
|
||||
|
||||
export function groupByDate(entries: PublicEntry[]): Map<string, PublicEntry[]> {
|
||||
const groups = new Map<string, PublicEntry[]>()
|
||||
for (const e of entries) {
|
||||
const d = e.entry_date
|
||||
if (!groups.has(d)) groups.set(d, [])
|
||||
groups.get(d)!.push(e)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useEffect, useState, useMemo, useRef, useCallback } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { journeyApi } from '../../api/client'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import type { JourneyMapHandle } from '../../components/Journey/JourneyMap'
|
||||
import { useIsMobile } from '../../hooks/useIsMobile'
|
||||
import { DAY_COLORS } from '../../components/Journey/dayColors'
|
||||
import { groupByDate, type PublicEntry, type PublicGalleryPhoto } from './journeyPublicModel'
|
||||
|
||||
/**
|
||||
* Public-journey (read-only share) data hook — owns the token fetch, the
|
||||
* loading/error state, the view state (timeline/gallery/map, lightbox, language
|
||||
* picker, active + viewing entry) and all the timeline/map derivations.
|
||||
* JourneyPublicPage stays a wiring container: it keeps the presentational
|
||||
* helpers (photoUrl, formatDate, mood/weather config) and the render functions
|
||||
* next to the JSX, and computes the t()-dependent `availableViews` itself.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useJourneyPublic() {
|
||||
const { token } = useParams()
|
||||
const [data, setData] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(false)
|
||||
const isMobile = useIsMobile()
|
||||
const [view, setView] = useState<'timeline' | 'gallery' | 'map'>('timeline')
|
||||
const [lightbox, setLightbox] = useState<{ photos: { id: string; src: string; caption?: string | null }[]; index: number } | null>(null)
|
||||
const [showLangPicker, setShowLangPicker] = useState(false)
|
||||
const locale = useSettingsStore(s => s.settings.language) || 'en'
|
||||
const mapRef = useRef<JourneyMapHandle>(null)
|
||||
const [activeEntryId, setActiveEntryId] = useState<string | null>(null)
|
||||
const [viewingEntry, setViewingEntry] = useState<PublicEntry | null>(null)
|
||||
|
||||
const handleMarkerClick = useCallback((entryId: string) => {
|
||||
setActiveEntryId(entryId)
|
||||
mapRef.current?.highlightMarker(entryId)
|
||||
document.querySelector(`[data-entry-id="${entryId}"]`)
|
||||
?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return
|
||||
journeyApi.getPublicJourney(token)
|
||||
.then(d => setData(d))
|
||||
.catch(() => setError(true))
|
||||
.finally(() => setLoading(false))
|
||||
}, [token])
|
||||
|
||||
const entries = (data?.entries || []) as PublicEntry[]
|
||||
const gallery = (data?.gallery || []) as PublicGalleryPhoto[]
|
||||
const perms = data?.permissions || {}
|
||||
const journey = data?.journey || {}
|
||||
const stats = data?.stats || {}
|
||||
|
||||
const timelineEntries = useMemo(() => entries, [entries])
|
||||
const groupedEntries = useMemo(() => groupByDate(timelineEntries), [timelineEntries])
|
||||
const sortedDates = useMemo(() => [...groupedEntries.keys()].sort(), [groupedEntries])
|
||||
const mapEntries = useMemo(
|
||||
() => timelineEntries.filter(e => e.location_lat && e.location_lng),
|
||||
[timelineEntries],
|
||||
)
|
||||
const allPhotos = gallery
|
||||
|
||||
// Map entries with day color/label for colored markers.
|
||||
// dayIdx is derived from sortedDates (ALL timeline dates) so marker colors
|
||||
// stay in sync with the timeline day headers even when some days have no locations.
|
||||
const sidebarMapItems = useMemo(() => {
|
||||
const counters = new Map<string, number>()
|
||||
return mapEntries.map(e => {
|
||||
const dayIdx = sortedDates.indexOf(e.entry_date)
|
||||
const dayLabel = (counters.get(e.entry_date) ?? 0) + 1
|
||||
counters.set(e.entry_date, dayLabel)
|
||||
return {
|
||||
id: String(e.id),
|
||||
lat: e.location_lat!,
|
||||
lng: e.location_lng!,
|
||||
title: e.title || '',
|
||||
mood: e.mood,
|
||||
created_at: e.entry_date,
|
||||
entry_date: e.entry_date,
|
||||
dayColor: DAY_COLORS[dayIdx % DAY_COLORS.length],
|
||||
dayLabel,
|
||||
}
|
||||
})
|
||||
}, [mapEntries, sortedDates])
|
||||
|
||||
// Two-column desktop layout: timeline feed left + sticky map right
|
||||
const desktopTwoColumn = !isMobile && perms.share_timeline && perms.share_map
|
||||
|
||||
// Set default view based on permissions
|
||||
useEffect(() => {
|
||||
if (!perms.share_timeline && perms.share_gallery) setView('gallery')
|
||||
else if (!perms.share_timeline && !perms.share_gallery && perms.share_map) setView('map')
|
||||
}, [perms])
|
||||
|
||||
// When switching to desktop two-column, 'map' standalone tab no longer exists
|
||||
useEffect(() => {
|
||||
if (desktopTwoColumn && view === 'map') setView('timeline')
|
||||
}, [desktopTwoColumn, view])
|
||||
|
||||
return {
|
||||
token, data, loading, error, isMobile, locale,
|
||||
view, setView, lightbox, setLightbox, showLangPicker, setShowLangPicker,
|
||||
mapRef, activeEntryId, setActiveEntryId, viewingEntry, setViewingEntry, handleMarkerClick,
|
||||
perms, journey, stats,
|
||||
timelineEntries, groupedEntries, sortedDates, sidebarMapItems, allPhotos,
|
||||
desktopTwoColumn,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import { useState, useEffect, useMemo, useRef } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useSettingsStore, hasStoredLanguage } from '../../store/settingsStore'
|
||||
import { useTranslation, detectBrowserLanguage } from '../../i18n'
|
||||
import { authApi, configApi } from '../../api/client'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
|
||||
interface AppConfig {
|
||||
has_users: boolean
|
||||
allow_registration: boolean
|
||||
setup_complete: boolean
|
||||
demo_mode: boolean
|
||||
oidc_configured: boolean
|
||||
oidc_display_name?: string
|
||||
oidc_only_mode: boolean
|
||||
password_login: boolean
|
||||
password_registration: boolean
|
||||
oidc_login: boolean
|
||||
oidc_registration: boolean
|
||||
env_override_oidc_only: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Login data hook — owns the whole auth surface: login/register/demo, the MFA
|
||||
* step-up, the must-change-password step, the OIDC code exchange + error
|
||||
* handling, the app-config probe (with cache fallback) and the language
|
||||
* detection chain. LoginPage is a pure wiring container that renders what this
|
||||
* returns. Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useLogin() {
|
||||
const { t } = useTranslation()
|
||||
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 [inviteToken, setInviteToken] = useState<string>('')
|
||||
const [inviteValid, setInviteValid] = useState<boolean>(false)
|
||||
const exchangeInitiated = useRef(false)
|
||||
|
||||
const [langDropdownOpen, setLangDropdownOpen] = useState<boolean>(false)
|
||||
|
||||
const [showTakeoff, setShowTakeoff] = useState<boolean>(false)
|
||||
const [mfaStep, setMfaStep] = useState(false)
|
||||
const [mfaToken, setMfaToken] = useState('')
|
||||
const [mfaCode, setMfaCode] = useState('')
|
||||
const [passwordChangeStep, setPasswordChangeStep] = useState(false)
|
||||
const [savedLoginPassword, setSavedLoginPassword] = useState('')
|
||||
const [newPassword, setNewPassword] = useState('')
|
||||
const [confirmPassword, setConfirmPassword] = useState('')
|
||||
|
||||
const { login, register, demoLogin, completeMfaLogin, loadUser } = useAuthStore()
|
||||
const { setLanguageLocal, setLanguageTransient } = useSettingsStore()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const noRedirect = !!(location.state as { noRedirect?: boolean } | null)?.noRedirect
|
||||
|
||||
const redirectTarget = useMemo(() => {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const redirect = params.get('redirect')
|
||||
// Only allow relative paths starting with / to prevent open redirect attacks
|
||||
if (redirect && redirect.startsWith('/') && !redirect.startsWith('//') && !redirect.startsWith('/\\')) {
|
||||
return redirect
|
||||
}
|
||||
return '/dashboard'
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (redirectTarget !== '/dashboard') {
|
||||
sessionStorage.setItem('oidc_redirect', redirectTarget)
|
||||
}
|
||||
}, [redirectTarget])
|
||||
|
||||
useEffect(() => {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
|
||||
const invite = params.get('invite')
|
||||
const oidcCode = params.get('oidc_code')
|
||||
const oidcError = params.get('oidc_error')
|
||||
|
||||
if (invite) {
|
||||
setInviteToken(invite)
|
||||
setMode('register')
|
||||
authApi.validateInvite(invite).then(() => {
|
||||
setInviteValid(true)
|
||||
}).catch(() => {
|
||||
setError(t('login.invalidInviteLink'))
|
||||
})
|
||||
window.history.replaceState({}, '', window.location.pathname)
|
||||
}
|
||||
|
||||
if (oidcCode) {
|
||||
if (exchangeInitiated.current) return
|
||||
exchangeInitiated.current = true
|
||||
setIsLoading(true)
|
||||
fetch('/api/auth/oidc/exchange?code=' + encodeURIComponent(oidcCode), { credentials: 'include' })
|
||||
.then(r => r.json())
|
||||
.then(async data => {
|
||||
window.history.replaceState({}, '', '/login')
|
||||
if (data.token) {
|
||||
await loadUser()
|
||||
const savedRedirect = sessionStorage.getItem('oidc_redirect') || '/dashboard'
|
||||
sessionStorage.removeItem('oidc_redirect')
|
||||
navigate(savedRedirect, { replace: true })
|
||||
} else {
|
||||
setError(data.error || t('login.oidcFailed'))
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
window.history.replaceState({}, '', '/login')
|
||||
setError(t('login.oidcFailed'))
|
||||
})
|
||||
.finally(() => setIsLoading(false))
|
||||
return
|
||||
}
|
||||
|
||||
if (oidcError) {
|
||||
const errorMessages: Record<string, string> = {
|
||||
registration_disabled: t('login.oidc.registrationDisabled'),
|
||||
no_email: t('login.oidc.noEmail'),
|
||||
token_failed: t('login.oidc.tokenFailed'),
|
||||
invalid_state: t('login.oidc.invalidState'),
|
||||
}
|
||||
setError(errorMessages[oidcError] || oidcError)
|
||||
sessionStorage.removeItem('oidc_redirect')
|
||||
window.history.replaceState({}, '', '/login')
|
||||
return
|
||||
}
|
||||
|
||||
const CONFIG_CACHE_KEY = 'trek_app_config_cache'
|
||||
authApi.getAppConfig?.()
|
||||
.then((config: AppConfig) => {
|
||||
try { localStorage.setItem(CONFIG_CACHE_KEY, JSON.stringify(config)) } catch { /* ignore quota errors */ }
|
||||
return { config, fromCache: false }
|
||||
})
|
||||
.catch(() => {
|
||||
try {
|
||||
const raw = localStorage.getItem(CONFIG_CACHE_KEY)
|
||||
return raw ? { config: JSON.parse(raw) as AppConfig, fromCache: true } : { config: null as AppConfig | null, fromCache: false }
|
||||
} catch { return { config: null as AppConfig | null, fromCache: false } }
|
||||
})
|
||||
.then(({ config, fromCache }) => {
|
||||
if (config) {
|
||||
setAppConfig(config)
|
||||
if (!config.has_users) setMode('register')
|
||||
// Skip auto-redirect when config is from cache — network is unreliable
|
||||
// and auto-redirecting to the IdP could loop if the proxy changed.
|
||||
if (!fromCache && !config.password_login && config.oidc_login && config.oidc_configured && config.has_users && !invite && !noRedirect) {
|
||||
window.location.href = '/api/auth/oidc/login'
|
||||
}
|
||||
}
|
||||
})
|
||||
}, [navigate, t, noRedirect])
|
||||
|
||||
// Language detection chain (runs once on mount, only if user has no saved preference):
|
||||
// 1. localStorage → already in store initial state, skip
|
||||
// 2. Browser/OS language (navigator.languages)
|
||||
// 3. Server default (DEFAULT_LANGUAGE env var)
|
||||
// 4. 'en' → hardcoded fallback already in store
|
||||
useEffect(() => {
|
||||
if (hasStoredLanguage()) return
|
||||
|
||||
const detected = detectBrowserLanguage()
|
||||
if (detected) {
|
||||
setLanguageTransient(detected)
|
||||
return
|
||||
}
|
||||
|
||||
configApi.getPublicConfig()
|
||||
.then(({ defaultLanguage }) => { if (defaultLanguage) setLanguageTransient(defaultLanguage) })
|
||||
.catch((err) => console.warn('Failed to fetch default language config:', err))
|
||||
}, [setLanguageTransient])
|
||||
|
||||
useEffect(() => {
|
||||
if (!langDropdownOpen) return
|
||||
const close = () => setLangDropdownOpen(false)
|
||||
document.addEventListener('click', close)
|
||||
return () => document.removeEventListener('click', close)
|
||||
}, [langDropdownOpen])
|
||||
|
||||
const handleDemoLogin = async (): Promise<void> => {
|
||||
setError('')
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await demoLogin()
|
||||
setShowTakeoff(true)
|
||||
setTimeout(() => navigate(redirectTarget), 2600)
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : t('login.demoFailed'))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>): Promise<void> => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setIsLoading(true)
|
||||
try {
|
||||
if (passwordChangeStep) {
|
||||
if (!newPassword) { setError(t('settings.passwordRequired')); setIsLoading(false); return }
|
||||
if (newPassword.length < 8) { setError(t('settings.passwordTooShort')); setIsLoading(false); return }
|
||||
if (newPassword !== confirmPassword) { setError(t('settings.passwordMismatch')); setIsLoading(false); return }
|
||||
await authApi.changePassword({ current_password: savedLoginPassword, new_password: newPassword })
|
||||
await loadUser({ silent: true })
|
||||
setShowTakeoff(true)
|
||||
setTimeout(() => navigate(redirectTarget), 2600)
|
||||
return
|
||||
}
|
||||
if (mode === 'login' && mfaStep) {
|
||||
if (!mfaCode.trim()) {
|
||||
setError(t('login.mfaCodeRequired'))
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
const mfaResult = await completeMfaLogin(mfaToken, mfaCode)
|
||||
if ('user' in mfaResult && mfaResult.user?.must_change_password) {
|
||||
setSavedLoginPassword(password)
|
||||
setPasswordChangeStep(true)
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
setShowTakeoff(true)
|
||||
setTimeout(() => navigate(redirectTarget), 2600)
|
||||
return
|
||||
}
|
||||
if (mode === 'register') {
|
||||
if (!username.trim()) { setError(t('login.usernameRequired')); setIsLoading(false); return }
|
||||
if (password.length < 8) { setError(t('login.passwordMinLength')); setIsLoading(false); return }
|
||||
await register(username, email, password, inviteToken || undefined)
|
||||
} else {
|
||||
const result = await login(email, password)
|
||||
if ('mfa_required' in result && result.mfa_required && 'mfa_token' in result) {
|
||||
setMfaToken(result.mfa_token)
|
||||
setMfaStep(true)
|
||||
setMfaCode('')
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
if ('user' in result && result.user?.must_change_password) {
|
||||
setSavedLoginPassword(password)
|
||||
setPasswordChangeStep(true)
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
setShowTakeoff(true)
|
||||
setTimeout(() => navigate(redirectTarget), 2600)
|
||||
} catch (err: unknown) {
|
||||
setError(getApiErrorMessage(err, t('login.error')))
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const showRegisterOption = (appConfig?.password_registration || !appConfig?.has_users || inviteValid) && (appConfig?.setup_complete !== false || !appConfig?.has_users)
|
||||
|
||||
// In OIDC-only mode, show a minimal page that redirects directly to the IdP
|
||||
const oidcOnly = !appConfig?.password_login && appConfig?.oidc_login && appConfig?.oidc_configured
|
||||
|
||||
return {
|
||||
navigate,
|
||||
mode, setMode,
|
||||
username, setUsername, email, setEmail, password, setPassword, showPassword, setShowPassword,
|
||||
isLoading, error, setError, appConfig, inviteToken,
|
||||
langDropdownOpen, setLangDropdownOpen, setLanguageLocal,
|
||||
showTakeoff, mfaStep, setMfaStep, mfaToken, setMfaToken, mfaCode, setMfaCode,
|
||||
passwordChangeStep, newPassword, setNewPassword, confirmPassword, setConfirmPassword,
|
||||
noRedirect, showRegisterOption, oidcOnly,
|
||||
handleDemoLogin, handleSubmit,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { oauthApi } from '../../api/client'
|
||||
import { SCOPE_GROUPS } from '../../api/oauthScopes'
|
||||
import { useTranslation } from '../../i18n'
|
||||
|
||||
interface ValidateResult {
|
||||
valid: boolean
|
||||
error?: string
|
||||
error_description?: string
|
||||
client?: { name: string; allowed_scopes: string[] }
|
||||
scopes?: string[]
|
||||
consentRequired?: boolean
|
||||
loginRequired?: boolean
|
||||
scopeSelectable?: boolean
|
||||
}
|
||||
|
||||
type PageState = 'loading' | 'login_required' | 'consent' | 'auto_approving' | 'error' | 'done'
|
||||
|
||||
/**
|
||||
* OAuth authorize/consent screen logic — owns the validate→consent state machine,
|
||||
* the requested-scope selection and the login/redirect plumbing. The page reads
|
||||
* the query string once here so the controller stays a pure renderer.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useOAuthAuthorize() {
|
||||
const { t } = useTranslation()
|
||||
const { isAuthenticated, isLoading: authLoading, loadUser } = useAuthStore()
|
||||
const [pageState, setPageState] = useState<PageState>('loading')
|
||||
const [validation, setValidation] = useState<ValidateResult | null>(null)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null)
|
||||
const [selectedScopes, setSelectedScopes] = useState<string[]>([])
|
||||
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const clientId = params.get('client_id') || ''
|
||||
const redirectUri = params.get('redirect_uri') || ''
|
||||
const scope = params.get('scope') || ''
|
||||
const state = params.get('state') || ''
|
||||
const codeChallenge = params.get('code_challenge') || ''
|
||||
const ccMethod = params.get('code_challenge_method') || ''
|
||||
const resource = params.get('resource') || undefined
|
||||
|
||||
// Load auth state once, then validate
|
||||
useEffect(() => {
|
||||
loadUser({ silent: true }).catch(() => {})
|
||||
}, [loadUser])
|
||||
|
||||
useEffect(() => {
|
||||
if (authLoading) return
|
||||
validateRequest()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [authLoading, isAuthenticated])
|
||||
|
||||
async function validateRequest() {
|
||||
setPageState('loading')
|
||||
try {
|
||||
const result = await oauthApi.validate({
|
||||
client_id: clientId,
|
||||
redirect_uri: redirectUri,
|
||||
scope,
|
||||
state,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: ccMethod,
|
||||
response_type: 'code',
|
||||
resource,
|
||||
})
|
||||
setValidation(result)
|
||||
|
||||
if (!result.valid) {
|
||||
setPageState('error')
|
||||
setErrorMsg(result.error_description || result.error || 'Invalid authorization request')
|
||||
return
|
||||
}
|
||||
|
||||
if (result.loginRequired) {
|
||||
setPageState('login_required')
|
||||
return
|
||||
}
|
||||
|
||||
if (!result.consentRequired) {
|
||||
// Consent already on record — auto-approve silently with the full validated scope
|
||||
setPageState('auto_approving')
|
||||
await submitConsent(true, result.scopes ?? [])
|
||||
return
|
||||
}
|
||||
|
||||
// Pre-select all scopes the client is requesting — user can deselect
|
||||
setSelectedScopes(result.scopes ?? [])
|
||||
setPageState('consent')
|
||||
} catch (err: unknown) {
|
||||
setPageState('error')
|
||||
setErrorMsg('Failed to validate authorization request. Please try again.')
|
||||
}
|
||||
}
|
||||
|
||||
async function submitConsent(approved: boolean, scopes: string[] = selectedScopes) {
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const result = await oauthApi.authorize({
|
||||
client_id: clientId,
|
||||
redirect_uri: redirectUri,
|
||||
// When approving, send only the scopes the user selected; deny uses original scope
|
||||
scope: approved ? scopes.join(' ') : scope,
|
||||
state,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: ccMethod,
|
||||
approved,
|
||||
resource,
|
||||
})
|
||||
setPageState('done')
|
||||
window.location.href = result.redirect
|
||||
} catch {
|
||||
setPageState('error')
|
||||
setErrorMsg('Authorization failed. Please try again.')
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
function toggleScope(s: string) {
|
||||
setSelectedScopes(prev =>
|
||||
prev.includes(s) ? prev.filter(x => x !== s) : [...prev, s]
|
||||
)
|
||||
}
|
||||
|
||||
function toggleGroup(groupScopes: string[], allSelected: boolean) {
|
||||
setSelectedScopes(prev =>
|
||||
allSelected
|
||||
? prev.filter(s => !groupScopes.includes(s))
|
||||
: [...new Set([...prev, ...groupScopes])]
|
||||
)
|
||||
}
|
||||
|
||||
function handleLoginRedirect() {
|
||||
const next = '/oauth/consent?' + params.toString() + window.location.hash
|
||||
window.location.href = '/login?redirect=' + encodeURIComponent(next)
|
||||
}
|
||||
|
||||
// Group requested scopes by their translated group name
|
||||
const scopesByGroup = useMemo(() => {
|
||||
const requested = validation?.scopes || []
|
||||
const groups: Record<string, string[]> = {}
|
||||
for (const s of requested) {
|
||||
const keys = SCOPE_GROUPS[s]
|
||||
const group = keys ? t(keys.groupKey) : 'Other'
|
||||
if (!groups[group]) groups[group] = []
|
||||
groups[group].push(s)
|
||||
}
|
||||
return groups
|
||||
}, [validation, t])
|
||||
|
||||
return {
|
||||
pageState, validation, submitting, errorMsg, selectedScopes, clientId,
|
||||
scopesByGroup, submitConsent, toggleScope, toggleGroup, handleLoginRedirect,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
|
||||
/**
|
||||
* Register data hook — owns the form state, the client-side validation and the
|
||||
* register → redirect flow. RegisterPage is a pure wiring container. Behaviour
|
||||
* is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useRegister() {
|
||||
const { t } = useTranslation()
|
||||
const { register } = useAuthStore()
|
||||
const navigate = useNavigate()
|
||||
|
||||
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 handleSubmit = async (e: React.FormEvent<HTMLFormElement>): Promise<void> => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
setError(t('register.passwordMismatch'))
|
||||
return
|
||||
}
|
||||
|
||||
if (password.length < 8) {
|
||||
setError(t('register.passwordTooShort'))
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await register(username, email, password)
|
||||
navigate('/dashboard')
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : t('register.failed'))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
username, setUsername, email, setEmail, password, setPassword,
|
||||
confirmPassword, setConfirmPassword, showPassword, setShowPassword,
|
||||
isLoading, error, handleSubmit,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useState, useEffect, type FormEvent } from 'react'
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { authApi } from '../../api/client'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import { useTranslation } from '../../i18n'
|
||||
|
||||
/**
|
||||
* Reset-password data hook — owns the token lookup, the form state, the
|
||||
* client-side validation and the submit (incl. the MFA step-up branch).
|
||||
* ResetPasswordPage is a pure wiring container. Behaviour is identical to the
|
||||
* previous in-component logic.
|
||||
*/
|
||||
export function useResetPassword() {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const [params] = useSearchParams()
|
||||
const token = params.get('token') || ''
|
||||
|
||||
const [pw, setPw] = useState('')
|
||||
const [pw2, setPw2] = useState('')
|
||||
const [showPw, setShowPw] = useState(false)
|
||||
const [mfaCode, setMfaCode] = useState('')
|
||||
const [mfaRequired, setMfaRequired] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [success, setSuccess] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) setError(t('login.resetPasswordInvalidLink'))
|
||||
}, [token, t])
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (isLoading) return
|
||||
setError('')
|
||||
if (!token) return
|
||||
if (pw.length < 8) { setError(t('login.passwordMinLength')); return }
|
||||
if (pw !== pw2) { setError(t('login.passwordsDontMatch')); return }
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const res = await authApi.resetPassword({
|
||||
token,
|
||||
new_password: pw,
|
||||
...(mfaRequired && mfaCode ? { mfa_code: mfaCode.trim() } : {}),
|
||||
})
|
||||
if (res.mfa_required) {
|
||||
setMfaRequired(true)
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
if (res.success) {
|
||||
setSuccess(true)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(getApiErrorMessage(err, t('login.resetPasswordFailed')))
|
||||
}
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return {
|
||||
navigate, token,
|
||||
pw, setPw, pw2, setPw2, showPw, setShowPw,
|
||||
mfaCode, setMfaCode, mfaRequired, error, success, isLoading,
|
||||
handleSubmit,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
import { authApi } from '../../api/client'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
|
||||
/**
|
||||
* Settings page logic — loads addons + the app version, tracks the active tab
|
||||
* and the integrations-enabled gate, and auto-switches to the account tab when
|
||||
* the URL signals MFA is required. SettingsPage stays a wiring container that
|
||||
* builds the (t-dependent) tab list and renders the tab bodies.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useSettings() {
|
||||
const [searchParams] = useSearchParams()
|
||||
const { isEnabled: addonEnabled, loadAddons } = useAddonStore()
|
||||
|
||||
const memoriesEnabled = addonEnabled('memories')
|
||||
const mcpEnabled = addonEnabled('mcp')
|
||||
const hasIntegrations = memoriesEnabled || mcpEnabled
|
||||
|
||||
const [appVersion, setAppVersion] = useState<string | null>(null)
|
||||
const [activeTab, setActiveTab] = useState('display')
|
||||
|
||||
useEffect(() => {
|
||||
loadAddons()
|
||||
authApi.getAppConfig?.().then(c => setAppVersion(c?.version)).catch(() => {})
|
||||
}, [])
|
||||
|
||||
// Auto-switch to account tab when MFA is required
|
||||
useEffect(() => {
|
||||
if (searchParams.get('mfa') === 'required') {
|
||||
setActiveTab('account')
|
||||
}
|
||||
}, [searchParams])
|
||||
|
||||
return { hasIntegrations, appVersion, activeTab, setActiveTab }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { shareApi } from '../../api/client'
|
||||
|
||||
/**
|
||||
* Shared-trip (public) data hook — owns the token lookup, the read-only share
|
||||
* fetch and the view state (selected day, active tab, language picker).
|
||||
* SharedTripPage is a pure wiring container; the post-load derivations
|
||||
* (sortedDays, map places, …) stay in the page next to the JSX that uses them.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useSharedTrip() {
|
||||
const { token } = useParams<{ token: string }>()
|
||||
// The shared payload is an open-ended snapshot (trip, days, assignments, …),
|
||||
// matched 1:1 from the public share endpoint — kept loosely typed as before.
|
||||
const [data, setData] = useState<any>(null)
|
||||
const [error, setError] = useState(false)
|
||||
const [selectedDay, setSelectedDay] = useState<number | null>(null)
|
||||
const [activeTab, setActiveTab] = useState('plan')
|
||||
const [showLangPicker, setShowLangPicker] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return
|
||||
shareApi.getSharedTrip(token).then(setData).catch(() => setError(true))
|
||||
}, [token])
|
||||
|
||||
return { data, error, selectedDay, setSelectedDay, activeTab, setActiveTab, showLangPicker, setShowLangPicker }
|
||||
}
|
||||
@@ -0,0 +1,644 @@
|
||||
import { useState, useEffect, useCallback, useMemo, useRef } from 'react'
|
||||
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { getCached, fetchPhoto } from '../../services/photoService'
|
||||
import { useToast } from '../../components/shared/Toast'
|
||||
import { Map, Ticket, PackageCheck, Wallet, FolderOpen, Users, Train } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { addonsApi, accommodationsApi, authApi, tripsApi, assignmentsApi } from '../../api/client'
|
||||
import { accommodationRepo } from '../../repo/accommodationRepo'
|
||||
import { offlineDb } from '../../db/offlineDb'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useResizablePanels } from '../../hooks/useResizablePanels'
|
||||
import { useTripWebSocket } from '../../hooks/useTripWebSocket'
|
||||
import { useRouteCalculation } from '../../hooks/useRouteCalculation'
|
||||
import { usePlaceSelection } from '../../hooks/usePlaceSelection'
|
||||
import { usePlannerHistory } from '../../hooks/usePlannerHistory'
|
||||
import type { Accommodation, TripMember, Day, Place, Reservation } from '../../types'
|
||||
|
||||
/**
|
||||
* Trip planner page logic — the big one. Owns the trip store wiring, addon
|
||||
* gating, accommodations/members loading, the tab + resizable-panel + selection
|
||||
* state, every place/assignment/reservation/transport CRUD handler (with undo),
|
||||
* the map filters/derivations and the splash gate. TripPlannerPage stays a
|
||||
* wiring container that lays out the day/map/places panes and modals.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useTripPlanner() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
// The route param is a string; convert once here so every downstream component
|
||||
// prop and store call gets a real number. An absent/invalid id becomes NaN,
|
||||
// which stays falsy in the `if (tripId)` guards below.
|
||||
const tripId = id ? Number(id) : NaN
|
||||
const navigate = useNavigate()
|
||||
const toast = useToast()
|
||||
const { t, language } = useTranslation()
|
||||
const { settings } = useSettingsStore()
|
||||
const placesPhotosEnabled = useAuthStore(s => s.placesPhotosEnabled)
|
||||
const trip = useTripStore(s => s.trip)
|
||||
const days = useTripStore(s => s.days)
|
||||
const places = useTripStore(s => s.places)
|
||||
const assignments = useTripStore(s => s.assignments)
|
||||
const packingItems = useTripStore(s => s.packingItems)
|
||||
const todoItems = useTripStore(s => s.todoItems)
|
||||
const categories = useTripStore(s => s.categories)
|
||||
const reservations = useTripStore(s => s.reservations)
|
||||
const budgetItems = useTripStore(s => s.budgetItems)
|
||||
const files = useTripStore(s => s.files)
|
||||
const selectedDayId = useTripStore(s => s.selectedDayId)
|
||||
const isLoading = useTripStore(s => s.isLoading)
|
||||
// Actions — stable references, don't cause re-renders
|
||||
const tripActions = useRef(useTripStore.getState()).current
|
||||
const can = useCanDo()
|
||||
const canUploadFiles = can('file_upload', trip)
|
||||
const { pushUndo, undo, canUndo, lastActionLabel } = usePlannerHistory()
|
||||
|
||||
const handleUndo = useCallback(async () => {
|
||||
const label = lastActionLabel
|
||||
await undo()
|
||||
toast.info(t('undo.done', { action: label ?? '' }))
|
||||
}, [undo, lastActionLabel, toast])
|
||||
|
||||
const [enabledAddons, setEnabledAddons] = useState<Record<string, boolean>>({ packing: true, budget: true, documents: true, collab: false })
|
||||
const [collabFeatures, setCollabFeatures] = useState<{ chat: boolean; notes: boolean; polls: boolean; whatsnext: boolean }>({ chat: true, notes: true, polls: true, whatsnext: true })
|
||||
const [tripAccommodations, setTripAccommodations] = useState<Accommodation[]>([])
|
||||
const [allowedFileTypes, setAllowedFileTypes] = useState<string | null>(null)
|
||||
const [tripMembers, setTripMembers] = useState<TripMember[]>([])
|
||||
|
||||
const loadAccommodations = useCallback(() => {
|
||||
if (tripId) {
|
||||
accommodationRepo.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {})
|
||||
tripActions.loadReservations(tripId)
|
||||
}
|
||||
}, [tripId])
|
||||
|
||||
useEffect(() => {
|
||||
addonsApi.enabled().then(data => {
|
||||
const map: Record<string, boolean> = {}
|
||||
data.addons.forEach(a => { map[a.id] = true })
|
||||
setEnabledAddons({ packing: !!map.packing, budget: !!map.budget, documents: !!map.documents, collab: !!map.collab })
|
||||
if (data.collabFeatures) setCollabFeatures(data.collabFeatures)
|
||||
}).catch(() => {})
|
||||
authApi.getAppConfig().then(config => {
|
||||
if (config.allowed_file_types) setAllowedFileTypes(config.allowed_file_types)
|
||||
}).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const TRANSPORT_TYPES = new Set(['flight', 'train', 'car', 'cruise', 'bus'])
|
||||
|
||||
const TRIP_TABS = [
|
||||
{ id: 'plan', label: t('trip.tabs.plan'), icon: Map },
|
||||
{ id: 'transports', label: t('trip.tabs.transports'), icon: Train },
|
||||
{ id: 'buchungen', label: t('trip.tabs.reservations'), shortLabel: t('trip.tabs.reservationsShort'), icon: Ticket },
|
||||
...(enabledAddons.packing ? [{ id: 'listen', label: t('trip.tabs.lists'), shortLabel: t('trip.tabs.listsShort'), icon: PackageCheck }] : []),
|
||||
...(enabledAddons.budget ? [{ id: 'finanzplan', label: t('trip.tabs.budget'), icon: Wallet }] : []),
|
||||
...(enabledAddons.documents ? [{ id: 'dateien', label: t('trip.tabs.files'), icon: FolderOpen }] : []),
|
||||
...(enabledAddons.collab ? [{ id: 'collab', label: t('admin.addons.catalog.collab.name'), icon: Users }] : []),
|
||||
]
|
||||
|
||||
const [activeTab, setActiveTab] = useState<string>(() => {
|
||||
const saved = sessionStorage.getItem(`trip-tab-${tripId}`)
|
||||
return saved || 'plan'
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
const validTabIds = TRIP_TABS.map(t => t.id)
|
||||
if (!validTabIds.includes(activeTab)) {
|
||||
setActiveTab('plan')
|
||||
sessionStorage.setItem(`trip-tab-${tripId}`, 'plan')
|
||||
}
|
||||
}, [enabledAddons])
|
||||
|
||||
const handleTabChange = (tabId: string): void => {
|
||||
setActiveTab(tabId)
|
||||
sessionStorage.setItem(`trip-tab-${tripId}`, tabId)
|
||||
if (tabId === 'finanzplan') tripActions.loadBudgetItems?.(tripId)
|
||||
if (tabId === 'dateien' && (!files || files.length === 0)) tripActions.loadFiles?.(tripId)
|
||||
}
|
||||
const { leftWidth, rightWidth, leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed, startResizeLeft, startResizeRight } = useResizablePanels()
|
||||
const { selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment } = usePlaceSelection()
|
||||
const [showDayDetail, setShowDayDetail] = useState<Day | null>(null)
|
||||
const [dayDetailCollapsed, setDayDetailCollapsed] = useState(false)
|
||||
const [showPlaceForm, setShowPlaceForm] = useState<boolean>(false)
|
||||
const [editingPlace, setEditingPlace] = useState<Place | null>(null)
|
||||
const [prefillCoords, setPrefillCoords] = useState<{ lat: number; lng: number; name?: string; address?: string } | null>(null)
|
||||
const [editingAssignmentId, setEditingAssignmentId] = useState<number | null>(null)
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
|
||||
// The bottom-nav "+" opens the new-place form via ?create=place.
|
||||
useEffect(() => {
|
||||
if (searchParams.get('create') === 'place') {
|
||||
setEditingPlace(null); setEditingAssignmentId(null); setShowPlaceForm(true)
|
||||
setSearchParams(p => { p.delete('create'); return p }, { replace: true })
|
||||
}
|
||||
}, [searchParams])
|
||||
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 [bookingForAssignmentId, setBookingForAssignmentId] = useState<number | null>(null)
|
||||
const [showTransportModal, setShowTransportModal] = useState<boolean>(false)
|
||||
const [editingTransport, setEditingTransport] = useState<Reservation | null>(null)
|
||||
const [transportModalDayId, setTransportModalDayId] = useState<number | null>(null)
|
||||
// Manual route planning: off by default, toggled from the day-plan footer. Mode
|
||||
// (driving/walking) is per-session and selects which travel time the connectors show.
|
||||
const [routeShown, setRouteShown] = useState(false)
|
||||
const [routeProfile, setRouteProfile] = useState<'driving' | 'walking'>('driving')
|
||||
const [fitKey, setFitKey] = useState<number>(0)
|
||||
const initialFitTripId = useRef<number | null>(null)
|
||||
const [mobileSidebarOpen, setMobileSidebarOpen] = useState<'left' | 'right' | null>(null)
|
||||
const mobilePlanScrollTopRef = useRef<number>(0)
|
||||
const mobilePlacesScrollTopRef = useRef<number>(0)
|
||||
const [deletePlaceId, setDeletePlaceId] = useState<number | null>(null)
|
||||
const [deletePlaceIds, setDeletePlaceIds] = useState<number[] | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!trip) return
|
||||
if (initialFitTripId.current === trip.id) return
|
||||
const hasGeoPlaces = places.some(p => p.lat != null && p.lng != null)
|
||||
if (!hasGeoPlaces) return
|
||||
initialFitTripId.current = trip.id
|
||||
setFitKey(k => k + 1)
|
||||
}, [trip, places])
|
||||
|
||||
const connectionsStorageKey = tripId ? `trek:visible-connections:${tripId}` : null
|
||||
const [visibleConnections, setVisibleConnections] = useState<number[]>(() => {
|
||||
if (typeof window === 'undefined' || !connectionsStorageKey) return []
|
||||
try {
|
||||
const stored = window.localStorage.getItem(connectionsStorageKey)
|
||||
return stored ? JSON.parse(stored) as number[] : []
|
||||
} catch { return [] }
|
||||
})
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined' || !connectionsStorageKey) return
|
||||
window.localStorage.setItem(connectionsStorageKey, JSON.stringify(visibleConnections))
|
||||
}, [connectionsStorageKey, visibleConnections])
|
||||
const toggleConnection = useCallback((id: number) => {
|
||||
setVisibleConnections(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
|
||||
}, [])
|
||||
const [mapTransportDetail, setMapTransportDetail] = useState<Reservation | null>(null)
|
||||
|
||||
const [isMobile, setIsMobile] = useState(() => window.innerWidth < 768)
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia('(max-width: 767px)')
|
||||
const handler = (e: MediaQueryListEvent) => setIsMobile(e.matches)
|
||||
mq.addEventListener('change', handler)
|
||||
return () => mq.removeEventListener('change', handler)
|
||||
}, [])
|
||||
|
||||
// Start photo fetches during splash screen so images are ready when map mounts
|
||||
useEffect(() => {
|
||||
if (isLoading || !places || places.length === 0 || !placesPhotosEnabled) return
|
||||
for (const p of places) {
|
||||
if (p.image_url) continue
|
||||
const cacheKey = p.google_place_id || p.osm_id || `${p.lat},${p.lng}`
|
||||
if (!cacheKey || getCached(cacheKey)) continue
|
||||
const photoId = p.google_place_id || p.osm_id
|
||||
if (photoId || (p.lat && p.lng)) {
|
||||
fetchPhoto(cacheKey, photoId || `coords:${p.lat}:${p.lng}`, p.lat, p.lng, p.name)
|
||||
}
|
||||
}
|
||||
}, [isLoading, places])
|
||||
|
||||
// Load trip + files (needed for place inspector file section)
|
||||
useEffect(() => {
|
||||
if (tripId) {
|
||||
tripActions.loadTrip(tripId).catch(() => { toast.error(t('trip.toast.loadError')); navigate('/dashboard') })
|
||||
tripActions.loadFiles(tripId)
|
||||
loadAccommodations()
|
||||
if (!navigator.onLine) {
|
||||
offlineDb.tripMembers.where('tripId').equals(Number(tripId)).toArray()
|
||||
.then(rows => setTripMembers(rows))
|
||||
.catch(() => {})
|
||||
} else {
|
||||
tripsApi.getMembers(tripId).then(d => {
|
||||
const all = [d.owner, ...(d.members || [])].filter(Boolean)
|
||||
setTripMembers(all)
|
||||
}).catch(() => {})
|
||||
}
|
||||
}
|
||||
}, [tripId])
|
||||
|
||||
useEffect(() => {
|
||||
if (tripId) {
|
||||
tripActions.loadReservations(tripId)
|
||||
tripActions.loadBudgetItems?.(tripId)
|
||||
}
|
||||
}, [tripId])
|
||||
|
||||
useTripWebSocket(tripId)
|
||||
|
||||
const [mapCategoryFilter, setMapCategoryFilter] = useState<Set<string>>(new Set())
|
||||
const [mapPlacesFilter, setMapPlacesFilter] = useState<string>('all')
|
||||
|
||||
const [expandedDayIds, setExpandedDayIds] = useState<Set<number> | null>(null)
|
||||
|
||||
const mapPlaces = useMemo(() => {
|
||||
// Build set of place IDs assigned to collapsed days
|
||||
const hiddenPlaceIds = new Set<number>()
|
||||
if (expandedDayIds) {
|
||||
for (const [dayId, dayAssignments] of Object.entries(assignments)) {
|
||||
if (!expandedDayIds.has(Number(dayId))) {
|
||||
for (const a of dayAssignments) {
|
||||
if (a.place?.id) hiddenPlaceIds.add(a.place.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Don't hide places that are also assigned to an expanded day
|
||||
for (const [dayId, dayAssignments] of Object.entries(assignments)) {
|
||||
if (expandedDayIds.has(Number(dayId))) {
|
||||
for (const a of dayAssignments) {
|
||||
hiddenPlaceIds.delete(a.place?.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build set of planned place IDs for unplanned filter
|
||||
const plannedIds = mapPlacesFilter === 'unplanned'
|
||||
? new Set(Object.values(assignments).flatMap(da => da.map(a => a.place?.id).filter(Boolean)))
|
||||
: null
|
||||
|
||||
return places.filter(p => {
|
||||
if (!p.lat || !p.lng) return false
|
||||
if (mapPlacesFilter === 'tracks' && !p.route_geometry) return false
|
||||
if (mapCategoryFilter.size > 0) {
|
||||
if (p.category_id == null) {
|
||||
if (!mapCategoryFilter.has('uncategorized')) return false
|
||||
} else if (!mapCategoryFilter.has(String(p.category_id))) return false
|
||||
}
|
||||
if (hiddenPlaceIds.has(p.id)) return false
|
||||
if (plannedIds && plannedIds.has(p.id)) return false
|
||||
return true
|
||||
})
|
||||
}, [places, mapCategoryFilter, mapPlacesFilter, assignments, expandedDayIds])
|
||||
|
||||
const { route, routeSegments, routeInfo, setRoute, setRouteInfo, updateRouteForDay } = useRouteCalculation({ assignments } as any, selectedDayId, routeShown, routeProfile)
|
||||
|
||||
const handleSelectDay = useCallback((dayId: number | null, skipFit?: boolean) => {
|
||||
const changed = dayId !== selectedDayId
|
||||
tripActions.setSelectedDay(dayId)
|
||||
if (changed && !skipFit) setFitKey(k => k + 1)
|
||||
setMobileSidebarOpen(null)
|
||||
updateRouteForDay(dayId)
|
||||
}, [updateRouteForDay, selectedDayId])
|
||||
|
||||
const handlePlaceClick = useCallback((placeId: number | null, assignmentId?: number | null) => {
|
||||
if (assignmentId) {
|
||||
selectAssignment(assignmentId, placeId)
|
||||
} else {
|
||||
setSelectedPlaceId(placeId)
|
||||
}
|
||||
if (placeId) { setShowDayDetail(null); setLeftCollapsed(false); setRightCollapsed(false) }
|
||||
}, [selectAssignment, setSelectedPlaceId])
|
||||
|
||||
const handleMarkerClick = useCallback((placeId?: number) => {
|
||||
if (placeId === undefined) {
|
||||
setSelectedPlaceId(null)
|
||||
return
|
||||
}
|
||||
// Find every assignment for this place (same place can sit on several
|
||||
// days / be planned twice in one day). Cycle through them on repeated
|
||||
// marker clicks so the sidebar highlight jumps to the next occurrence
|
||||
// instead of leaving the user confused.
|
||||
const allAssignments = Object.values(useTripStore.getState().assignments || {}).flat()
|
||||
const matching = allAssignments.filter(a => a?.place?.id === placeId)
|
||||
|
||||
if (matching.length === 0) {
|
||||
setSelectedPlaceId(selectedPlaceId === placeId ? null : placeId)
|
||||
} else if (matching.length === 1) {
|
||||
const only = matching[0]
|
||||
if (selectedAssignmentId === only.id) {
|
||||
setSelectedPlaceId(null)
|
||||
} else {
|
||||
selectAssignment(only.id, placeId)
|
||||
}
|
||||
} else {
|
||||
const currentIdx = matching.findIndex(a => a.id === selectedAssignmentId)
|
||||
const nextIdx = currentIdx === -1 ? 0 : currentIdx + 1
|
||||
if (nextIdx >= matching.length) {
|
||||
// cycled past the last occurrence — clear selection so the next
|
||||
// click starts fresh at occurrence 0.
|
||||
setSelectedPlaceId(null)
|
||||
} else {
|
||||
selectAssignment(matching[nextIdx].id, placeId)
|
||||
}
|
||||
}
|
||||
setLeftCollapsed(false); setRightCollapsed(false)
|
||||
}, [selectAssignment, selectedAssignmentId, selectedPlaceId, setSelectedPlaceId])
|
||||
|
||||
const handleMapClick = useCallback(() => {
|
||||
setSelectedPlaceId(null)
|
||||
}, [])
|
||||
|
||||
const handleMapContextMenu = useCallback(async (e) => {
|
||||
if (!can('place_edit', trip)) return
|
||||
e.originalEvent?.preventDefault()
|
||||
const { lat, lng } = e.latlng
|
||||
setPrefillCoords({ lat, lng })
|
||||
setEditingPlace(null)
|
||||
setEditingAssignmentId(null)
|
||||
setShowPlaceForm(true)
|
||||
try {
|
||||
const { mapsApi } = await import('../../api/client')
|
||||
const data = await mapsApi.reverse(lat, lng, language)
|
||||
if (data.name || data.address) {
|
||||
setPrefillCoords(prev => prev ? { ...prev, name: data.name || '', address: data.address || '' } : prev)
|
||||
}
|
||||
} catch { /* best effort */ }
|
||||
}, [language])
|
||||
|
||||
const handleSavePlace = useCallback(async (data) => {
|
||||
const pendingFiles = data._pendingFiles
|
||||
delete data._pendingFiles
|
||||
if (editingPlace) {
|
||||
// Always strip time fields from place update — time is per-assignment only
|
||||
const { place_time, end_time, ...placeData } = data
|
||||
await tripActions.updatePlace(tripId, editingPlace.id, placeData)
|
||||
// If editing from assignment context, save time per-assignment
|
||||
if (editingAssignmentId) {
|
||||
await assignmentsApi.updateTime(tripId, editingAssignmentId, { place_time: place_time || null, end_time: end_time || null })
|
||||
await tripActions.refreshDays(tripId)
|
||||
}
|
||||
// Upload pending files with place_id
|
||||
if (pendingFiles?.length > 0) {
|
||||
for (const file of pendingFiles) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
fd.append('place_id', String(editingPlace.id))
|
||||
try { await tripActions.addFile(tripId, fd) } catch { toast.error(t('files.uploadError')) }
|
||||
}
|
||||
}
|
||||
toast.success(t('trip.toast.placeUpdated'))
|
||||
} else {
|
||||
const place = await tripActions.addPlace(tripId, data)
|
||||
if (pendingFiles?.length > 0 && place?.id) {
|
||||
for (const file of pendingFiles) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
fd.append('place_id', String(place.id))
|
||||
try { await tripActions.addFile(tripId, fd) } catch { toast.error(t('files.uploadError')) }
|
||||
}
|
||||
}
|
||||
toast.success(t('trip.toast.placeAdded'))
|
||||
if (place?.id) {
|
||||
const capturedId = place.id
|
||||
pushUndo(t('undo.addPlace'), async () => {
|
||||
await tripActions.deletePlace(tripId, capturedId)
|
||||
})
|
||||
}
|
||||
}
|
||||
}, [editingPlace, editingAssignmentId, tripId, toast, pushUndo])
|
||||
|
||||
const handleDeletePlace = useCallback((placeId) => {
|
||||
setDeletePlaceId(placeId)
|
||||
}, [])
|
||||
|
||||
const confirmDeletePlace = useCallback(async () => {
|
||||
if (!deletePlaceId) return
|
||||
const state = useTripStore.getState()
|
||||
const capturedPlace = state.places.find(p => p.id === deletePlaceId)
|
||||
const capturedAssignments = Object.entries(state.assignments).flatMap(([dayId, as]) =>
|
||||
as.filter(a => a.place?.id === deletePlaceId).map(a => ({ dayId: Number(dayId), orderIndex: a.order_index }))
|
||||
)
|
||||
try {
|
||||
await tripActions.deletePlace(tripId, deletePlaceId)
|
||||
if (selectedPlaceId === deletePlaceId) setSelectedPlaceId(null)
|
||||
updateRouteForDay(selectedDayId)
|
||||
toast.success(t('trip.toast.placeDeleted'))
|
||||
if (capturedPlace) {
|
||||
pushUndo(t('undo.deletePlace'), async () => {
|
||||
const newPlace = await tripActions.addPlace(tripId, {
|
||||
name: capturedPlace.name,
|
||||
description: capturedPlace.description,
|
||||
lat: capturedPlace.lat,
|
||||
lng: capturedPlace.lng,
|
||||
address: capturedPlace.address,
|
||||
category_id: capturedPlace.category_id,
|
||||
price: capturedPlace.price,
|
||||
})
|
||||
for (const { dayId, orderIndex } of capturedAssignments) {
|
||||
await tripActions.assignPlaceToDay(tripId, dayId, newPlace.id, orderIndex)
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}, [deletePlaceId, tripId, toast, selectedPlaceId, selectedDayId, updateRouteForDay, pushUndo])
|
||||
|
||||
const confirmDeletePlaces = useCallback(async (ids?: number[]) => {
|
||||
const targetIds = ids ?? deletePlaceIds
|
||||
if (!targetIds?.length) return
|
||||
const state = useTripStore.getState()
|
||||
const capturedPlaces = state.places.filter(p => targetIds.includes(p.id))
|
||||
const capturedAssignments = Object.entries(state.assignments).flatMap(([dayId, as]) =>
|
||||
as.filter(a => a.place?.id != null && targetIds.includes(a.place.id)).map(a => ({ dayId: Number(dayId), placeId: a.place!.id, orderIndex: a.order_index }))
|
||||
)
|
||||
try {
|
||||
await tripActions.deletePlacesMany(tripId, targetIds)
|
||||
if (selectedPlaceId != null && targetIds.includes(selectedPlaceId)) setSelectedPlaceId(null)
|
||||
if (!ids) setDeletePlaceIds(null)
|
||||
updateRouteForDay(selectedDayId)
|
||||
toast.success(t('trip.toast.placesDeleted', { count: capturedPlaces.length }))
|
||||
if (capturedPlaces.length > 0) {
|
||||
pushUndo(t('undo.deletePlaces'), async () => {
|
||||
for (const place of capturedPlaces) {
|
||||
const newPlace = await tripActions.addPlace(tripId, {
|
||||
name: place.name, description: place.description,
|
||||
lat: place.lat, lng: place.lng, address: place.address,
|
||||
category_id: place.category_id, price: place.price,
|
||||
})
|
||||
for (const a of capturedAssignments.filter(x => x.placeId === place.id)) {
|
||||
await tripActions.assignPlaceToDay(tripId, a.dayId, newPlace.id, a.orderIndex)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}, [deletePlaceIds, tripId, toast, selectedPlaceId, selectedDayId, updateRouteForDay, pushUndo])
|
||||
|
||||
const handleAssignToDay = useCallback(async (placeId: number, dayId?: number, position?: number) => {
|
||||
const target = dayId || selectedDayId
|
||||
if (!target) { toast.error(t('trip.toast.selectDay')); return }
|
||||
try {
|
||||
const assignment = await tripActions.assignPlaceToDay(tripId, target, placeId, position)
|
||||
toast.success(t('trip.toast.assignedToDay'))
|
||||
updateRouteForDay(target)
|
||||
if (assignment?.id) {
|
||||
const capturedAssignmentId = assignment.id
|
||||
const capturedTarget = target
|
||||
pushUndo(t('undo.assignPlace'), async () => {
|
||||
await tripActions.removeAssignment(tripId, capturedTarget, capturedAssignmentId)
|
||||
})
|
||||
}
|
||||
} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}, [selectedDayId, tripId, toast, updateRouteForDay, pushUndo])
|
||||
|
||||
const handleRemoveAssignment = useCallback(async (dayId: number, assignmentId: number) => {
|
||||
const state = useTripStore.getState()
|
||||
const capturedAssignment = (state.assignments[String(dayId)] || []).find(a => a.id === assignmentId)
|
||||
const capturedPlaceId = capturedAssignment?.place?.id
|
||||
const capturedOrderIndex = capturedAssignment?.order_index ?? 0
|
||||
try {
|
||||
await tripActions.removeAssignment(tripId, dayId, assignmentId)
|
||||
updateRouteForDay(dayId)
|
||||
if (capturedPlaceId != null) {
|
||||
const capturedDayId = dayId
|
||||
const capturedPos = capturedOrderIndex
|
||||
pushUndo(t('undo.removeAssignment'), async () => {
|
||||
await tripActions.assignPlaceToDay(tripId, capturedDayId, capturedPlaceId, capturedPos)
|
||||
})
|
||||
}
|
||||
}
|
||||
catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}, [tripId, toast, updateRouteForDay, pushUndo])
|
||||
|
||||
const handleReorder = useCallback((dayId: number, orderedIds: number[]) => {
|
||||
const prevIds = (useTripStore.getState().assignments[String(dayId)] || [])
|
||||
.slice().sort((a, b) => a.order_index - b.order_index).map(a => a.id)
|
||||
try {
|
||||
tripActions.reorderAssignments(tripId, dayId, orderedIds)
|
||||
.then(() => {
|
||||
const capturedDayId = dayId
|
||||
const capturedPrevIds = prevIds
|
||||
pushUndo(t('undo.reorder'), async () => {
|
||||
await tripActions.reorderAssignments(tripId, capturedDayId, capturedPrevIds)
|
||||
})
|
||||
})
|
||||
.catch(err => toast.error(err instanceof Error ? err.message : t('trip.toast.reorderError')))
|
||||
updateRouteForDay(dayId)
|
||||
}
|
||||
catch { toast.error(t('trip.toast.reorderError')) }
|
||||
}, [tripId, toast, pushUndo, updateRouteForDay])
|
||||
|
||||
const handleUpdateDayTitle = useCallback(async (dayId, title) => {
|
||||
try { await tripActions.updateDayTitle(tripId, dayId, title) }
|
||||
catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}, [tripId, toast])
|
||||
|
||||
const handleSaveReservation = async (data: Record<string, string | number | null> & { title: string }) => {
|
||||
try {
|
||||
if (editingReservation) {
|
||||
const r = await tripActions.updateReservation(tripId, editingReservation.id, { ...data, day_id: selectedDayId || null })
|
||||
toast.success(t('trip.toast.reservationUpdated'))
|
||||
setShowReservationModal(false)
|
||||
setEditingReservation(null)
|
||||
if (data.type === 'hotel') {
|
||||
accommodationsApi.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {})
|
||||
}
|
||||
return r
|
||||
} else {
|
||||
const r = await tripActions.addReservation(tripId, { ...data, day_id: selectedDayId || null })
|
||||
toast.success(t('trip.toast.reservationAdded'))
|
||||
setShowReservationModal(false)
|
||||
// Refresh accommodations if hotel was created
|
||||
if (data.type === 'hotel') {
|
||||
accommodationsApi.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {})
|
||||
}
|
||||
return r
|
||||
}
|
||||
} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}
|
||||
|
||||
const handleSaveTransport = async (data: Record<string, any> & { title: string }) => {
|
||||
try {
|
||||
if (editingTransport) {
|
||||
const r = await tripActions.updateReservation(tripId, editingTransport.id, data)
|
||||
toast.success(t('trip.toast.reservationUpdated'))
|
||||
setShowTransportModal(false)
|
||||
setEditingTransport(null)
|
||||
setTransportModalDayId(null)
|
||||
return r
|
||||
} else {
|
||||
const r = await tripActions.addReservation(tripId, data)
|
||||
toast.success(t('trip.toast.reservationAdded'))
|
||||
setShowTransportModal(false)
|
||||
setEditingTransport(null)
|
||||
setTransportModalDayId(null)
|
||||
return r
|
||||
}
|
||||
} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}
|
||||
|
||||
const handleDeleteReservation = async (id) => {
|
||||
try {
|
||||
await tripActions.deleteReservation(tripId, id)
|
||||
toast.success(t('trip.toast.deleted'))
|
||||
// Refresh accommodations in case a hotel booking was deleted
|
||||
accommodationsApi.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {})
|
||||
}
|
||||
catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }
|
||||
}
|
||||
|
||||
const selectedPlace = selectedPlaceId ? places.find(p => p.id === selectedPlaceId) : null
|
||||
|
||||
// Build placeId → order-number map from the selected day's assignments
|
||||
const dayOrderMap = useMemo(() => {
|
||||
if (!selectedDayId) return {}
|
||||
const da = assignments[String(selectedDayId)] || []
|
||||
const sorted = [...da].sort((a, b) => a.order_index - b.order_index)
|
||||
const map = {}
|
||||
sorted.forEach((a, i) => {
|
||||
if (!a.place?.id) return
|
||||
if (!map[a.place.id]) map[a.place.id] = []
|
||||
map[a.place.id].push(i + 1)
|
||||
})
|
||||
return map
|
||||
}, [selectedDayId, assignments])
|
||||
|
||||
// Places assigned to selected day (with coords) — used for map fitting
|
||||
const dayPlaces = useMemo(() => {
|
||||
if (!selectedDayId) return []
|
||||
const da = assignments[String(selectedDayId)] || []
|
||||
return da.map(a => a.place).filter(p => p?.lat && p?.lng)
|
||||
}, [selectedDayId, assignments])
|
||||
|
||||
const mapTileUrl = settings.map_tile_url || 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png'
|
||||
const defaultCenter = [settings.default_lat || 48.8566, settings.default_lng || 2.3522]
|
||||
const defaultZoom = settings.default_zoom || 10
|
||||
|
||||
const fontStyle = { fontFamily: "-apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Segoe UI', system-ui, sans-serif" }
|
||||
|
||||
// Splash screen — show for initial load + a brief moment for photos to start loading
|
||||
const [splashDone, setSplashDone] = useState(false)
|
||||
useEffect(() => {
|
||||
if (!isLoading && trip) {
|
||||
const timer = setTimeout(() => setSplashDone(true), 1500)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [isLoading, trip])
|
||||
|
||||
return {
|
||||
tripId, navigate, toast, t, language, settings, placesPhotosEnabled,
|
||||
trip, days, places, assignments, packingItems, todoItems, categories, reservations, budgetItems, files,
|
||||
selectedDayId, isLoading, tripActions, can, canUploadFiles,
|
||||
pushUndo, undo, canUndo, lastActionLabel, handleUndo,
|
||||
enabledAddons, collabFeatures, tripAccommodations, setTripAccommodations,
|
||||
allowedFileTypes, tripMembers, setTripMembers, loadAccommodations,
|
||||
TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange,
|
||||
leftWidth, rightWidth, leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed, startResizeLeft, startResizeRight,
|
||||
selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment,
|
||||
showDayDetail, setShowDayDetail, dayDetailCollapsed, setDayDetailCollapsed,
|
||||
showPlaceForm, setShowPlaceForm, editingPlace, setEditingPlace,
|
||||
prefillCoords, setPrefillCoords, editingAssignmentId, setEditingAssignmentId,
|
||||
showTripForm, setShowTripForm, showMembersModal, setShowMembersModal,
|
||||
showReservationModal, setShowReservationModal, editingReservation, setEditingReservation,
|
||||
bookingForAssignmentId, setBookingForAssignmentId,
|
||||
showTransportModal, setShowTransportModal, editingTransport, setEditingTransport,
|
||||
transportModalDayId, setTransportModalDayId,
|
||||
routeShown, setRouteShown, routeProfile, setRouteProfile, fitKey, setFitKey,
|
||||
mobileSidebarOpen, setMobileSidebarOpen, mobilePlanScrollTopRef, mobilePlacesScrollTopRef,
|
||||
deletePlaceId, setDeletePlaceId, deletePlaceIds, setDeletePlaceIds,
|
||||
visibleConnections, setVisibleConnections, toggleConnection, mapTransportDetail, setMapTransportDetail,
|
||||
isMobile, mapCategoryFilter, setMapCategoryFilter, mapPlacesFilter, setMapPlacesFilter,
|
||||
expandedDayIds, setExpandedDayIds, mapPlaces,
|
||||
route, routeSegments, routeInfo, setRoute, setRouteInfo, updateRouteForDay,
|
||||
handleSelectDay, handlePlaceClick, handleMarkerClick, handleMapClick, handleMapContextMenu,
|
||||
handleSavePlace, handleDeletePlace, confirmDeletePlace, confirmDeletePlaces,
|
||||
handleAssignToDay, handleRemoveAssignment, handleReorder, handleUpdateDayTitle,
|
||||
handleSaveReservation, handleSaveTransport, handleDeleteReservation,
|
||||
selectedPlace, dayOrderMap, dayPlaces,
|
||||
mapTileUrl, defaultCenter, defaultZoom, fontStyle, splashDone,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useEffect, useState, useCallback } from 'react'
|
||||
import { useVacayStore } from '../../store/vacayStore'
|
||||
import { addListener, removeListener } from '../../api/websocket'
|
||||
|
||||
/**
|
||||
* Vacay page logic — pulls the vacay store, owns the page-local UI state
|
||||
* (settings modal, delete-year prompt, mobile drawer), wires the WebSocket live
|
||||
* sync and the per-year (re)loads, and exposes the add-prev/next-year helpers.
|
||||
* VacayPage stays a wiring container around its sidebar/calendar JSX.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useVacay() {
|
||||
const { years, selectedYear, setSelectedYear, addYear, removeYear, loadAll, loadPlan, loadEntries, loadStats, loadHolidays, loading, incomingInvites, acceptInvite, declineInvite, plan } = useVacayStore()
|
||||
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: { type: string }) => {
|
||||
if (msg.type === 'vacay:update' || msg.type === 'vacay:settings') {
|
||||
loadPlan()
|
||||
loadEntries(selectedYear)
|
||||
loadStats(selectedYear)
|
||||
if (msg.type === 'vacay:settings') loadAll()
|
||||
}
|
||||
if (msg.type === 'vacay:invite' || msg.type === 'vacay:accepted' || msg.type === 'vacay:declined' || msg.type === 'vacay:cancelled' || msg.type === 'vacay:dissolved') {
|
||||
loadAll()
|
||||
}
|
||||
}, [selectedYear])
|
||||
|
||||
useEffect(() => {
|
||||
addListener(handleWsMessage)
|
||||
return () => removeListener(handleWsMessage)
|
||||
}, [handleWsMessage])
|
||||
useEffect(() => {
|
||||
if (selectedYear) { loadEntries(selectedYear); loadStats(selectedYear); loadHolidays(selectedYear) }
|
||||
}, [selectedYear])
|
||||
|
||||
const handleAddNextYear = () => {
|
||||
const nextYear = years.length > 0 ? Math.max(...years) + 1 : new Date().getFullYear()
|
||||
addYear(nextYear)
|
||||
}
|
||||
|
||||
const handleAddPrevYear = () => {
|
||||
const prevYear = years.length > 0 ? Math.min(...years) - 1 : new Date().getFullYear()
|
||||
addYear(prevYear)
|
||||
}
|
||||
|
||||
return {
|
||||
years, selectedYear, setSelectedYear, removeYear, loading,
|
||||
incomingInvites, acceptInvite, declineInvite, plan,
|
||||
showSettings, setShowSettings, deleteYear, setDeleteYear,
|
||||
showMobileSidebar, setShowMobileSidebar,
|
||||
handleAddNextYear, handleAddPrevYear,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user