mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 18:34:09 +00:00
@@ -3,3 +3,6 @@ e2e/.tmp/
|
||||
test-results/
|
||||
playwright-report/
|
||||
playwright/.cache/
|
||||
|
||||
# vite-plugin-pwa dev output (devOptions.enabled)
|
||||
dev-dist/
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
Scope: the **`@trek/client`** workspace (React 19 + Vite + Zustand + Tailwind PWA). See the repo-root `CLAUDE.md` for the monorepo picture and `server/CLAUDE.md` for the API. This file covers client internals only.
|
||||
|
||||
## Commands (run from `client/`)
|
||||
|
||||
```bash
|
||||
npm run dev # Vite dev server; proxies /api,/ws,/uploads,/oauth → http://localhost:3001
|
||||
npm run build # prebuild generates PWA icons, then vite build
|
||||
npm run typecheck # tsc --noEmit
|
||||
npm run lint # eslint .
|
||||
npm run lint:pages # enforce the Page pattern (scripts/check-page-pattern.mjs)
|
||||
npm run test # vitest run (tests/** + src/**/*.test.{ts,tsx})
|
||||
npm run test:unit # tests/unit
|
||||
npm run test:integration # tests/integration + co-located src tests
|
||||
npm run test:coverage # v8 coverage
|
||||
npm run e2e # Playwright
|
||||
npm run e2e:report # open last Playwright report
|
||||
npm run shots # Playwright screenshots project (shots:promote to accept)
|
||||
npm run theme:lint # theme conformance audit (theme:lint:strict exits 1 on findings; not a CI gate)
|
||||
```
|
||||
|
||||
Single test:
|
||||
|
||||
```bash
|
||||
npx vitest run src/store/slices/budgetSlice.test.ts
|
||||
npx vitest run -t "optimistically adds the place"
|
||||
npx vitest watch src/pages/DashboardPage.test.tsx
|
||||
```
|
||||
|
||||
The dev server needs the API on **:3001** — run the server (`npm run dev` from root or `server/`) alongside, or `npm run dev` at the repo root to start both.
|
||||
|
||||
## Page pattern (enforced — `lint:pages` will fail otherwise)
|
||||
|
||||
Every `src/pages/*Page.tsx` is a thin **wiring container**; all state/effects/handlers live in a co-located **`use<Page>()` hook** under `src/pages/<page>/`. The page body must **not** call `useState/useReducer/useEffect/useLayoutEffect/useMemo/useCallback/useRef` — only context hooks like `useTranslation()` are allowed. Optional `<page>Model.ts` holds pure (React-free) types/helpers. Full spec in `src/pages/PATTERN.md`. When extracting, keep rendered JSX byte-identical — it's a refactor of where logic lives.
|
||||
|
||||
## Data flow — offline-first
|
||||
|
||||
The layering is **store → repo → api | Dexie**, and writes go through a mutation queue:
|
||||
|
||||
- **`src/store/`** — Zustand. `tripStore.ts` is composed from **slices** in `store/slices/` (places, days, packing, todo, budget, reservations, files, assignments, dayNotes). Other stores: auth, settings, addon, permissions, inAppNotification, journey, vacay, systemNotice, collection, saveToCollection, plugin, backgroundTasks. `slices/remoteEventHandler.ts` applies inbound WebSocket events to local state.
|
||||
- **`src/repo/`** — per-entity repositories that mediate between the network and the offline cache. The pattern: if `navigator.onLine`, call the REST API and upsert into Dexie; if offline, read from Dexie. Always go through a repo for trip data, not the API directly.
|
||||
- **`src/api/client.ts`** — single Axios instance; request/response types imported from `@trek/shared` Zod schemas. `api/websocket.ts` manages the `/ws` connection.
|
||||
- **`src/db/offlineDb.ts`** — Dexie/IndexedDB schema: cached entities + the `QueuedMutation` table + `SyncMeta` (per-trip last-sync, prefetched-tiles bbox) + a `BlobCache` for offline file/photo access.
|
||||
- **`src/sync/`** — `mutationQueue.ts`: offline writes do an optimistic Dexie write (with a temporary **negative id** for creates), then on reconnect `flush()` replays REST with the mutation's UUID as the **`X-Idempotency-Key`** header (matching the server interceptor) and reconciles the Dexie row. `tripSyncManager.ts` / `syncTriggers.ts` / `connectivity.ts` drive reconnection sync; `tilePrefetcher.ts` pre-downloads map tiles.
|
||||
|
||||
## Direction (from the 2026 audit)
|
||||
|
||||
The offline core is flagship work surrounded by a periphery that ignores it. New code must extend the core's discipline, not the periphery's shortcuts:
|
||||
|
||||
- **One data path, no layer skips**: component → feature hook → store/slice → `repo/` → `api/` | Dexie. **Never import `api/client` (or raw fetch/axios) from a component or modal** — especially never *write* from one. A long tail of existing files (~190 at last count) bypasses the layering and no lint ratchet holds the line yet; that's debt, not precedent. New API surface goes in a per-domain `api/<domain>.ts`, not the `client.ts` god module.
|
||||
- **Offline-first is the product promise, not a trip-planner feature.** New domains should get a repo with both read-through and offline writes (temp id → optimistic Dexie write → idempotent queue entry), extending the existing pattern rather than hand-rolling a variant. If a domain is deliberately online-only, mark it so explicitly.
|
||||
- **No God components or God hooks.** The page pattern is a floor, not a ceiling — a 900-line `use<Page>()` hook that satisfies the linter is still coupling. Decompose hooks by concern, split renders into memoizable sections, and don't pass 50-field prop bags with inline-arrow callbacks (it defeats `React.memo`).
|
||||
- **Prefer React 19 idioms over hand-rolled machinery**: `useOptimistic` for optimistic updates, `useActionState`/`useFormStatus` for forms, `use()` + Suspense for read paths, `useSyncExternalStore` for external subscriptions (`hooks/useNetworkMode` is the reference implementation).
|
||||
- **Optimistic writes must reconcile** — rollback + user-visible toast on failure. No `.catch(() => {})`, no bare `catch {}`; silently keeping state the server rejected is a data-integrity bug.
|
||||
- **WS remote-event handling must match local slice reducers field-for-field.** If a slice reducer preserves embedded fields on update (e.g. `place_time`/`end_time`), the corresponding `remoteEventHandler` branch must apply the identical merge semantics — divergence is silent, cross-user data loss.
|
||||
- **Subscribe with selectors** (`useShallow` for multi-field reads); never `const s = useStore()` whole-store; no store getters that allocate per call. Use `getState()` for imperative access in effects.
|
||||
- **Connectivity**: `isEffectivelyOffline()` is the single source of truth — never read `navigator.onLine` directly in feature code.
|
||||
- **Rendering security**: never interpolate user content into HTML strings (map tooltips/popups included — build via DOM + `textContent`); untrusted or cross-user markdown gets `rehype-sanitize`; never `rehype-raw` near those surfaces.
|
||||
- **No `window` CustomEvent buses or global mutable `window` state** — use the store or a typed emitter. No `any` at boundaries: WS payloads and map renderer props get real types, validated where they enter.
|
||||
- **Hygiene**: error boundaries around new shells/routes; every async `.then(setState)` needs a cancelled flag or `AbortController`; no `eslint-disable exhaustive-deps` as a routine tool (a missing memo dep has already shipped wrong money on screen); no sequential-await N+1 fetch loops — batch; search for an existing utility/hook before writing a duplicate.
|
||||
- **Theming**: use the semantic Tailwind tokens (`bg-surface*`, `text-content`, `border-edge`, `bg-accent`, status colors) — no raw palette classes, hex literals, or invented CSS vars; only `applyAppearance()` mutates `<html>` styling.
|
||||
|
||||
## Other big-picture pieces
|
||||
|
||||
- **Maps** (`src/components/Map/`): two interchangeable renderers — Leaflet (`MapView.tsx`) and Mapbox GL (`MapViewGL.tsx`), chosen at runtime by `MapViewAuto.tsx` based on the tile-source setting. GL-specific overlay/marker logic lives in the `*Mapbox.ts` siblings. Keep both renderers in sync when changing map features. **Offline maps**: only Leaflet supports full pre-download (raster tiles via `sync/tilePrefetcher.ts`, cached by the Workbox `map-tiles` rule). Mapbox GL is best-effort offline — its vector tiles are cached opportunistically as you browse online (the `mapbox-tiles` SW rule), not prefetched. Tile requests stay `no-cors` so self-hosted/custom tile providers without CORS headers keep working; `navigator.storage.persist()` (called at app init) keeps cached tiles from being evicted under storage pressure.
|
||||
- **i18n** (`src/i18n/TranslationContext.tsx`): `en` is bundled synchronously as the fallback; every other locale is a **dynamic `import('@trek/shared/i18n/<locale>')`** so Vite code-splits one chunk per locale and only the active one is fetched. `t(key)` resolves top-level keys from `@trek/shared/i18n`. Add new strings to the locale files in **`shared/`**, not here. RTL handled via `isRtlLanguage`.
|
||||
- **Mobile shell** (`src/mobile/`): below 768px (`useIsPhone`, reactive via matchMedia) `App.tsx` wraps routes in `MobileShell`, and phone-specific screens under `mobile/screens/<domain>/` (trip, dashboard, atlas, vacay, settings, admin, …) take over; the desktop/tablet experience at ≥768px is untouched. UI changes to a domain that has an `M*` screen usually need both the desktop component and the mobile screen updated.
|
||||
- **Plugins UI** (`src/components/Plugins/`): third-party plugin surfaces render in a sandboxed iframe — `PluginFrame.tsx` owns the postMessage bridge and hands the plugin the current theme's design tokens (live re-sync on theme/accent change). Contribution points: `PluginWidgets.tsx` (dashboard), `PluginDaySchedule.tsx` (itinerary rows), `Map/MapPluginLayers.tsx`/`MapPluginMarkers.tsx` (map). `store/pluginStore.ts` holds installed-plugin state; admin install/manage in `components/Admin/AdminPluginsPanel.tsx`. The server-side runtime is `server/src/nest/plugins/`; plugin authoring is covered by the `trek-plugin-dev` skill.
|
||||
- **PWA** (`vite.config.js`): `VitePWA` with `registerType: 'autoUpdate'` and Workbox `runtimeCaching` for tiles/API/uploads. `prebuild` (`scripts/generate-icons.mjs`) generates app icons before build.
|
||||
- **Native shell** (`client/src/platform/`): the Capacitor apps are not served from the same origin as the API, so `getServerOrigin()` is the single source of truth for where the server lives — `''` in the web build (relative URLs stay relative), the user's chosen server in native. Requests go through `apiFetch` / the `apiClient` interceptor, assets through `resolveAssetUrl` / `<ServerImage>`; ESLint blocks bare `fetch('/api…')` and `/uploads` literals so the seam cannot reopen. Native authenticates with `Authorization: Bearer` because the session cookie is `sameSite: 'lax'` and a webview can never send it cross-site. Saved servers are "profiles" (`serverProfiles.ts`, Capacitor Preferences) with tokens in device secure storage (`serverTokens.ts`) and a per-profile Dexie namespace. **The web build must stay byte-identical — especially Dexie names**; see `offlineDb.naming.test.ts`.
|
||||
|
||||
## Tests
|
||||
|
||||
vitest with `@vitejs/plugin-react`, jsdom (custom `tests/environment/jsdom-native-abort.ts`), `forks` pool. Tests live both in `tests/{unit,integration}/` and co-located as `src/**/*.test.{ts,tsx}`. `msw` mocks HTTP, `fake-indexeddb` backs Dexie in tests. Page tests render JSX against a mocked hook; hook/slice logic is tested in isolation (see `store/slices/budgetSlice.test.ts`). Playwright e2e config separate (`npm run e2e`).
|
||||
@@ -1,4 +1,5 @@
|
||||
import { test as setup, expect } from '@playwright/test'
|
||||
import { dismissSystemNotices } from './helpers'
|
||||
|
||||
// Relative to the config dir (client/), matching `storageState` in
|
||||
// playwright.config.ts. Playwright runs from the client workspace root.
|
||||
@@ -27,16 +28,12 @@ setup('authenticate the seeded admin (incl. forced password change)', async ({ p
|
||||
|
||||
await page.waitForURL('**/dashboard', { timeout: 30_000 })
|
||||
|
||||
// Dismiss the first-run "Welcome to TREK" system-notice modal(s). It renders
|
||||
// asynchronously (after the notices fetch), so wait for it before clicking.
|
||||
// Dismissal is recorded server-side against this user, so clearing it here
|
||||
// keeps it cleared for every authenticated flow in the run (shared test DB).
|
||||
const ok = page.getByRole('button', { name: 'OK', exact: true })
|
||||
await ok.waitFor({ state: 'visible', timeout: 10_000 }).catch(() => {})
|
||||
for (let i = 0; i < 8 && (await ok.isVisible().catch(() => false)); i++) {
|
||||
await ok.click()
|
||||
await page.waitForTimeout(400)
|
||||
}
|
||||
// Dismiss the first-run system-notice modal(s) — currently the thank-you /
|
||||
// support modal, which has NO "OK" button (only CTAs + the X). The shared
|
||||
// helper handles both notice shapes; dismissal is recorded server-side
|
||||
// against this user, so clearing it here keeps it cleared for every
|
||||
// authenticated flow in the run (shared test DB).
|
||||
await dismissSystemNotices(page, 10_000)
|
||||
|
||||
await page.context().storageState({ path: stateFile })
|
||||
})
|
||||
|
||||
+35
-14
@@ -1,22 +1,43 @@
|
||||
import type { Page } from '@playwright/test'
|
||||
|
||||
/**
|
||||
* Dismiss the release-notice modal (SystemNoticeHost), which greets a freshly seeded
|
||||
* user on first load and covers the dashboard — its backdrop swallows clicks aimed at
|
||||
* anything underneath, `.add-trip-card` included.
|
||||
* Dismiss the system-notice modal(s) (SystemNoticeHost), which greet a freshly
|
||||
* seeded user on first load and cover the dashboard — the backdrop swallows
|
||||
* clicks aimed at anything underneath, `.add-trip-card` included.
|
||||
*
|
||||
* The X only appears on the notice's last page, so page through first. Dismissal is
|
||||
* persisted server-side per user, but each spec gets a fresh DB, so every spec that
|
||||
* touches the dashboard has to clear it.
|
||||
* The host renders asynchronously (after the notices fetch), so wait for the
|
||||
* notice dialog before deciding there is nothing to clear. Every lookup is
|
||||
* scoped INSIDE the dialog — an unscoped /next/i can match dashboard buttons
|
||||
* (carousel arrows) and satisfy the wait before the modal even mounts.
|
||||
*
|
||||
* A notice closes one of two ways depending on its shape:
|
||||
* - CTA-bearing notices (e.g. the thank-you/support modal) only offer the
|
||||
* X button (`aria-label="Dismiss"`), shown on the last page.
|
||||
* - CTA-less notices show an "OK" button that pages forward and dismisses on
|
||||
* the last page.
|
||||
* Multi-page notices are paged through via the pager's Next button first.
|
||||
* Dismissal is persisted server-side per user, so clearing once keeps it
|
||||
* cleared for every later spec in the run (shared test DB).
|
||||
*/
|
||||
export async function dismissSystemNotices(page: Page): Promise<void> {
|
||||
const next = page.getByRole('button', { name: /next/i })
|
||||
for (let i = 0; i < 6 && (await next.isVisible().catch(() => false)); i++) {
|
||||
if (!(await next.isEnabled())) break
|
||||
await next.click()
|
||||
export async function dismissSystemNotices(page: Page, appearTimeoutMs = 3_000): Promise<void> {
|
||||
const dialog = page.getByRole('dialog').first()
|
||||
await dialog.waitFor({ state: 'visible', timeout: appearTimeoutMs }).catch(() => {})
|
||||
|
||||
// Clear up to a handful of queued notices.
|
||||
for (let notice = 0; notice < 4 && (await dialog.isVisible().catch(() => false)); notice++) {
|
||||
const next = dialog.getByRole('button', { name: /next/i })
|
||||
for (let i = 0; i < 8 && (await next.isVisible().catch(() => false)); i++) {
|
||||
if (!(await next.isEnabled().catch(() => false))) break
|
||||
await next.click()
|
||||
}
|
||||
const dismiss = dialog.getByRole('button', { name: 'Dismiss', exact: true })
|
||||
const ok = dialog.getByRole('button', { name: 'OK', exact: true })
|
||||
if (await dismiss.isVisible().catch(() => false)) await dismiss.click()
|
||||
else if (await ok.isVisible().catch(() => false)) await ok.click()
|
||||
else break
|
||||
// Exit animation + the next queued notice mounting.
|
||||
await page.waitForTimeout(400)
|
||||
}
|
||||
|
||||
const dismiss = page.getByRole('button', { name: 'Dismiss' })
|
||||
if (await dismiss.isVisible().catch(() => false)) await dismiss.click()
|
||||
await dismiss.waitFor({ state: 'detached' }).catch(() => {})
|
||||
await dialog.waitFor({ state: 'detached', timeout: 5_000 }).catch(() => {})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { test, expect, devices } from '@playwright/test'
|
||||
import type { Page } from '@playwright/test'
|
||||
import { dismissSystemNotices } from './helpers'
|
||||
|
||||
// Phone coverage for #2051: the day details area steps days under a horizontal
|
||||
// swipe, so the trip is navigable one-handed instead of only from the chip rail
|
||||
// pinned to the top of the screen.
|
||||
//
|
||||
// jsdom can drive the handlers but not the browser around them: whether the
|
||||
// gesture survives real touch dispatch, whether the browser hands the vertical
|
||||
// axis to its own scroller first, and whether a swipe at the first day stays put
|
||||
// are all engine behaviour. This drives CDP's Input.dispatchTouchEvent, so the
|
||||
// events are the ones a finger produces — not synthesised TouchEvent objects.
|
||||
//
|
||||
// Chromium, because CDP is where real touch injection lives. The file-level
|
||||
// device sets a phone viewport with a coarse pointer, which is what puts the
|
||||
// mobile shell on screen at all.
|
||||
test.use({ ...devices['Pixel 7'] })
|
||||
|
||||
/** One finger, dispatched through the browser's own input pipeline. */
|
||||
async function swipe(page: Page, from: { x: number; y: number }, to: { x: number; y: number }, steps = 8) {
|
||||
const cdp = await page.context().newCDPSession(page)
|
||||
await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: from.x, y: from.y }] })
|
||||
for (let i = 1; i <= steps; i++) {
|
||||
await cdp.send('Input.dispatchTouchEvent', {
|
||||
type: 'touchMove',
|
||||
touchPoints: [{
|
||||
x: from.x + ((to.x - from.x) * i) / steps,
|
||||
y: from.y + ((to.y - from.y) * i) / steps,
|
||||
}],
|
||||
})
|
||||
}
|
||||
await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] })
|
||||
await cdp.detach()
|
||||
// The out leg is 150ms and the in leg 220ms.
|
||||
await page.waitForTimeout(500)
|
||||
}
|
||||
|
||||
const activeChip = (page: Page) => page.locator('button[aria-current="true"]')
|
||||
|
||||
test('#2051 phone: the day details area swipes between days', async ({ page }) => {
|
||||
await page.goto('/dashboard')
|
||||
await dismissSystemNotices(page)
|
||||
|
||||
// Without a phone viewport and a coarse pointer the mobile shell never mounts,
|
||||
// and everything below would be proving nothing.
|
||||
const env = await page.evaluate(() => ({
|
||||
width: window.innerWidth,
|
||||
coarse: window.matchMedia('(pointer: coarse)').matches,
|
||||
}))
|
||||
expect(env.width, 'Pixel sits below the 768px phone breakpoint').toBeLessThan(768)
|
||||
expect(env.coarse, 'Pixel reports a coarse primary pointer').toBe(true)
|
||||
|
||||
const stamp = Date.now()
|
||||
const created = await page.request.post('/api/trips', {
|
||||
data: { title: `Day swipe ${stamp}`, start_date: '2099-06-01', end_date: '2099-06-05' },
|
||||
})
|
||||
expect(created.ok(), 'seed trip').toBeTruthy()
|
||||
const tripId = (await created.json()).trip?.id ?? (await created.json()).id
|
||||
|
||||
await page.goto(`/trips/${tripId}`)
|
||||
await expect(activeChip(page)).toBeVisible({ timeout: 30_000 })
|
||||
|
||||
const chips = page.locator('button[aria-current], button[aria-current="true"]')
|
||||
const rail = activeChip(page).locator('xpath=..')
|
||||
expect(await rail.locator('button').count(), 'the seeded trip has five days').toBe(5)
|
||||
expect(await chips.count()).toBeGreaterThan(0)
|
||||
|
||||
// The swipe zone: below the chip rail, above the dock, across the middle.
|
||||
const mid = Math.round(env.width / 2)
|
||||
const y = 460
|
||||
|
||||
const day1 = (await activeChip(page).textContent())!.trim()
|
||||
|
||||
// 1. A swipe left steps forward.
|
||||
await swipe(page, { x: mid + 90, y }, { x: mid - 90, y })
|
||||
const day2 = (await activeChip(page).textContent())!.trim()
|
||||
expect(day2, 'swiping left moved to the next day').not.toBe(day1)
|
||||
|
||||
// 2. A swipe right steps back to where it started.
|
||||
await swipe(page, { x: mid - 90, y }, { x: mid + 90, y })
|
||||
expect((await activeChip(page).textContent())!.trim()).toBe(day1)
|
||||
|
||||
// 3. The first day has nowhere to go back to — it must stay put, and the
|
||||
// browser must not have been handed a page-back either.
|
||||
await swipe(page, { x: mid - 90, y }, { x: mid + 90, y })
|
||||
expect((await activeChip(page).textContent())!.trim()).toBe(day1)
|
||||
expect(page.url()).toContain(`/trips/${tripId}`)
|
||||
|
||||
// 4. A vertical drag belongs to the card's own scroller, never to the day.
|
||||
await swipe(page, { x: mid, y: y + 120 }, { x: mid, y: y - 120 })
|
||||
expect((await activeChip(page).textContent())!.trim()).toBe(day1)
|
||||
|
||||
// 5. And the rail itself still works, so the gesture added a path rather than
|
||||
// replacing one.
|
||||
await rail.locator('button').nth(2).click()
|
||||
await expect(activeChip(page)).not.toHaveText(day1)
|
||||
})
|
||||
@@ -0,0 +1,105 @@
|
||||
import { test, expect, devices } from '@playwright/test'
|
||||
import { dismissSystemNotices } from './helpers'
|
||||
|
||||
// Phone regression guard for #1809: the dashboard must scroll the DOCUMENT.
|
||||
//
|
||||
// iOS Safari minimises its address bar only in reaction to the root scroller
|
||||
// moving. V4 blocked that twice over: html was globally overflow:hidden and the
|
||||
// mobile shell added a scroll container of its own, so the gesture never
|
||||
// reached the viewport and the bar kept ~1/6th of the screen forever. The bar
|
||||
// itself is not observable from page context, but the invariant it hangs off is:
|
||||
// document.scrollingElement has to move.
|
||||
//
|
||||
// Needs WebKit (`npx playwright install webkit`). playwright.config.ts has no
|
||||
// webkit project, the engine comes from this file-level device (defaultBrowserType
|
||||
// 'webkit'), same as e2e/ipad-scroll-1432.spec.ts. WebKit is the point here, not
|
||||
// a nicety: viewport propagation and the toolbar behaviour are Safari's.
|
||||
//
|
||||
// The file sorts last in the e2e run, so the trips it seeds cannot show up in
|
||||
// another spec's dashboard assertions.
|
||||
test.use({ ...devices['iPhone 14'] })
|
||||
|
||||
function readScroll() {
|
||||
const el = document.scrollingElement as HTMLElement
|
||||
return {
|
||||
top: el.scrollTop,
|
||||
scrollHeight: el.scrollHeight,
|
||||
viewport: window.innerHeight,
|
||||
htmlOverflow: getComputedStyle(document.documentElement).overflowY,
|
||||
}
|
||||
}
|
||||
|
||||
test('#1809 iPhone: flow screens scroll the document, full-screen ones do not', async ({ page }) => {
|
||||
await page.goto('/dashboard')
|
||||
await dismissSystemNotices(page)
|
||||
|
||||
// The context has to be the one from the report: phone width, coarse pointer.
|
||||
// If either is wrong, nothing below proves anything.
|
||||
const env = await page.evaluate(() => ({
|
||||
width: window.innerWidth,
|
||||
coarse: window.matchMedia('(pointer: coarse)').matches,
|
||||
}))
|
||||
expect(env.width, 'iPhone sits below the 768px phone breakpoint').toBeLessThan(768)
|
||||
expect(env.coarse, 'iPhone reports a coarse primary pointer').toBe(true)
|
||||
|
||||
// Enough trips for the dashboard to overflow a phone screen.
|
||||
const stamp = Date.now()
|
||||
for (let i = 1; i <= 20; i++) {
|
||||
const res = await page.request.post('/api/trips', {
|
||||
data: { title: `URL bar ${stamp} ${i}`, start_date: '2099-06-01', end_date: '2099-06-10' },
|
||||
})
|
||||
expect(res.ok(), `seed trip ${i}`).toBeTruthy()
|
||||
}
|
||||
await page.reload()
|
||||
await dismissSystemNotices(page)
|
||||
await expect(page.getByText(`URL bar ${stamp} 1`).first()).toBeVisible({ timeout: 20_000 })
|
||||
|
||||
// 1. The root scroller is unlocked and the page is longer than the viewport.
|
||||
const before = await page.evaluate(readScroll)
|
||||
expect(before.htmlOverflow, 'html must not lock the viewport scroller').not.toBe('hidden')
|
||||
expect(before.scrollHeight, 'dashboard is longer than one viewport').toBeGreaterThan(before.viewport)
|
||||
expect(before.top).toBe(0)
|
||||
|
||||
// 2. Scrolling moves the document, the signal Safari retracts its bar for.
|
||||
await page.evaluate(() => window.scrollBy(0, 400))
|
||||
const scrolled = await page.evaluate(readScroll)
|
||||
expect(scrolled.top, 'the document itself scrolled').toBeGreaterThan(0)
|
||||
|
||||
// 3. The brand tile scrolls the page back up (it used to walk up to the shell
|
||||
// container, which no longer exists).
|
||||
await page.getByRole('button', { name: 'TREK' }).click()
|
||||
await expect.poll(() => page.evaluate(() => document.scrollingElement!.scrollTop)).toBe(0)
|
||||
|
||||
// 4. The shared body scroll lock: with the document as the scroller, an open
|
||||
// sheet must freeze the page behind it and give the position back.
|
||||
await page.evaluate(() => window.scrollBy(0, 300))
|
||||
const locked = await page.evaluate(readScroll)
|
||||
expect(locked.top).toBeGreaterThan(0)
|
||||
|
||||
await page.getByRole('button', { name: 'New Trip' }).click()
|
||||
await expect(page.getByRole('dialog')).toBeVisible()
|
||||
await page.evaluate(() => window.scrollBy(0, 300))
|
||||
expect(await page.evaluate(() => document.scrollingElement!.scrollTop)).toBe(locked.top)
|
||||
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(page.getByRole('dialog')).toHaveCount(0)
|
||||
expect(await page.evaluate(() => document.scrollingElement!.scrollTop)).toBe(locked.top)
|
||||
await page.evaluate(() => window.scrollBy(0, 200))
|
||||
expect(await page.evaluate(() => document.scrollingElement!.scrollTop)).toBeGreaterThan(locked.top)
|
||||
|
||||
// 5. Counter-probe: the map screens keep their own full-viewport layout. They
|
||||
// deliberately do NOT scroll the document (and so keep the address bar), and
|
||||
// the map must not collapse to zero height now that the shell has none.
|
||||
await page.goto('/atlas')
|
||||
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 })
|
||||
const atlas = await page.evaluate(() => {
|
||||
const map = document.querySelector('.leaflet-container') as HTMLElement
|
||||
window.scrollBy(0, 400)
|
||||
return {
|
||||
top: document.scrollingElement!.scrollTop,
|
||||
mapHeight: map.getBoundingClientRect().height,
|
||||
}
|
||||
})
|
||||
expect(atlas.top, 'the atlas does not move the document').toBe(0)
|
||||
expect(atlas.mapHeight, 'the atlas map keeps a real height').toBeGreaterThan(200)
|
||||
})
|
||||
@@ -75,4 +75,25 @@ export default tseslint.config(
|
||||
'preserve-caught-error': 'warn',
|
||||
},
|
||||
},
|
||||
{
|
||||
// react-dom/server was worth ~190 KB raw / 57 KB gzip in a chunk three lazy
|
||||
// routes share — including the Leaflet renderer, which is the default — for
|
||||
// output that is always a single <svg>. utils/iconMarkup.ts does that job
|
||||
// without Fizz, and this keeps the import from creeping back: nothing else
|
||||
// would notice, the build stays green and the app keeps working.
|
||||
files: ['src/**/*.{ts,tsx}'],
|
||||
ignores: ['src/**/*.test.{ts,tsx}'],
|
||||
rules: {
|
||||
'no-restricted-imports': ['error', {
|
||||
paths: [{
|
||||
name: 'react-dom/server',
|
||||
message: 'Use renderIconMarkup from utils/iconMarkup — Fizz is ~190 KB for one <svg>.',
|
||||
}],
|
||||
}],
|
||||
'no-restricted-syntax': ['error', {
|
||||
selector: "ImportExpression > Literal[value=/^react-dom\\u002F(server|static)/]",
|
||||
message: 'Use renderIconMarkup from utils/iconMarkup — Fizz is ~190 KB for one <svg>.',
|
||||
}],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
+1
-4
@@ -19,10 +19,7 @@
|
||||
<!-- Favicon -->
|
||||
<link rel="icon" type="image/svg+xml" href="/icons/icon.svg" />
|
||||
|
||||
<!-- Fonts -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link href="https://fonts.googleapis.com/css2?family=MuseoModerno:wght@400;700;800&display=swap" rel="stylesheet" />
|
||||
<!-- Fonts are bundled from @fontsource in src/main.tsx, see the note there. -->
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
+12
-6
@@ -7,6 +7,7 @@
|
||||
"dev": "vite",
|
||||
"prebuild": "node scripts/generate-icons.mjs",
|
||||
"build": "vite build",
|
||||
"build:analyze": "vite build --mode analyze",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
@@ -17,6 +18,7 @@
|
||||
"lint": "eslint .",
|
||||
"lint:check": "eslint .",
|
||||
"lint:pages": "node scripts/check-page-pattern.mjs",
|
||||
"check:gl-split": "node scripts/check-gl-split.mjs",
|
||||
"theme:lint": "node scripts/theme-lint.mjs",
|
||||
"theme:lint:strict": "node scripts/theme-lint.mjs --strict",
|
||||
"e2e": "playwright test",
|
||||
@@ -27,9 +29,14 @@
|
||||
"format:check": "prettier --check \"src/**/*.tsx\" \"src/**/*.css\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/bebas-neue": "^5.3.0",
|
||||
"@fontsource/eb-garamond": "^5.3.0",
|
||||
"@fontsource/geist-sans": "^5.2.5",
|
||||
"@fontsource/inter": "^5.3.0",
|
||||
"@fontsource/lora": "^5.3.0",
|
||||
"@fontsource/museomoderno": "^5.3.0",
|
||||
"@fontsource/playfair-display": "^5.3.0",
|
||||
"@fontsource/poppins": "^5.2.7",
|
||||
"@react-pdf/renderer": "^4.5.1",
|
||||
"@simplewebauthn/browser": "^13.1.2",
|
||||
"@trek/shared": "*",
|
||||
"axios": "^1.6.7",
|
||||
@@ -49,15 +56,14 @@
|
||||
"react-leaflet": "^5.0.0",
|
||||
"react-leaflet-cluster": "^4.1.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router-dom": "^6.22.2",
|
||||
"react-window": "^2.2.7",
|
||||
"react-router": "^7.18.2",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-breaks": "^4.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"topojson-client": "^3.1.0",
|
||||
"tz-lookup": "^6.1.25",
|
||||
"zod": "^4.3.6",
|
||||
"zustand": "^4.5.2"
|
||||
"zustand": "^5.0.14"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
@@ -70,7 +76,6 @@
|
||||
"@types/node": "^25.9.3",
|
||||
"@types/react": "^19.2.15",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/react-window": "^1.8.8",
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"@vitest/coverage-v8": "^4.1.9",
|
||||
"autoprefixer": "^10.4.18",
|
||||
@@ -86,7 +91,8 @@
|
||||
"prettier": "^3.8.3",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
"prettier-plugin-tailwindcss": "^0.8.0",
|
||||
"sharp": "^0.33.0",
|
||||
"rollup-plugin-visualizer": "^7.0.1",
|
||||
"sharp": "^0.35.0",
|
||||
"tailwindcss": "^3.4.1",
|
||||
"typescript": "^6.0.2",
|
||||
"typescript-eslint": "^8.58.2",
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Country silhouettes for TREK Studio, built from the boundaries the server
|
||||
* already bundles for Atlas.
|
||||
*
|
||||
* node scripts/build-country-shapes.mjs
|
||||
*
|
||||
* Writes `src/components/Studio/countryShapes.ts`. Run it when
|
||||
* `server/assets/atlas/admin0.geojson.gz` changes; the output is committed, so
|
||||
* a normal build never runs this.
|
||||
*
|
||||
* ── Why a second, tiny copy of the boundaries ─────────────────────────────
|
||||
*
|
||||
* Atlas's admin-0 file is 4.3MB gzipped and ~30MB parsed, sized for a slippy
|
||||
* map you can zoom into. A book page draws a country at 20mm across, where the
|
||||
* ten thousand points describing a fjord land inside one printer dot. Shipping
|
||||
* the map data to draw a stamp would cost more than the entire Studio bundle.
|
||||
*
|
||||
* So: project, drop the islands nobody can see at that size, simplify hard, and
|
||||
* normalise each country into its own 0..100 box. What comes out is a few
|
||||
* hundred bytes per country and prints identically, because at 20mm it *is*
|
||||
* identical.
|
||||
*
|
||||
* ── The three things that are easy to get wrong ───────────────────────────
|
||||
*
|
||||
* 1. **Project before simplifying.** Simplifying in degrees and projecting
|
||||
* afterwards removes the wrong points: a degree of longitude is 111km at the
|
||||
* equator and 30km at Reykjavík, so a fixed tolerance eats Iceland's coast
|
||||
* while leaving Kenya's untouched.
|
||||
* 2. **Countries that cross the antimeridian.** Russia and Fiji have parts at
|
||||
* +179 and -179. Taken literally their bounding box is the whole world and
|
||||
* the silhouette is a horizontal smear. Rings that span more than half the
|
||||
* globe get their negative longitudes lifted by 360 so the country is
|
||||
* contiguous again.
|
||||
* 3. **Islands.** Keeping every ring turns Norway into a dust cloud and Greece
|
||||
* into static. Rings below a fraction of the largest one are dropped — the
|
||||
* mainland is what makes a country recognisable at a glance.
|
||||
*/
|
||||
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import url from 'node:url'
|
||||
import zlib from 'node:zlib'
|
||||
|
||||
const HERE = path.dirname(url.fileURLToPath(import.meta.url))
|
||||
const SRC = path.join(HERE, '..', '..', 'server', 'assets', 'atlas', 'admin0.geojson.gz')
|
||||
const OUT = path.join(HERE, '..', 'src', 'components', 'Studio', 'countryShapes.ts')
|
||||
|
||||
/** Rings smaller than this share of the biggest one are not drawn. */
|
||||
const ISLAND_CUTOFF = 0.012
|
||||
/** Never draw more than this many rings for one country. */
|
||||
const MAX_RINGS = 14
|
||||
/** Point budget per country, across every ring it keeps. */
|
||||
const MAX_POINTS = 190
|
||||
|
||||
/** Web Mercator, unscaled. y is flipped so it grows downwards like SVG's. */
|
||||
function project([lng, lat]) {
|
||||
const clamped = Math.max(-85.05, Math.min(85.05, lat))
|
||||
const rad = (clamped * Math.PI) / 180
|
||||
return [lng, -(Math.log(Math.tan(Math.PI / 4 + rad / 2)) * 180) / Math.PI]
|
||||
}
|
||||
|
||||
function ringArea(ring) {
|
||||
let a = 0
|
||||
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
|
||||
a += ring[j][0] * ring[i][1] - ring[i][0] * ring[j][1]
|
||||
}
|
||||
return Math.abs(a / 2)
|
||||
}
|
||||
|
||||
/** Perpendicular distance from p to the segment ab, squared. */
|
||||
function segDistSq(p, a, b) {
|
||||
let x = a[0], y = a[1]
|
||||
let dx = b[0] - x, dy = b[1] - y
|
||||
if (dx !== 0 || dy !== 0) {
|
||||
const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy)
|
||||
if (t > 1) { x = b[0]; y = b[1] } else if (t > 0) { x += dx * t; y += dy * t }
|
||||
}
|
||||
dx = p[0] - x
|
||||
dy = p[1] - y
|
||||
return dx * dx + dy * dy
|
||||
}
|
||||
|
||||
/** Douglas-Peucker, iterative so a long coastline cannot blow the stack. */
|
||||
function simplify(points, tolerance) {
|
||||
if (points.length < 3) return points
|
||||
const tolSq = tolerance * tolerance
|
||||
const keep = new Uint8Array(points.length)
|
||||
keep[0] = 1
|
||||
keep[points.length - 1] = 1
|
||||
const stack = [[0, points.length - 1]]
|
||||
|
||||
while (stack.length) {
|
||||
const [first, last] = stack.pop()
|
||||
let maxSq = 0
|
||||
let index = 0
|
||||
for (let i = first + 1; i < last; i++) {
|
||||
const d = segDistSq(points[i], points[first], points[last])
|
||||
if (d > maxSq) { maxSq = d; index = i }
|
||||
}
|
||||
if (maxSq > tolSq) {
|
||||
keep[index] = 1
|
||||
stack.push([first, index], [index, last])
|
||||
}
|
||||
}
|
||||
return points.filter((_, i) => keep[i])
|
||||
}
|
||||
|
||||
/** Every outer ring of a Polygon or MultiPolygon, holes discarded. */
|
||||
function outerRings(geometry) {
|
||||
if (!geometry) return []
|
||||
if (geometry.type === 'Polygon') return geometry.coordinates.slice(0, 1)
|
||||
if (geometry.type === 'MultiPolygon') return geometry.coordinates.map(poly => poly[0])
|
||||
return []
|
||||
}
|
||||
|
||||
/**
|
||||
* Lift a ring that straddles the antimeridian into a continuous longitude
|
||||
* range. A ring whose points span more than half the globe is, in practice,
|
||||
* always a wrap rather than a genuinely hemisphere-wide landmass.
|
||||
*/
|
||||
function unwrap(ring) {
|
||||
let min = Infinity
|
||||
let max = -Infinity
|
||||
for (const [lng] of ring) { if (lng < min) min = lng; if (lng > max) max = lng }
|
||||
if (max - min <= 180) return ring
|
||||
return ring.map(([lng, lat]) => [lng < 0 ? lng + 360 : lng, lat])
|
||||
}
|
||||
|
||||
function build(feature) {
|
||||
const rings = outerRings(feature.geometry)
|
||||
.map(unwrap)
|
||||
.map(ring => ring.map(project))
|
||||
.map(ring => ({ ring, area: ringArea(ring) }))
|
||||
.sort((a, b) => b.area - a.area)
|
||||
|
||||
if (!rings.length) return null
|
||||
|
||||
const biggest = rings[0].area
|
||||
const kept = rings
|
||||
.filter(r => r.area >= biggest * ISLAND_CUTOFF)
|
||||
.slice(0, MAX_RINGS)
|
||||
.map(r => r.ring)
|
||||
|
||||
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
|
||||
for (const ring of kept) {
|
||||
for (const [x, y] of ring) {
|
||||
if (x < minX) minX = x
|
||||
if (x > maxX) maxX = x
|
||||
if (y < minY) minY = y
|
||||
if (y > maxY) maxY = y
|
||||
}
|
||||
}
|
||||
const spanX = maxX - minX
|
||||
const spanY = maxY - minY
|
||||
if (!(spanX > 0) || !(spanY > 0)) return null
|
||||
|
||||
// The longer side becomes 100 and the shorter one keeps its proportion, so a
|
||||
// country never has to be squashed to fit the box it is drawn in.
|
||||
const scale = 100 / Math.max(spanX, spanY)
|
||||
const w = spanX * scale
|
||||
const h = spanY * scale
|
||||
const normalised = kept.map(ring =>
|
||||
ring.map(([x, y]) => [(x - minX) * scale, (y - minY) * scale]))
|
||||
|
||||
// Tolerance climbs until the whole country fits its point budget. Starting
|
||||
// from the diagonal keeps the loop short for a country of any size.
|
||||
let tolerance = 0.14
|
||||
let simplified = normalised.map(r => simplify(r, tolerance))
|
||||
let guard = 0
|
||||
while (simplified.reduce((n, r) => n + r.length, 0) > MAX_POINTS && guard++ < 40) {
|
||||
tolerance *= 1.35
|
||||
simplified = normalised.map(r => simplify(r, tolerance))
|
||||
}
|
||||
|
||||
const d = simplified
|
||||
.filter(ring => ring.length >= 3)
|
||||
.map(ring => `M${ring.map(([x, y]) => `${round(x)} ${round(y)}`).join('L')}Z`)
|
||||
.join('')
|
||||
|
||||
// The projected bounds, kept so the same path can be replayed in world
|
||||
// coordinates. A country drawn on its own wants its own box; the same country
|
||||
// on a route map has to sit where it actually is, next to its neighbours. One
|
||||
// normalised path plus these four numbers serves both, where storing two sets
|
||||
// of coordinates would be twice the bytes and one more thing to disagree.
|
||||
return d ? { d, w: round(w), h: round(h), b: [minX, minY, maxX, maxY].map(v => Math.round(v * 100) / 100) } : null
|
||||
}
|
||||
|
||||
const round = n => Math.round(n * 10) / 10
|
||||
|
||||
const raw = zlib.gunzipSync(fs.readFileSync(SRC))
|
||||
const collection = JSON.parse(raw.toString('utf8'))
|
||||
|
||||
const shapes = new Map()
|
||||
for (const feature of collection.features) {
|
||||
const code = String(feature.properties?.ISO_A2 || '').toUpperCase()
|
||||
if (code.length !== 2 || code === '-9') continue
|
||||
const built = build(feature)
|
||||
if (!built) continue
|
||||
// A code appearing twice means two features for one country; keep the one
|
||||
// with more outline, which is the mainland rather than a dependency.
|
||||
const prev = shapes.get(code)
|
||||
if (!prev || built.d.length > prev.d.length) shapes.set(code, built)
|
||||
}
|
||||
|
||||
const codes = [...shapes.keys()].sort()
|
||||
const body = codes
|
||||
.map(code => {
|
||||
const s = shapes.get(code)
|
||||
return ` ${code}: { d: '${s.d}', w: ${s.w}, h: ${s.h}, b: [${s.b.join(', ')}] },`
|
||||
})
|
||||
.join('\n')
|
||||
|
||||
const file = `/**
|
||||
* GENERATED — do not edit. Run \`node scripts/build-country-shapes.mjs\`.
|
||||
*
|
||||
* Country silhouettes, simplified from the admin-0 boundaries the server
|
||||
* bundles for Atlas (geoBoundaries, CC BY 4.0). Each path is Web Mercator,
|
||||
* normalised so the longer side is 100 units; \`w\` and \`h\` give the shape's
|
||||
* own proportions inside that box so it can be drawn without being squashed.
|
||||
*
|
||||
* ${codes.length} countries, built for print at postage-stamp size — islands
|
||||
* below ${ISLAND_CUTOFF * 100}% of the mainland are dropped and each outline is
|
||||
* simplified to at most ${MAX_POINTS} points.
|
||||
*/
|
||||
|
||||
export interface CountryShape {
|
||||
/** Path on a 0..100 box, outer rings only. */
|
||||
d: string
|
||||
/** The shape's own width and height inside that box. */
|
||||
w: number
|
||||
h: number
|
||||
/** Projected bounds \`[minX, minY, maxX, maxY]\`, for drawing it in place. */
|
||||
b: [number, number, number, number]
|
||||
}
|
||||
|
||||
/**
|
||||
* Web Mercator, matching the projection the paths were built with. Longitude
|
||||
* passes through as degrees; latitude is flipped so y grows downwards like
|
||||
* SVG's does.
|
||||
*/
|
||||
export function projectMercator(lng: number, lat: number): { x: number; y: number } {
|
||||
const clamped = Math.max(-85.05, Math.min(85.05, lat))
|
||||
const rad = (clamped * Math.PI) / 180
|
||||
return { x: lng, y: -(Math.log(Math.tan(Math.PI / 4 + rad / 2)) * 180) / Math.PI }
|
||||
}
|
||||
|
||||
/**
|
||||
* The same outline, placed in projected world coordinates.
|
||||
*
|
||||
* The stored path is normalised into its own box; multiplying by the box's span
|
||||
* and shifting by its origin puts it back where the country actually is, which
|
||||
* is what a map with more than one country on it needs.
|
||||
*/
|
||||
export function countryWorldPath(shape: CountryShape): string {
|
||||
const span = Math.max(shape.b[2] - shape.b[0], shape.b[3] - shape.b[1]) / 100
|
||||
let axis = 0
|
||||
return shape.d.replace(/-?\\d*\\.?\\d+/g, m => {
|
||||
const isX = axis++ % 2 === 0
|
||||
const v = Number(m) * span + (isX ? shape.b[0] : shape.b[1])
|
||||
return String(Math.round(v * 1000) / 1000)
|
||||
})
|
||||
}
|
||||
|
||||
export const COUNTRY_SHAPES: Record<string, CountryShape> = {
|
||||
${body}
|
||||
}
|
||||
|
||||
/** The silhouette for an ISO-3166-1 alpha-2 code, or null if we have none. */
|
||||
export function countryShape(code: string | null | undefined): CountryShape | null {
|
||||
if (!code) return null
|
||||
return COUNTRY_SHAPES[code.toUpperCase()] ?? null
|
||||
}
|
||||
`
|
||||
|
||||
fs.writeFileSync(OUT, file, 'utf8')
|
||||
const kb = Math.round(Buffer.byteLength(file) / 102.4) / 10
|
||||
console.log(`[country-shapes] ${codes.length} countries, ${kb} kB → ${path.relative(process.cwd(), OUT)}`)
|
||||
@@ -0,0 +1,47 @@
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
/**
|
||||
* Fails when a built chunk contains both WebGL map engines.
|
||||
*
|
||||
* mapbox-gl and maplibre-gl used to be static imports in the same three
|
||||
* components, so rollup emitted a single 2.8 MB chunk carrying both. Every map
|
||||
* user downloaded 1.8 MB of mapbox plus 1.1 MB of maplibre and ran one of them.
|
||||
* A stray static import anywhere in the map tree brings that straight back, and
|
||||
* nothing else would notice — the build stays green and the app still works.
|
||||
*
|
||||
* The markers are chosen to appear only inside the SDKs themselves, verified in
|
||||
* node_modules. Do NOT test for the bare string "maplibre": the provider value
|
||||
* 'maplibre-gl' and the setting key maplibre_style also appear in app code, so it
|
||||
* matches the shared core chunk too.
|
||||
*/
|
||||
const DIR = 'dist/assets'
|
||||
const MAPBOX = 'events.mapbox.com' // 1 hit in mapbox-gl, 0 in maplibre-gl
|
||||
const MAPLIBRE = 'maplibregl-canvas' // 2 hits in maplibre-gl, 0 in mapbox-gl
|
||||
|
||||
let mixed = 0
|
||||
let found = 0
|
||||
|
||||
for (const file of readdirSync(DIR).filter(f => f.endsWith('.js'))) {
|
||||
const path = join(DIR, file)
|
||||
const src = readFileSync(path, 'utf8')
|
||||
const hasMapbox = src.includes(MAPBOX)
|
||||
const hasMaplibre = src.includes(MAPLIBRE)
|
||||
if (!hasMapbox && !hasMaplibre) continue
|
||||
|
||||
found++
|
||||
const size = statSync(path).size
|
||||
if (hasMapbox && hasMaplibre) {
|
||||
console.error(`FAIL both GL engines in one chunk: ${file} (${size} B)`)
|
||||
mixed++
|
||||
} else {
|
||||
console.log(`${hasMapbox ? 'mapbox ' : 'maplibre'} ${file} ${size} B`)
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
console.error('FAIL no chunk contains either GL engine — did the build run?')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
process.exit(mixed ? 1 : 0)
|
||||
@@ -2,9 +2,12 @@
|
||||
// src/pages/PATTERN.md). A *Page.tsx default-export component should wire a
|
||||
// co-located use<Page>() hook into JSX — it must not own state/effects itself.
|
||||
//
|
||||
// We scan only the default-export component body (from `export default function`
|
||||
// up to the next top-level `function` declaration or EOF), so presentational
|
||||
// sub-components and helper hooks living in the same file are not flagged.
|
||||
// We scan the default-export component body (from `export default function` up
|
||||
// to the next top-level `function` declaration or EOF), and the same span of a
|
||||
// top-level `*PageDesktop`/`*PageMobile` — since ViewportRoute started picking
|
||||
// the branch, the default export is a two-line shim and the real container is
|
||||
// one of those two. Everything else at top level stays exempt: presentational
|
||||
// sub-components and helper hooks live in these files on purpose.
|
||||
// Context hooks like useTranslation/useParams are fine; the smell is stateful
|
||||
// logic — useState/useReducer/useEffect/useLayoutEffect/useMemo/useCallback/useRef.
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
@@ -13,23 +16,38 @@ import { fileURLToPath } from 'node:url'
|
||||
|
||||
const pagesDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'pages')
|
||||
const BANNED = ['useState', 'useReducer', 'useEffect', 'useLayoutEffect', 'useMemo', 'useCallback', 'useRef']
|
||||
const bannedRe = new RegExp(`\\b(${BANNED.join('|')})\\s*\\(`)
|
||||
// `[<(]` rather than `\(`: a generic call — `useRef<() => void>(null)` — is the
|
||||
// same thing, and it slipped through for as long as the pattern only knew `(`.
|
||||
const bannedRe = new RegExp(`\\b(${BANNED.join('|')})\\s*[<(]`)
|
||||
|
||||
// Declarations the widened scan caught that are not this change's to move.
|
||||
// Listed by the name they declare rather than by line, so an entry dies with
|
||||
// its declaration instead of drifting onto whatever follows it. The rest of
|
||||
// each listed file is still checked.
|
||||
const KNOWN_ESCAPES = {
|
||||
'TripPlannerPage.tsx': ['glMap', 'bookingExpense'],
|
||||
}
|
||||
|
||||
const violations = []
|
||||
for (const file of readdirSync(pagesDir)) {
|
||||
if (!file.endsWith('Page.tsx') || file.endsWith('.test.tsx')) continue
|
||||
const src = readFileSync(join(pagesDir, file), 'utf8')
|
||||
const lines = src.split('\n')
|
||||
const start = lines.findIndex(l => /export default function/.test(l))
|
||||
if (start === -1) continue
|
||||
// The page body ends at the next top-level declaration (a `function` at
|
||||
// column 0) — everything after that is a sub-component or helper.
|
||||
let end = lines.length
|
||||
for (let i = start + 1; i < lines.length; i++) {
|
||||
if (/^(function |const [A-Z]\w* = )/.test(lines[i])) { end = i; break }
|
||||
}
|
||||
for (let i = start; i < end; i++) {
|
||||
if (bannedRe.test(lines[i])) {
|
||||
const allowed = KNOWN_ESCAPES[file] ?? []
|
||||
const starts = []
|
||||
lines.forEach((line, i) => {
|
||||
if (/export default function/.test(line) || /^function \w+Page(Desktop|Mobile)\b/.test(line)) starts.push(i)
|
||||
})
|
||||
for (const start of starts) {
|
||||
// The page body ends at the next top-level declaration (a `function` at
|
||||
// column 0) — everything after that is a sub-component or helper.
|
||||
let end = lines.length
|
||||
for (let i = start + 1; i < lines.length; i++) {
|
||||
if (/^(function |const [A-Z]\w* = )/.test(lines[i])) { end = i; break }
|
||||
}
|
||||
for (let i = start; i < end; i++) {
|
||||
if (!bannedRe.test(lines[i])) continue
|
||||
if (allowed.some(name => new RegExp(`\\b${name}\\b`).test(lines[i]))) continue
|
||||
violations.push(`${file}:${i + 1} ${lines[i].trim()}`)
|
||||
}
|
||||
}
|
||||
|
||||
+260
-4
@@ -1,13 +1,15 @@
|
||||
import React from 'react'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { render, screen, waitFor, act } from '@testing-library/react'
|
||||
import { MemoryRouter, useLocation } from 'react-router'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { server } from '../tests/helpers/msw/server'
|
||||
import { useAuthStore } from './store/authStore'
|
||||
import { useSettingsStore } from './store/settingsStore'
|
||||
import { resetAllStores } from '../tests/helpers/store'
|
||||
import { buildUser, buildSettings } from '../tests/helpers/factories'
|
||||
import { buildUser, buildSettings, buildTrip } from '../tests/helpers/factories'
|
||||
import { offlineDb } from './db/offlineDb'
|
||||
import { SETTINGS_WAIT_MS } from './utils/startDestination'
|
||||
import App from './App'
|
||||
|
||||
// ── Mock page components ───────────────────────────────────────────────────────
|
||||
@@ -29,10 +31,19 @@ vi.mock('./hooks/useInAppNotificationListener.ts', () => ({
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Reports the router's current location, so a test can assert where App sent it. */
|
||||
function LocationProbe() {
|
||||
const loc = useLocation()
|
||||
return <span data-testid="loc">{loc.pathname + loc.search}</span>
|
||||
}
|
||||
|
||||
const currentPath = () => screen.getByTestId('loc').textContent
|
||||
|
||||
function renderApp(initialPath = '/') {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[initialPath]}>
|
||||
<App />
|
||||
<LocationProbe />
|
||||
</MemoryRouter>
|
||||
)
|
||||
}
|
||||
@@ -81,6 +92,105 @@ describe('RootRedirect', () => {
|
||||
})
|
||||
})
|
||||
|
||||
// ── RootRedirect — startup destination ────────────────────────────────────────
|
||||
|
||||
describe('RootRedirect — startup destination', () => {
|
||||
/** Serves GET /api/trips/active and reports whether it was asked at all. */
|
||||
function stubActiveTrip(trip: { id: number; title: string } | null) {
|
||||
const calls: string[] = []
|
||||
server.use(
|
||||
http.get('/api/trips/active', ({ request }) => {
|
||||
calls.push(request.url)
|
||||
return HttpResponse.json({ trip })
|
||||
}),
|
||||
)
|
||||
return calls
|
||||
}
|
||||
|
||||
it('FE-COMP-APP-026: opens the active trip on the chosen tab', async () => {
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({
|
||||
isLoaded: true,
|
||||
settings: buildSettings({ start_page: 'active_trip', start_trip_tab: 'finanzplan' }),
|
||||
})
|
||||
stubActiveTrip({ id: 42, title: 'Japan' })
|
||||
|
||||
renderApp('/')
|
||||
await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-027: falls back to the dashboard when the user has no trip', async () => {
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({
|
||||
isLoaded: true,
|
||||
settings: buildSettings({ start_page: 'active_trip', start_trip_tab: 'finanzplan' }),
|
||||
})
|
||||
stubActiveTrip(null)
|
||||
|
||||
renderApp('/')
|
||||
await waitFor(() => expect(screen.getByText('Dashboard')).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-028: falls back to the dashboard when the lookup fails', async () => {
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({
|
||||
isLoaded: true,
|
||||
settings: buildSettings({ start_page: 'active_trip' }),
|
||||
})
|
||||
server.use(http.get('/api/trips/active', () => HttpResponse.error()))
|
||||
|
||||
renderApp('/')
|
||||
await waitFor(() => expect(screen.getByText('Dashboard')).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-028b: opens the cached active trip when the launch is offline', async () => {
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({
|
||||
isLoaded: true,
|
||||
settings: buildSettings({ start_page: 'active_trip' }),
|
||||
})
|
||||
const today = new Date()
|
||||
const iso = (d: Date) => d.toISOString().slice(0, 10)
|
||||
await offlineDb.trips.put(buildTrip({ id: 42, title: 'Japan', start_date: iso(today), end_date: iso(today) }))
|
||||
const onLine = Object.getOwnPropertyDescriptor(Navigator.prototype, 'onLine')
|
||||
Object.defineProperty(navigator, 'onLine', { value: false, configurable: true })
|
||||
|
||||
// navigator and the Dexie table are shared with every other test in the
|
||||
// file, so a failed assertion must not leave the rest of them offline.
|
||||
try {
|
||||
renderApp('/')
|
||||
await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument())
|
||||
} finally {
|
||||
if (onLine) Object.defineProperty(Navigator.prototype, 'onLine', onLine)
|
||||
delete (navigator as unknown as { onLine?: boolean }).onLine
|
||||
await offlineDb.trips.clear()
|
||||
}
|
||||
})
|
||||
|
||||
// The whole point of the localStorage mirror: the default launch must not pay
|
||||
// for a lookup it doesn't need.
|
||||
it('FE-COMP-APP-029: never asks for the active trip when starting on the dashboard', async () => {
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({ isLoaded: true, settings: buildSettings({ start_page: 'dashboard' }) })
|
||||
const calls = stubActiveTrip({ id: 42, title: 'Japan' })
|
||||
|
||||
renderApp('/')
|
||||
await waitFor(() => expect(screen.getByText('Dashboard')).toBeInTheDocument())
|
||||
expect(calls).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-030: reads the preference from localStorage before settings have loaded', async () => {
|
||||
localStorage.setItem('trek_start_page', 'active_trip')
|
||||
localStorage.setItem('trek_start_trip_tab', 'finanzplan')
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({ isLoaded: false })
|
||||
stubActiveTrip({ id: 42, title: 'Japan' })
|
||||
|
||||
renderApp('/')
|
||||
await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument())
|
||||
})
|
||||
})
|
||||
|
||||
// ── ProtectedRoute — unauthenticated ──────────────────────────────────────────
|
||||
|
||||
describe('ProtectedRoute — unauthenticated', () => {
|
||||
@@ -90,6 +200,22 @@ describe('ProtectedRoute — unauthenticated', () => {
|
||||
await waitFor(() => expect(screen.getByText('Login')).toBeInTheDocument())
|
||||
})
|
||||
|
||||
// A session that ran out should return you to the page you were on. Pressing
|
||||
// "log out" should not: clearing isAuthenticated re-renders this route for the
|
||||
// page still on screen, and the ?redirect= it stamped there beat the user's
|
||||
// startup destination on every login after the first.
|
||||
it('FE-COMP-APP-034: keeps the return ticket when the session merely ended', async () => {
|
||||
seedAuth({ isAuthenticated: false, loggingOut: false })
|
||||
renderApp('/trips/1/files')
|
||||
await waitFor(() => expect(currentPath()).toBe('/login?redirect=%2Ftrips%2F1%2Ffiles'))
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-035: drops it on a deliberate sign-out, so the startup destination decides', async () => {
|
||||
seedAuth({ isAuthenticated: false, loggingOut: true })
|
||||
renderApp('/dashboard')
|
||||
await waitFor(() => expect(currentPath()).toBe('/login'))
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-005: /trips/42 redirects to /login when not authenticated', async () => {
|
||||
seedAuth({ isAuthenticated: false })
|
||||
renderApp('/trips/42')
|
||||
@@ -169,6 +295,8 @@ describe('ProtectedRoute — admin role check', () => {
|
||||
// ── Public routes ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('Public routes', () => {
|
||||
// Synchronous on purpose: LoginPage is the one page still statically imported,
|
||||
// so this also holds the line against someone making it lazy later.
|
||||
it('FE-COMP-APP-012: /login is accessible without authentication', async () => {
|
||||
seedAuth({ isAuthenticated: false })
|
||||
renderApp('/login')
|
||||
@@ -178,7 +306,7 @@ describe('Public routes', () => {
|
||||
it('FE-COMP-APP-013: /shared/:token is accessible without authentication', async () => {
|
||||
seedAuth({ isAuthenticated: false })
|
||||
renderApp('/shared/sometoken')
|
||||
expect(screen.getByText('SharedTrip')).toBeInTheDocument()
|
||||
expect(await screen.findByText('SharedTrip')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-014: unknown routes redirect to / which then redirects to /login', async () => {
|
||||
@@ -188,6 +316,57 @@ describe('Public routes', () => {
|
||||
})
|
||||
})
|
||||
|
||||
// ── PublicRoute — redirect already-authenticated visitors ─────────────────────
|
||||
|
||||
describe('PublicRoute — already authenticated', () => {
|
||||
/**
|
||||
* The bounce goes to START_DESTINATION_ROUTE, so RootRedirect resolves where
|
||||
* it actually lands — which needs settings, exactly like the cases above.
|
||||
*/
|
||||
function seedAuthedOnDashboard() {
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({
|
||||
isLoaded: true,
|
||||
settings: buildSettings({ start_page: 'dashboard' }),
|
||||
})
|
||||
}
|
||||
|
||||
it('FE-COMP-APP-012a: /login sends an authenticated visitor to the start destination', async () => {
|
||||
seedAuthedOnDashboard()
|
||||
renderApp('/login')
|
||||
await waitFor(() => expect(currentPath()).toBe('/dashboard'))
|
||||
expect(screen.queryByText('Login')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-012b: /register does the same', async () => {
|
||||
seedAuthedOnDashboard()
|
||||
renderApp('/register')
|
||||
await waitFor(() => expect(currentPath()).toBe('/dashboard'))
|
||||
expect(screen.queryByText('Login')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-012c: /login with a ?redirect= target is left to useLogin (OAuth consent handoff), not bounced', async () => {
|
||||
// The consent page parks its URL in ?redirect= when it needs a login; that
|
||||
// flow must reach the form even for an authenticated visitor, so the guard
|
||||
// stays out of the way whenever a redirect target is present.
|
||||
seedAuthedOnDashboard()
|
||||
const target = '/login?redirect=' + encodeURIComponent('/oauth/consent?client_id=x')
|
||||
renderApp(target)
|
||||
await waitFor(() => expect(screen.getByText('Login')).toBeInTheDocument())
|
||||
expect(currentPath()).toBe(target)
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-012d: /register?invite= reaches the form so the token can be validated', async () => {
|
||||
// An invite link is the one way someone joins a trip they were invited to
|
||||
// from an account they are already signed into; bouncing it would swallow
|
||||
// the token silently.
|
||||
seedAuthedOnDashboard()
|
||||
renderApp('/register?invite=abc123')
|
||||
await waitFor(() => expect(screen.getByText('Login')).toBeInTheDocument())
|
||||
expect(currentPath()).toBe('/register?invite=abc123')
|
||||
})
|
||||
})
|
||||
|
||||
// ── App — on-mount effects ─────────────────────────────────────────────────────
|
||||
|
||||
describe('App — on-mount effects', () => {
|
||||
@@ -233,6 +412,30 @@ describe('App — on-mount effects', () => {
|
||||
await waitFor(() => expect(setDemoMode).toHaveBeenCalledWith(true))
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-018b: setManaged mirrors the config flag, and defaults to false when it is absent', async () => {
|
||||
server.use(
|
||||
http.get('/api/auth/app-config', () => HttpResponse.json({ managed: true }))
|
||||
)
|
||||
const setManaged = vi.fn()
|
||||
useAuthStore.setState({
|
||||
isLoading: false,
|
||||
isAuthenticated: false,
|
||||
loadUser: vi.fn().mockResolvedValue(undefined),
|
||||
setManaged,
|
||||
})
|
||||
renderApp('/')
|
||||
await waitFor(() => expect(setManaged).toHaveBeenCalledWith(true))
|
||||
|
||||
// An older server that does not send the field must not leave the flag
|
||||
// stuck on from a previous install in the same browser profile.
|
||||
setManaged.mockClear()
|
||||
server.use(
|
||||
http.get('/api/auth/app-config', () => HttpResponse.json({}))
|
||||
)
|
||||
renderApp('/')
|
||||
await waitFor(() => expect(setManaged).toHaveBeenCalledWith(false))
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-019: loadSettings is called once the user is authenticated', async () => {
|
||||
const loadSettings = vi.fn().mockResolvedValue(undefined)
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
@@ -320,3 +523,56 @@ describe('Version cache-busting', () => {
|
||||
await waitFor(() => expect(reload).toHaveBeenCalled())
|
||||
})
|
||||
})
|
||||
|
||||
// Regression: a device that has never mirrored the preference must not treat
|
||||
// "nothing mirrored" as "user wants the dashboard".
|
||||
describe('RootRedirect — preference not mirrored on this device', () => {
|
||||
it('FE-COMP-APP-031: honours the server setting when localStorage is empty', async () => {
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
// Cold start: settings are still in flight when RootRedirect first runs.
|
||||
useSettingsStore.setState({ isLoaded: false })
|
||||
server.use(http.get('/api/trips/active', () => HttpResponse.json({ trip: { id: 42, title: 'Japan' } })))
|
||||
|
||||
renderApp('/')
|
||||
|
||||
// ...and land a moment later, exactly as loadSettings() does.
|
||||
await act(async () => {
|
||||
useSettingsStore.setState({
|
||||
isLoaded: true,
|
||||
settings: buildSettings({ start_page: 'active_trip', start_trip_tab: 'finanzplan' }),
|
||||
})
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument())
|
||||
})
|
||||
|
||||
// Waiting for someone else's effect to fetch the settings made the decision
|
||||
// ride on where that request landed in the queue — behind ~380 others on a
|
||||
// cold start, which is how the redirect silently lost the race and fell
|
||||
// through to the dashboard. It now asks for them itself.
|
||||
it('FE-COMP-APP-033: asks for the settings itself instead of waiting to be told', async () => {
|
||||
const loadSettings = vi.fn().mockResolvedValue(undefined)
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({ isLoaded: false, loadSettings })
|
||||
|
||||
renderApp('/')
|
||||
|
||||
await waitFor(() => expect(loadSettings).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
// loadSettings leaves isLoaded false on a failed request so it can retry, so
|
||||
// the wait above needs a floor or a launch with no backend never resolves.
|
||||
it('FE-COMP-APP-032: gives up on the settings after the timeout and opens the dashboard', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({ isLoaded: false })
|
||||
|
||||
renderApp('/')
|
||||
expect(screen.queryByText('Dashboard')).not.toBeInTheDocument()
|
||||
|
||||
await act(async () => { vi.advanceTimersByTime(SETTINGS_WAIT_MS + 100) })
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Dashboard')).toBeInTheDocument())
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
|
||||
+373
-177
@@ -1,36 +1,27 @@
|
||||
import React, { useEffect, ReactNode } from 'react'
|
||||
import { Routes, Route, Navigate, useLocation } from 'react-router-dom'
|
||||
import React, { useEffect, useState, useRef, ReactNode, Suspense } from 'react'
|
||||
import { Routes, Route, Navigate, useLocation } from 'react-router'
|
||||
import { useAuthStore } from './store/authStore'
|
||||
import { useSettingsStore } from './store/settingsStore'
|
||||
import { applyAppearance } from './theme/applyAppearance'
|
||||
import { useAddonStore } from './store/addonStore'
|
||||
import { usePluginStore } from './store/pluginStore'
|
||||
import PluginPage from './pages/PluginPage'
|
||||
// The one page that stays in the entry chunk. Anyone logged out lands here, and
|
||||
// every other route redirects here first — a chunk round trip in front of the login
|
||||
// form would slow down the single screen that has to be there immediately.
|
||||
import LoginPage from './pages/LoginPage'
|
||||
import ForgotPasswordPage from './pages/ForgotPasswordPage'
|
||||
import ResetPasswordPage from './pages/ResetPasswordPage'
|
||||
import DashboardPage from './pages/DashboardPage'
|
||||
import TripPlannerPage from './pages/TripPlannerPage'
|
||||
import FilesPage from './pages/FilesPage'
|
||||
import AdminPage from './pages/AdminPage'
|
||||
import SettingsPage from './pages/SettingsPage'
|
||||
import VacayPage from './pages/VacayPage'
|
||||
import HelpPage from './pages/HelpPage'
|
||||
import AtlasPage from './pages/AtlasPage'
|
||||
import JourneyPage from './pages/JourneyPage'
|
||||
import JourneyDetailPage from './pages/JourneyDetailPage'
|
||||
import CollectionsPage from './pages/CollectionsPage'
|
||||
import JourneyPublicPage from './pages/JourneyPublicPage'
|
||||
import SharedTripPage from './pages/SharedTripPage'
|
||||
import JoinTripPage from './pages/JoinTripPage'
|
||||
import InAppNotificationsPage from './pages/InAppNotificationsPage.tsx'
|
||||
import OAuthAuthorizePage from './pages/OAuthAuthorizePage'
|
||||
import { ToastContainer } from './components/shared/Toast'
|
||||
import SaveToCollectionModal from './components/Collections/SaveToCollectionModal'
|
||||
import MSaveToCollectionSheet from './components/Collections/MSaveToCollectionSheet'
|
||||
import BackgroundTasksWidget from './components/BackgroundTasks/BackgroundTasksWidget'
|
||||
import BottomNav from './components/Layout/BottomNav'
|
||||
import MobileShell from './mobile/MobileShell'
|
||||
import MRouteFallback from './mobile/components/MRouteFallback'
|
||||
import ErrorBoundary from './components/shared/ErrorBoundary'
|
||||
import { lazyWithRetry } from './utils/lazyWithRetry'
|
||||
import { useIsPhone } from './mobile/useIsPhone'
|
||||
import { TranslationProvider, useTranslation } from './i18n'
|
||||
import { authApi } from './api/client'
|
||||
import { tripRepo } from './repo/tripRepo'
|
||||
import { readStartDestination, tripStartPath, DEFAULT_START_PAGE, DEFAULT_START_TRIP_TAB, SETTINGS_WAIT_MS, START_DESTINATION_ROUTE } from './utils/startDestination'
|
||||
import { usePermissionsStore, PermissionLevel } from './store/permissionsStore'
|
||||
import { useInAppNotificationListener } from './hooks/useInAppNotificationListener.ts'
|
||||
import { registerSyncTriggers, unregisterSyncTriggers } from './sync/syncTriggers'
|
||||
@@ -38,6 +29,50 @@ import OfflineBanner from './components/Layout/OfflineBanner'
|
||||
import { SystemNoticeHost } from './components/SystemNotices/SystemNoticeHost.js'
|
||||
// Notice action registrations (side-effect imports):
|
||||
import './pages/Trips/noticeActions.js'
|
||||
import { managedRoutes } from './managed'
|
||||
|
||||
// Every page below loads on demand. The entry chunk used to carry all twenty of
|
||||
// them eagerly, so opening /dashboard also paid for the planner, the journal, the
|
||||
// atlas and the vacation planner. lazyWithRetry rather than lazy: a chunk that
|
||||
// fails once gets a second, cache-busted attempt before the route boundary reaches
|
||||
// for a reload.
|
||||
const PluginPage = lazyWithRetry(() => import('./pages/PluginPage'))
|
||||
const ForgotPasswordPage = lazyWithRetry(() => import('./pages/ForgotPasswordPage'))
|
||||
const ResetPasswordPage = lazyWithRetry(() => import('./pages/ResetPasswordPage'))
|
||||
const DashboardPage = lazyWithRetry(() => import('./pages/DashboardPage'))
|
||||
const TripPlannerPage = lazyWithRetry(() => import('./pages/TripPlannerPage'))
|
||||
const FilesPage = lazyWithRetry(() => import('./pages/FilesPage'))
|
||||
const AdminPage = lazyWithRetry(() => import('./pages/AdminPage'))
|
||||
const SettingsPage = lazyWithRetry(() => import('./pages/SettingsPage'))
|
||||
const VacayPage = lazyWithRetry(() => import('./pages/VacayPage'))
|
||||
const HelpPage = lazyWithRetry(() => import('./pages/HelpPage'))
|
||||
const AtlasPage = lazyWithRetry(() => import('./pages/AtlasPage'))
|
||||
const JourneyPage = lazyWithRetry(() => import('./pages/JourneyPage'))
|
||||
const JourneyDetailPage = lazyWithRetry(() => import('./pages/JourneyDetailPage'))
|
||||
const JourneyStudioPage = lazyWithRetry(() => import('./pages/JourneyStudioPage'))
|
||||
const CollectionsPage = lazyWithRetry(() => import('./pages/CollectionsPage'))
|
||||
const JourneyPublicPage = lazyWithRetry(() => import('./pages/JourneyPublicPage'))
|
||||
const SharedTripPage = lazyWithRetry(() => import('./pages/SharedTripPage'))
|
||||
const JoinTripPage = lazyWithRetry(() => import('./pages/JoinTripPage'))
|
||||
const InAppNotificationsPage = lazyWithRetry(() => import('./pages/InAppNotificationsPage.tsx'))
|
||||
const OAuthAuthorizePage = lazyWithRetry(() => import('./pages/OAuthAuthorizePage'))
|
||||
|
||||
// The ten phone screens are chunks of their own, alongside the desktop pages
|
||||
// rather than inside them. Each page used to import its M screen statically and
|
||||
// decide while rendering, so the route chunk always carried both trees and the
|
||||
// viewport only picked which half stayed dark. Here the branch decides the
|
||||
// chunk: a phone never loads the desktop planner, a desktop never the mobile
|
||||
// shell.
|
||||
const MDashboardScreen = lazyWithRetry(() => import('./mobile/screens/dashboard/MDashboard'))
|
||||
const MTripScreen = lazyWithRetry(() => import('./mobile/screens/trip/MTripShell'))
|
||||
const MAdminScreen = lazyWithRetry(() => import('./mobile/screens/admin/MAdmin'))
|
||||
const MSettingsScreen = lazyWithRetry(() => import('./mobile/screens/settings/MSettings'))
|
||||
const MVacayScreen = lazyWithRetry(() => import('./mobile/screens/vacay/MVacay'))
|
||||
const MAtlasScreen = lazyWithRetry(() => import('./mobile/screens/atlas/MAtlas'))
|
||||
const MJourneyScreen = lazyWithRetry(() => import('./mobile/screens/journey/MJourney'))
|
||||
const MJourneyDetailScreen = lazyWithRetry(() => import('./mobile/screens/journey/MJourneyDetail'))
|
||||
const MCollectionsScreen = lazyWithRetry(() => import('./mobile/screens/collections/MCollections'))
|
||||
const MNotificationsScreen = lazyWithRetry(() => import('./mobile/screens/notifications/MNotifications'))
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children: ReactNode
|
||||
@@ -50,9 +85,11 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR
|
||||
const user = useAuthStore((s) => s.user)
|
||||
const isLoading = useAuthStore((s) => s.isLoading)
|
||||
const appRequireMfa = useAuthStore((s) => s.appRequireMfa)
|
||||
const loggingOut = useAuthStore((s) => s.loggingOut)
|
||||
const addonStore = useAddonStore()
|
||||
const { t } = useTranslation()
|
||||
const location = useLocation()
|
||||
const isPhone = useIsPhone()
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -66,6 +103,10 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
// A session that ended on its own should come back to where it left off; a
|
||||
// deliberate sign-out is a fresh start and gets no return ticket, so the
|
||||
// startup destination decides where the next login lands.
|
||||
if (loggingOut) return <Navigate to="/login" replace />
|
||||
const redirectParam = encodeURIComponent(location.pathname + location.search + location.hash)
|
||||
return <Navigate to={`/login?redirect=${redirectParam}`} replace />
|
||||
}
|
||||
@@ -87,18 +128,132 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR
|
||||
return <Navigate to="/dashboard" replace />
|
||||
}
|
||||
|
||||
// Below the md breakpoint the new mobile shell owns chrome (tokens, dock,
|
||||
// sheets, toasts); from 768px up the legacy wrapper stays untouched. The
|
||||
// shell branches internally so pages keep their state when the viewport
|
||||
// crosses the breakpoint.
|
||||
// The boundary sits inside the shell so a broken page keeps the navigation the
|
||||
// user needs to leave it — outside, the route would be a dead end, and the
|
||||
// mobile --m-* tokens live on the shell's .m-root anyway.
|
||||
//
|
||||
// key, not resetKeys: ProtectedRoute is the same component at the same position
|
||||
// for all 16 protected routes, so without it React could keep the failed
|
||||
// instance across a navigation and the error would follow the user around.
|
||||
return (
|
||||
<div className="flex flex-col h-dvh md:block md:h-auto">
|
||||
<div className="flex-1 overflow-y-auto md:overflow-visible">{children}</div>
|
||||
<BottomNav />
|
||||
</div>
|
||||
<MobileShell isPhone={isPhone}>
|
||||
<ErrorBoundary
|
||||
key={location.pathname}
|
||||
boundaryId="route"
|
||||
level="route"
|
||||
variant={isPhone ? 'mobile' : 'desktop'}
|
||||
>
|
||||
{children}
|
||||
</ErrorBoundary>
|
||||
</MobileShell>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The public routes render outside ProtectedRoute, so the route boundary above
|
||||
* never sees them — including /login, where someone lands when everything else
|
||||
* failed, and the two anonymous share pages.
|
||||
*/
|
||||
function PublicRoute({ children, redirectAuthed = false }: { children: React.ReactNode; redirectAuthed?: boolean }) {
|
||||
const location = useLocation()
|
||||
// redirectAuthed (only /login and /register) bounces a visitor who is already
|
||||
// authenticated when they land here — manual URL, browser back button (#1810).
|
||||
// Only on a bare URL, because every parameter this page takes is a flow that
|
||||
// has to reach useLogin intact: ?redirect= carries the OAuth consent handoff
|
||||
// (bouncing drops it, or loops if the server still reports login_required),
|
||||
// ?invite= puts the form into register mode against a validated token, and
|
||||
// ?oidc_code= / ?oidc_error= complete an external login. A visitor with any of
|
||||
// those in the URL asked for this page on purpose.
|
||||
// Capture the flag at mount so a fresh login is left alone: it flips
|
||||
// isAuthenticated to true while the takeoff animation still plays here, before
|
||||
// useLogin navigates away.
|
||||
// The target is START_DESTINATION_ROUTE, not /dashboard, so the bounce honours
|
||||
// the start-page preference the same way useLogin does.
|
||||
const wasAuthenticated = useRef(useAuthStore.getState().isAuthenticated)
|
||||
if (redirectAuthed && wasAuthenticated.current && !location.search) {
|
||||
return <Navigate to={START_DESTINATION_ROUTE} replace />
|
||||
}
|
||||
return (
|
||||
<ErrorBoundary key={location.pathname} boundaryId="public-route" level="route">
|
||||
{children}
|
||||
</ErrorBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the chunk, not just the branch. Both sides come through lazyWithRetry,
|
||||
* so exactly one of them is fetched for a given viewport — which is the whole
|
||||
* point: the ternary that used to sit in each page only ran once the browser
|
||||
* had already paid for both trees.
|
||||
*/
|
||||
function ViewportRoute({ phone: Phone, desktop: Desktop }: {
|
||||
phone: React.ComponentType
|
||||
desktop: React.ComponentType
|
||||
}): React.ReactElement {
|
||||
const isPhone = useIsPhone()
|
||||
return isPhone ? <Phone /> : <Desktop />
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry point every shortcut, bookmark and the installed PWA share
|
||||
* (manifest start_url is '/'), which is why the startup destination is decided
|
||||
* here rather than on /dashboard — landing on the dashboard directly has to keep
|
||||
* working, or there would be no way back to it.
|
||||
*
|
||||
* Once this device has seen the preference it comes from the localStorage
|
||||
* mirror, so the common launch waits for nothing. A device that has never seen
|
||||
* it waits for the settings instead of assuming the default — the preference
|
||||
* lives on the server, and guessing here would ignore it on every browser that
|
||||
* didn't set it. Only 'active_trip' costs the one lookup that finds the trip,
|
||||
* and any failure along the way lands on the dashboard.
|
||||
*/
|
||||
function RootRedirect() {
|
||||
const { isAuthenticated, isLoading } = useAuthStore()
|
||||
const settingsLoaded = useSettingsStore((s) => s.isLoaded)
|
||||
const settings = useSettingsStore((s) => s.settings)
|
||||
const loadSettings = useSettingsStore((s) => s.loadSettings)
|
||||
const [target, setTarget] = useState<string | null>(null)
|
||||
// Bounds the wait below: loadSettings deliberately leaves isLoaded false on a
|
||||
// failed request so it can retry, which would otherwise strand a launch that
|
||||
// started offline on the spinner.
|
||||
const [settingsGaveUp, setSettingsGaveUp] = useState(false)
|
||||
|
||||
if (isLoading) {
|
||||
useEffect(() => {
|
||||
if (settingsLoaded) return
|
||||
const timer = setTimeout(() => setSettingsGaveUp(true), SETTINGS_WAIT_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}, [settingsLoaded])
|
||||
|
||||
useEffect(() => {
|
||||
if (isLoading || !isAuthenticated || target) return
|
||||
const mirrored = readStartDestination()
|
||||
if (!mirrored && !settingsLoaded && !settingsGaveUp) {
|
||||
// Ask for the settings instead of waiting for whoever else might. The
|
||||
// store de-dupes concurrent loads, so this is free when one is already in
|
||||
// flight — and it stops the decision from riding on where that request
|
||||
// happens to land in the queue behind everything else a launch fires off.
|
||||
loadSettings()
|
||||
return
|
||||
}
|
||||
// Loaded settings are the truth; the mirror is what we knew last time.
|
||||
const { page, tab } = settingsLoaded
|
||||
? { page: settings.start_page ?? DEFAULT_START_PAGE, tab: settings.start_trip_tab ?? DEFAULT_START_TRIP_TAB }
|
||||
: (mirrored ?? { page: DEFAULT_START_PAGE, tab: DEFAULT_START_TRIP_TAB })
|
||||
if (page !== 'active_trip') { setTarget('/dashboard'); return }
|
||||
let cancelled = false
|
||||
// Through the repo, not the api: offline this answers from Dexie instead of
|
||||
// bouncing a cached trip to the dashboard.
|
||||
tripRepo.active()
|
||||
.then(({ trip }) => { if (!cancelled) setTarget(trip ? tripStartPath(trip.id, tab) : '/dashboard') })
|
||||
.catch(() => { if (!cancelled) setTarget('/dashboard') })
|
||||
return () => { cancelled = true }
|
||||
}, [isLoading, isAuthenticated, settingsLoaded, settingsGaveUp, settings, target])
|
||||
|
||||
if (isLoading || (isAuthenticated && !target)) {
|
||||
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-900 rounded-full animate-spin"></div>
|
||||
@@ -106,11 +261,29 @@ function RootRedirect() {
|
||||
)
|
||||
}
|
||||
|
||||
return <Navigate to={isAuthenticated ? '/dashboard' : '/login'} replace />
|
||||
return <Navigate to={isAuthenticated ? (target ?? '/dashboard') : '/login'} replace />
|
||||
}
|
||||
|
||||
/**
|
||||
* Shown while a route chunk is in flight. Same geometry as the auth spinner above,
|
||||
* but on theme tokens — that one predates the styleguide and a new surface does not
|
||||
* get to inherit its raw slate.
|
||||
*/
|
||||
function RouteFallback() {
|
||||
// The fallback renders above MobileShell, so it has to pick its own palette —
|
||||
// on a phone the desktop spinner on bg-surface would be a foreign white sheet
|
||||
// in front of the mobile screen.
|
||||
const isPhone = useIsPhone()
|
||||
if (isPhone) return <MRouteFallback />
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-surface">
|
||||
<div className="w-10 h-10 border-4 border-edge border-t-content rounded-full animate-spin"></div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const { loadUser, isAuthenticated, demoMode, setDemoMode, setDevMode, setIsPrerelease, setAppVersion, setHasMapsKey, setServerTimezone, setAppRequireMfa, setTripRemindersEnabled, setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled } = useAuthStore()
|
||||
const { loadUser, isAuthenticated, demoMode, setManaged, setDemoMode, setDevMode, setIsPrerelease, setAppVersion, setHasMapsKey, setServerTimezone, setAppRequireMfa, setTripRemindersEnabled, setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled, setPlacesEnrichEnabled } = useAuthStore()
|
||||
const { loadSettings } = useSettingsStore()
|
||||
const { loadAddons } = useAddonStore()
|
||||
const { loadPlugins } = usePluginStore()
|
||||
@@ -127,7 +300,8 @@ export default function App() {
|
||||
loadUser()
|
||||
}
|
||||
}
|
||||
authApi.getAppConfig().then(async (config: { demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; permissions?: Record<string, PermissionLevel> }) => {
|
||||
authApi.getAppConfig().then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; permissions?: Record<string, PermissionLevel> }) => {
|
||||
setManaged(!!config?.managed)
|
||||
setDemoMode(!!config?.demo_mode)
|
||||
if (config?.dev_mode) setDevMode(true)
|
||||
if (config?.is_prerelease !== undefined) setIsPrerelease(config.is_prerelease)
|
||||
@@ -139,6 +313,7 @@ export default function App() {
|
||||
if (config?.places_photos_enabled !== undefined) setPlacesPhotosEnabled(config.places_photos_enabled)
|
||||
if (config?.places_autocomplete_enabled !== undefined) setPlacesAutocompleteEnabled(config.places_autocomplete_enabled)
|
||||
if (config?.places_details_enabled !== undefined) setPlacesDetailsEnabled(config.places_details_enabled)
|
||||
if (config?.places_enrich_enabled !== undefined) setPlacesEnrichEnabled(config.places_enrich_enabled)
|
||||
if (config?.permissions) usePermissionsStore.getState().setPermissions(config.permissions)
|
||||
|
||||
if (config?.version) {
|
||||
@@ -200,6 +375,7 @@ export default function App() {
|
||||
}
|
||||
}, [settings.dark_mode, settings.appearance, isSharedPage])
|
||||
|
||||
const isPhone = useIsPhone()
|
||||
const isAuthPage = location.pathname.startsWith('/login')
|
||||
|| location.pathname.startsWith('/register')
|
||||
|| location.pathname.startsWith('/forgot-password')
|
||||
@@ -207,153 +383,173 @@ export default function App() {
|
||||
|
||||
return (
|
||||
<TranslationProvider>
|
||||
{!isAuthPage && <SystemNoticeHost />}
|
||||
<ToastContainer />
|
||||
{!isAuthPage && <BackgroundTasksWidget />}
|
||||
{!isAuthPage && <SaveToCollectionModal />}
|
||||
<OfflineBanner />
|
||||
<Routes>
|
||||
<Route path="/" element={<RootRedirect />} />
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/shared/:token" element={<SharedTripPage />} />
|
||||
<Route path="/public/journey/:token" element={<JourneyPublicPage />} />
|
||||
<Route path="/register" element={<LoginPage />} />
|
||||
<Route path="/forgot-password" element={<ForgotPasswordPage />} />
|
||||
<Route path="/reset-password" element={<ResetPasswordPage />} />
|
||||
{/* OAuth 2.1 consent page — intentionally outside ProtectedRoute */}
|
||||
<Route path="/oauth/consent" element={<OAuthAuthorizePage />} />
|
||||
<Route
|
||||
path="/dashboard"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<DashboardPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
{/* Trip invite link (#1143) — behind ProtectedRoute so an anonymous
|
||||
visitor is redirected to /login (never registration) and returns here. */}
|
||||
<Route
|
||||
path="/join/:token"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<JoinTripPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/help"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<HelpPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/help/:slug"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<HelpPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/trips/:id"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<TripPlannerPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/trips/:id/files"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<FilesPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
<ProtectedRoute adminRequired>
|
||||
<AdminPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/settings"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<SettingsPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/plugins/:pluginId"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<PluginPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/vacay"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<VacayPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/atlas"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<AtlasPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/journey"
|
||||
element={
|
||||
<ProtectedRoute addonId="journey">
|
||||
<JourneyPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/journey/:id"
|
||||
element={
|
||||
<ProtectedRoute addonId="journey">
|
||||
<JourneyDetailPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/collections"
|
||||
element={
|
||||
<ProtectedRoute addonId="collections">
|
||||
<CollectionsPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/collections/:id"
|
||||
element={
|
||||
<ProtectedRoute addonId="collections">
|
||||
<CollectionsPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/notifications"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<InAppNotificationsPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
{!isAuthPage && <ErrorBoundary boundaryId="widget:system-notice" fallback={null}><SystemNoticeHost /></ErrorBoundary>}
|
||||
<ErrorBoundary boundaryId="widget:toast" fallback={null}><ToastContainer /></ErrorBoundary>
|
||||
{!isAuthPage && <ErrorBoundary boundaryId="widget:background-tasks" fallback={null}><BackgroundTasksWidget /></ErrorBoundary>}
|
||||
{!isAuthPage && (isPhone ? <MSaveToCollectionSheet /> : <SaveToCollectionModal />)}
|
||||
<ErrorBoundary boundaryId="widget:offline-banner" fallback={null}><OfflineBanner /></ErrorBoundary>
|
||||
{/* One boundary for all route chunks, above <Routes> so it stays mounted
|
||||
across navigations. react-router runs location updates inside a transition,
|
||||
so a mounted boundary keeps the current page on screen instead of flashing
|
||||
a spinner on every jump — the spinner is for the first paint of a deep link. */}
|
||||
<Suspense fallback={<RouteFallback />}>
|
||||
<Routes>
|
||||
<Route path="/" element={<RootRedirect />} />
|
||||
<Route path="/login" element={<PublicRoute redirectAuthed><LoginPage /></PublicRoute>} />
|
||||
<Route path="/shared/:token" element={<PublicRoute><SharedTripPage /></PublicRoute>} />
|
||||
<Route path="/public/journey/:token" element={<PublicRoute><JourneyPublicPage /></PublicRoute>} />
|
||||
<Route path="/register" element={<PublicRoute redirectAuthed><LoginPage /></PublicRoute>} />
|
||||
<Route path="/forgot-password" element={<PublicRoute><ForgotPasswordPage /></PublicRoute>} />
|
||||
<Route path="/reset-password" element={<PublicRoute><ResetPasswordPage /></PublicRoute>} />
|
||||
{/* OAuth 2.1 consent page — intentionally outside ProtectedRoute */}
|
||||
<Route path="/oauth/consent" element={<PublicRoute><OAuthAuthorizePage /></PublicRoute>} />
|
||||
<Route
|
||||
path="/dashboard"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<ViewportRoute phone={MDashboardScreen} desktop={DashboardPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
{/* Trip invite link (#1143) — behind ProtectedRoute so an anonymous
|
||||
visitor is redirected to /login (never registration) and returns here. */}
|
||||
<Route
|
||||
path="/join/:token"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<JoinTripPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/help"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<HelpPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/help/:slug"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<HelpPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/trips/:id"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<ViewportRoute phone={MTripScreen} desktop={TripPlannerPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/trips/:id/files"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<FilesPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
<ProtectedRoute adminRequired>
|
||||
<ViewportRoute phone={MAdminScreen} desktop={AdminPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/settings"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<ViewportRoute phone={MSettingsScreen} desktop={SettingsPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/plugins/:pluginId"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<PluginPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
{/* Empty in this repository, and read unconditionally so the public
|
||||
build walks the same path as any other. See client/src/managed. */}
|
||||
{managedRoutes.map(r => (
|
||||
<Route
|
||||
key={r.path}
|
||||
path={r.path}
|
||||
element={<ProtectedRoute adminRequired={r.adminOnly}>{r.element}</ProtectedRoute>}
|
||||
/>
|
||||
))}
|
||||
<Route
|
||||
path="/vacay"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<ViewportRoute phone={MVacayScreen} desktop={VacayPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/atlas"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<ViewportRoute phone={MAtlasScreen} desktop={AtlasPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/journey"
|
||||
element={
|
||||
<ProtectedRoute addonId="journey">
|
||||
<ViewportRoute phone={MJourneyScreen} desktop={JourneyPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/journey/:id"
|
||||
element={
|
||||
<ProtectedRoute addonId="journey">
|
||||
<ViewportRoute phone={MJourneyDetailScreen} desktop={JourneyDetailPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
>
|
||||
{/* Studio is nested so the journey stays mounted underneath it and
|
||||
shows through the panel's margin — it is opened on top of the
|
||||
journey, not navigated away to. */}
|
||||
<Route path="studio" element={<JourneyStudioPage />} />
|
||||
</Route>
|
||||
<Route
|
||||
path="/collections"
|
||||
element={
|
||||
<ProtectedRoute addonId="collections">
|
||||
<ViewportRoute phone={MCollectionsScreen} desktop={CollectionsPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/collections/:id"
|
||||
element={
|
||||
<ProtectedRoute addonId="collections">
|
||||
<ViewportRoute phone={MCollectionsScreen} desktop={CollectionsPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/notifications"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<ViewportRoute phone={MNotificationsScreen} desktop={InAppNotificationsPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
</TranslationProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import React from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { MemoryRouter } from 'react-router'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { useAuthStore } from './store/authStore'
|
||||
import { useAddonStore } from './store/addonStore'
|
||||
import { resetAllStores } from '../tests/helpers/store'
|
||||
import { buildUser } from '../tests/helpers/factories'
|
||||
import App from './App'
|
||||
|
||||
/**
|
||||
* The viewport decides which chunk gets fetched, so the switch lives in App.tsx
|
||||
* and no longer in the pages. This is that contract, for all ten routes in one
|
||||
* place — it used to be five scattered spot checks, one per page test.
|
||||
*
|
||||
* A stub per screen keeps the test about one thing: below the breakpoint the M
|
||||
* root hangs off the route, and the desktop page is never rendered at all.
|
||||
*/
|
||||
|
||||
const isPhone = vi.hoisted(() => ({ value: false }))
|
||||
vi.mock('./mobile/useIsPhone', () => ({ useIsPhone: () => isPhone.value }))
|
||||
|
||||
vi.mock('./mobile/screens/dashboard/MDashboard', () => ({ default: () => <div>m-dashboard</div> }))
|
||||
vi.mock('./mobile/screens/trip/MTripShell', () => ({ default: () => <div>m-trip</div> }))
|
||||
vi.mock('./mobile/screens/admin/MAdmin', () => ({ default: () => <div>m-admin</div> }))
|
||||
vi.mock('./mobile/screens/settings/MSettings', () => ({ default: () => <div>m-settings</div> }))
|
||||
vi.mock('./mobile/screens/vacay/MVacay', () => ({ default: () => <div>m-vacay</div> }))
|
||||
vi.mock('./mobile/screens/atlas/MAtlas', () => ({ default: () => <div>m-atlas</div> }))
|
||||
vi.mock('./mobile/screens/journey/MJourney', () => ({ default: () => <div>m-journey</div> }))
|
||||
vi.mock('./mobile/screens/journey/MJourneyDetail', () => ({ default: () => <div>m-journey-detail</div> }))
|
||||
vi.mock('./mobile/screens/collections/MCollections', () => ({ default: () => <div>m-collections</div> }))
|
||||
vi.mock('./mobile/screens/notifications/MNotifications', () => ({ default: () => <div>m-notifications</div> }))
|
||||
|
||||
vi.mock('./pages/DashboardPage', () => ({ default: () => <div>d-dashboard</div> }))
|
||||
vi.mock('./pages/TripPlannerPage', () => ({ default: () => <div>d-trip</div> }))
|
||||
vi.mock('./pages/AdminPage', () => ({ default: () => <div>d-admin</div> }))
|
||||
vi.mock('./pages/SettingsPage', () => ({ default: () => <div>d-settings</div> }))
|
||||
vi.mock('./pages/VacayPage', () => ({ default: () => <div>d-vacay</div> }))
|
||||
vi.mock('./pages/AtlasPage', () => ({ default: () => <div>d-atlas</div> }))
|
||||
vi.mock('./pages/JourneyPage', () => ({ default: () => <div>d-journey</div> }))
|
||||
vi.mock('./pages/JourneyDetailPage', () => ({ default: () => <div>d-journey-detail</div> }))
|
||||
vi.mock('./pages/CollectionsPage', () => ({ default: () => <div>d-collections</div> }))
|
||||
vi.mock('./pages/InAppNotificationsPage.tsx', () => ({ default: () => <div>d-notifications</div> }))
|
||||
|
||||
// The notification listener opens a WebSocket on mount.
|
||||
vi.mock('./hooks/useInAppNotificationListener.ts', () => ({
|
||||
useInAppNotificationListener: vi.fn(),
|
||||
}))
|
||||
|
||||
/** path, mobile marker, desktop marker */
|
||||
const ROUTES: [string, string, string][] = [
|
||||
['/dashboard', 'm-dashboard', 'd-dashboard'],
|
||||
['/trips/1', 'm-trip', 'd-trip'],
|
||||
['/admin', 'm-admin', 'd-admin'],
|
||||
['/settings', 'm-settings', 'd-settings'],
|
||||
['/vacay', 'm-vacay', 'd-vacay'],
|
||||
['/atlas', 'm-atlas', 'd-atlas'],
|
||||
['/journey', 'm-journey', 'd-journey'],
|
||||
['/journey/1', 'm-journey-detail', 'd-journey-detail'],
|
||||
['/collections', 'm-collections', 'd-collections'],
|
||||
['/collections/1', 'm-collections', 'd-collections'],
|
||||
['/notifications', 'm-notifications', 'd-notifications'],
|
||||
]
|
||||
|
||||
function renderAt(path: string) {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<App />
|
||||
</MemoryRouter>
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores()
|
||||
vi.clearAllMocks()
|
||||
isPhone.value = false
|
||||
// An admin passes the role check on /admin; every other route ignores it.
|
||||
useAuthStore.setState({
|
||||
isLoading: false,
|
||||
isAuthenticated: true,
|
||||
user: buildUser({ role: 'admin', mfa_enabled: true }),
|
||||
appRequireMfa: false,
|
||||
loadUser: vi.fn().mockResolvedValue(undefined),
|
||||
})
|
||||
// /journey and /collections sit behind addons; without this they redirect to
|
||||
// the dashboard and the route under test never renders.
|
||||
useAddonStore.setState({ loaded: true, isEnabled: () => true })
|
||||
})
|
||||
|
||||
describe('App — viewport routing', () => {
|
||||
it.each(ROUTES)(
|
||||
'FE-COMP-APPVP-001: %s renders the mobile screen below the breakpoint',
|
||||
async (path, mobile, desktop) => {
|
||||
isPhone.value = true
|
||||
renderAt(path)
|
||||
|
||||
expect(await screen.findByText(mobile)).toBeInTheDocument()
|
||||
expect(screen.queryByText(desktop)).not.toBeInTheDocument()
|
||||
}
|
||||
)
|
||||
|
||||
it.each(ROUTES)(
|
||||
'FE-COMP-APPVP-002: %s renders the desktop page above the breakpoint',
|
||||
async (path, mobile, desktop) => {
|
||||
renderAt(path)
|
||||
|
||||
expect(await screen.findByText(desktop)).toBeInTheDocument()
|
||||
expect(screen.queryByText(mobile)).not.toBeInTheDocument()
|
||||
}
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,511 @@
|
||||
// FE-APIWIRE-001 to FE-APIWIRE-036
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { server } from '../../tests/helpers/msw/server'
|
||||
import { weatherResultSchema } from '@trek/shared'
|
||||
|
||||
// client.ts probes the health endpoint to tell an edge-proxy auth wall apart
|
||||
// from a plain offline boot — the probe result decides whether it tears down
|
||||
// the service worker, so the tests drive it directly.
|
||||
const { probeNow } = vi.hoisted(() => ({
|
||||
probeNow: vi.fn(async (): Promise<'online' | 'offline' | 'proxy-wall'> => 'offline'),
|
||||
}))
|
||||
vi.mock('../sync/connectivity', () => ({ probeNow }))
|
||||
|
||||
const { apiClient, adminApi, mapsApi, pluginsApi, parseInDev } = await import('./client')
|
||||
|
||||
interface FakeLocation {
|
||||
href: string
|
||||
origin: string
|
||||
pathname: string
|
||||
search: string
|
||||
hash: string
|
||||
reload: () => void
|
||||
}
|
||||
|
||||
let reload: ReturnType<typeof vi.fn<() => void>>
|
||||
|
||||
function setLocation(pathname: string, search = '', hash = ''): FakeLocation {
|
||||
reload = vi.fn<() => void>()
|
||||
const loc: FakeLocation = {
|
||||
href: `http://localhost:3000${pathname}${search}${hash}`,
|
||||
origin: 'http://localhost:3000',
|
||||
pathname,
|
||||
search,
|
||||
hash,
|
||||
reload,
|
||||
}
|
||||
Object.defineProperty(window, 'location', { writable: true, configurable: true, value: loc })
|
||||
return loc
|
||||
}
|
||||
|
||||
const realLocation = window.location
|
||||
|
||||
/** Records the outgoing config and answers 200 without touching the network. */
|
||||
function okAdapter(sink: InternalAxiosRequestConfig[]): AxiosAdapter {
|
||||
return (config) => {
|
||||
sink.push(config)
|
||||
return Promise.resolve({
|
||||
data: { ok: true }, status: 200, statusText: 'OK', headers: {}, config,
|
||||
} as AxiosResponse)
|
||||
}
|
||||
}
|
||||
|
||||
/** Rejects the way a CORS/offline failure does: an error with no `response`. */
|
||||
const networkErrorAdapter: AxiosAdapter = (config) =>
|
||||
Promise.reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config))
|
||||
|
||||
async function captureError(run: () => Promise<unknown>): Promise<AxiosError> {
|
||||
const err = await run().then(() => null, (e: unknown) => e as AxiosError)
|
||||
expect(err, 'expected the request to reject').not.toBeNull()
|
||||
return err as AxiosError
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
probeNow.mockResolvedValue('offline')
|
||||
setLocation('/dashboard')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
Object.defineProperty(window, 'location', { writable: true, configurable: true, value: realLocation })
|
||||
delete (navigator as { serviceWorker?: unknown }).serviceWorker
|
||||
})
|
||||
|
||||
describe('client > request interceptor', () => {
|
||||
it('FE-APIWIRE-001: mutating requests get an idempotency key, reads do not', async () => {
|
||||
const sink: InternalAxiosRequestConfig[] = []
|
||||
const adapter = okAdapter(sink)
|
||||
|
||||
await apiClient.get('/probe', { adapter })
|
||||
await apiClient.post('/probe', {}, { adapter })
|
||||
await apiClient.put('/probe', {}, { adapter })
|
||||
await apiClient.patch('/probe', {}, { adapter })
|
||||
await apiClient.delete('/probe', { adapter })
|
||||
|
||||
const keys = sink.map(c => c.headers['X-Idempotency-Key'])
|
||||
expect(keys[0]).toBeUndefined()
|
||||
for (const key of keys.slice(1)) expect(typeof key).toBe('string')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-002: each write gets its own key so retries can be deduplicated', async () => {
|
||||
const sink: InternalAxiosRequestConfig[] = []
|
||||
const adapter = okAdapter(sink)
|
||||
|
||||
await apiClient.post('/probe', {}, { adapter })
|
||||
await apiClient.post('/probe', {}, { adapter })
|
||||
|
||||
expect(sink[0].headers['X-Idempotency-Key']).not.toBe(sink[1].headers['X-Idempotency-Key'])
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-003: a pre-generated key from the mutation queue is left alone', async () => {
|
||||
const sink: InternalAxiosRequestConfig[] = []
|
||||
|
||||
await apiClient.post('/probe', {}, {
|
||||
adapter: okAdapter(sink),
|
||||
headers: { 'X-Idempotency-Key': 'queued-key' },
|
||||
})
|
||||
|
||||
expect(sink[0].headers['X-Idempotency-Key']).toBe('queued-key')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-004: falls back to getRandomValues when crypto.randomUUID is missing', async () => {
|
||||
const realCrypto = globalThis.crypto
|
||||
vi.stubGlobal('crypto', {
|
||||
getRandomValues: realCrypto.getRandomValues.bind(realCrypto),
|
||||
} as unknown as Crypto)
|
||||
|
||||
const sink: InternalAxiosRequestConfig[] = []
|
||||
await apiClient.post('/probe', {}, { adapter: okAdapter(sink) })
|
||||
|
||||
// randomUUID needs a secure context, so on the plain-http installs the
|
||||
// README documents this branch is what actually runs. getRandomValues has no
|
||||
// such requirement, so the fallback is still a full v4 UUID.
|
||||
expect(String(sink[0].headers['X-Idempotency-Key'])).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
|
||||
)
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-004b: the last-resort key is never degenerate, even with no Web Crypto at all', async () => {
|
||||
vi.stubGlobal('crypto', undefined)
|
||||
|
||||
const keys = new Set<string>()
|
||||
for (let i = 0; i < 50; i++) {
|
||||
const sink: InternalAxiosRequestConfig[] = []
|
||||
await apiClient.post('/probe', {}, { adapter: okAdapter(sink) })
|
||||
keys.add(String(sink[0].headers['X-Idempotency-Key']))
|
||||
}
|
||||
|
||||
// The old fallback was Math.random().toString(36).slice(2), which is not
|
||||
// length-stable: 0.5 yields a single character and 0 yields the empty string.
|
||||
// An empty key makes the server skip deduplication entirely, so a retried
|
||||
// write applies twice.
|
||||
for (const k of keys) expect(k.length).toBeGreaterThan(16)
|
||||
expect(keys.size).toBe(50)
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-005: the socket id header is omitted while no socket is connected', async () => {
|
||||
const sink: InternalAxiosRequestConfig[] = []
|
||||
await apiClient.get('/probe', { adapter: okAdapter(sink) })
|
||||
expect(sink[0].headers['X-Socket-Id']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-034: a rejection from an earlier request interceptor is passed on untouched', async () => {
|
||||
const boom = new Error('interceptor refused the request')
|
||||
const id = apiClient.interceptors.request.use(() => Promise.reject(boom))
|
||||
const sink: InternalAxiosRequestConfig[] = []
|
||||
|
||||
try {
|
||||
await expect(apiClient.post('/probe', {}, { adapter: okAdapter(sink) })).rejects.toBe(boom)
|
||||
} finally {
|
||||
apiClient.interceptors.request.eject(id)
|
||||
}
|
||||
|
||||
expect(sink).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('client > rate-limit translation', () => {
|
||||
beforeEach(() => {
|
||||
server.use(http.get('/api/limited', () => HttpResponse.json({ error: 'Too Many Requests' }, { status: 429 })))
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-006: a 429 is rewritten in the stored app language', async () => {
|
||||
localStorage.setItem('app_language', 'de')
|
||||
const err = await captureError(() => apiClient.get('/limited'))
|
||||
|
||||
expect(err.message).toBe('Zu viele Versuche. Bitte versuchen Sie es später erneut.')
|
||||
expect((err.response?.data as { error: string }).error)
|
||||
.toBe('Zu viele Versuche. Bitte versuchen Sie es später erneut.')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-007: an unsupported language falls back to English', async () => {
|
||||
localStorage.setItem('app_language', 'kl')
|
||||
const err = await captureError(() => apiClient.get('/limited'))
|
||||
expect(err.message).toBe('Too many attempts. Please try again later.')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-008: no stored language falls back to English', async () => {
|
||||
const err = await captureError(() => apiClient.get('/limited'))
|
||||
expect(err.message).toBe('Too many attempts. Please try again later.')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-009: a blocked localStorage still yields the English message', async () => {
|
||||
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
|
||||
throw new Error('storage disabled')
|
||||
})
|
||||
const err = await captureError(() => apiClient.get('/limited'))
|
||||
expect(err.message).toBe('Too many attempts. Please try again later.')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-010: a non-object 429 body is replaced with the translated error object', async () => {
|
||||
server.use(http.get('/api/limited', () => new HttpResponse('slow down', { status: 429 })))
|
||||
const err = await captureError(() => apiClient.get('/limited'))
|
||||
expect(err.response?.data).toEqual({ error: 'Too many attempts. Please try again later.' })
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-035: an array 429 body is replaced, not grafted onto', async () => {
|
||||
server.use(http.get('/api/limited', () => HttpResponse.json([{ field: 'email' }], { status: 429 })))
|
||||
const err = await captureError(() => apiClient.get('/limited'))
|
||||
expect(err.response?.data).toEqual({ error: 'Too many attempts. Please try again later.' })
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-036: Catalan, Greek and Vietnamese have their own 429 message', async () => {
|
||||
for (const lang of ['ca', 'gr', 'vi']) {
|
||||
localStorage.setItem('app_language', lang)
|
||||
const err = await captureError(() => apiClient.get('/limited'))
|
||||
expect(err.message).not.toBe('Too many attempts. Please try again later.')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('client > proxy auth challenges', () => {
|
||||
function installServiceWorker(unregister: () => Promise<boolean>) {
|
||||
const getRegistration = vi.fn(async () => ({ unregister }))
|
||||
Object.defineProperty(navigator, 'serviceWorker', {
|
||||
writable: true, configurable: true, value: { getRegistration },
|
||||
})
|
||||
return getRegistration
|
||||
}
|
||||
|
||||
it('FE-APIWIRE-011: an HTML 401 unregisters the service worker and reloads', async () => {
|
||||
const unregister = vi.fn(async () => true)
|
||||
installServiceWorker(unregister)
|
||||
server.use(http.get('/api/auth/me', () =>
|
||||
new HttpResponse('<html>login</html>', { status: 401, headers: { 'Content-Type': 'text/html' } })))
|
||||
|
||||
await captureError(() => apiClient.get('/auth/me'))
|
||||
|
||||
expect(unregister).toHaveBeenCalled()
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
expect(sessionStorage.getItem('proxy_reauth_attempted')).toBe('1')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-012: the reauth reload only fires once per session', async () => {
|
||||
installServiceWorker(vi.fn(async () => true))
|
||||
sessionStorage.setItem('proxy_reauth_attempted', '1')
|
||||
server.use(http.get('/api/auth/me', () =>
|
||||
new HttpResponse('<html>login</html>', { status: 401, headers: { 'Content-Type': 'text/html' } })))
|
||||
|
||||
await captureError(() => apiClient.get('/auth/me'))
|
||||
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-013: an HTML 401 on a public path never reloads', async () => {
|
||||
setLocation('/login')
|
||||
server.use(http.get('/api/auth/me', () =>
|
||||
new HttpResponse('<html>login</html>', { status: 401, headers: { 'Content-Type': 'text/html' } })))
|
||||
|
||||
await captureError(() => apiClient.get('/auth/me'))
|
||||
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
expect(sessionStorage.getItem('proxy_reauth_attempted')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-014: a response-less failure that probes proxy-wall reloads', async () => {
|
||||
probeNow.mockResolvedValue('proxy-wall')
|
||||
installServiceWorker(vi.fn(async () => true))
|
||||
|
||||
await captureError(() => apiClient.get('/auth/me', { adapter: networkErrorAdapter }))
|
||||
|
||||
expect(probeNow).toHaveBeenCalled()
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-015: a response-less failure that probes offline keeps the SW (#1346)', async () => {
|
||||
probeNow.mockResolvedValue('offline')
|
||||
const getRegistration = installServiceWorker(vi.fn(async () => true))
|
||||
|
||||
await captureError(() => apiClient.get('/auth/me', { adapter: networkErrorAdapter }))
|
||||
|
||||
expect(getRegistration).not.toHaveBeenCalled()
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
expect(sessionStorage.getItem('proxy_reauth_attempted')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-016: a failing unregister still reloads into the proxy challenge', async () => {
|
||||
probeNow.mockResolvedValue('proxy-wall')
|
||||
Object.defineProperty(navigator, 'serviceWorker', {
|
||||
writable: true, configurable: true,
|
||||
value: { getRegistration: vi.fn(async () => { throw new Error('SW gone') }) },
|
||||
})
|
||||
|
||||
await captureError(() => apiClient.get('/auth/me', { adapter: networkErrorAdapter }))
|
||||
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-017: a proxy-wall probe on a shared page does not reload', async () => {
|
||||
setLocation('/shared/tok123')
|
||||
probeNow.mockResolvedValue('proxy-wall')
|
||||
|
||||
await captureError(() => apiClient.get('/auth/me', { adapter: networkErrorAdapter }))
|
||||
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-035: a 401 without a content-type is not mistaken for a proxy login page', async () => {
|
||||
installServiceWorker(vi.fn(async () => true))
|
||||
server.use(http.get('/api/auth/me', () => new HttpResponse(null, { status: 401 })))
|
||||
|
||||
await captureError(() => apiClient.get('/auth/me'))
|
||||
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
expect(sessionStorage.getItem('proxy_reauth_attempted')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-018: a successful response clears the reauth marker', async () => {
|
||||
sessionStorage.setItem('proxy_reauth_attempted', '1')
|
||||
server.use(http.get('/api/auth/me', () => HttpResponse.json({ ok: true })))
|
||||
|
||||
await apiClient.get('/auth/me')
|
||||
|
||||
expect(sessionStorage.getItem('proxy_reauth_attempted')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('client > redirect handling', () => {
|
||||
it('FE-APIWIRE-019: a JSON AUTH_REQUIRED 401 redirects with the full current path', async () => {
|
||||
const loc = setLocation('/trips/7', '?tab=map', '#day-2')
|
||||
server.use(http.get('/api/auth/me', () => HttpResponse.json({ code: 'AUTH_REQUIRED' }, { status: 401 })))
|
||||
|
||||
await captureError(() => apiClient.get('/auth/me'))
|
||||
|
||||
expect(loc.href).toBe('/login?redirect=' + encodeURIComponent('/trips/7?tab=map#day-2'))
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-020: an MFA_REQUIRED 403 sends the user to the settings page', async () => {
|
||||
const loc = setLocation('/dashboard')
|
||||
server.use(http.get('/api/auth/me', () => HttpResponse.json({ code: 'MFA_REQUIRED' }, { status: 403 })))
|
||||
|
||||
await captureError(() => apiClient.get('/auth/me'))
|
||||
|
||||
expect(loc.href).toBe('/settings?mfa=required')
|
||||
})
|
||||
})
|
||||
|
||||
describe('client > dev-only contract drift checks', () => {
|
||||
it('FE-APIWIRE-021: parseInDev passes a matching payload straight through', () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const payload = { temp: 21, main: 'Clear', description: 'clear sky', type: 'sun' }
|
||||
|
||||
expect(parseInDev(weatherResultSchema, payload, 'weather.get')).toBe(payload)
|
||||
expect(warn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-022: parseInDev warns but still returns a drifting payload', () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const payload = { temp: 'warm', main: 'Clear', description: 'clear sky', type: 'sun' }
|
||||
|
||||
expect(parseInDev(weatherResultSchema, payload, 'weather.get')).toBe(payload)
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
'[api] weather.get: response did not match the @trek/shared schema',
|
||||
expect.anything(),
|
||||
)
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-023: a drifting maps response is reported under its own label', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
server.use(http.post('/api/maps/search', () => HttpResponse.json({ nonsense: true })))
|
||||
|
||||
await expect(mapsApi.search('Rome')).resolves.toEqual({ nonsense: true })
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
'[api] maps.search: response did not match the @trek/shared schema',
|
||||
expect.anything(),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('client > pluginsApi.invoke namespace guard', () => {
|
||||
it('FE-APIWIRE-024: a relative sub-path stays inside the plugin namespace', async () => {
|
||||
let seen = ''
|
||||
server.use(http.get('/api/plugins/koffi/ping', ({ request }) => {
|
||||
seen = new URL(request.url).pathname
|
||||
return HttpResponse.json({ pong: true })
|
||||
}))
|
||||
|
||||
await expect(pluginsApi.invoke('koffi', '/ping')).resolves.toEqual({ pong: true })
|
||||
expect(seen).toBe('/api/plugins/koffi/ping')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-025: method, body and query string survive the rewrite', async () => {
|
||||
let received: unknown
|
||||
let query = ''
|
||||
server.use(http.post('/api/plugins/koffi/sync', async ({ request }) => {
|
||||
received = await request.json()
|
||||
query = new URL(request.url).search
|
||||
return HttpResponse.json({ ok: true })
|
||||
}))
|
||||
|
||||
await pluginsApi.invoke('koffi', 'sync?full=1', { method: 'POST', body: { since: 5 } })
|
||||
|
||||
expect(received).toEqual({ since: 5 })
|
||||
expect(query).toBe('?full=1')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-026: traversal out of the plugin prefix is refused', async () => {
|
||||
await expect(pluginsApi.invoke('koffi', '/../../auth/me'))
|
||||
.rejects.toThrow('plugin route escapes its namespace')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-027: an absolute off-origin target is refused', async () => {
|
||||
await expect(pluginsApi.invoke('koffi', 'https://evil.test/steal'))
|
||||
.rejects.toThrow('plugin route escapes its namespace')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-028: an unparseable sub-path is refused before any request', async () => {
|
||||
await expect(pluginsApi.invoke('koffi', 'http://')).rejects.toThrow('invalid plugin route')
|
||||
})
|
||||
})
|
||||
|
||||
describe('client > adminApi.llmLocalPull', () => {
|
||||
function streamingResponse(chunks: string[]): Response {
|
||||
let i = 0
|
||||
const encoder = new TextEncoder()
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
body: {
|
||||
getReader: () => ({
|
||||
read: async () => (i < chunks.length
|
||||
? { done: false, value: encoder.encode(chunks[i++]) }
|
||||
: { done: true, value: undefined }),
|
||||
cancel: async () => {},
|
||||
}),
|
||||
},
|
||||
} as unknown as Response
|
||||
}
|
||||
|
||||
it('FE-APIWIRE-029: NDJSON progress lines are reported even when split across chunks', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(streamingResponse([
|
||||
'{"status":"pulling","total":100,"completed":10}\n{"status":"pul',
|
||||
'ling","total":100,"completed":90}\n{"status":"success"}\n',
|
||||
]))
|
||||
const onProgress = vi.fn((_p: { status?: string }) => {})
|
||||
|
||||
await adminApi.llmLocalPull('http://ollama:11434', 'qwen3:8b', onProgress)
|
||||
|
||||
expect(onProgress.mock.calls.map(c => c[0])).toEqual([
|
||||
{ status: 'pulling', total: 100, completed: 10 },
|
||||
{ status: 'pulling', total: 100, completed: 90 },
|
||||
{ status: 'success' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-030: blank and half-written lines are skipped instead of throwing', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(streamingResponse([
|
||||
'\n \n{"status":"a"}\nnot-json\n{"status":"b"}\n',
|
||||
]))
|
||||
const onProgress = vi.fn((_p: { status?: string }) => {})
|
||||
|
||||
await adminApi.llmLocalPull('http://ollama:11434', 'qwen3:8b', onProgress)
|
||||
|
||||
expect(onProgress.mock.calls.map(c => c[0])).toEqual([{ status: 'a' }, { status: 'b' }])
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-031: a JSON error body becomes the thrown message', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce({
|
||||
ok: false, status: 502, body: null,
|
||||
json: async () => ({ error: 'ollama unreachable' }),
|
||||
} as unknown as Response)
|
||||
|
||||
await expect(adminApi.llmLocalPull('http://ollama:11434', 'x', vi.fn()))
|
||||
.rejects.toThrow('ollama unreachable')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-032: a non-JSON error body falls back to the status code', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce({
|
||||
ok: false, status: 500, body: null,
|
||||
json: async () => { throw new SyntaxError('not json') },
|
||||
} as unknown as Response)
|
||||
|
||||
await expect(adminApi.llmLocalPull('http://ollama:11434', 'x', vi.fn()))
|
||||
.rejects.toThrow('Pull failed (500)')
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-036: a throw from onProgress aborts the pull', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(streamingResponse([
|
||||
'{"status":"pulling manifest"}\n{"error":"manifest not found"}\n{"status":"success"}\n',
|
||||
]))
|
||||
const onProgress = vi.fn((p: { error?: string }) => {
|
||||
if (p.error) throw new Error(p.error)
|
||||
})
|
||||
|
||||
await expect(adminApi.llmLocalPull('http://ollama:11434', 'x', onProgress))
|
||||
.rejects.toThrow('manifest not found')
|
||||
expect(onProgress).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('FE-APIWIRE-033: a 200 without a readable body reports the missing stream', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce({
|
||||
ok: true, status: 200, body: null,
|
||||
json: async () => ({}),
|
||||
} as unknown as Response)
|
||||
|
||||
await expect(adminApi.llmLocalPull('http://ollama:11434', 'x', vi.fn()))
|
||||
.rejects.toThrow('Pull returned no progress stream')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,865 @@
|
||||
// FE-APISURF-001 to FE-APISURF-054
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import type { AxiosResponse } from 'axios'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { server } from '../../tests/helpers/msw/server'
|
||||
import {
|
||||
apiClient,
|
||||
authApi, oauthApi, tripsApi, daysApi, placesApi, assignmentsApi, packingApi, todoApi,
|
||||
tagsApi, categoriesApi, adminApi, addonsApi, pluginsApi, airtrailApi, journeyApi,
|
||||
mapsApi, airportsApi, budgetApi, filesApi, reservationsApi, healthApi, weatherApi,
|
||||
configApi, helpApi, settingsApi, accommodationsApi, dayNotesApi, collabApi, backupApi,
|
||||
shareApi, transitApi, tripInviteApi, notificationsApi, inAppNotificationsApi, memoriesApi,
|
||||
} from './client'
|
||||
|
||||
interface Recorded { method: string; url: string; body: unknown }
|
||||
|
||||
let log: Recorded[] = []
|
||||
|
||||
/** One record per outgoing request: verb, path+query and (parsed) JSON body. */
|
||||
function recorder() {
|
||||
return http.all(/\/api\//, async ({ request }) => {
|
||||
const url = new URL(request.url)
|
||||
const raw = await request.text()
|
||||
let body: unknown
|
||||
if (raw) {
|
||||
try { body = JSON.parse(raw) } catch { body = raw }
|
||||
}
|
||||
log.push({ method: request.method, url: url.pathname + url.search, body })
|
||||
return HttpResponse.json({ ok: true })
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
log = []
|
||||
server.use(recorder())
|
||||
// parseInDev/checkInDev warn on every stub payload that doesn't match its
|
||||
// @trek/shared schema — expected here, so keep the output readable.
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
interface Call { n: string; r: () => Promise<unknown>; e: string }
|
||||
|
||||
/** Runs every call in isolation and checks the verb + path it produced. */
|
||||
async function assertCalls(calls: Call[]): Promise<void> {
|
||||
for (const c of calls) {
|
||||
log = []
|
||||
await c.r()
|
||||
expect(log.length, `${c.n}: expected exactly one request`).toBe(1)
|
||||
const rec = log[0]
|
||||
const [path] = rec.url.split('?')
|
||||
expect(`${rec.method} ${path}`, c.n).toBe(c.e)
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs one call and returns the request it produced. */
|
||||
async function traceOne(run: () => Promise<unknown>): Promise<Recorded> {
|
||||
log = []
|
||||
await run()
|
||||
expect(log).toHaveLength(1)
|
||||
return log[0]
|
||||
}
|
||||
|
||||
describe('client > endpoint wiring', () => {
|
||||
it('FE-APISURF-001: authApi maps every method to its auth endpoint', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'register', r: () => authApi.register({ email: 'a@b.c', password: 'pw' }), e: 'POST /api/auth/register' },
|
||||
{ n: 'validateInvite', r: () => authApi.validateInvite('inv-tok'), e: 'GET /api/auth/invite/inv-tok' },
|
||||
{ n: 'login', r: () => authApi.login({ email: 'a@b.c', password: 'pw' }), e: 'POST /api/auth/login' },
|
||||
{ n: 'verifyMfaLogin', r: () => authApi.verifyMfaLogin({ mfa_token: 'm', code: '123456' }), e: 'POST /api/auth/mfa/verify-login' },
|
||||
{ n: 'mfaSetup', r: () => authApi.mfaSetup(), e: 'POST /api/auth/mfa/setup' },
|
||||
{ n: 'mfaEnable', r: () => authApi.mfaEnable({ code: '123456' }), e: 'POST /api/auth/mfa/enable' },
|
||||
{ n: 'mfaDisable', r: () => authApi.mfaDisable({ password: 'pw', code: '123456' }), e: 'POST /api/auth/mfa/disable' },
|
||||
{ n: 'me', r: () => authApi.me(), e: 'GET /api/auth/me' },
|
||||
{ n: 'updateMapsKey', r: () => authApi.updateMapsKey('gkey'), e: 'PUT /api/auth/me/maps-key' },
|
||||
{ n: 'updateApiKeys', r: () => authApi.updateApiKeys({ google_maps: null }), e: 'PUT /api/auth/me/api-keys' },
|
||||
{ n: 'updateSettings', r: () => authApi.updateSettings({ theme: 'dark' }), e: 'PUT /api/auth/me/settings' },
|
||||
{ n: 'getSettings', r: () => authApi.getSettings(), e: 'GET /api/auth/me/settings' },
|
||||
{ n: 'listUsers', r: () => authApi.listUsers(), e: 'GET /api/auth/users' },
|
||||
{ n: 'deleteAvatar', r: () => authApi.deleteAvatar(), e: 'DELETE /api/auth/avatar' },
|
||||
{ n: 'getAppConfig', r: () => authApi.getAppConfig(), e: 'GET /api/auth/app-config' },
|
||||
{ n: 'updateAppSettings', r: () => authApi.updateAppSettings({ registration_enabled: true }), e: 'PUT /api/auth/app-settings' },
|
||||
{ n: 'validateKeys', r: () => authApi.validateKeys(), e: 'GET /api/auth/validate-keys' },
|
||||
{ n: 'travelStats', r: () => authApi.travelStats(), e: 'GET /api/auth/travel-stats' },
|
||||
{ n: 'changePassword', r: () => authApi.changePassword({ current_password: 'a', new_password: 'b' }), e: 'PUT /api/auth/me/password' },
|
||||
{ n: 'forgotPassword', r: () => authApi.forgotPassword({ email: 'a@b.c' }), e: 'POST /api/auth/forgot-password' },
|
||||
{ n: 'resetPassword', r: () => authApi.resetPassword({ token: 't', new_password: 'b' }), e: 'POST /api/auth/reset-password' },
|
||||
{ n: 'deleteOwnAccount', r: () => authApi.deleteOwnAccount(), e: 'DELETE /api/auth/me' },
|
||||
{ n: 'demoLogin', r: () => authApi.demoLogin(), e: 'POST /api/auth/demo-login' },
|
||||
{ n: 'mcpTokens.list', r: () => authApi.mcpTokens.list(), e: 'GET /api/auth/mcp-tokens' },
|
||||
{ n: 'mcpTokens.create', r: () => authApi.mcpTokens.create('cli'), e: 'POST /api/auth/mcp-tokens' },
|
||||
{ n: 'mcpTokens.delete', r: () => authApi.mcpTokens.delete(7), e: 'DELETE /api/auth/mcp-tokens/7' },
|
||||
{ n: 'passkey.registerOptions', r: () => authApi.passkey.registerOptions('pw'), e: 'POST /api/auth/passkey/register/options' },
|
||||
{ n: 'passkey.registerVerify', r: () => authApi.passkey.registerVerify({ id: 'cred' }, 'Yubikey'), e: 'POST /api/auth/passkey/register/verify' },
|
||||
{ n: 'passkey.loginOptions', r: () => authApi.passkey.loginOptions(), e: 'POST /api/auth/passkey/login/options' },
|
||||
{ n: 'passkey.loginVerify', r: () => authApi.passkey.loginVerify({ id: 'cred' }), e: 'POST /api/auth/passkey/login/verify' },
|
||||
{ n: 'passkey.list', r: () => authApi.passkey.list(), e: 'GET /api/auth/passkey/credentials' },
|
||||
{ n: 'passkey.rename', r: () => authApi.passkey.rename(3, 'Phone'), e: 'PATCH /api/auth/passkey/credentials/3' },
|
||||
{ n: 'passkey.delete', r: () => authApi.passkey.delete(3, 'pw'), e: 'DELETE /api/auth/passkey/credentials/3' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-002: oauthApi maps consent + client/session management endpoints', async () => {
|
||||
const params = {
|
||||
response_type: 'code', client_id: 'cid', redirect_uri: 'https://app/cb',
|
||||
scope: 'trips:read', code_challenge: 'chal', code_challenge_method: 'S256',
|
||||
}
|
||||
await assertCalls([
|
||||
{ n: 'validate', r: () => oauthApi.validate(params), e: 'GET /api/oauth/authorize/validate' },
|
||||
{ n: 'authorize', r: () => oauthApi.authorize({ ...params, approved: true }), e: 'POST /api/oauth/authorize' },
|
||||
{ n: 'clients.list', r: () => oauthApi.clients.list(), e: 'GET /api/oauth/clients' },
|
||||
{ n: 'clients.create', r: () => oauthApi.clients.create({ name: 'App', allowed_scopes: ['trips:read'] }), e: 'POST /api/oauth/clients' },
|
||||
{ n: 'clients.rotate', r: () => oauthApi.clients.rotate('cid'), e: 'POST /api/oauth/clients/cid/rotate' },
|
||||
{ n: 'clients.delete', r: () => oauthApi.clients.delete('cid'), e: 'DELETE /api/oauth/clients/cid' },
|
||||
{ n: 'sessions.list', r: () => oauthApi.sessions.list(), e: 'GET /api/oauth/sessions' },
|
||||
{ n: 'sessions.revoke', r: () => oauthApi.sessions.revoke(4), e: 'DELETE /api/oauth/sessions/4' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-003: tripsApi maps trip, member and guest endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'list', r: () => tripsApi.list(), e: 'GET /api/trips' },
|
||||
{ n: 'create', r: () => tripsApi.create({ title: 'Rome' }), e: 'POST /api/trips' },
|
||||
{ n: 'get', r: () => tripsApi.get(3), e: 'GET /api/trips/3' },
|
||||
{ n: 'update', r: () => tripsApi.update(3, { title: 'Rome 2' }), e: 'PUT /api/trips/3' },
|
||||
{ n: 'delete', r: () => tripsApi.delete(3), e: 'DELETE /api/trips/3' },
|
||||
{ n: 'searchCoverImages', r: () => tripsApi.searchCoverImages('rome'), e: 'GET /api/trips/cover-images/search' },
|
||||
{ n: 'archive', r: () => tripsApi.archive(3), e: 'PUT /api/trips/3' },
|
||||
{ n: 'unarchive', r: () => tripsApi.unarchive(3), e: 'PUT /api/trips/3' },
|
||||
{ n: 'getMembers', r: () => tripsApi.getMembers(3), e: 'GET /api/trips/3/members' },
|
||||
{ n: 'addMember', r: () => tripsApi.addMember(3, 'bob'), e: 'POST /api/trips/3/members' },
|
||||
{ n: 'removeMember', r: () => tripsApi.removeMember(3, 9), e: 'DELETE /api/trips/3/members/9' },
|
||||
{ n: 'transferOwnership', r: () => tripsApi.transferOwnership(3, 9), e: 'POST /api/trips/3/transfer' },
|
||||
{ n: 'createGuest', r: () => tripsApi.createGuest(3, 'Anna'), e: 'POST /api/trips/3/guests' },
|
||||
{ n: 'renameGuest', r: () => tripsApi.renameGuest(3, 9, 'Ana'), e: 'PUT /api/trips/3/guests/9' },
|
||||
{ n: 'deleteGuest', r: () => tripsApi.deleteGuest(3, 9), e: 'DELETE /api/trips/3/guests/9' },
|
||||
{ n: 'copy', r: () => tripsApi.copy(3, { title: 'Copy' }), e: 'POST /api/trips/3/copy' },
|
||||
{ n: 'bundle', r: () => tripsApi.bundle(3), e: 'GET /api/trips/3/bundle' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-004: daysApi and dayNotesApi map their nested trip endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'days.list', r: () => daysApi.list(1), e: 'GET /api/trips/1/days' },
|
||||
{ n: 'days.create', r: () => daysApi.create(1, { date: '2026-06-01' }), e: 'POST /api/trips/1/days' },
|
||||
{ n: 'days.update', r: () => daysApi.update(1, 2, { notes: 'hi' }), e: 'PUT /api/trips/1/days/2' },
|
||||
{ n: 'days.updateTransport', r: () => daysApi.updateTransport(1, 2, 'car'), e: 'PUT /api/trips/1/days/2/transport' },
|
||||
{ n: 'days.delete', r: () => daysApi.delete(1, 2), e: 'DELETE /api/trips/1/days/2' },
|
||||
{ n: 'days.reorder', r: () => daysApi.reorder(1, [2, 1]), e: 'PUT /api/trips/1/days/reorder' },
|
||||
{ n: 'dayNotes.list', r: () => dayNotesApi.list(1, 2), e: 'GET /api/trips/1/days/2/notes' },
|
||||
{ n: 'dayNotes.create', r: () => dayNotesApi.create(1, 2, { text: 'note' }), e: 'POST /api/trips/1/days/2/notes' },
|
||||
{ n: 'dayNotes.update', r: () => dayNotesApi.update(1, 2, 5, { text: 'edit' }), e: 'PUT /api/trips/1/days/2/notes/5' },
|
||||
{ n: 'dayNotes.delete', r: () => dayNotesApi.delete(1, 2, 5), e: 'DELETE /api/trips/1/days/2/notes/5' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-005: placesApi maps CRUD, rating and list-import endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'list', r: () => placesApi.list(1), e: 'GET /api/trips/1/places' },
|
||||
{ n: 'create', r: () => placesApi.create(1, { name: 'Colosseum' }), e: 'POST /api/trips/1/places' },
|
||||
{ n: 'get', r: () => placesApi.get(1, 5), e: 'GET /api/trips/1/places/5' },
|
||||
{ n: 'update', r: () => placesApi.update(1, 5, { name: 'Forum' }), e: 'PUT /api/trips/1/places/5' },
|
||||
{ n: 'delete', r: () => placesApi.delete(1, 5), e: 'DELETE /api/trips/1/places/5' },
|
||||
{ n: 'searchImage', r: () => placesApi.searchImage(1, 5), e: 'GET /api/trips/1/places/5/image' },
|
||||
{ n: 'importGoogleList', r: () => placesApi.importGoogleList(1, 'https://maps.app/x'), e: 'POST /api/trips/1/places/import/google-list' },
|
||||
{ n: 'importNaverList', r: () => placesApi.importNaverList(1, 'https://naver/x'), e: 'POST /api/trips/1/places/import/naver-list' },
|
||||
{ n: 'bulkDelete', r: () => placesApi.bulkDelete(1, [5, 6]), e: 'POST /api/trips/1/places/bulk-delete' },
|
||||
{ n: 'bulkUpdate', r: () => placesApi.bulkUpdate(1, [5], { category_id: 2 }), e: 'POST /api/trips/1/places/bulk-update' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-006: assignmentsApi maps day-plan endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'list', r: () => assignmentsApi.list(1, 2), e: 'GET /api/trips/1/days/2/assignments' },
|
||||
{ n: 'create', r: () => assignmentsApi.create(1, 2, { place_id: 5 }), e: 'POST /api/trips/1/days/2/assignments' },
|
||||
{ n: 'delete', r: () => assignmentsApi.delete(1, 2, 7), e: 'DELETE /api/trips/1/days/2/assignments/7' },
|
||||
{ n: 'reorder', r: () => assignmentsApi.reorder(1, 2, [7, 8]), e: 'PUT /api/trips/1/days/2/assignments/reorder' },
|
||||
{ n: 'move', r: () => assignmentsApi.move(1, 7, 3, 0), e: 'PUT /api/trips/1/assignments/7/move' },
|
||||
{ n: 'update', r: () => assignmentsApi.update(1, 2, 7, { notes: 'x' }), e: 'PUT /api/trips/1/days/2/assignments/7' },
|
||||
{ n: 'getParticipants', r: () => assignmentsApi.getParticipants(1, 7), e: 'GET /api/trips/1/assignments/7/participants' },
|
||||
{ n: 'setParticipants', r: () => assignmentsApi.setParticipants(1, 7, [4]), e: 'PUT /api/trips/1/assignments/7/participants' },
|
||||
{ n: 'updateTime', r: () => assignmentsApi.updateTime(1, 7, { place_time: '09:00' }), e: 'PUT /api/trips/1/assignments/7/time' },
|
||||
{ n: 'updateTransport', r: () => assignmentsApi.updateTransport(1, 7, null), e: 'PUT /api/trips/1/assignments/7/transport' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-007: packingApi maps item, bag and template endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'list', r: () => packingApi.list(1), e: 'GET /api/trips/1/packing' },
|
||||
{ n: 'create', r: () => packingApi.create(1, { name: 'Towel' }), e: 'POST /api/trips/1/packing' },
|
||||
{ n: 'bulkImport', r: () => packingApi.bulkImport(1, [{ name: 'Socks' }]), e: 'POST /api/trips/1/packing/import' },
|
||||
{ n: 'update', r: () => packingApi.update(1, 4, { checked: true }), e: 'PUT /api/trips/1/packing/4' },
|
||||
{ n: 'delete', r: () => packingApi.delete(1, 4), e: 'DELETE /api/trips/1/packing/4' },
|
||||
{ n: 'reorder', r: () => packingApi.reorder(1, [4, 5]), e: 'PUT /api/trips/1/packing/reorder' },
|
||||
{ n: 'setSharing', r: () => packingApi.setSharing(1, 4, { visibility: 'shared' }), e: 'PUT /api/trips/1/packing/4/sharing' },
|
||||
{ n: 'clone', r: () => packingApi.clone(1, 4), e: 'POST /api/trips/1/packing/4/clone' },
|
||||
{ n: 'addContributor', r: () => packingApi.addContributor(1, 4), e: 'POST /api/trips/1/packing/4/contributors' },
|
||||
{ n: 'removeContributor', r: () => packingApi.removeContributor(1, 4, 9), e: 'DELETE /api/trips/1/packing/4/contributors/9' },
|
||||
{ n: 'getCategoryAssignees', r: () => packingApi.getCategoryAssignees(1), e: 'GET /api/trips/1/packing/category-assignees' },
|
||||
{ n: 'listTemplates', r: () => packingApi.listTemplates(1), e: 'GET /api/trips/1/packing/templates' },
|
||||
{ n: 'applyTemplate', r: () => packingApi.applyTemplate(1, 6), e: 'POST /api/trips/1/packing/apply-template/6' },
|
||||
{ n: 'saveAsTemplate', r: () => packingApi.saveAsTemplate(1, 'Beach'), e: 'POST /api/trips/1/packing/save-as-template' },
|
||||
{ n: 'setBagMembers', r: () => packingApi.setBagMembers(1, 2, [9]), e: 'PUT /api/trips/1/packing/bags/2/members' },
|
||||
{ n: 'listBags', r: () => packingApi.listBags(1), e: 'GET /api/trips/1/packing/bags' },
|
||||
{ n: 'createBag', r: () => packingApi.createBag(1, { name: 'Carry-on' }), e: 'POST /api/trips/1/packing/bags' },
|
||||
{ n: 'updateBag', r: () => packingApi.updateBag(1, 2, { name: 'Hold' }), e: 'PUT /api/trips/1/packing/bags/2' },
|
||||
{ n: 'deleteBag', r: () => packingApi.deleteBag(1, 2), e: 'DELETE /api/trips/1/packing/bags/2' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-008: todoApi maps todo endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'list', r: () => todoApi.list(1), e: 'GET /api/trips/1/todo' },
|
||||
{ n: 'create', r: () => todoApi.create(1, { name: 'Book train' }), e: 'POST /api/trips/1/todo' },
|
||||
{ n: 'update', r: () => todoApi.update(1, 3, { checked: true }), e: 'PUT /api/trips/1/todo/3' },
|
||||
{ n: 'delete', r: () => todoApi.delete(1, 3), e: 'DELETE /api/trips/1/todo/3' },
|
||||
{ n: 'reorder', r: () => todoApi.reorder(1, [3, 4]), e: 'PUT /api/trips/1/todo/reorder' },
|
||||
{ n: 'getCategoryAssignees', r: () => todoApi.getCategoryAssignees(1), e: 'GET /api/trips/1/todo/category-assignees' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-009: tagsApi and categoriesApi map their global endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'tags.list', r: () => tagsApi.list(), e: 'GET /api/tags' },
|
||||
{ n: 'tags.create', r: () => tagsApi.create({ name: 'Food' }), e: 'POST /api/tags' },
|
||||
{ n: 'tags.update', r: () => tagsApi.update(2, { name: 'Eat' }), e: 'PUT /api/tags/2' },
|
||||
{ n: 'tags.delete', r: () => tagsApi.delete(2), e: 'DELETE /api/tags/2' },
|
||||
{ n: 'categories.list', r: () => categoriesApi.list(), e: 'GET /api/categories' },
|
||||
{ n: 'categories.create', r: () => categoriesApi.create({ name: 'Museum' }), e: 'POST /api/categories' },
|
||||
{ n: 'categories.update', r: () => categoriesApi.update(2, { name: 'Art' }), e: 'PUT /api/categories/2' },
|
||||
{ n: 'categories.delete', r: () => categoriesApi.delete(2), e: 'DELETE /api/categories/2' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-010: adminApi maps user, addon and settings endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'users', r: () => adminApi.users(), e: 'GET /api/admin/users' },
|
||||
{ n: 'createUser', r: () => adminApi.createUser({ email: 'a@b.c' }), e: 'POST /api/admin/users' },
|
||||
{ n: 'updateUser', r: () => adminApi.updateUser(2, { role: 'admin' }), e: 'PUT /api/admin/users/2' },
|
||||
{ n: 'deleteUser', r: () => adminApi.deleteUser(2), e: 'DELETE /api/admin/users/2' },
|
||||
{ n: 'resetUserPasskeys', r: () => adminApi.resetUserPasskeys(2), e: 'DELETE /api/admin/users/2/passkeys' },
|
||||
{ n: 'stats', r: () => adminApi.stats(), e: 'GET /api/admin/stats' },
|
||||
{ n: 'saveDemoBaseline', r: () => adminApi.saveDemoBaseline(), e: 'POST /api/admin/save-demo-baseline' },
|
||||
{ n: 'getOidc', r: () => adminApi.getOidc(), e: 'GET /api/admin/oidc' },
|
||||
{ n: 'updateOidc', r: () => adminApi.updateOidc({ enabled: true }), e: 'PUT /api/admin/oidc' },
|
||||
{ n: 'addons', r: () => adminApi.addons(), e: 'GET /api/admin/addons' },
|
||||
{ n: 'updateAddon', r: () => adminApi.updateAddon(3, { enabled: false }), e: 'PUT /api/admin/addons/3' },
|
||||
{ n: 'checkVersion', r: () => adminApi.checkVersion(), e: 'GET /api/admin/version-check' },
|
||||
{ n: 'getBagTracking', r: () => adminApi.getBagTracking(), e: 'GET /api/admin/bag-tracking' },
|
||||
{ n: 'updateBagTracking', r: () => adminApi.updateBagTracking(true), e: 'PUT /api/admin/bag-tracking' },
|
||||
{ n: 'getPlacesPhotos', r: () => adminApi.getPlacesPhotos(), e: 'GET /api/admin/places-photos' },
|
||||
{ n: 'updatePlacesPhotos', r: () => adminApi.updatePlacesPhotos(false), e: 'PUT /api/admin/places-photos' },
|
||||
{ n: 'getPlacesAutocomplete', r: () => adminApi.getPlacesAutocomplete(), e: 'GET /api/admin/places-autocomplete' },
|
||||
{ n: 'updatePlacesAutocomplete', r: () => adminApi.updatePlacesAutocomplete(true), e: 'PUT /api/admin/places-autocomplete' },
|
||||
{ n: 'getPlacesDetails', r: () => adminApi.getPlacesDetails(), e: 'GET /api/admin/places-details' },
|
||||
{ n: 'updatePlacesDetails', r: () => adminApi.updatePlacesDetails(true), e: 'PUT /api/admin/places-details' },
|
||||
{ n: 'getCollabFeatures', r: () => adminApi.getCollabFeatures(), e: 'GET /api/admin/collab-features' },
|
||||
{ n: 'updateCollabFeatures', r: () => adminApi.updateCollabFeatures({ polls: true }), e: 'PUT /api/admin/collab-features' },
|
||||
{ n: 'getPermissions', r: () => adminApi.getPermissions(), e: 'GET /api/admin/permissions' },
|
||||
{ n: 'updatePermissions', r: () => adminApi.updatePermissions({ edit_trip: 'member' }), e: 'PUT /api/admin/permissions' },
|
||||
{ n: 'rotateJwtSecret', r: () => adminApi.rotateJwtSecret(), e: 'POST /api/admin/rotate-jwt-secret' },
|
||||
{ n: 'sendTestNotification', r: () => adminApi.sendTestNotification({ channel: 'email' }), e: 'POST /api/admin/dev/test-notification' },
|
||||
{ n: 'getNotificationPreferences', r: () => adminApi.getNotificationPreferences(), e: 'GET /api/admin/notification-preferences' },
|
||||
{ n: 'updateNotificationPreferences', r: () => adminApi.updateNotificationPreferences({ email: { trip_invite: true } }), e: 'PUT /api/admin/notification-preferences' },
|
||||
{ n: 'getDefaultUserSettings', r: () => adminApi.getDefaultUserSettings(), e: 'GET /api/admin/default-user-settings' },
|
||||
{ n: 'updateDefaultUserSettings', r: () => adminApi.updateDefaultUserSettings({ language: 'de' }), e: 'PUT /api/admin/default-user-settings' },
|
||||
{ n: 'getStorage', r: () => adminApi.getStorage(), e: 'GET /api/admin/storage' },
|
||||
{ n: 'updateStorage', r: () => adminApi.updateStorage({ backends: [], categories: {}, version: 0 }), e: 'PUT /api/admin/storage' },
|
||||
{ n: 'testStorageBackend', r: () => adminApi.testStorageBackend({ name: 'x', type: 'local', options: { root: '/data' } }), e: 'POST /api/admin/storage/test' },
|
||||
{ n: 'startStorageBackfill', r: () => adminApi.startStorageBackfill('m'), e: 'POST /api/admin/storage/backends/m/backfill' },
|
||||
{ n: 'cancelStorageBackfill', r: () => adminApi.cancelStorageBackfill('m'), e: 'DELETE /api/admin/storage/backends/m/backfill' },
|
||||
{ n: 'startStorageMigration', r: () => adminApi.startStorageMigration('files', 'dest'), e: 'POST /api/admin/storage/migrations' },
|
||||
{ n: 'cancelStorageMigration', r: () => adminApi.cancelStorageMigration('files'), e: 'DELETE /api/admin/storage/migrations/files' },
|
||||
{ n: 'refreshStorageStats', r: () => adminApi.refreshStorageStats(), e: 'POST /api/admin/storage/stats/refresh' },
|
||||
{ n: 'mcpTokens', r: () => adminApi.mcpTokens(), e: 'GET /api/admin/mcp-tokens' },
|
||||
{ n: 'deleteMcpToken', r: () => adminApi.deleteMcpToken(4), e: 'DELETE /api/admin/mcp-tokens/4' },
|
||||
{ n: 'oauthSessions', r: () => adminApi.oauthSessions(), e: 'GET /api/admin/oauth-sessions' },
|
||||
{ n: 'revokeOAuthSession', r: () => adminApi.revokeOAuthSession(4), e: 'DELETE /api/admin/oauth-sessions/4' },
|
||||
{ n: 'listInvites', r: () => adminApi.listInvites(), e: 'GET /api/admin/invites' },
|
||||
{ n: 'listInviteTrips', r: () => adminApi.listInviteTrips(), e: 'GET /api/admin/invites/trips' },
|
||||
{ n: 'createInvite', r: () => adminApi.createInvite({ max_uses: 3 }), e: 'POST /api/admin/invites' },
|
||||
{ n: 'deleteInvite', r: () => adminApi.deleteInvite(8), e: 'DELETE /api/admin/invites/8' },
|
||||
{ n: 'auditLog', r: () => adminApi.auditLog(), e: 'GET /api/admin/audit-log' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-011: adminApi maps the plugin management endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'plugins', r: () => adminApi.plugins(), e: 'GET /api/admin/plugins' },
|
||||
{ n: 'pluginBrowse', r: () => adminApi.pluginBrowse(), e: 'GET /api/admin/plugins/registry' },
|
||||
{ n: 'pluginDetail', r: () => adminApi.pluginDetail('trek/koffi'), e: 'GET /api/admin/plugins/registry/trek%2Fkoffi' },
|
||||
{ n: 'pluginInstall', r: () => adminApi.pluginInstall('koffi', { version: '1.0.0' }), e: 'POST /api/admin/plugins/install' },
|
||||
{ n: 'pluginActivate', r: () => adminApi.pluginActivate('koffi'), e: 'POST /api/admin/plugins/koffi/activate' },
|
||||
{ n: 'pluginDeactivate', r: () => adminApi.pluginDeactivate('koffi'), e: 'POST /api/admin/plugins/koffi/deactivate' },
|
||||
{ n: 'pluginUpdate', r: () => adminApi.pluginUpdate('koffi'), e: 'POST /api/admin/plugins/koffi/update' },
|
||||
{ n: 'pluginRetrust', r: () => adminApi.pluginRetrust('koffi', '2.0.0', 'PUBKEY'), e: 'POST /api/admin/plugins/koffi/retrust' },
|
||||
{ n: 'pluginUninstall', r: () => adminApi.pluginUninstall('koffi', true), e: 'POST /api/admin/plugins/koffi/uninstall' },
|
||||
{ n: 'pluginRescan', r: () => adminApi.pluginRescan(), e: 'POST /api/admin/plugins/rescan' },
|
||||
{ n: 'pluginLink', r: () => adminApi.pluginLink('/srv/plugin'), e: 'POST /api/admin/plugins/link' },
|
||||
{ n: 'pluginReload', r: () => adminApi.pluginReload('koffi'), e: 'POST /api/admin/plugins/koffi/reload' },
|
||||
{ n: 'pluginEgressHosts', r: () => adminApi.pluginEgressHosts('koffi'), e: 'GET /api/admin/plugins/koffi/egress-hosts' },
|
||||
{ n: 'pluginSetEgressHosts', r: () => adminApi.pluginSetEgressHosts('koffi', ['a.example']), e: 'PUT /api/admin/plugins/koffi/egress-hosts' },
|
||||
{ n: 'pluginErrors', r: () => adminApi.pluginErrors('koffi'), e: 'GET /api/admin/plugins/koffi/errors' },
|
||||
{ n: 'pluginAudit', r: () => adminApi.pluginAudit('koffi'), e: 'GET /api/admin/plugins/koffi/audit' },
|
||||
{ n: 'llmLocalModels', r: () => adminApi.llmLocalModels('http://ollama:11434'), e: 'GET /api/admin/llm/local/models' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-012: adminApi maps the packing-template endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'packingTemplates', r: () => adminApi.packingTemplates(), e: 'GET /api/admin/packing-templates' },
|
||||
{ n: 'getPackingTemplate', r: () => adminApi.getPackingTemplate(1), e: 'GET /api/admin/packing-templates/1' },
|
||||
{ n: 'createPackingTemplate', r: () => adminApi.createPackingTemplate({ name: 'Ski' }), e: 'POST /api/admin/packing-templates' },
|
||||
{ n: 'updatePackingTemplate', r: () => adminApi.updatePackingTemplate(1, { name: 'Ski 2' }), e: 'PUT /api/admin/packing-templates/1' },
|
||||
{ n: 'deletePackingTemplate', r: () => adminApi.deletePackingTemplate(1), e: 'DELETE /api/admin/packing-templates/1' },
|
||||
{ n: 'addTemplateCategory', r: () => adminApi.addTemplateCategory(1, { name: 'Clothes' }), e: 'POST /api/admin/packing-templates/1/categories' },
|
||||
{ n: 'updateTemplateCategory', r: () => adminApi.updateTemplateCategory(1, 2, { name: 'Wear' }), e: 'PUT /api/admin/packing-templates/1/categories/2' },
|
||||
{ n: 'deleteTemplateCategory', r: () => adminApi.deleteTemplateCategory(1, 2), e: 'DELETE /api/admin/packing-templates/1/categories/2' },
|
||||
{ n: 'addTemplateItem', r: () => adminApi.addTemplateItem(1, 2, { name: 'Gloves' }), e: 'POST /api/admin/packing-templates/1/categories/2/items' },
|
||||
{ n: 'updateTemplateItem', r: () => adminApi.updateTemplateItem(1, 3, { name: 'Mittens' }), e: 'PUT /api/admin/packing-templates/1/items/3' },
|
||||
{ n: 'deleteTemplateItem', r: () => adminApi.deleteTemplateItem(1, 3), e: 'DELETE /api/admin/packing-templates/1/items/3' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-013: pluginsApi maps every host-mediated plugin endpoint', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'active', r: () => pluginsApi.active(), e: 'GET /api/plugins' },
|
||||
{ n: 'placeDetails', r: () => pluginsApi.placeDetails(5), e: 'GET /api/place-details/5' },
|
||||
{ n: 'tripWarnings', r: () => pluginsApi.tripWarnings(1), e: 'GET /api/trip-warnings/1' },
|
||||
{ n: 'viewContributions', r: () => pluginsApi.viewContributions('places', 1), e: 'GET /api/view-contributions/places/1' },
|
||||
{ n: 'mapMarkers', r: () => pluginsApi.mapMarkers(1), e: 'GET /api/map-markers/1' },
|
||||
{ n: 'mapLayers', r: () => pluginsApi.mapLayers(1), e: 'GET /api/map-layers/1' },
|
||||
{ n: 'pluginRoute', r: () => pluginsApi.pluginRoute('koffi', 'ev', { tripId: 1, waypoints: [{ lat: 1, lng: 2 }] }), e: 'POST /api/plugin-routes/koffi/ev' },
|
||||
{ n: 'daySchedule', r: () => pluginsApi.daySchedule(1), e: 'GET /api/day-schedule/1' },
|
||||
{ n: 'pdfSections', r: () => pluginsApi.pdfSections(1), e: 'GET /api/pdf-sections/1' },
|
||||
{ n: 'atlasLayers', r: () => pluginsApi.atlasLayers(), e: 'GET /api/atlas-layers' },
|
||||
{ n: 'journalEntryRows', r: () => pluginsApi.journalEntryRows(9), e: 'GET /api/journal-entry-rows/9' },
|
||||
{ n: 'tripCardContributions', r: () => pluginsApi.tripCardContributions([1, 2]), e: 'GET /api/trip-card-contributions' },
|
||||
{ n: 'myActivity', r: () => pluginsApi.myActivity(), e: 'GET /api/plugin-activity' },
|
||||
{ n: 'userSettings', r: () => pluginsApi.userSettings('koffi'), e: 'GET /api/plugin-settings/koffi' },
|
||||
{ n: 'runAction', r: () => pluginsApi.runAction('koffi', 'test connection'), e: 'POST /api/plugin-settings/koffi/actions/test%20connection' },
|
||||
{ n: 'saveUserSettings', r: () => pluginsApi.saveUserSettings('koffi', { key: 'v' }), e: 'POST /api/plugin-settings/koffi' },
|
||||
{ n: 'oauthStatus', r: () => pluginsApi.oauthStatus('koffi'), e: 'GET /api/plugin-oauth/koffi/status' },
|
||||
{ n: 'oauthConnect', r: () => pluginsApi.oauthConnect('koffi'), e: 'POST /api/plugin-oauth/koffi/connect' },
|
||||
{ n: 'oauthDisconnect', r: () => pluginsApi.oauthDisconnect('koffi'), e: 'POST /api/plugin-oauth/koffi/disconnect' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-014: airtrailApi maps the integration endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'getSettings', r: () => airtrailApi.getSettings(), e: 'GET /api/integrations/airtrail/settings' },
|
||||
{ n: 'saveSettings', r: () => airtrailApi.saveSettings({ url: 'https://at' }), e: 'PUT /api/integrations/airtrail/settings' },
|
||||
{ n: 'status', r: () => airtrailApi.status(), e: 'GET /api/integrations/airtrail/status' },
|
||||
{ n: 'test', r: () => airtrailApi.test({ url: 'https://at' }), e: 'POST /api/integrations/airtrail/test' },
|
||||
{ n: 'sync', r: () => airtrailApi.sync(), e: 'POST /api/integrations/airtrail/sync' },
|
||||
{ n: 'flights', r: () => airtrailApi.flights(), e: 'GET /api/integrations/airtrail/flights' },
|
||||
{ n: 'import', r: () => airtrailApi.import(1, ['f1']), e: 'POST /api/trips/1/reservations/import/airtrail' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-015: journeyApi maps journal, entry and photo endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'list', r: () => journeyApi.list(), e: 'GET /api/journeys' },
|
||||
{ n: 'create', r: () => journeyApi.create({ title: 'Asia' }), e: 'POST /api/journeys' },
|
||||
{ n: 'get', r: () => journeyApi.get(2), e: 'GET /api/journeys/2' },
|
||||
{ n: 'update', r: () => journeyApi.update(2, { title: 'Asia 24' }), e: 'PATCH /api/journeys/2' },
|
||||
{ n: 'delete', r: () => journeyApi.delete(2), e: 'DELETE /api/journeys/2' },
|
||||
{ n: 'suggestions', r: () => journeyApi.suggestions(), e: 'GET /api/journeys/suggestions' },
|
||||
{ n: 'availableTrips', r: () => journeyApi.availableTrips(), e: 'GET /api/journeys/available-trips' },
|
||||
{ n: 'addTrip', r: () => journeyApi.addTrip(2, 1), e: 'POST /api/journeys/2/trips' },
|
||||
{ n: 'removeTrip', r: () => journeyApi.removeTrip(2, 1), e: 'DELETE /api/journeys/2/trips/1' },
|
||||
{ n: 'listEntries', r: () => journeyApi.listEntries(2), e: 'GET /api/journeys/2/entries' },
|
||||
{ n: 'createEntry', r: () => journeyApi.createEntry(2, { title: 'Day 1' }), e: 'POST /api/journeys/2/entries' },
|
||||
{ n: 'updateEntry', r: () => journeyApi.updateEntry(9, { title: 'Day 2' }), e: 'PATCH /api/journeys/entries/9' },
|
||||
{ n: 'deleteEntry', r: () => journeyApi.deleteEntry(9), e: 'DELETE /api/journeys/entries/9' },
|
||||
{ n: 'reorderEntries', r: () => journeyApi.reorderEntries(2, [9, 8]), e: 'PUT /api/journeys/2/entries/reorder' },
|
||||
{ n: 'addProviderPhotosToGallery', r: () => journeyApi.addProviderPhotosToGallery(2, 'immich', ['a1']), e: 'POST /api/journeys/2/gallery/provider-photos' },
|
||||
{ n: 'addProviderPhoto', r: () => journeyApi.addProviderPhoto(9, 'immich', 'a1'), e: 'POST /api/journeys/entries/9/provider-photos' },
|
||||
{ n: 'addProviderPhotos', r: () => journeyApi.addProviderPhotos(9, 'immich', ['a1']), e: 'POST /api/journeys/entries/9/provider-photos' },
|
||||
{ n: 'linkPhoto', r: () => journeyApi.linkPhoto(9, 11), e: 'POST /api/journeys/entries/9/link-photo' },
|
||||
{ n: 'unlinkPhoto', r: () => journeyApi.unlinkPhoto(9, 11), e: 'DELETE /api/journeys/entries/9/photos/11' },
|
||||
{ n: 'deleteGalleryPhoto', r: () => journeyApi.deleteGalleryPhoto(2, 11), e: 'DELETE /api/journeys/2/gallery/11' },
|
||||
{ n: 'updatePhoto', r: () => journeyApi.updatePhoto(11, { caption: 'x' }), e: 'PATCH /api/journeys/photos/11' },
|
||||
{ n: 'deletePhoto', r: () => journeyApi.deletePhoto(11), e: 'DELETE /api/journeys/photos/11' },
|
||||
{ n: 'addContributor', r: () => journeyApi.addContributor(2, 4, 'editor'), e: 'POST /api/journeys/2/contributors' },
|
||||
{ n: 'updateContributor', r: () => journeyApi.updateContributor(2, 4, 'viewer'), e: 'PATCH /api/journeys/2/contributors/4' },
|
||||
{ n: 'removeContributor', r: () => journeyApi.removeContributor(2, 4), e: 'DELETE /api/journeys/2/contributors/4' },
|
||||
{ n: 'updatePreferences', r: () => journeyApi.updatePreferences(2, { hide_skeletons: true }), e: 'PATCH /api/journeys/2/preferences' },
|
||||
{ n: 'getShareLink', r: () => journeyApi.getShareLink(2), e: 'GET /api/journeys/2/share-link' },
|
||||
{ n: 'createShareLink', r: () => journeyApi.createShareLink(2, { share_map: true }), e: 'POST /api/journeys/2/share-link' },
|
||||
{ n: 'deleteShareLink', r: () => journeyApi.deleteShareLink(2), e: 'DELETE /api/journeys/2/share-link' },
|
||||
{ n: 'getPublicJourney', r: () => journeyApi.getPublicJourney('pub-tok'), e: 'GET /api/public/journey/pub-tok' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-053: memoriesApi maps the photo-provider endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'status', r: () => memoriesApi.status('immich'), e: 'GET /api/integrations/memories/immich/status' },
|
||||
{ n: 'search', r: () => memoriesApi.search('immich', { from: '2026-01-01', to: '2026-01-02', page: 1, size: 50 }), e: 'POST /api/integrations/memories/immich/search' },
|
||||
{ n: 'albums', r: () => memoriesApi.albums('immich'), e: 'GET /api/integrations/memories/immich/albums' },
|
||||
{ n: 'albumPhotos', r: () => memoriesApi.albumPhotos('immich', 'alb-1'), e: 'GET /api/integrations/memories/immich/albums/alb-1/photos' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-054: memoriesApi passes the album passphrase as a query parameter', async () => {
|
||||
const rec = await traceOne(() => memoriesApi.albumPhotos('synologyphotos', 'alb-2', 'p/w?'))
|
||||
expect(rec.url).toBe('/api/integrations/memories/synologyphotos/albums/alb-2/photos?passphrase=p%2Fw%3F')
|
||||
})
|
||||
|
||||
it('FE-APISURF-016: mapsApi and airportsApi map the geo endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'maps.search', r: () => mapsApi.search('Rome'), e: 'POST /api/maps/search' },
|
||||
{ n: 'maps.autocomplete', r: () => mapsApi.autocomplete('Rom'), e: 'POST /api/maps/autocomplete' },
|
||||
{ n: 'maps.details', r: () => mapsApi.details('place/1'), e: 'GET /api/maps/details/place%2F1' },
|
||||
{ n: 'maps.placePhoto', r: () => mapsApi.placePhoto('place/1'), e: 'GET /api/maps/place-photo/place%2F1' },
|
||||
{ n: 'maps.reverse', r: () => mapsApi.reverse(41.9, 12.5), e: 'GET /api/maps/reverse' },
|
||||
{ n: 'maps.resolveUrl', r: () => mapsApi.resolveUrl('https://maps.app.goo.gl/x'), e: 'POST /api/maps/resolve-url' },
|
||||
{ n: 'maps.pois', r: () => mapsApi.pois('cafe', { south: 1, west: 2, north: 3, east: 4 }), e: 'GET /api/maps/pois' },
|
||||
{ n: 'airports.search', r: () => airportsApi.search('BER'), e: 'GET /api/airports/search' },
|
||||
{ n: 'airports.byIata', r: () => airportsApi.byIata('b/er'), e: 'GET /api/airports/b%2Fer' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-017: budgetApi maps item, member and settlement endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'list', r: () => budgetApi.list(1), e: 'GET /api/trips/1/budget' },
|
||||
{ n: 'create', r: () => budgetApi.create(1, { name: 'Hotel' }), e: 'POST /api/trips/1/budget' },
|
||||
{ n: 'update', r: () => budgetApi.update(1, 2, { name: 'Hostel' }), e: 'PUT /api/trips/1/budget/2' },
|
||||
{ n: 'delete', r: () => budgetApi.delete(1, 2), e: 'DELETE /api/trips/1/budget/2' },
|
||||
{ n: 'setMembers', r: () => budgetApi.setMembers(1, 2, [4, 5]), e: 'PUT /api/trips/1/budget/2/members' },
|
||||
{ n: 'togglePaid', r: () => budgetApi.togglePaid(1, 2, 4, true), e: 'PUT /api/trips/1/budget/2/members/4/paid' },
|
||||
{ n: 'setPayers', r: () => budgetApi.setPayers(1, 2, [{ user_id: 4, amount: 10 }]), e: 'PUT /api/trips/1/budget/2/payers' },
|
||||
{ n: 'perPersonSummary', r: () => budgetApi.perPersonSummary(1), e: 'GET /api/trips/1/budget/summary/per-person' },
|
||||
{ n: 'settlement', r: () => budgetApi.settlement(1), e: 'GET /api/trips/1/budget/settlement' },
|
||||
{ n: 'createSettlement', r: () => budgetApi.createSettlement(1, { from_user_id: 4, to_user_id: 5, amount: 10 }), e: 'POST /api/trips/1/budget/settlements' },
|
||||
{ n: 'updateSettlement', r: () => budgetApi.updateSettlement(1, 6, { from_user_id: 4, to_user_id: 5, amount: 12 }), e: 'PUT /api/trips/1/budget/settlements/6' },
|
||||
{ n: 'deleteSettlement', r: () => budgetApi.deleteSettlement(1, 6), e: 'DELETE /api/trips/1/budget/settlements/6' },
|
||||
{ n: 'reorderItems', r: () => budgetApi.reorderItems(1, [2, 3]), e: 'PUT /api/trips/1/budget/reorder/items' },
|
||||
{ n: 'reorderCategories', r: () => budgetApi.reorderCategories(1, ['Food']), e: 'PUT /api/trips/1/budget/reorder/categories' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-018: filesApi maps file, trash and link endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'list', r: () => filesApi.list(1), e: 'GET /api/trips/1/files' },
|
||||
{ n: 'update', r: () => filesApi.update(1, 3, { description: 'x' }), e: 'PUT /api/trips/1/files/3' },
|
||||
{ n: 'delete', r: () => filesApi.delete(1, 3), e: 'DELETE /api/trips/1/files/3' },
|
||||
{ n: 'toggleStar', r: () => filesApi.toggleStar(1, 3), e: 'PATCH /api/trips/1/files/3/star' },
|
||||
{ n: 'restore', r: () => filesApi.restore(1, 3), e: 'POST /api/trips/1/files/3/restore' },
|
||||
{ n: 'permanentDelete', r: () => filesApi.permanentDelete(1, 3), e: 'DELETE /api/trips/1/files/3/permanent' },
|
||||
{ n: 'emptyTrash', r: () => filesApi.emptyTrash(1), e: 'DELETE /api/trips/1/files/trash/empty' },
|
||||
{ n: 'addLink', r: () => filesApi.addLink(1, 3, { place_id: 5 }), e: 'POST /api/trips/1/files/3/link' },
|
||||
{ n: 'removeLink', r: () => filesApi.removeLink(1, 3, 7), e: 'DELETE /api/trips/1/files/3/link/7' },
|
||||
{ n: 'getLinks', r: () => filesApi.getLinks(1, 3), e: 'GET /api/trips/1/files/3/links' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-019: reservationsApi and accommodationsApi map booking endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'reservations.list', r: () => reservationsApi.list(1), e: 'GET /api/trips/1/reservations' },
|
||||
{ n: 'reservations.upcoming', r: () => reservationsApi.upcoming(), e: 'GET /api/reservations/upcoming' },
|
||||
{ n: 'reservations.create', r: () => reservationsApi.create(1, { title: 'Hotel' }), e: 'POST /api/trips/1/reservations' },
|
||||
{ n: 'reservations.update', r: () => reservationsApi.update(1, 2, { title: 'Hostel' }), e: 'PUT /api/trips/1/reservations/2' },
|
||||
{ n: 'reservations.delete', r: () => reservationsApi.delete(1, 2), e: 'DELETE /api/trips/1/reservations/2' },
|
||||
{ n: 'reservations.setTravelers', r: () => reservationsApi.setTravelers(1, 2, [4]), e: 'PUT /api/trips/1/reservations/2/travelers' },
|
||||
{ n: 'reservations.updatePositions', r: () => reservationsApi.updatePositions(1, [{ id: 2, day_plan_position: 0 }], 3), e: 'PUT /api/trips/1/reservations/positions' },
|
||||
{ n: 'reservations.importBookingConfirm', r: () => reservationsApi.importBookingConfirm(1, []), e: 'POST /api/trips/1/reservations/import/booking/confirm' },
|
||||
{ n: 'reservations.importJobStatus', r: () => reservationsApi.importJobStatus(1, 'job-1'), e: 'GET /api/trips/1/reservations/import/jobs/job-1' },
|
||||
{ n: 'accommodations.list', r: () => accommodationsApi.list(1), e: 'GET /api/trips/1/accommodations' },
|
||||
{ n: 'accommodations.create', r: () => accommodationsApi.create(1, { place_id: 5, start_day_id: 1, end_day_id: 2 }), e: 'POST /api/trips/1/accommodations' },
|
||||
{ n: 'accommodations.update', r: () => accommodationsApi.update(1, 4, { end_day_id: 3 }), e: 'PUT /api/trips/1/accommodations/4' },
|
||||
{ n: 'accommodations.delete', r: () => accommodationsApi.delete(1, 4), e: 'DELETE /api/trips/1/accommodations/4' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-020: collabApi maps note, poll and message endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'getNotes', r: () => collabApi.getNotes(1), e: 'GET /api/trips/1/collab/notes' },
|
||||
{ n: 'createNote', r: () => collabApi.createNote(1, { title: 'Ideas' }), e: 'POST /api/trips/1/collab/notes' },
|
||||
{ n: 'updateNote', r: () => collabApi.updateNote(1, 2, { title: 'More' }), e: 'PUT /api/trips/1/collab/notes/2' },
|
||||
{ n: 'deleteNote', r: () => collabApi.deleteNote(1, 2), e: 'DELETE /api/trips/1/collab/notes/2' },
|
||||
{ n: 'deleteNoteFile', r: () => collabApi.deleteNoteFile(1, 2, 3), e: 'DELETE /api/trips/1/collab/notes/2/files/3' },
|
||||
{ n: 'getPolls', r: () => collabApi.getPolls(1), e: 'GET /api/trips/1/collab/polls' },
|
||||
{ n: 'createPoll', r: () => collabApi.createPoll(1, { question: 'Where?', options: ['A', 'B'] }), e: 'POST /api/trips/1/collab/polls' },
|
||||
{ n: 'votePoll', r: () => collabApi.votePoll(1, 2, 1), e: 'POST /api/trips/1/collab/polls/2/vote' },
|
||||
{ n: 'closePoll', r: () => collabApi.closePoll(1, 2), e: 'PUT /api/trips/1/collab/polls/2/close' },
|
||||
{ n: 'deletePoll', r: () => collabApi.deletePoll(1, 2), e: 'DELETE /api/trips/1/collab/polls/2' },
|
||||
{ n: 'getMessages', r: () => collabApi.getMessages(1), e: 'GET /api/trips/1/collab/messages' },
|
||||
{ n: 'sendMessage', r: () => collabApi.sendMessage(1, { text: 'hi' }), e: 'POST /api/trips/1/collab/messages' },
|
||||
{ n: 'deleteMessage', r: () => collabApi.deleteMessage(1, 2), e: 'DELETE /api/trips/1/collab/messages/2' },
|
||||
{ n: 'reactMessage', r: () => collabApi.reactMessage(1, 2, '👍'), e: 'POST /api/trips/1/collab/messages/2/react' },
|
||||
{ n: 'linkPreview', r: () => collabApi.linkPreview(1, 'https://x.test/a?b=1'), e: 'GET /api/trips/1/collab/link-preview' },
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-APISURF-021: the remaining namespaces map their endpoints', async () => {
|
||||
await assertCalls([
|
||||
{ n: 'addons.enabled', r: () => addonsApi.enabled(), e: 'GET /api/addons' },
|
||||
{ n: 'health.features', r: () => healthApi.features(), e: 'GET /api/health/features' },
|
||||
{ n: 'weather.get', r: () => weatherApi.get(41.9, 12.5, '2026-06-01'), e: 'GET /api/weather' },
|
||||
{ n: 'weather.getCurrent', r: () => weatherApi.getCurrent(41.9, 12.5), e: 'GET /api/weather' },
|
||||
{ n: 'weather.getDetailed', r: () => weatherApi.getDetailed(41.9, 12.5, '2026-06-01'), e: 'GET /api/weather/detailed' },
|
||||
{ n: 'config.getPublicConfig', r: () => configApi.getPublicConfig(), e: 'GET /api/config' },
|
||||
{ n: 'help.index', r: () => helpApi.index(), e: 'GET /api/help/index' },
|
||||
{ n: 'help.page', r: () => helpApi.page('getting started'), e: 'GET /api/help/page/getting%20started' },
|
||||
{ n: 'settings.get', r: () => settingsApi.get(), e: 'GET /api/settings' },
|
||||
{ n: 'settings.set', r: () => settingsApi.set('theme', 'dark'), e: 'PUT /api/settings' },
|
||||
{ n: 'settings.setBulk', r: () => settingsApi.setBulk({ theme: 'dark' }), e: 'POST /api/settings/bulk' },
|
||||
{ n: 'backup.list', r: () => backupApi.list(), e: 'GET /api/backup/list' },
|
||||
{ n: 'backup.create', r: () => backupApi.create(), e: 'POST /api/backup/create' },
|
||||
{ n: 'backup.delete', r: () => backupApi.delete('b.zip'), e: 'DELETE /api/backup/b.zip' },
|
||||
{ n: 'backup.restore', r: () => backupApi.restore('b.zip'), e: 'POST /api/backup/restore/b.zip' },
|
||||
{ n: 'backup.getAutoSettings', r: () => backupApi.getAutoSettings(), e: 'GET /api/backup/auto-settings' },
|
||||
{ n: 'backup.setAutoSettings', r: () => backupApi.setAutoSettings({ enabled: true }), e: 'PUT /api/backup/auto-settings' },
|
||||
{ n: 'share.getLink', r: () => shareApi.getLink(1), e: 'GET /api/trips/1/share-link' },
|
||||
{ n: 'share.createLink', r: () => shareApi.createLink(1, { edit: false }), e: 'POST /api/trips/1/share-link' },
|
||||
{ n: 'share.deleteLink', r: () => shareApi.deleteLink(1), e: 'DELETE /api/trips/1/share-link' },
|
||||
{ n: 'share.getSharedTrip', r: () => shareApi.getSharedTrip('tok'), e: 'GET /api/shared/tok' },
|
||||
{ n: 'transit.geocode', r: () => transitApi.geocode('Roma Termini'), e: 'GET /api/transit/geocode' },
|
||||
{ n: 'transit.plan', r: () => transitApi.plan({ from: 'a', to: 'b' }), e: 'GET /api/transit/plan' },
|
||||
{ n: 'tripInvite.getLink', r: () => tripInviteApi.getLink(1), e: 'GET /api/trips/1/invite-link' },
|
||||
{ n: 'tripInvite.createLink', r: () => tripInviteApi.createLink(1, 7), e: 'POST /api/trips/1/invite-link' },
|
||||
{ n: 'tripInvite.deleteLink', r: () => tripInviteApi.deleteLink(1), e: 'DELETE /api/trips/1/invite-link' },
|
||||
{ n: 'tripInvite.preview', r: () => tripInviteApi.preview('tok'), e: 'GET /api/trip-invites/tok' },
|
||||
{ n: 'tripInvite.accept', r: () => tripInviteApi.accept('tok'), e: 'POST /api/trip-invites/tok/accept' },
|
||||
{ n: 'notifications.getPreferences', r: () => notificationsApi.getPreferences(), e: 'GET /api/notifications/preferences' },
|
||||
{ n: 'notifications.updatePreferences', r: () => notificationsApi.updatePreferences({ email: { trip_invite: true } }), e: 'PUT /api/notifications/preferences' },
|
||||
{ n: 'notifications.testSmtp', r: () => notificationsApi.testSmtp('a@b.c'), e: 'POST /api/notifications/test-smtp' },
|
||||
{ n: 'notifications.testWebhook', r: () => notificationsApi.testWebhook('https://hook'), e: 'POST /api/notifications/test-webhook' },
|
||||
{ n: 'notifications.testNtfy', r: () => notificationsApi.testNtfy({ topic: 't' }), e: 'POST /api/notifications/test-ntfy' },
|
||||
{ n: 'notifications.testChannel', r: () => notificationsApi.testChannel('plugin/ch'), e: 'POST /api/notifications/test/plugin%2Fch' },
|
||||
{ n: 'inApp.list', r: () => inAppNotificationsApi.list(), e: 'GET /api/notifications/in-app' },
|
||||
{ n: 'inApp.unreadCount', r: () => inAppNotificationsApi.unreadCount(), e: 'GET /api/notifications/in-app/unread-count' },
|
||||
{ n: 'inApp.markRead', r: () => inAppNotificationsApi.markRead(3), e: 'PUT /api/notifications/in-app/3/read' },
|
||||
{ n: 'inApp.markUnread', r: () => inAppNotificationsApi.markUnread(3), e: 'PUT /api/notifications/in-app/3/unread' },
|
||||
{ n: 'inApp.markAllRead', r: () => inAppNotificationsApi.markAllRead(), e: 'PUT /api/notifications/in-app/read-all' },
|
||||
{ n: 'inApp.delete', r: () => inAppNotificationsApi.delete(3), e: 'DELETE /api/notifications/in-app/3' },
|
||||
{ n: 'inApp.deleteAll', r: () => inAppNotificationsApi.deleteAll(), e: 'DELETE /api/notifications/in-app/all' },
|
||||
{ n: 'inApp.respond', r: () => inAppNotificationsApi.respond(3, 'positive'), e: 'POST /api/notifications/in-app/3/respond' },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('client > request payloads', () => {
|
||||
it('FE-APISURF-022: reorder helpers wrap their ids in the contract field', async () => {
|
||||
expect((await traceOne(() => daysApi.reorder(1, [3, 1, 2]))).body).toEqual({ orderedIds: [3, 1, 2] })
|
||||
expect((await traceOne(() => packingApi.reorder(1, [2, 1]))).body).toEqual({ orderedIds: [2, 1] })
|
||||
expect((await traceOne(() => todoApi.reorder(1, [9]))).body).toEqual({ orderedIds: [9] })
|
||||
expect((await traceOne(() => budgetApi.reorderItems(1, [4, 5]))).body).toEqual({ orderedIds: [4, 5] })
|
||||
expect((await traceOne(() => budgetApi.reorderCategories(1, ['Food', 'Fun']))).body)
|
||||
.toEqual({ orderedCategories: ['Food', 'Fun'] })
|
||||
expect((await traceOne(() => journeyApi.reorderEntries(2, [8, 7]))).body).toEqual({ orderedIds: [8, 7] })
|
||||
})
|
||||
|
||||
it('FE-APISURF-023: user-id collections are sent as user_ids', async () => {
|
||||
expect((await traceOne(() => assignmentsApi.setParticipants(1, 7, [4, 5]))).body).toEqual({ user_ids: [4, 5] })
|
||||
expect((await traceOne(() => budgetApi.setMembers(1, 2, [4]))).body).toEqual({ user_ids: [4] })
|
||||
expect((await traceOne(() => packingApi.setBagMembers(1, 2, [6]))).body).toEqual({ user_ids: [6] })
|
||||
expect((await traceOne(() => reservationsApi.setTravelers(1, 2, [4, 6]))).body).toEqual({ user_ids: [4, 6] })
|
||||
})
|
||||
|
||||
it('FE-APISURF-024: single-value helpers wrap their argument in the documented key', async () => {
|
||||
expect((await traceOne(() => authApi.updateMapsKey(null))).body).toEqual({ maps_api_key: null })
|
||||
expect((await traceOne(() => tripsApi.addMember(1, 'bob@x.test'))).body).toEqual({ identifier: 'bob@x.test' })
|
||||
expect((await traceOne(() => tripsApi.transferOwnership(1, 9))).body).toEqual({ newOwnerId: 9 })
|
||||
expect((await traceOne(() => tripsApi.createGuest(1, 'Anna'))).body).toEqual({ name: 'Anna' })
|
||||
expect((await traceOne(() => daysApi.updateTransport(1, 2, 'walk'))).body).toEqual({ transport_mode: 'walk' })
|
||||
expect((await traceOne(() => assignmentsApi.updateTransport(1, 7, null))).body).toEqual({ transport_mode: null })
|
||||
expect((await traceOne(() => collabApi.votePoll(1, 2, 3))).body).toEqual({ option_index: 3 })
|
||||
expect((await traceOne(() => collabApi.reactMessage(1, 2, '🎉'))).body).toEqual({ emoji: '🎉' })
|
||||
expect((await traceOne(() => settingsApi.set('theme', 'dark'))).body).toEqual({ key: 'theme', value: 'dark' })
|
||||
expect((await traceOne(() => settingsApi.setBulk({ a: 1 }))).body).toEqual({ settings: { a: 1 } })
|
||||
expect((await traceOne(() => budgetApi.togglePaid(1, 2, 4, false))).body).toEqual({ paid: false })
|
||||
expect((await traceOne(() => adminApi.updateBagTracking(true))).body).toEqual({ enabled: true })
|
||||
expect((await traceOne(() => adminApi.updatePermissions({ edit: 'owner' }))).body)
|
||||
.toEqual({ permissions: { edit: 'owner' } })
|
||||
expect((await traceOne(() => pluginsApi.saveUserSettings('koffi', { k: 'v' }))).body)
|
||||
.toEqual({ config: { k: 'v' } })
|
||||
})
|
||||
|
||||
it('FE-APISURF-025: tripsApi.archive/unarchive send the is_archived flag', async () => {
|
||||
expect((await traceOne(() => tripsApi.archive(3))).body).toEqual({ is_archived: true })
|
||||
expect((await traceOne(() => tripsApi.unarchive(3))).body).toEqual({ is_archived: false })
|
||||
})
|
||||
|
||||
it('FE-APISURF-026: placesApi bulk operations merge ids with the patch', async () => {
|
||||
expect((await traceOne(() => placesApi.bulkDelete(1, [5, 6]))).body).toEqual({ ids: [5, 6] })
|
||||
expect((await traceOne(() => placesApi.bulkUpdate(1, [5], { category_id: null }))).body)
|
||||
.toEqual({ ids: [5], category_id: null })
|
||||
})
|
||||
|
||||
it('FE-APISURF-027: placesApi.rate deletes on null and PUTs the value otherwise', async () => {
|
||||
const cleared = await traceOne(() => placesApi.rate(1, 5, null))
|
||||
expect(cleared.method).toBe('DELETE')
|
||||
expect(cleared.url).toBe('/api/trips/1/places/5/rating')
|
||||
|
||||
const set = await traceOne(() => placesApi.rate(1, 5, 4))
|
||||
expect(set.method).toBe('PUT')
|
||||
expect(set.url).toBe('/api/trips/1/places/5/rating')
|
||||
expect(set.body).toEqual({ rating: 4 })
|
||||
})
|
||||
|
||||
it('FE-APISURF-028: airtrailApi.import only sends connections when there are any', async () => {
|
||||
expect((await traceOne(() => airtrailApi.import(1, ['f1', 'f2']))).body).toEqual({ flightIds: ['f1', 'f2'] })
|
||||
expect((await traceOne(() => airtrailApi.import(1, ['f1'], []))).body).toEqual({ flightIds: ['f1'] })
|
||||
expect((await traceOne(() => airtrailApi.import(1, ['f1', 'f2'], [['f1', 'f2']]))).body)
|
||||
.toEqual({ flightIds: ['f1', 'f2'], connections: [['f1', 'f2']] })
|
||||
})
|
||||
|
||||
it('FE-APISURF-029: journeyApi provider-photo calls omit optional passphrase and media types', async () => {
|
||||
expect((await traceOne(() => journeyApi.addProviderPhotosToGallery(2, 'immich', ['a1']))).body)
|
||||
.toEqual({ provider: 'immich', asset_ids: ['a1'] })
|
||||
expect((await traceOne(() => journeyApi.addProviderPhotosToGallery(2, 'immich', ['a1'], 'secret', ['video']))).body)
|
||||
.toEqual({ provider: 'immich', asset_ids: ['a1'], passphrase: 'secret', media_types: ['video'] })
|
||||
expect((await traceOne(() => journeyApi.addProviderPhoto(9, 'immich', 'a1', 'cap', 'secret'))).body)
|
||||
.toEqual({ provider: 'immich', asset_id: 'a1', caption: 'cap', passphrase: 'secret' })
|
||||
expect((await traceOne(() => journeyApi.addProviderPhotos(9, 'immich', ['a1'], 'cap'))).body)
|
||||
.toEqual({ provider: 'immich', asset_ids: ['a1'], caption: 'cap' })
|
||||
expect((await traceOne(() => journeyApi.addProviderPhotos(9, 'immich', ['a1'], 'cap', 'secret', ['image', 'video']))).body)
|
||||
.toEqual({ provider: 'immich', asset_ids: ['a1'], caption: 'cap', passphrase: 'secret', media_types: ['image', 'video'] })
|
||||
})
|
||||
|
||||
it('FE-APISURF-030: adminApi.pluginActivate only sends consent when granted', async () => {
|
||||
expect((await traceOne(() => adminApi.pluginActivate('koffi'))).body).toEqual({})
|
||||
expect((await traceOne(() => adminApi.pluginActivate('koffi', true))).body).toEqual({ consent: true })
|
||||
})
|
||||
|
||||
it('FE-APISURF-031: adminApi.pluginInstall spreads its options next to the id', async () => {
|
||||
expect((await traceOne(() => adminApi.pluginInstall('koffi'))).body).toEqual({ id: 'koffi' })
|
||||
expect((await traceOne(() => adminApi.pluginInstall('koffi', { version: '2.0.0', withDependencies: true }))).body)
|
||||
.toEqual({ id: 'koffi', version: '2.0.0', withDependencies: true })
|
||||
})
|
||||
|
||||
it('FE-APISURF-032: tripInviteApi.createLink normalises a missing expiry to null', async () => {
|
||||
expect((await traceOne(() => tripInviteApi.createLink(1))).body).toEqual({ expires_in_days: null })
|
||||
expect((await traceOne(() => tripInviteApi.createLink(1, 14))).body).toEqual({ expires_in_days: 14 })
|
||||
})
|
||||
|
||||
it('FE-APISURF-033: tripsApi.copy and shareApi.createLink default to an empty body', async () => {
|
||||
expect((await traceOne(() => tripsApi.copy(3))).body).toEqual({})
|
||||
expect((await traceOne(() => shareApi.createLink(1))).body).toEqual({})
|
||||
})
|
||||
|
||||
it('FE-APISURF-034: authApi.passkey.delete sends the password in the DELETE body', async () => {
|
||||
const rec = await traceOne(() => authApi.passkey.delete(3, 'hunter2'))
|
||||
expect(rec.method).toBe('DELETE')
|
||||
expect(rec.body).toEqual({ password: 'hunter2' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('client > query parameters', () => {
|
||||
it('FE-APISURF-035: tripsApi.list forwards arbitrary filters as query params', async () => {
|
||||
const rec = await traceOne(() => tripsApi.list({ archived: true, q: 'rome' }))
|
||||
const qs = new URLSearchParams(rec.url.split('?')[1])
|
||||
expect(qs.get('archived')).toBe('true')
|
||||
expect(qs.get('q')).toBe('rome')
|
||||
})
|
||||
|
||||
it('FE-APISURF-036: filesApi.list only sets the trash flag when asked', async () => {
|
||||
expect((await traceOne(() => filesApi.list(1))).url).toBe('/api/trips/1/files')
|
||||
expect((await traceOne(() => filesApi.list(1, true))).url).toBe('/api/trips/1/files?trash=true')
|
||||
})
|
||||
|
||||
it('FE-APISURF-037: budgetApi.settlement adds the base currency only when given', async () => {
|
||||
expect((await traceOne(() => budgetApi.settlement(1))).url).toBe('/api/trips/1/budget/settlement')
|
||||
expect((await traceOne(() => budgetApi.settlement(1, 'EUR'))).url).toBe('/api/trips/1/budget/settlement?base=EUR')
|
||||
})
|
||||
|
||||
it('FE-APISURF-038: collabApi.getMessages appends the before cursor', async () => {
|
||||
expect((await traceOne(() => collabApi.getMessages(1))).url).toBe('/api/trips/1/collab/messages')
|
||||
expect((await traceOne(() => collabApi.getMessages(1, '2026-01-01'))).url)
|
||||
.toBe('/api/trips/1/collab/messages?before=2026-01-01')
|
||||
})
|
||||
|
||||
it('FE-APISURF-039: adminApi.pluginBrowse only sets refresh when forced', async () => {
|
||||
expect((await traceOne(() => adminApi.pluginBrowse())).url).toBe('/api/admin/plugins/registry')
|
||||
expect((await traceOne(() => adminApi.pluginBrowse(true))).url).toBe('/api/admin/plugins/registry?refresh=1')
|
||||
})
|
||||
|
||||
it('FE-APISURF-040: adminApi.auditLog and llmLocalModels pass their params through', async () => {
|
||||
const audit = await traceOne(() => adminApi.auditLog({ limit: 50, offset: 100 }))
|
||||
expect(new URLSearchParams(audit.url.split('?')[1]).get('limit')).toBe('50')
|
||||
expect(new URLSearchParams(audit.url.split('?')[1]).get('offset')).toBe('100')
|
||||
|
||||
const models = await traceOne(() => adminApi.llmLocalModels('http://ollama:11434'))
|
||||
expect(new URLSearchParams(models.url.split('?')[1]).get('baseUrl')).toBe('http://ollama:11434')
|
||||
})
|
||||
|
||||
it('FE-APISURF-041: mapsApi flattens the POI bbox into the query string', async () => {
|
||||
const rec = await traceOne(() => mapsApi.pois('cafe', { south: 41.8, west: 12.4, north: 42.0, east: 12.6 }, 'de'))
|
||||
const qs = new URLSearchParams(rec.url.split('?')[1])
|
||||
expect(qs.get('category')).toBe('cafe')
|
||||
expect(qs.get('south')).toBe('41.8')
|
||||
expect(qs.get('west')).toBe('12.4')
|
||||
expect(qs.get('north')).toBe('42')
|
||||
expect(qs.get('east')).toBe('12.6')
|
||||
expect(qs.get('lang')).toBe('de')
|
||||
})
|
||||
|
||||
it('FE-APISURF-042: weatherApi sends lat/lng plus the date or language', async () => {
|
||||
const forecast = await traceOne(() => weatherApi.get(41.9, 12.5, '2026-06-01'))
|
||||
const fq = new URLSearchParams(forecast.url.split('?')[1])
|
||||
expect([fq.get('lat'), fq.get('lng'), fq.get('date')]).toEqual(['41.9', '12.5', '2026-06-01'])
|
||||
|
||||
const current = await traceOne(() => weatherApi.getCurrent(41.9, 12.5, 'de'))
|
||||
expect(new URLSearchParams(current.url.split('?')[1]).get('lang')).toBe('de')
|
||||
})
|
||||
|
||||
it('FE-APISURF-043: pluginsApi joins trip ids and defaults the activity limit', async () => {
|
||||
expect((await traceOne(() => pluginsApi.tripCardContributions([1, 2, 3]))).url)
|
||||
.toBe('/api/trip-card-contributions?tripIds=1,2,3')
|
||||
expect((await traceOne(() => pluginsApi.myActivity())).url).toBe('/api/plugin-activity?limit=200')
|
||||
expect((await traceOne(() => pluginsApi.myActivity(5))).url).toBe('/api/plugin-activity?limit=5')
|
||||
})
|
||||
|
||||
it('FE-APISURF-044: packing/todo category assignees encode the category name', async () => {
|
||||
const packing = await traceOne(() => packingApi.setCategoryAssignees(1, 'Rain gear/Wet', [4]))
|
||||
expect(packing.url).toBe('/api/trips/1/packing/category-assignees/Rain%20gear%2FWet')
|
||||
expect(packing.body).toEqual({ user_ids: [4] })
|
||||
|
||||
const todo = await traceOne(() => todoApi.setCategoryAssignees(1, 'Before & after', [5]))
|
||||
expect(todo.url).toBe('/api/trips/1/todo/category-assignees/Before%20%26%20after')
|
||||
expect(todo.body).toEqual({ user_ids: [5] })
|
||||
})
|
||||
|
||||
it('FE-APISURF-045: collabApi.linkPreview URL-encodes the previewed link', async () => {
|
||||
const rec = await traceOne(() => collabApi.linkPreview(1, 'https://x.test/a?b=1&c=2'))
|
||||
expect(rec.url).toBe('/api/trips/1/collab/link-preview?url=https%3A%2F%2Fx.test%2Fa%3Fb%3D1%26c%3D2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('client > multipart uploads', () => {
|
||||
// jsdom FormData bodies deadlock inside MSW, so uploads are asserted at the
|
||||
// axios boundary instead (same approach as tests/integration/api/client.test.ts).
|
||||
function spyPost() {
|
||||
return vi.spyOn(apiClient, 'post')
|
||||
.mockResolvedValue({ data: { ok: true } } as unknown as AxiosResponse)
|
||||
}
|
||||
|
||||
it('FE-APISURF-046: every upload opts out of the 8s global timeout', async () => {
|
||||
const post = spyPost()
|
||||
const fd = new FormData()
|
||||
|
||||
await authApi.uploadAvatar(fd)
|
||||
await tripsApi.uploadCover(3, fd)
|
||||
await filesApi.upload(1, fd)
|
||||
await journeyApi.uploadPhotos(9, fd)
|
||||
await journeyApi.uploadGalleryPhotos(2, fd)
|
||||
await journeyApi.uploadGalleryVideo(2, fd)
|
||||
await journeyApi.uploadCover(2, fd)
|
||||
await collabApi.uploadNoteFile(1, 2, fd)
|
||||
|
||||
expect(post.mock.calls.map(c => c[0])).toEqual([
|
||||
'/auth/avatar',
|
||||
'/trips/3/cover',
|
||||
'/trips/1/files',
|
||||
'/journeys/entries/9/photos',
|
||||
'/journeys/2/gallery/photos',
|
||||
'/journeys/2/gallery/video',
|
||||
'/journeys/2/cover',
|
||||
'/trips/1/collab/notes/2/files',
|
||||
])
|
||||
for (const call of post.mock.calls) {
|
||||
expect(call[1]).toBeInstanceOf(FormData)
|
||||
expect(call[2]).toMatchObject({ timeout: 0 })
|
||||
expect((call[2] as { headers: Record<string, string> }).headers['Content-Type']).toBe('multipart/form-data')
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-APISURF-047: postMultipart forwards progress, abort signal and idempotency key', async () => {
|
||||
const post = spyPost()
|
||||
const onUploadProgress = vi.fn((_e: unknown) => {})
|
||||
const controller = new AbortController()
|
||||
|
||||
await filesApi.upload(1, new FormData(), {
|
||||
onUploadProgress,
|
||||
signal: controller.signal,
|
||||
idempotencyKey: 'fixed-key',
|
||||
})
|
||||
|
||||
const config = post.mock.calls[0][2] as {
|
||||
headers: Record<string, string>
|
||||
onUploadProgress?: unknown
|
||||
signal?: AbortSignal
|
||||
timeout: number
|
||||
}
|
||||
expect(config.headers['X-Idempotency-Key']).toBe('fixed-key')
|
||||
expect(config.onUploadProgress).toBe(onUploadProgress)
|
||||
expect(config.signal).toBe(controller.signal)
|
||||
expect(config.timeout).toBe(0)
|
||||
})
|
||||
|
||||
it('FE-APISURF-048: placesApi.uploadImage posts the file under the image field', async () => {
|
||||
const post = spyPost()
|
||||
const file = new File(['bytes'], 'shot.jpg', { type: 'image/jpeg' })
|
||||
|
||||
await placesApi.uploadImage(1, 5, file)
|
||||
|
||||
expect(post.mock.calls[0][0]).toBe('/trips/1/places/5/image')
|
||||
const fd = post.mock.calls[0][1] as FormData
|
||||
expect((fd.get('image') as File).name).toBe('shot.jpg')
|
||||
})
|
||||
|
||||
it('FE-APISURF-049: placesApi.importGpx only appends the flags it was given', async () => {
|
||||
const post = spyPost()
|
||||
const file = new File(['<gpx/>'], 'track.gpx')
|
||||
|
||||
await placesApi.importGpx(1, file)
|
||||
expect(post.mock.calls[0][0]).toBe('/trips/1/places/import/gpx')
|
||||
const bare = post.mock.calls[0][1] as FormData
|
||||
expect(bare.get('importWaypoints')).toBeNull()
|
||||
expect(bare.get('importRoutes')).toBeNull()
|
||||
expect(bare.get('importTracks')).toBeNull()
|
||||
|
||||
await placesApi.importGpx(1, file, { waypoints: true, routes: false, tracks: true })
|
||||
const flagged = post.mock.calls[1][1] as FormData
|
||||
expect(flagged.get('importWaypoints')).toBe('true')
|
||||
expect(flagged.get('importRoutes')).toBe('false')
|
||||
expect(flagged.get('importTracks')).toBe('true')
|
||||
})
|
||||
|
||||
it('FE-APISURF-050: placesApi.importMapFile appends the point/path flags', async () => {
|
||||
const post = spyPost()
|
||||
const file = new File(['{}'], 'map.kml')
|
||||
|
||||
await placesApi.importMapFile(1, file)
|
||||
expect(post.mock.calls[0][0]).toBe('/trips/1/places/import/map')
|
||||
expect((post.mock.calls[0][1] as FormData).get('importPoints')).toBeNull()
|
||||
|
||||
await placesApi.importMapFile(1, file, { points: true, paths: false })
|
||||
const flagged = post.mock.calls[1][1] as FormData
|
||||
expect(flagged.get('importPoints')).toBe('true')
|
||||
expect(flagged.get('importPaths')).toBe('false')
|
||||
})
|
||||
|
||||
it('FE-APISURF-051: booking import posts every file plus the extraction mode', async () => {
|
||||
const post = spyPost()
|
||||
const files = [new File(['a'], 'a.pdf'), new File(['b'], 'b.pdf')]
|
||||
|
||||
await reservationsApi.importBookingPreview(1, files, 'force-ai')
|
||||
expect(post.mock.calls[0][0]).toBe('/trips/1/reservations/import/booking')
|
||||
const preview = post.mock.calls[0][1] as FormData
|
||||
expect(preview.getAll('files')).toHaveLength(2)
|
||||
expect(preview.get('mode')).toBe('force-ai')
|
||||
|
||||
await reservationsApi.importBookingAsync(1, files)
|
||||
expect(post.mock.calls[1][0]).toBe('/trips/1/reservations/import/booking/async')
|
||||
expect((post.mock.calls[1][1] as FormData).get('mode')).toBe('no-ai')
|
||||
})
|
||||
|
||||
it('FE-APISURF-052: adminApi.pluginUpload and backupApi.uploadRestore name their form fields', async () => {
|
||||
const post = spyPost()
|
||||
|
||||
await adminApi.pluginUpload(new File(['zip'], 'plugin.zip'))
|
||||
expect(post.mock.calls[0][0]).toBe('/admin/plugins/upload')
|
||||
expect(((post.mock.calls[0][1] as FormData).get('file') as File).name).toBe('plugin.zip')
|
||||
|
||||
await backupApi.uploadRestore(new File(['zip'], 'backup.zip'))
|
||||
expect(post.mock.calls[1][0]).toBe('/backup/upload-restore')
|
||||
expect(((post.mock.calls[1][1] as FormData).get('backup') as File).name).toBe('backup.zip')
|
||||
})
|
||||
})
|
||||
+240
-34
@@ -1,5 +1,7 @@
|
||||
import axios, { AxiosInstance } from 'axios'
|
||||
import type { z } from 'zod'
|
||||
import type { Place } from '../types'
|
||||
import { randomId } from '../utils/randomId'
|
||||
import {
|
||||
weatherResultSchema, type WeatherResult,
|
||||
inAppListResultSchema, type InAppListResult,
|
||||
@@ -7,9 +9,11 @@ import {
|
||||
channelTestResultSchema,
|
||||
mapsSearchResultSchema, mapsAutocompleteResultSchema, mapsPlaceDetailsResultSchema,
|
||||
mapsPlacePhotoResultSchema, mapsReverseResultSchema, mapsResolveUrlResultSchema,
|
||||
mapsPlaceEnrichmentResultSchema,
|
||||
type NotificationRespondRequest,
|
||||
type SettingUpsertRequest, type SettingsBulkRequest,
|
||||
type JourneyCreateRequest, type JourneyAddTripRequest,
|
||||
type JourneyCreateRequest, type JourneyAddTripRequest, type JourneyTracksResponse,
|
||||
type JourneyStats, type BookRecord, type BookSaveRequest,
|
||||
type JourneyReorderEntriesRequest, type JourneyProviderPhotosRequest,
|
||||
type JourneyShareLinkRequest,
|
||||
type RegisterRequest, type LoginRequest, type ForgotPasswordRequest,
|
||||
@@ -18,7 +22,7 @@ import {
|
||||
type TripAddMemberRequest, type TripTransferOwnershipRequest,
|
||||
type TripCreateGuestRequest, type TripRenameGuestRequest, type AssignmentReorderRequest,
|
||||
type PackingReorderRequest, type PackingCreateBagRequest, type TodoReorderRequest,
|
||||
type TripCreateRequest, type TripUpdateRequest, type TripCopyRequest,
|
||||
type TripCreateRequest, type TripUpdateRequest, type TripCopyRequest, type ActiveTripResponse,
|
||||
type DayCreateRequest, type DayUpdateRequest, type DayReorderRequest,
|
||||
type PlaceCreateRequest, type PlaceUpdateRequest,
|
||||
type ReservationCreateRequest, type ReservationUpdateRequest,
|
||||
@@ -26,7 +30,7 @@ import {
|
||||
type BudgetCreateItemRequest, type BudgetUpdateItemRequest,
|
||||
type PackingCreateItemRequest, type PackingUpdateItemRequest, type PackingSetSharingRequest,
|
||||
type TodoCreateItemRequest, type TodoUpdateItemRequest,
|
||||
type AssignmentCreateRequest, type AssignmentParticipantsRequest, type AssignmentTimeRequest,
|
||||
type AssignmentCreateRequest, type AssignmentParticipantsRequest, type AssignmentTimeRequest, type AssignmentTransportRequest,
|
||||
type PlaceBulkDeleteRequest,
|
||||
type PlaceBulkUpdateRequest,
|
||||
type DayNoteCreateRequest, type DayNoteUpdateRequest,
|
||||
@@ -44,9 +48,15 @@ import {
|
||||
type BookingImportPreviewResponse,
|
||||
type BookingImportConfirmResponse,
|
||||
type BookingImportMode,
|
||||
type StorageAdminState,
|
||||
type StorageBackend,
|
||||
type StorageConfigPut,
|
||||
type StorageTestResponse,
|
||||
type StorageUsage,
|
||||
} from '@trek/shared'
|
||||
import { getSocketId } from './websocket'
|
||||
import { probeNow } from '../sync/connectivity'
|
||||
import { downloadBlob } from '../utils/fileDownload'
|
||||
|
||||
/**
|
||||
* Validate a response payload against its @trek/shared Zod schema — but only in
|
||||
@@ -104,6 +114,9 @@ const RATE_LIMIT_MESSAGES: Record<string, string> = {
|
||||
ko: '시도 횟수가 너무 많습니다. 잠시 후 다시 시도해 주세요.',
|
||||
uk: 'Занадто багато спроб. Спробуйте пізніше.',
|
||||
sv: 'För många försök. Prova igen senare.',
|
||||
ca: 'Massa intents. Torneu-ho a provar més tard.',
|
||||
gr: 'Πάρα πολλές προσπάθειες. Δοκιμάστε ξανά αργότερα.',
|
||||
vi: 'Quá nhiều lần thử. Vui lòng thử lại sau.',
|
||||
}
|
||||
|
||||
function translateRateLimit(): string {
|
||||
@@ -139,10 +152,7 @@ apiClient.interceptors.request.use(
|
||||
// The mutation queue sets its own pre-generated key; skip if already set.
|
||||
const method = (config.method ?? '').toLowerCase()
|
||||
if (MUTATING_METHODS.has(method) && !config.headers['X-Idempotency-Key']) {
|
||||
const key = typeof crypto !== 'undefined' && crypto.randomUUID
|
||||
? crypto.randomUUID()
|
||||
: Math.random().toString(36).slice(2)
|
||||
config.headers['X-Idempotency-Key'] = key
|
||||
config.headers['X-Idempotency-Key'] = randomId()
|
||||
}
|
||||
return config
|
||||
},
|
||||
@@ -227,9 +237,11 @@ apiClient.interceptors.response.use(
|
||||
}
|
||||
if (error.response?.status === 429) {
|
||||
const translated = translateRateLimit()
|
||||
const data = error.response.data as { error?: string } | undefined
|
||||
if (data && typeof data === 'object') {
|
||||
data.error = translated
|
||||
const data = error.response.data
|
||||
// Only a plain object body carries an `error` field worth overwriting;
|
||||
// an array (a validation-error list) or a string is replaced outright.
|
||||
if (data && typeof data === 'object' && !Array.isArray(data)) {
|
||||
(data as { error?: string }).error = translated
|
||||
} else {
|
||||
error.response.data = { error: translated }
|
||||
}
|
||||
@@ -366,6 +378,9 @@ export const tripsApi = {
|
||||
list: (params?: Record<string, unknown>) => apiClient.get('/trips', { params }).then(r => r.data),
|
||||
create: (data: TripCreateRequest) => apiClient.post('/trips', data).then(r => r.data),
|
||||
get: (id: number | string) => apiClient.get(`/trips/${id}`).then(r => r.data),
|
||||
// The startup redirect's one lookup — deliberately not list(), which would pull
|
||||
// every trip with its counts just to read one id.
|
||||
active: (): Promise<ActiveTripResponse> => apiClient.get('/trips/active').then(r => r.data),
|
||||
update: (id: number | string, data: TripUpdateRequest) => apiClient.put(`/trips/${id}`, data).then(r => r.data),
|
||||
delete: (id: number | string) => apiClient.delete(`/trips/${id}`).then(r => r.data),
|
||||
uploadCover: (id: number | string, formData: FormData) => postMultipart(`/trips/${id}/cover`, formData),
|
||||
@@ -387,6 +402,8 @@ export const daysApi = {
|
||||
list: (tripId: number | string) => apiClient.get(`/trips/${tripId}/days`).then(r => r.data),
|
||||
create: (tripId: number | string, data: DayCreateRequest) => apiClient.post(`/trips/${tripId}/days`, data).then(r => r.data),
|
||||
update: (tripId: number | string, dayId: number | string, data: DayUpdateRequest) => apiClient.put(`/trips/${tripId}/days/${dayId}`, data).then(r => r.data),
|
||||
// Whole-day default route mode (#1281); per-segment leg modes override it.
|
||||
updateTransport: (tripId: number | string, dayId: number | string, mode: string | null) => apiClient.put(`/trips/${tripId}/days/${dayId}/transport`, { transport_mode: mode }).then(r => r.data),
|
||||
delete: (tripId: number | string, dayId: number | string) => apiClient.delete(`/trips/${tripId}/days/${dayId}`).then(r => r.data),
|
||||
reorder: (tripId: number | string, orderedIds: number[]) => apiClient.put(`/trips/${tripId}/days/reorder`, { orderedIds } satisfies DayReorderRequest).then(r => r.data),
|
||||
}
|
||||
@@ -398,6 +415,15 @@ export const placesApi = {
|
||||
update: (tripId: number | string, id: number | string, data: PlaceUpdateRequest) => apiClient.put(`/trips/${tripId}/places/${id}`, data).then(r => r.data),
|
||||
delete: (tripId: number | string, id: number | string) => apiClient.delete(`/trips/${tripId}/places/${id}`).then(r => r.data),
|
||||
searchImage: (tripId: number | string, id: number | string) => apiClient.get(`/trips/${tripId}/places/${id}/image`).then(r => r.data),
|
||||
uploadImage: (tripId: number | string, id: number | string, file: File) => {
|
||||
const fd = new FormData()
|
||||
fd.append('image', file)
|
||||
return postMultipart<{ place: Place }>(`/trips/${tripId}/places/${id}/image`, fd)
|
||||
},
|
||||
rate: (tripId: number | string, id: number | string, rating: number | null): Promise<{ place: Place }> =>
|
||||
rating === null
|
||||
? apiClient.delete(`/trips/${tripId}/places/${id}/rating`).then(r => r.data)
|
||||
: apiClient.put(`/trips/${tripId}/places/${id}/rating`, { rating }).then(r => r.data),
|
||||
importGpx: (tripId: number | string, file: File, opts?: { waypoints?: boolean; routes?: boolean; tracks?: boolean }) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
@@ -433,6 +459,10 @@ export const assignmentsApi = {
|
||||
getParticipants: (tripId: number | string, id: number) => apiClient.get(`/trips/${tripId}/assignments/${id}/participants`).then(r => r.data),
|
||||
setParticipants: (tripId: number | string, id: number, userIds: number[]) => apiClient.put(`/trips/${tripId}/assignments/${id}/participants`, { user_ids: userIds } satisfies AssignmentParticipantsRequest).then(r => r.data),
|
||||
updateTime: (tripId: number | string, id: number, times: AssignmentTimeRequest) => apiClient.put(`/trips/${tripId}/assignments/${id}/time`, times).then(r => r.data),
|
||||
// Per-segment travel mode (#1281): mode of the leg leaving this stop (null = inherit day default).
|
||||
// direction defaults to 'outgoing' server-side, so only send it for the incoming (boundary-leg) case
|
||||
// and keep the outgoing payload byte-for-byte identical to the pre-#1281 shape.
|
||||
updateTransport: (tripId: number | string, id: number, mode: string | null, direction: 'outgoing' | 'incoming' = 'outgoing') => apiClient.put(`/trips/${tripId}/assignments/${id}/transport`, (direction === 'incoming' ? { transport_mode: mode, direction } : { transport_mode: mode }) satisfies Partial<AssignmentTransportRequest>).then(r => r.data),
|
||||
}
|
||||
|
||||
export const packingApi = {
|
||||
@@ -501,7 +531,12 @@ export const adminApi = {
|
||||
apiClient.post('/admin/plugins/install', { id, ...opts }).then(r => r.data),
|
||||
pluginActivate: (id: string, consent?: boolean) => apiClient.post(`/admin/plugins/${id}/activate`, consent ? { consent: true } : {}).then(r => r.data),
|
||||
pluginDeactivate: (id: string) => apiClient.post(`/admin/plugins/${id}/deactivate`).then(r => r.data),
|
||||
pluginUpdate: (id: string) => apiClient.post(`/admin/plugins/${id}/update`).then(r => r.data),
|
||||
// `version` pins the exact version to install (the rollback path); omitted, the server
|
||||
// resolves the newest TREK-compatible version itself.
|
||||
pluginUpdate: (id: string, version?: string) =>
|
||||
apiClient.post(`/admin/plugins/${id}/update`, version ? { version } : {}).then(r => r.data),
|
||||
// Release a per-plugin update hold (set by a deliberate non-latest install).
|
||||
pluginResumeUpdates: (id: string) => apiClient.post(`/admin/plugins/${id}/resume-updates`).then(r => r.data),
|
||||
// Re-trust a ROTATED author signing key and update, in ONE call. `publicKey` is the
|
||||
// full key the admin was shown (not a fingerprint): the server compares it exactly, so
|
||||
// it can refuse if the registry entry was re-keyed again since the dialog rendered.
|
||||
@@ -537,24 +572,35 @@ export const adminApi = {
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ baseUrl, model }),
|
||||
})
|
||||
if (!res.ok || !res.body) {
|
||||
if (!res.ok) {
|
||||
let msg = `Pull failed (${res.status})`
|
||||
try { msg = (await res.json())?.error ?? msg } catch { /* non-json */ }
|
||||
throw new Error(msg)
|
||||
}
|
||||
// An accepted request without a stream can't be followed to completion.
|
||||
if (!res.body) throw new Error('Pull returned no progress stream')
|
||||
const reader = res.body.getReader()
|
||||
const dec = new TextDecoder()
|
||||
let buf = ''
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
buf += dec.decode(value, { stream: true })
|
||||
const lines = buf.split('\n')
|
||||
buf = lines.pop() ?? ''
|
||||
for (const line of lines) {
|
||||
if (!line.trim()) continue
|
||||
try { onProgress(JSON.parse(line)) } catch { /* skip partial */ }
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
buf += dec.decode(value, { stream: true })
|
||||
// split() always yields at least one element; the last one is the
|
||||
// trailing (possibly partial) line carried into the next chunk.
|
||||
const lines = buf.split('\n')
|
||||
buf = lines.pop()!
|
||||
for (const line of lines) {
|
||||
if (!line.trim()) continue
|
||||
// Only the parse is swallowed — a throw from onProgress aborts the pull.
|
||||
let frame: { status?: string; total?: number; completed?: number; error?: string }
|
||||
try { frame = JSON.parse(line) } catch { continue }
|
||||
onProgress(frame)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.cancel().catch(() => {})
|
||||
}
|
||||
},
|
||||
checkVersion: () => apiClient.get('/admin/version-check').then(r => r.data),
|
||||
@@ -566,6 +612,8 @@ export const adminApi = {
|
||||
updatePlacesAutocomplete: (enabled: boolean) => apiClient.put('/admin/places-autocomplete', { enabled }).then(r => r.data),
|
||||
getPlacesDetails: () => apiClient.get('/admin/places-details').then(r => r.data),
|
||||
updatePlacesDetails: (enabled: boolean) => apiClient.put('/admin/places-details', { enabled }).then(r => r.data),
|
||||
getPlacesEnrich: () => apiClient.get('/admin/places-enrich').then(r => r.data),
|
||||
updatePlacesEnrich: (enabled: boolean) => apiClient.put('/admin/places-enrich', { enabled }).then(r => r.data),
|
||||
getCollabFeatures: () => apiClient.get('/admin/collab-features').then(r => r.data),
|
||||
updateCollabFeatures: (features: Record<string, boolean>) => apiClient.put('/admin/collab-features', features).then(r => r.data),
|
||||
packingTemplates: () => apiClient.get('/admin/packing-templates').then(r => r.data),
|
||||
@@ -598,6 +646,26 @@ export const adminApi = {
|
||||
updateNotificationPreferences: (prefs: Record<string, Record<string, boolean>>) => apiClient.put('/admin/notification-preferences', prefs).then(r => r.data),
|
||||
getDefaultUserSettings: () => apiClient.get('/admin/default-user-settings').then(r => r.data),
|
||||
updateDefaultUserSettings: (settings: Record<string, unknown>) => apiClient.put('/admin/default-user-settings', settings).then(r => r.data),
|
||||
getStorage: (): Promise<StorageAdminState> => apiClient.get('/admin/storage').then(r => r.data),
|
||||
updateStorage: (config: StorageConfigPut): Promise<StorageAdminState> =>
|
||||
apiClient.put('/admin/storage', config).then(r => r.data),
|
||||
// A probe is bounded by the target driver's own timeout (default 30s, ×2 with
|
||||
// one retry) and a mirror probes its targets sequentially — the instance-wide
|
||||
// 8s axios timeout would abort a legitimate slow probe, so this call carries
|
||||
// its own generous ceiling.
|
||||
testStorageBackend: (backend: StorageBackend): Promise<StorageTestResponse> =>
|
||||
apiClient.post('/admin/storage/test', { backend }, { timeout: 120_000 }).then(r => r.data),
|
||||
startStorageBackfill: (backend: string): Promise<{ started: true }> =>
|
||||
apiClient.post(`/admin/storage/backends/${encodeURIComponent(backend)}/backfill`).then(r => r.data),
|
||||
cancelStorageBackfill: (backend: string): Promise<{ cancelled: true }> =>
|
||||
apiClient.delete(`/admin/storage/backends/${encodeURIComponent(backend)}/backfill`).then(r => r.data),
|
||||
startStorageMigration: (category: string, to: string): Promise<{ started: true }> =>
|
||||
apiClient.post('/admin/storage/migrations', { category, to }).then(r => r.data),
|
||||
cancelStorageMigration: (category: string): Promise<{ cancelled: true }> =>
|
||||
apiClient.delete(`/admin/storage/migrations/${encodeURIComponent(category)}`).then(r => r.data),
|
||||
// A full scan of a large install can exceed the 8s instance timeout.
|
||||
refreshStorageStats: (): Promise<StorageUsage> =>
|
||||
apiClient.post('/admin/storage/stats/refresh', undefined, { timeout: 120_000 }).then(r => r.data),
|
||||
}
|
||||
|
||||
export const addonsApi = {
|
||||
@@ -624,6 +692,74 @@ export interface PluginMapMarker {
|
||||
tone: 'default' | 'success' | 'warn' | 'danger'
|
||||
}
|
||||
|
||||
/** One shape of a plugin map layer (mapLayerProvider hook). Server-normalized:
|
||||
* coordinates range-checked, vertex budget capped, styling clamped to the tone
|
||||
* palette + bounded numerics — never free-form CSS or markup. */
|
||||
export interface PluginMapLayerFeature {
|
||||
type: 'polyline' | 'polygon' | 'circle';
|
||||
points?: Array<[number, number]>;
|
||||
center?: [number, number];
|
||||
radiusM?: number;
|
||||
tone: 'default' | 'success' | 'warn' | 'danger';
|
||||
width: number;
|
||||
dash: 'solid' | 'dash' | 'dot';
|
||||
opacity: number;
|
||||
fill: boolean;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
/** A vector overlay a plugin draws on the trip map (routes, corridors, zones). */
|
||||
export interface PluginMapLayer {
|
||||
pluginId: string; id: string; name?: string;
|
||||
features: PluginMapLayerFeature[];
|
||||
}
|
||||
|
||||
/** A time contribution a dayScheduleProvider plugin attaches to the day plan
|
||||
* ("35 min charging at this stop"). Server-normalized: dayIds checked against
|
||||
* the trip, minutes clamped to a day, labels sanitized + capped. */
|
||||
export interface PluginDayScheduleItem {
|
||||
pluginId: string; id: string; dayId: number;
|
||||
assignmentId?: number; reservationId?: number;
|
||||
position?: 'start' | 'end';
|
||||
minutes?: number; label: string;
|
||||
tone: 'default' | 'success' | 'warn' | 'danger';
|
||||
}
|
||||
|
||||
/** The colours a dayTintProvider plugin puts into one day card, so leg membership is
|
||||
* visible while scrolling the itinerary. The card has three separately tintable
|
||||
* regions; an absent one is not tinted and renders exactly as it does with no plugin.
|
||||
* Server-normalized: dayIds checked against the trip, one contribution per day (first
|
||||
* granted provider wins), the `tone` / `color` shorthands already resolved into the
|
||||
* regions, labels sanitized + capped.
|
||||
*
|
||||
* A region carries EITHER a tone from the fixed palette or the plugin's own colour,
|
||||
* never both — the server picked the winner. `*Color` is guaranteed `#rrggbb` (nothing
|
||||
* else survives normalization, because it lands inside a CSS value); the client still
|
||||
* owns how strongly it renders — alpha per theme and per region, lightness clamped
|
||||
* into a readable band. */
|
||||
export type PluginDayTintTone = 'default' | 'success' | 'warn' | 'danger'
|
||||
export interface PluginDayTint {
|
||||
pluginId: string; dayId: number;
|
||||
badgeTone?: PluginDayTintTone;
|
||||
badgeColor?: string;
|
||||
headerTone?: PluginDayTintTone;
|
||||
headerColor?: string;
|
||||
activityTone?: PluginDayTintTone;
|
||||
activityColor?: string;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
/** A route computed by a routeProvider plugin (server-normalized: coordinates
|
||||
* range-checked, legs forced to waypoints-1, vias capped). null = provider failed
|
||||
* or refused — the caller falls back to straight lines like on an OSRM outage. */
|
||||
export interface PluginRouteResult {
|
||||
pluginId: string; profile: string;
|
||||
coordinates: Array<[number, number]>;
|
||||
distance: number; duration: number;
|
||||
legs: Array<{ distance: number; duration: number; note?: string }>;
|
||||
viaPoints: Array<{ lat: number; lng: number; label?: string; tone: 'default' | 'success' | 'warn' | 'danger'; dwellSeconds?: number }>;
|
||||
}
|
||||
|
||||
/** A text-only section a pdfSectionProvider plugin appends to the trip PDF export.
|
||||
* Server-normalized: counts + lengths are capped, cells are plain strings. */
|
||||
export interface PluginPdfSection {
|
||||
@@ -667,6 +803,23 @@ export const pluginsApi = {
|
||||
// (#587). Host-normalized + range-checked; fail-safe (skips slow/failing providers).
|
||||
mapMarkers: (tripId: number | string) =>
|
||||
apiClient.get(`/map-markers/${tripId}`).then(r => r.data as { markers: PluginMapMarker[] }),
|
||||
// Vector overlays (polylines/polygons/circles) plugins draw on the trip map via
|
||||
// the mapLayerProvider hook. Host-normalized + vertex-budgeted; fail-safe.
|
||||
mapLayers: (tripId: number | string) =>
|
||||
apiClient.get(`/map-layers/${tripId}`).then(r => r.data as { layers: PluginMapLayer[] }),
|
||||
// Route the given waypoints through ONE routeProvider plugin profile (targeted,
|
||||
// not a fan-out — the user picked this profile in the route toggle). Slow by
|
||||
// design (external solvers): the server allows the plugin 20 s.
|
||||
pluginRoute: (pluginId: string, profileId: string, body: { tripId: number | string; dayId?: number | null; waypoints: Array<{ lat: number; lng: number; name?: string; placeId?: number }> }, opts: { signal?: AbortSignal } = {}) =>
|
||||
apiClient.post(`/plugin-routes/${pluginId}/${profileId}`, body, { timeout: 25000, signal: opts.signal }).then(r => r.data as { route: PluginRouteResult | null }),
|
||||
// Time contributions plugins attach to the day plan via the dayScheduleProvider
|
||||
// hook (charging stops, security buffers). Host-normalized; fail-safe.
|
||||
daySchedule: (tripId: number | string) =>
|
||||
apiClient.get(`/day-schedule/${tripId}`).then(r => r.data as { items: PluginDayScheduleItem[] }),
|
||||
// Per-day colours plugins put behind the day cards via the dayTintProvider hook
|
||||
// (which leg of the trip a day belongs to). Host-normalized; fail-safe.
|
||||
dayTints: (tripId: number | string) =>
|
||||
apiClient.get(`/day-tints/${tripId}`).then(r => r.data as { tints: PluginDayTint[] }),
|
||||
// Text-only sections plugins append to the trip PDF export via the
|
||||
// pdfSectionProvider hook. Host-normalized (counts + lengths capped); fail-safe.
|
||||
pdfSections: (tripId: number | string) =>
|
||||
@@ -764,6 +917,22 @@ export const journeyApi = {
|
||||
|
||||
// Entries
|
||||
listEntries: (id: number) => apiClient.get(`/journeys/${id}/entries`).then(r => r.data),
|
||||
// GPX tracks of the trips this journey's entries came from (#1260).
|
||||
listTracks: (id: number): Promise<JourneyTracksResponse> => apiClient.get(`/journeys/${id}/tracks`).then(r => r.data),
|
||||
// What the journey adds up to — distance, days, countries, the route (#1973).
|
||||
// Read by TREK Studio, which freezes the answer into the book document.
|
||||
stats: (id: number): Promise<JourneyStats> => apiClient.get(`/journeys/${id}/stats`).then(r => r.data),
|
||||
|
||||
// The Studio book (#1973). `book` is null for a journey that has none yet —
|
||||
// Studio lays one out and the first save creates it.
|
||||
getBook: (id: number): Promise<{ book: BookRecord | null }> =>
|
||||
apiClient.get(`/journeys/${id}/book`).then(r => r.data),
|
||||
// A 409 carries the current record in its body, so a conflict can be shown
|
||||
// rather than only announced. See useBookStore.
|
||||
saveBook: (id: number, body: BookSaveRequest): Promise<BookRecord> =>
|
||||
apiClient.put(`/journeys/${id}/book`, body).then(r => r.data),
|
||||
deleteBook: (id: number): Promise<void> =>
|
||||
apiClient.delete(`/journeys/${id}/book`).then(r => r.data),
|
||||
createEntry: (id: number, data: Record<string, unknown>) => apiClient.post(`/journeys/${id}/entries`, data).then(r => r.data),
|
||||
updateEntry: (entryId: number, data: Record<string, unknown>) => apiClient.patch(`/journeys/entries/${entryId}`, data).then(r => r.data),
|
||||
deleteEntry: (entryId: number) => apiClient.delete(`/journeys/entries/${entryId}`).then(r => r.data),
|
||||
@@ -803,19 +972,58 @@ export const journeyApi = {
|
||||
getPublicJourney: (token: string) => apiClient.get(`/public/journey/${token}`).then(r => r.data),
|
||||
}
|
||||
|
||||
// Photo providers (Immich, Synology Photos, …) behind /api/integrations/memories.
|
||||
// The provider sits on the user's own hardware and the server proxies through to
|
||||
// it, so the 8s default does not apply — and neither does any number picked
|
||||
// here. The server already holds the deadline, and its worst case is longer than
|
||||
// anything that would look reasonable in this file: a Synology call is 30s, and
|
||||
// an expired session makes it re-authenticate and try again. A client cap below
|
||||
// that turns a slow NAS into a NAS that reads as disconnected, which is what
|
||||
// these calls looked like before they moved off raw fetch (which had no timeout
|
||||
// either). Callers that need to give up early pass an AbortSignal.
|
||||
const MEMORIES_TIMEOUT = 0
|
||||
|
||||
export const memoriesApi = {
|
||||
status: (provider: string): Promise<{ connected: boolean }> =>
|
||||
apiClient.get(`/integrations/memories/${provider}/status`, { timeout: MEMORIES_TIMEOUT }).then(r => r.data),
|
||||
search: (provider: string, body: { from: string; to: string; page: number; size: number }, signal?: AbortSignal) =>
|
||||
apiClient.post(`/integrations/memories/${provider}/search`, body, { timeout: MEMORIES_TIMEOUT, signal }).then(r => r.data),
|
||||
albums: (provider: string) =>
|
||||
apiClient.get(`/integrations/memories/${provider}/albums`, { timeout: MEMORIES_TIMEOUT }).then(r => r.data),
|
||||
albumPhotos: (provider: string, albumId: string, passphrase?: string, signal?: AbortSignal) =>
|
||||
apiClient.get(`/integrations/memories/${provider}/albums/${albumId}/photos`, {
|
||||
timeout: MEMORIES_TIMEOUT,
|
||||
params: passphrase ? { passphrase } : undefined,
|
||||
signal,
|
||||
}).then(r => r.data),
|
||||
}
|
||||
|
||||
export const mapsApi = {
|
||||
search: (query: string, lang?: string) => apiClient.post(`/maps/search?lang=${lang || 'en'}`, { query }).then(r => checkInDev(mapsSearchResultSchema, r.data, 'maps.search')),
|
||||
autocomplete: (input: string, lang?: string, locationBias?: { low: { lat: number; lng: number }; high: { lat: number; lng: number } }, signal?: AbortSignal) =>
|
||||
apiClient.post('/maps/autocomplete', { input, lang, locationBias }, { signal }).then(r => checkInDev(mapsAutocompleteResultSchema, r.data, 'maps.autocomplete')),
|
||||
details: (placeId: string, lang?: string) => apiClient.get(`/maps/details/${encodeURIComponent(placeId)}`, { params: { lang } }).then(r => checkInDev(mapsPlaceDetailsResultSchema, r.data, 'maps.details')),
|
||||
autocomplete: (input: string, lang?: string, locationBias?: { low: { lat: number; lng: number }; high: { lat: number; lng: number } }, signal?: AbortSignal, sessionToken?: string) =>
|
||||
apiClient.post('/maps/autocomplete', { input, lang, locationBias, sessionToken }, { signal }).then(r => checkInDev(mapsAutocompleteResultSchema, r.data, 'maps.autocomplete')),
|
||||
details: (placeId: string, lang?: string, sessionToken?: string) => apiClient.get(`/maps/details/${encodeURIComponent(placeId)}`, { params: { lang, sessionToken } }).then(r => checkInDev(mapsPlaceDetailsResultSchema, r.data, 'maps.details')),
|
||||
// Pictures and a description for a place that is being looked at but not yet
|
||||
// saved. Fans out to several providers server-side, so it takes a signal and
|
||||
// the caller is expected to abort it when the selection changes, and a longer
|
||||
// timeout than the global 8s — a cold Wikimedia connection alone can eat that.
|
||||
placeEnrichment: (
|
||||
body: { placeId?: string; lat: number; lng: number; name: string; lang?: string; details?: Record<string, unknown> },
|
||||
signal?: AbortSignal,
|
||||
) => apiClient.post('/maps/enrichment', body, { signal, timeout: 25000 })
|
||||
.then(r => checkInDev(mapsPlaceEnrichmentResultSchema, r.data, 'maps.placeEnrichment')),
|
||||
// Author + licence for a picture already stored in the photo cache, keyed by
|
||||
// the cache key embedded in its proxy URL. Local read, no provider call.
|
||||
placePhotoCredit: (key: string) =>
|
||||
apiClient.get(`/maps/enrichment/credit/${encodeURIComponent(key)}`).then(r => r.data as { credit: string | null }),
|
||||
placePhoto: (placeId: string, lat?: number, lng?: number, name?: string) => apiClient.get(`/maps/place-photo/${encodeURIComponent(placeId)}`, { params: { lat, lng, name } }).then(r => checkInDev(mapsPlacePhotoResultSchema, r.data, 'maps.placePhoto')),
|
||||
reverse: (lat: number, lng: number, lang?: string) => apiClient.get('/maps/reverse', { params: { lat, lng, lang } }).then(r => checkInDev(mapsReverseResultSchema, r.data, 'maps.reverse')),
|
||||
resolveUrl: (url: string) => apiClient.post('/maps/resolve-url', { url }).then(r => checkInDev(mapsResolveUrlResultSchema, r.data, 'maps.resolveUrl')),
|
||||
// OSM-only POI explore: places of a category within the current map viewport bbox.
|
||||
// Overpass can be slow on a fresh (uncached) area, so this call gets a longer
|
||||
// timeout than the global default instead of aborting at 8s and showing nothing.
|
||||
pois: (category: string, bbox: { south: number; west: number; north: number; east: number }, signal?: AbortSignal) =>
|
||||
apiClient.get('/maps/pois', { params: { category, ...bbox }, signal, timeout: 20000 }).then(r => r.data as { pois: import('../components/Map/poiCategories').Poi[]; source: string; truncated: boolean; clamped?: boolean }),
|
||||
pois: (category: string, bbox: { south: number; west: number; north: number; east: number }, lang?: string, signal?: AbortSignal) =>
|
||||
apiClient.get('/maps/pois', { params: { category, ...bbox, lang }, signal, timeout: 20000 }).then(r => r.data as { pois: import('../components/Map/poiCategories').Poi[]; source: string; truncated: boolean; clamped?: boolean }),
|
||||
}
|
||||
|
||||
export const airportsApi = {
|
||||
@@ -860,6 +1068,8 @@ export const reservationsApi = {
|
||||
create: (tripId: number | string, data: ReservationCreateRequest) => apiClient.post(`/trips/${tripId}/reservations`, data).then(r => r.data),
|
||||
update: (tripId: number | string, id: number, data: ReservationUpdateRequest) => apiClient.put(`/trips/${tripId}/reservations/${id}`, data).then(r => r.data),
|
||||
delete: (tripId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/reservations/${id}`).then(r => r.data),
|
||||
// Assign trip members / named guests to a booking (#1517).
|
||||
setTravelers: (tripId: number | string, id: number, userIds: number[]) => apiClient.put(`/trips/${tripId}/reservations/${id}/travelers`, { user_ids: userIds }).then(r => r.data),
|
||||
updatePositions: (tripId: number | string, positions: { id: number; day_plan_position: number }[], dayId?: number) => apiClient.put(`/trips/${tripId}/reservations/positions`, { positions, day_id: dayId }).then(r => r.data),
|
||||
importBookingPreview: (tripId: number | string, files: File[], mode: BookingImportMode = 'no-ai'): Promise<BookingImportPreviewResponse> => {
|
||||
const fd = new FormData()
|
||||
@@ -889,7 +1099,9 @@ export const healthApi = {
|
||||
}
|
||||
|
||||
export const weatherApi = {
|
||||
get: (lat: number, lng: number, date: string): Promise<WeatherResult> => apiClient.get('/weather', { params: { lat, lng, date } }).then(r => parseInDev(weatherResultSchema, r.data, 'weather.get')),
|
||||
// `time` (HH:MM) makes a past date answer for that hour instead of the day (#1614).
|
||||
get: (lat: number, lng: number, date: string, time?: string): Promise<WeatherResult> => apiClient.get('/weather', { params: { lat, lng, date, time } }).then(r => parseInDev(weatherResultSchema, r.data, 'weather.get')),
|
||||
getCurrent: (lat: number, lng: number, lang?: string): Promise<WeatherResult> => apiClient.get('/weather', { params: { lat, lng, lang } }).then(r => parseInDev(weatherResultSchema, r.data, 'weather.getCurrent')),
|
||||
getDetailed: (lat: number, lng: number, date: string, lang?: string): Promise<WeatherResult> => apiClient.get('/weather/detailed', { params: { lat, lng, date, lang } }).then(r => parseInDev(weatherResultSchema, r.data, 'weather.getDetailed')),
|
||||
}
|
||||
|
||||
@@ -962,13 +1174,7 @@ export const backupApi = {
|
||||
credentials: 'include',
|
||||
})
|
||||
if (!res.ok) throw new Error('Download failed')
|
||||
const blob = await res.blob()
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = filename
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
downloadBlob(await res.blob(), filename)
|
||||
},
|
||||
delete: (filename: string) => apiClient.delete(`/backup/${filename}`).then(r => r.data),
|
||||
restore: (filename: string) => apiClient.post(`/backup/restore/${filename}`).then(r => r.data),
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
// FE-API-COLLECTIONS-001 to FE-API-COLLECTIONS-032
|
||||
//
|
||||
// The Collections addon wrapper is thin, but every method encodes a URL, a verb and a
|
||||
// request-body shape that the server contract depends on. These tests drive each method
|
||||
// through MSW and pin the method + path + payload, plus the unwrapping of `r.data`.
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { http, HttpResponse, type JsonBodyType } from 'msw'
|
||||
import { server } from '../../tests/helpers/msw/server'
|
||||
import { collectionsApi } from './collections'
|
||||
import type { Collection, CollectionLabel, CollectionPlace } from '@trek/shared'
|
||||
|
||||
const BASE = '/api/addons/collections'
|
||||
|
||||
const collection: Collection = { id: 1, owner_id: 1, name: 'Tokyo', place_count: 2, is_owner: true }
|
||||
const place: CollectionPlace = { id: 10, collection_id: 1, name: 'Shibuya Crossing', status: 'want' }
|
||||
const label: CollectionLabel = { id: 3, collection_id: 1, name: 'Food', color: '#ef4444' }
|
||||
|
||||
let requestUrl = ''
|
||||
let requestBody: unknown
|
||||
|
||||
beforeEach(() => {
|
||||
requestUrl = ''
|
||||
requestBody = undefined
|
||||
})
|
||||
|
||||
/** Records url + parsed JSON body of the intercepted request, then answers with `data`. */
|
||||
function record<T extends JsonBodyType>(data: T) {
|
||||
return async ({ request }: { request: Request }) => {
|
||||
requestUrl = request.url
|
||||
const text = await request.text()
|
||||
if (text) {
|
||||
try {
|
||||
requestBody = JSON.parse(text)
|
||||
} catch {
|
||||
requestBody = text
|
||||
}
|
||||
}
|
||||
return HttpResponse.json(data)
|
||||
}
|
||||
}
|
||||
|
||||
describe('collectionsApi', () => {
|
||||
it('FE-API-COLLECTIONS-001: list() unwraps the collections + incomingInvites envelope', async () => {
|
||||
server.use(http.get(BASE, record({ collections: [collection], incomingInvites: [] })))
|
||||
|
||||
const res = await collectionsApi.list()
|
||||
|
||||
expect(res.collections).toEqual([collection])
|
||||
expect(res.incomingInvites).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-002: get() requests the list by id', async () => {
|
||||
server.use(http.get(`${BASE}/:id`, record({ collection, places: [place] })))
|
||||
|
||||
const res = await collectionsApi.get(1)
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/1`)
|
||||
expect(res.places).toEqual([place])
|
||||
expect(res.collection.name).toBe('Tokyo')
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-003: create() posts the create payload', async () => {
|
||||
server.use(http.post(BASE, record({ collection })))
|
||||
|
||||
const res = await collectionsApi.create({ name: 'Tokyo', color: '#111827' })
|
||||
|
||||
expect(requestBody).toEqual({ name: 'Tokyo', color: '#111827' })
|
||||
expect(res.collection.id).toBe(1)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-004: update() patches the list by id', async () => {
|
||||
server.use(http.patch(`${BASE}/:id`, record({ collection })))
|
||||
|
||||
const res = await collectionsApi.update(1, { name: 'Tokyo 2026' })
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/1`)
|
||||
expect(requestBody).toEqual({ name: 'Tokyo 2026' })
|
||||
expect(res.collection).toEqual(collection)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-005: uploadCover() posts multipart to the cover endpoint', async () => {
|
||||
server.use(http.post(`${BASE}/:id/cover`, record(collection)))
|
||||
|
||||
const fd = new FormData()
|
||||
fd.append('cover', new File(['x'], 'cover.jpg'))
|
||||
const res = await collectionsApi.uploadCover(1, fd)
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/1/cover`)
|
||||
expect(res).toEqual(collection)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-006: remove() deletes the list', async () => {
|
||||
server.use(http.delete(`${BASE}/:id`, record({ success: true })))
|
||||
|
||||
const res = await collectionsApi.remove(4)
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/4`)
|
||||
expect(res).toEqual({ success: true })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-007: reorder() posts the ordered ids', async () => {
|
||||
server.use(http.post(`${BASE}/reorder`, record({ success: true })))
|
||||
|
||||
await collectionsApi.reorder([3, 1, 2])
|
||||
|
||||
expect(requestBody).toEqual({ orderedIds: [3, 1, 2] })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-008: savePlace() posts the place payload', async () => {
|
||||
server.use(http.post(`${BASE}/places`, record({ place })))
|
||||
|
||||
const res = await collectionsApi.savePlace({ collection_id: 1, name: 'Shibuya Crossing', force: true })
|
||||
|
||||
expect(requestBody).toEqual({ collection_id: 1, name: 'Shibuya Crossing', force: true })
|
||||
expect(res.place).toEqual(place)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-009: saveFromTrip() posts the provenance-only payload', async () => {
|
||||
server.use(http.post(`${BASE}/places/from-trip`, record({ duplicate: true, duplicateOf: { id: 9, name: 'Shibuya' } })))
|
||||
|
||||
const res = await collectionsApi.saveFromTrip({ collection_id: 1, source_trip_id: 7, source_place_id: 42 })
|
||||
|
||||
expect(requestBody).toEqual({ collection_id: 1, source_trip_id: 7, source_place_id: 42 })
|
||||
expect(res.duplicate).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-010: saveFromTripMany() maps its arguments onto the bulk payload', async () => {
|
||||
server.use(http.post(`${BASE}/places/from-trip-many`, record({ copied: 2, skipped: [] })))
|
||||
|
||||
const res = await collectionsApi.saveFromTripMany(1, 7, [11, 12], true)
|
||||
|
||||
expect(requestBody).toEqual({ collection_id: 1, source_trip_id: 7, source_place_ids: [11, 12], force: true })
|
||||
expect(res.copied).toBe(2)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-011: updatePlace() patches the place and returns it unwrapped', async () => {
|
||||
server.use(http.patch(`${BASE}/places/:pid`, record({ ...place, notes: 'busy at night' })))
|
||||
|
||||
const res = await collectionsApi.updatePlace(10, { notes: 'busy at night' })
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/places/10`)
|
||||
expect(requestBody).toEqual({ notes: 'busy at night' })
|
||||
expect(res.notes).toBe('busy at night')
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-012: uploadPlaceImage() posts multipart to the place image endpoint', async () => {
|
||||
server.use(http.post(`${BASE}/places/:pid/image`, record({ ...place, image_url: '/uploads/p.jpg' })))
|
||||
|
||||
const fd = new FormData()
|
||||
fd.append('image', new File(['x'], 'p.jpg'))
|
||||
const res = await collectionsApi.uploadPlaceImage(10, fd)
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/places/10/image`)
|
||||
expect(res.image_url).toBe('/uploads/p.jpg')
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-013: setStatus() posts the status', async () => {
|
||||
server.use(http.post(`${BASE}/places/:pid/status`, record({ ...place, status: 'visited' })))
|
||||
|
||||
const res = await collectionsApi.setStatus(10, 'visited')
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/places/10/status`)
|
||||
expect(requestBody).toEqual({ status: 'visited' })
|
||||
expect(res.status).toBe('visited')
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-014: ratePlace() PUTs a numeric rating', async () => {
|
||||
server.use(http.put(`${BASE}/places/:pid/rating`, record({ ...place, rating_avg: 4 })))
|
||||
|
||||
const res = await collectionsApi.ratePlace(10, 4)
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/places/10/rating`)
|
||||
expect(requestBody).toEqual({ rating: 4 })
|
||||
expect(res.rating_avg).toBe(4)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-015: ratePlace(null) DELETEs the rating instead', async () => {
|
||||
let deleted = false
|
||||
server.use(
|
||||
http.put(`${BASE}/places/:pid/rating`, () => HttpResponse.json({ error: 'should not be called' }, { status: 500 })),
|
||||
http.delete(`${BASE}/places/:pid/rating`, () => {
|
||||
deleted = true
|
||||
return HttpResponse.json({ ...place, rating_avg: null })
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await collectionsApi.ratePlace(10, null)
|
||||
|
||||
expect(deleted).toBe(true)
|
||||
expect(res.rating_avg).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-016: deletePlace() deletes the saved place', async () => {
|
||||
server.use(http.delete(`${BASE}/places/:pid`, record({ success: true })))
|
||||
|
||||
await collectionsApi.deletePlace(10)
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/places/10`)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-017: deleteMany() posts the id list', async () => {
|
||||
server.use(http.post(`${BASE}/places/delete-many`, record({ deleted: 2 })))
|
||||
|
||||
const res = await collectionsApi.deleteMany([10, 11])
|
||||
|
||||
expect(requestBody).toEqual({ ids: [10, 11] })
|
||||
expect(res).toEqual({ deleted: 2 })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-018: copyToTrip() posts the copy payload and returns the dedup report', async () => {
|
||||
server.use(http.post(`${BASE}/copy-to-trip`, record({ copied: 1, skipped: [{ id: 11, name: 'Shibuya' }] })))
|
||||
|
||||
const res = await collectionsApi.copyToTrip({ trip_id: 7, place_ids: [10, 11] })
|
||||
|
||||
expect(requestBody).toEqual({ trip_id: 7, place_ids: [10, 11] })
|
||||
expect(res.copied).toBe(1)
|
||||
expect(res.skipped).toEqual([{ id: 11, name: 'Shibuya' }])
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-019: membership() sends the lookup as query params', async () => {
|
||||
server.use(http.get(`${BASE}/membership`, record({ saved: true, lists: [{ collection_id: 1, name: 'Tokyo', place_id: 10 }] })))
|
||||
|
||||
const res = await collectionsApi.membership({ google_place_id: 'g1', lat: 35.6, lng: 139.7 })
|
||||
const params = new URL(requestUrl).searchParams
|
||||
|
||||
expect(params.get('google_place_id')).toBe('g1')
|
||||
expect(params.get('lat')).toBe('35.6')
|
||||
expect(params.get('lng')).toBe('139.7')
|
||||
expect(res.saved).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-020: invite() posts collection_id, user_id and role', async () => {
|
||||
server.use(http.post(`${BASE}/invite`, record({ success: true })))
|
||||
|
||||
await collectionsApi.invite(1, 5, 'admin')
|
||||
|
||||
expect(requestBody).toEqual({ collection_id: 1, user_id: 5, role: 'admin' })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-021: setMemberRole() posts the new role', async () => {
|
||||
server.use(http.post(`${BASE}/members/role`, record({ success: true })))
|
||||
|
||||
await collectionsApi.setMemberRole(1, 5, 'viewer')
|
||||
|
||||
expect(requestBody).toEqual({ collection_id: 1, user_id: 5, role: 'viewer' })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-022: acceptInvite() posts only the collection id', async () => {
|
||||
server.use(http.post(`${BASE}/invite/accept`, record({ success: true })))
|
||||
|
||||
await collectionsApi.acceptInvite(1)
|
||||
|
||||
expect(requestBody).toEqual({ collection_id: 1 })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-023: declineInvite() posts only the collection id', async () => {
|
||||
server.use(http.post(`${BASE}/invite/decline`, record({ success: true })))
|
||||
|
||||
await collectionsApi.declineInvite(2)
|
||||
|
||||
expect(requestBody).toEqual({ collection_id: 2 })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-024: cancelInvite() posts collection_id and user_id', async () => {
|
||||
server.use(http.post(`${BASE}/invite/cancel`, record({ success: true })))
|
||||
|
||||
await collectionsApi.cancelInvite(1, 5)
|
||||
|
||||
expect(requestBody).toEqual({ collection_id: 1, user_id: 5 })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-025: leave() posts the collection id', async () => {
|
||||
server.use(http.post(`${BASE}/leave`, record({ success: true })))
|
||||
|
||||
await collectionsApi.leave(3)
|
||||
|
||||
expect(requestBody).toEqual({ collection_id: 3 })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-026: removeMember() posts collection_id and user_id', async () => {
|
||||
server.use(http.post(`${BASE}/members/remove`, record({ success: true })))
|
||||
|
||||
await collectionsApi.removeMember(1, 9)
|
||||
|
||||
expect(requestBody).toEqual({ collection_id: 1, user_id: 9 })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-027: availableUsers() reads the invitable users for a list', async () => {
|
||||
server.use(http.get(`${BASE}/:id/available-users`, record({ users: [{ id: 5, username: 'bob' }] })))
|
||||
|
||||
const res = await collectionsApi.availableUsers(1)
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/1/available-users`)
|
||||
expect(res.users).toEqual([{ id: 5, username: 'bob' }])
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-028: createLabel() posts collection_id, name and color', async () => {
|
||||
server.use(http.post(`${BASE}/labels`, record(label)))
|
||||
|
||||
const res = await collectionsApi.createLabel(1, 'Food', '#ef4444')
|
||||
|
||||
expect(requestBody).toEqual({ collection_id: 1, name: 'Food', color: '#ef4444' })
|
||||
expect(res).toEqual(label)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-029: updateLabel() patches the label by id', async () => {
|
||||
server.use(http.patch(`${BASE}/labels/:id`, record({ ...label, name: 'Eats' })))
|
||||
|
||||
const res = await collectionsApi.updateLabel(3, { name: 'Eats' })
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/labels/3`)
|
||||
expect(requestBody).toEqual({ name: 'Eats' })
|
||||
expect(res.name).toBe('Eats')
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-030: deleteLabel() deletes the label by id', async () => {
|
||||
server.use(http.delete(`${BASE}/labels/:id`, record({ success: true })))
|
||||
|
||||
await collectionsApi.deleteLabel(3)
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/labels/3`)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-031: assignLabels() posts label_ids and place_ids', async () => {
|
||||
server.use(http.post(`${BASE}/labels/assign`, record({ changed: 2 })))
|
||||
|
||||
const res = await collectionsApi.assignLabels([3], [10, 11])
|
||||
|
||||
expect(requestBody).toEqual({ label_ids: [3], place_ids: [10, 11] })
|
||||
expect(res.changed).toBe(2)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-032: unassignLabels() posts to the unassign endpoint', async () => {
|
||||
server.use(http.post(`${BASE}/labels/unassign`, record({ changed: 1 })))
|
||||
|
||||
const res = await collectionsApi.unassignLabels([3], [10])
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/labels/unassign`)
|
||||
expect(requestBody).toEqual({ label_ids: [3], place_ids: [10] })
|
||||
expect(res.changed).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
CollectionUpdateRequest,
|
||||
CollectionSavePlaceRequest,
|
||||
CollectionSaveFromTripRequest,
|
||||
CollectionImportablesResponse,
|
||||
CollectionPlaceUpdateRequest,
|
||||
CollectionCopyToTripRequest,
|
||||
CollectionInviteRequest,
|
||||
@@ -16,6 +17,7 @@ import type {
|
||||
CollectionInviteActionRequest,
|
||||
CollectionInviteCancelRequest,
|
||||
CollectionStatus,
|
||||
CollectionSetStatusManyResponse,
|
||||
Collection,
|
||||
CollectionPlace,
|
||||
CollectionLabel,
|
||||
@@ -68,10 +70,22 @@ export const collectionsApi = {
|
||||
ax.post(`${base}/places/from-trip`, body satisfies CollectionSaveFromTripRequest).then((r: AxiosResponse) => r.data),
|
||||
saveFromTripMany: (collectionId: number, tripId: number, placeIds: number[], force?: boolean): Promise<{ copied: number; skipped: { id: number; name: string }[] }> =>
|
||||
ax.post(`${base}/places/from-trip-many`, { collection_id: collectionId, source_trip_id: tripId, source_place_ids: placeIds, force }).then((r: AxiosResponse) => r.data),
|
||||
importable: (collectionId: number, tripId: number): Promise<CollectionImportablesResponse> =>
|
||||
ax.get(`${base}/${collectionId}/importable/${tripId}`).then((r: AxiosResponse) => r.data),
|
||||
updatePlace: (pid: number, body: CollectionPlaceUpdateRequest): Promise<CollectionPlace> =>
|
||||
ax.patch(`${base}/places/${pid}`, body satisfies CollectionPlaceUpdateRequest).then((r: AxiosResponse) => r.data),
|
||||
uploadPlaceImage: (pid: number, formData: FormData): Promise<CollectionPlace> =>
|
||||
postMultipart(`${base}/places/${pid}/image`, formData),
|
||||
setStatus: (pid: number, status: CollectionStatus): Promise<CollectionPlace> =>
|
||||
ax.post(`${base}/places/${pid}/status`, { status }).then((r: AxiosResponse) => r.data),
|
||||
setStatusMany: (ids: number[], status: CollectionStatus): Promise<CollectionSetStatusManyResponse> =>
|
||||
ax.post(`${base}/places/status-many`, { ids, status }).then((r: AxiosResponse) => r.data),
|
||||
setStatusFromTrip: (tripId: number, placeIds: number[], status: CollectionStatus): Promise<CollectionSetStatusManyResponse> =>
|
||||
ax.post(`${base}/places/status-from-trip`, { trip_id: tripId, place_ids: placeIds, status }).then((r: AxiosResponse) => r.data),
|
||||
ratePlace: (pid: number, rating: number | null): Promise<CollectionPlace> =>
|
||||
rating === null
|
||||
? ax.delete(`${base}/places/${pid}/rating`).then((r: AxiosResponse) => r.data)
|
||||
: ax.put(`${base}/places/${pid}/rating`, { rating }).then((r: AxiosResponse) => r.data),
|
||||
deletePlace: (pid: number): Promise<unknown> =>
|
||||
ax.delete(`${base}/places/${pid}`).then((r: AxiosResponse) => r.data),
|
||||
deleteMany: (ids: number[]): Promise<unknown> =>
|
||||
|
||||
@@ -1,12 +1,26 @@
|
||||
// FE-OAUTH-SCOPES-001 to FE-OAUTH-SCOPES-010
|
||||
// FE-OAUTH-SCOPES-001 to FE-OAUTH-SCOPES-011
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { SCOPE_GROUPS, ALL_SCOPES, SCOPE_GROUP_NAMES, getScopesByGroup } from './oauthScopes'
|
||||
|
||||
// The consent page mirrors the server's scope list by hand, so read the server
|
||||
// file and compare. Parsing keeps this a client-only test (no server import).
|
||||
function readServerScopes(): string[] {
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const src = readFileSync(resolve(here, '../../../server/src/mcp/scopes.ts'), 'utf8')
|
||||
const block = src.slice(src.indexOf('export const SCOPES = {'))
|
||||
const body = block.slice(0, block.indexOf('} as const;'))
|
||||
return [...body.matchAll(/^\s*[A-Z_]+:\s*'([a-z]+:[a-z]+)'/gm)].map(m => m[1])
|
||||
}
|
||||
|
||||
describe('SCOPE_GROUPS', () => {
|
||||
it('FE-OAUTH-SCOPES-001: contains all expected scope keys', () => {
|
||||
const expected = [
|
||||
'trips:read', 'trips:write', 'trips:delete', 'trips:share',
|
||||
'places:read', 'places:write',
|
||||
'collections:read', 'collections:write',
|
||||
'atlas:read', 'atlas:write',
|
||||
'packing:read', 'packing:write',
|
||||
'todos:read', 'todos:write',
|
||||
@@ -16,6 +30,7 @@ describe('SCOPE_GROUPS', () => {
|
||||
'notifications:read', 'notifications:write',
|
||||
'vacay:read', 'vacay:write',
|
||||
'geo:read', 'weather:read',
|
||||
'journey:read', 'journey:write', 'journey:share',
|
||||
]
|
||||
for (const scope of expected) {
|
||||
expect(SCOPE_GROUPS).toHaveProperty(scope)
|
||||
@@ -32,8 +47,16 @@ describe('SCOPE_GROUPS', () => {
|
||||
})
|
||||
|
||||
describe('ALL_SCOPES', () => {
|
||||
it('FE-OAUTH-SCOPES-003: contains exactly 27 scopes', () => {
|
||||
expect(ALL_SCOPES).toHaveLength(27)
|
||||
it('FE-OAUTH-SCOPES-003: contains exactly as many scopes as the server defines', () => {
|
||||
expect(ALL_SCOPES).toHaveLength(readServerScopes().length)
|
||||
})
|
||||
|
||||
it('FE-OAUTH-SCOPES-011: matches server/src/mcp/scopes.ts exactly', () => {
|
||||
const serverScopes = readServerScopes()
|
||||
// Guards the parse itself: a moved file or a reformatted list must fail
|
||||
// here rather than quietly compare two empty sets.
|
||||
expect(serverScopes.length).toBeGreaterThan(0)
|
||||
expect(new Set(ALL_SCOPES)).toEqual(new Set(serverScopes))
|
||||
})
|
||||
|
||||
it('FE-OAUTH-SCOPES-004: matches Object.keys(SCOPE_GROUPS)', () => {
|
||||
|
||||
@@ -20,6 +20,8 @@ export const SCOPE_GROUPS: Record<string, ScopeKeys> = {
|
||||
'trips:share': { labelKey: 'oauth.scope.trips:share.label', descriptionKey: 'oauth.scope.trips:share.description', groupKey: 'oauth.scope.group.trips' },
|
||||
'places:read': { labelKey: 'oauth.scope.places:read.label', descriptionKey: 'oauth.scope.places:read.description', groupKey: 'oauth.scope.group.places' },
|
||||
'places:write': { labelKey: 'oauth.scope.places:write.label', descriptionKey: 'oauth.scope.places:write.description', groupKey: 'oauth.scope.group.places' },
|
||||
'collections:read': { labelKey: 'oauth.scope.collections:read.label', descriptionKey: 'oauth.scope.collections:read.description', groupKey: 'oauth.scope.group.collections' },
|
||||
'collections:write': { labelKey: 'oauth.scope.collections:write.label', descriptionKey: 'oauth.scope.collections:write.description', groupKey: 'oauth.scope.group.collections' },
|
||||
'atlas:read': { labelKey: 'oauth.scope.atlas:read.label', descriptionKey: 'oauth.scope.atlas:read.description', groupKey: 'oauth.scope.group.atlas' },
|
||||
'atlas:write': { labelKey: 'oauth.scope.atlas:write.label', descriptionKey: 'oauth.scope.atlas:write.description', groupKey: 'oauth.scope.group.atlas' },
|
||||
'packing:read': { labelKey: 'oauth.scope.packing:read.label', descriptionKey: 'oauth.scope.packing:read.description', groupKey: 'oauth.scope.group.packing' },
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
// vi.unmock must run before the module is imported (tests/setup.ts mocks it globally)
|
||||
vi.unmock('./websocket')
|
||||
|
||||
// FE-WSCORE-001 to FE-WSCORE-014
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { server } from '../../tests/helpers/msw/server'
|
||||
import {
|
||||
connect, disconnect, joinTrip, leaveTrip, getActiveTrips,
|
||||
setRefetchCallback, setPreReconnectHook,
|
||||
} from './websocket'
|
||||
|
||||
class MockWebSocket {
|
||||
static CONNECTING = 0
|
||||
static OPEN = 1
|
||||
static CLOSING = 2
|
||||
static CLOSED = 3
|
||||
static instances: MockWebSocket[] = []
|
||||
|
||||
readyState: number = MockWebSocket.OPEN
|
||||
send = vi.fn((_data: string) => {})
|
||||
close = vi.fn(() => {})
|
||||
onopen: (() => void) | null = null
|
||||
onmessage: ((event: { data: string }) => void) | null = null
|
||||
onclose: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
|
||||
constructor(public url: string) {
|
||||
MockWebSocket.instances.push(this)
|
||||
}
|
||||
}
|
||||
|
||||
function lastSocket(): MockWebSocket {
|
||||
return MockWebSocket.instances[MockWebSocket.instances.length - 1]
|
||||
}
|
||||
|
||||
const realLocation = window.location
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
MockWebSocket.instances = []
|
||||
Object.defineProperty(globalThis, 'WebSocket', {
|
||||
writable: true, configurable: true, value: MockWebSocket,
|
||||
})
|
||||
server.use(http.post('/api/auth/ws-token', () => HttpResponse.json({ token: 'ws-tok' })))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
disconnect()
|
||||
setRefetchCallback(null)
|
||||
setPreReconnectHook(null)
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
Object.defineProperty(window, 'location', { writable: true, configurable: true, value: realLocation })
|
||||
})
|
||||
|
||||
/** connect() + settle the token fetch so a socket exists. */
|
||||
async function openSocket(): Promise<MockWebSocket> {
|
||||
connect()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
return lastSocket()
|
||||
}
|
||||
|
||||
describe('websocket > active trips', () => {
|
||||
it('FE-WSCORE-001: getActiveTrips lists the joined trips as strings', async () => {
|
||||
expect(getActiveTrips()).toEqual([])
|
||||
|
||||
joinTrip(42)
|
||||
joinTrip('7')
|
||||
expect(getActiveTrips()).toEqual(['42', '7'])
|
||||
|
||||
disconnect()
|
||||
expect(getActiveTrips()).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-WSCORE-013: join/leave still bookkeep while no socket is open', () => {
|
||||
joinTrip(5)
|
||||
expect(getActiveTrips()).toEqual(['5'])
|
||||
|
||||
leaveTrip(5)
|
||||
expect(getActiveTrips()).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-WSCORE-014: a trip joined before onopen is not re-sent while the socket is closing', async () => {
|
||||
joinTrip(11)
|
||||
const sock = await openSocket()
|
||||
sock.readyState = MockWebSocket.CLOSING
|
||||
|
||||
sock.onopen!()
|
||||
|
||||
expect(sock.send).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('websocket > reconnect refetch hook', () => {
|
||||
it('FE-WSCORE-002: the pre-reconnect hook is awaited before the refetch runs', async () => {
|
||||
const order: string[] = []
|
||||
setPreReconnectHook(async () => { order.push('flush') })
|
||||
setRefetchCallback(() => { order.push('refetch') })
|
||||
|
||||
joinTrip(3)
|
||||
const sock = await openSocket()
|
||||
sock.onopen!()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(order).toEqual(['flush', 'refetch'])
|
||||
})
|
||||
|
||||
it('FE-WSCORE-003: a rejecting pre-reconnect hook still lets the refetch run', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const refetch = vi.fn((_tripId: string) => {})
|
||||
setPreReconnectHook(async () => { throw new Error('queue flush failed') })
|
||||
setRefetchCallback(refetch)
|
||||
|
||||
joinTrip(3)
|
||||
const sock = await openSocket()
|
||||
sock.onopen!()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(refetch).toHaveBeenCalledWith('3')
|
||||
expect(consoleError).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-WSCORE-004: a throwing refetch callback is logged, not propagated', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
setRefetchCallback(() => { throw new Error('store blew up') })
|
||||
|
||||
joinTrip(3)
|
||||
const sock = await openSocket()
|
||||
|
||||
expect(() => sock.onopen!()).not.toThrow()
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
'Failed to refetch trip data on reconnect:',
|
||||
expect.any(Error),
|
||||
)
|
||||
})
|
||||
|
||||
it('FE-WSCORE-005: with no joined trips onopen sends nothing and skips the refetch', async () => {
|
||||
const refetch = vi.fn((_tripId: string) => {})
|
||||
setRefetchCallback(refetch)
|
||||
|
||||
const sock = await openSocket()
|
||||
sock.onopen!()
|
||||
|
||||
expect(sock.send).not.toHaveBeenCalled()
|
||||
expect(refetch).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('websocket > connection lifecycle', () => {
|
||||
it('FE-WSCORE-006: connect() is a no-op while a socket is still CONNECTING', async () => {
|
||||
const sock = await openSocket()
|
||||
sock.readyState = MockWebSocket.CONNECTING
|
||||
|
||||
connect()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(MockWebSocket.instances).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-WSCORE-007: connect() cancels a pending reconnect timer', async () => {
|
||||
server.use(http.post('/api/auth/ws-token', () => new HttpResponse(null, { status: 503 })))
|
||||
connect()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(MockWebSocket.instances).toHaveLength(0)
|
||||
|
||||
// A retry is now armed; connect() must clear it and dial immediately.
|
||||
server.use(http.post('/api/auth/ws-token', () => HttpResponse.json({ token: 'fresh' })))
|
||||
connect()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(MockWebSocket.instances).toHaveLength(1)
|
||||
|
||||
// The cancelled timer must not fire a second dial afterwards.
|
||||
await vi.advanceTimersByTimeAsync(5000)
|
||||
expect(MockWebSocket.instances).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-WSCORE-008: a duplicate close does not stack a second timer or skip a backoff step', async () => {
|
||||
const sock = await openSocket()
|
||||
|
||||
// Every further token fetch fails, so each retry attempt is countable.
|
||||
let attempts = 0
|
||||
server.use(http.post('/api/auth/ws-token', () => {
|
||||
attempts++
|
||||
return new HttpResponse(null, { status: 503 })
|
||||
}))
|
||||
|
||||
// A browser can deliver close twice (after onerror); the second must be ignored.
|
||||
sock.onclose!()
|
||||
sock.onclose!()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1001)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(attempts, 'first retry fires after the 1s delay').toBe(1)
|
||||
|
||||
// Backoff advanced once (1s → 2s), not twice, so the next retry lands at 2s.
|
||||
await vi.advanceTimersByTimeAsync(2001)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(attempts, 'second retry fires after the doubled 2s delay').toBe(2)
|
||||
|
||||
expect(MockWebSocket.instances).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-WSCORE-009: a failing ws-token fetch schedules a retry instead of throwing', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('offline'))
|
||||
|
||||
connect()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(MockWebSocket.instances).toHaveLength(0)
|
||||
|
||||
vi.mocked(globalThis.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ token: 'back-online' }), {
|
||||
status: 200, headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
)
|
||||
await vi.advanceTimersByTimeAsync(1001)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(MockWebSocket.instances).toHaveLength(1)
|
||||
expect(lastSocket().url).toContain('token=back-online')
|
||||
})
|
||||
|
||||
it('FE-WSCORE-010: the socket URL uses ws:// on http and wss:// on https', async () => {
|
||||
const httpSock = await openSocket()
|
||||
expect(httpSock.url.startsWith('ws://')).toBe(true)
|
||||
|
||||
disconnect()
|
||||
MockWebSocket.instances = []
|
||||
Object.defineProperty(window, 'location', {
|
||||
writable: true, configurable: true,
|
||||
value: {
|
||||
protocol: 'https:',
|
||||
host: 'trip.example',
|
||||
origin: 'https://trip.example',
|
||||
href: 'https://trip.example/dashboard',
|
||||
pathname: '/dashboard',
|
||||
},
|
||||
})
|
||||
|
||||
const secure = await openSocket()
|
||||
expect(secure.url).toBe('wss://trip.example/ws?token=ws-tok')
|
||||
})
|
||||
|
||||
it('FE-WSCORE-011: disconnect() detaches onclose so no reconnect is armed', async () => {
|
||||
const sock = await openSocket()
|
||||
disconnect()
|
||||
|
||||
expect(sock.onclose).toBeNull()
|
||||
expect(sock.close).toHaveBeenCalled()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(5000)
|
||||
expect(MockWebSocket.instances).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-WSCORE-012: onerror is inert — the reconnect is driven by onclose', async () => {
|
||||
const sock = await openSocket()
|
||||
|
||||
expect(() => sock.onerror!()).not.toThrow()
|
||||
expect(MockWebSocket.instances).toHaveLength(1)
|
||||
|
||||
sock.onclose!()
|
||||
await vi.advanceTimersByTimeAsync(1001)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(MockWebSocket.instances).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,15 @@ let reconnectDelay = 1000
|
||||
const MAX_RECONNECT_DELAY = 30000
|
||||
const listeners = new Set<WebSocketListener>()
|
||||
const activeTrips = new Set<string>()
|
||||
|
||||
/**
|
||||
* Studio books this tab has open, so presence survives a reconnect.
|
||||
*
|
||||
* Same reasoning as `activeTrips`: the server forgets the room when the socket
|
||||
* dies, and without rejoining, everyone else keeps showing a pointer for
|
||||
* somebody who is no longer there.
|
||||
*/
|
||||
const activeBooks = new Set<string>()
|
||||
let shouldReconnect = false
|
||||
let refetchCallback: RefetchCallback | null = null
|
||||
let mySocketId: string | null = null
|
||||
@@ -110,6 +119,11 @@ async function connectInternal(_isReconnect = false): Promise<void> {
|
||||
|
||||
socket.onopen = () => {
|
||||
reconnectDelay = 1000
|
||||
activeBooks.forEach(journeyId => {
|
||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify({ type: 'book:join', journeyId }))
|
||||
}
|
||||
})
|
||||
if (activeTrips.size > 0) {
|
||||
activeTrips.forEach(tripId => {
|
||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||
@@ -166,6 +180,7 @@ export function disconnect(): void {
|
||||
reconnectTimer = null
|
||||
}
|
||||
activeTrips.clear()
|
||||
activeBooks.clear()
|
||||
if (socket) {
|
||||
socket.onclose = null
|
||||
socket.close()
|
||||
@@ -187,6 +202,40 @@ export function leaveTrip(tripId: number | string): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a Studio book — presence and pointers, for as long as the editor is up.
|
||||
*/
|
||||
export function joinBook(journeyId: number | string): void {
|
||||
activeBooks.add(String(journeyId))
|
||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify({ type: 'book:join', journeyId: String(journeyId) }))
|
||||
}
|
||||
}
|
||||
|
||||
export function leaveBook(journeyId: number | string): void {
|
||||
activeBooks.delete(String(journeyId))
|
||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify({ type: 'book:leave', journeyId: String(journeyId) }))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where this tab's pointer is, in millimetres on the spread.
|
||||
*
|
||||
* Dropped silently when the socket is not open. A pointer is worth nothing a
|
||||
* moment later, so there is nothing to queue and nothing to retry — the next
|
||||
* one is along in a tenth of a second.
|
||||
*/
|
||||
export function sendBookCursor(
|
||||
journeyId: number | string,
|
||||
spreadIndex: number,
|
||||
x: number | null,
|
||||
y: number | null,
|
||||
): void {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) return
|
||||
socket.send(JSON.stringify({ type: 'book:cursor', journeyId: String(journeyId), spreadIndex, x, y }))
|
||||
}
|
||||
|
||||
export function addListener(fn: WebSocketListener): void {
|
||||
listeners.add(fn)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { TrekWsEventName } from '@trek/shared'
|
||||
|
||||
/**
|
||||
* Client-side handling policy for every event in the shared WS registry
|
||||
* (`TREK_WS_EVENTS` in @trek/shared). Together with the tripStore lookups
|
||||
* (DEXIE_WRITERS / STATE_APPLIERS in store/slices/remoteEventHandler.ts),
|
||||
* these lists partition the registry exactly — the registry-parity test
|
||||
* fails if a registry event is missing from all of them, or listed twice.
|
||||
* A new server event therefore forces an explicit client decision (handle
|
||||
* it, or add it here) instead of being dropped by a silent `default:`.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Events consumed by dedicated listeners outside the tripStore reducer.
|
||||
* Every entry names real handling code — if that code is removed, remove
|
||||
* the entry (the event then needs a new home or an IGNORED_WS_EVENTS slot).
|
||||
*/
|
||||
export const HANDLED_OUTSIDE_TRIP_STORE = [
|
||||
// Collab — Collab/MCollab components + useTripWebSocket's collabFileSync
|
||||
'collab:note:created',
|
||||
'collab:note:updated',
|
||||
'collab:note:deleted',
|
||||
'collab:poll:created',
|
||||
'collab:poll:voted',
|
||||
'collab:poll:closed',
|
||||
'collab:poll:deleted',
|
||||
'collab:message:created',
|
||||
'collab:message:reacted',
|
||||
'collab:message:deleted',
|
||||
// In-app notifications — hooks/useInAppNotificationListener
|
||||
'notification:new',
|
||||
'notification:updated',
|
||||
// Collections — pages/collections/useCollections ('collections:' prefix listener)
|
||||
'collections:updated',
|
||||
'collections:accepted',
|
||||
'collections:declined',
|
||||
'collections:left',
|
||||
'collections:deleted',
|
||||
'collections:cancelled',
|
||||
'collections:removed',
|
||||
'collections:invite',
|
||||
// Vacay — pages/vacay/useVacay
|
||||
'vacay:update',
|
||||
'vacay:settings',
|
||||
'vacay:accepted',
|
||||
'vacay:declined',
|
||||
'vacay:cancelled',
|
||||
'vacay:dissolved',
|
||||
'vacay:invite',
|
||||
'vacay:share',
|
||||
'vacay:share-removed',
|
||||
'vacay:shared-update',
|
||||
// Journey — pages/journeyDetail/useJourneyDetail ('journey:' prefix listener)
|
||||
'journey:trip:synced',
|
||||
'journey:entry:created',
|
||||
'journey:entry:updated',
|
||||
'journey:entry:deleted',
|
||||
'journey:entries:reordered',
|
||||
'journey:contributor:changed',
|
||||
// Studio book — components/Studio/useBookStore (its own listener: a client
|
||||
// with nothing outstanding takes the new version, one with unsaved edits
|
||||
// deliberately does not and conflicts on its next save instead)
|
||||
'journey:book:saved',
|
||||
// Studio presence — components/Studio/useBookPresence (its own listener:
|
||||
// who has the book open, and where their pointers are)
|
||||
'journey:book:peers',
|
||||
'journey:book:cursor',
|
||||
// Booking import — BackgroundTasks/BackgroundTasksWidget ('import:' prefix listener)
|
||||
'import:progress',
|
||||
'import:done',
|
||||
'import:error',
|
||||
] as const satisfies readonly TrekWsEventName[]
|
||||
|
||||
/**
|
||||
* Events the client deliberately does not act on today (state of the world
|
||||
* when the registry landed — every one of these was already dropped by the
|
||||
* old silent `default:` branches). Removing an entry means the event is now
|
||||
* handled somewhere; ADDING an entry is a product decision that a new server
|
||||
* event should have no client reaction — never add one just to silence the
|
||||
* registry-parity test.
|
||||
*/
|
||||
export const IGNORED_WS_EVENTS = [
|
||||
'assignment:participants',
|
||||
'packing:reordered',
|
||||
'packing:bag-created',
|
||||
'packing:bag-updated',
|
||||
'packing:bag-deleted',
|
||||
'packing:bag-members-updated',
|
||||
'packing:assignees',
|
||||
'packing:template-applied',
|
||||
'todo:assignees',
|
||||
'budget:settlement-created',
|
||||
'budget:settlement-updated',
|
||||
'budget:settlement-deleted',
|
||||
'reservation:positions',
|
||||
// Accommodations live in page-local planner state; the client refetches
|
||||
// them off trip:updated date changes, never off these events.
|
||||
'accommodation:created',
|
||||
'accommodation:updated',
|
||||
'accommodation:deleted',
|
||||
'trip:deleted',
|
||||
'member:added',
|
||||
'member:removed',
|
||||
] as const satisfies readonly TrekWsEventName[]
|
||||
@@ -1,7 +1,7 @@
|
||||
// FE-ADMIN-ADDON-001 to FE-ADMIN-ADDON-011
|
||||
// FE-ADMIN-ADDON-001 to FE-ADMIN-ADDON-025
|
||||
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { delay, http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
@@ -21,6 +21,45 @@ function buildAddon(overrides = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function addonsRoute(addons: ReturnType<typeof buildAddon>[]) {
|
||||
return http.get('/api/admin/addons', () => HttpResponse.json({ addons }));
|
||||
}
|
||||
|
||||
function llmAddon(config: Record<string, unknown> = {}) {
|
||||
return buildAddon({
|
||||
id: 'llm_parsing',
|
||||
name: 'AI Parsing',
|
||||
description: 'Extract bookings from files',
|
||||
icon: 'Sparkles',
|
||||
type: 'integration',
|
||||
enabled: true,
|
||||
config,
|
||||
});
|
||||
}
|
||||
|
||||
function modelsRoute(names: string[], seen?: (string | null)[]) {
|
||||
return http.get('/api/admin/llm/local/models', ({ request }) => {
|
||||
seen?.push(new URL(request.url).searchParams.get('baseUrl'));
|
||||
return HttpResponse.json({ models: names.map(name => ({ name, size: 1 })) });
|
||||
});
|
||||
}
|
||||
|
||||
/** The pill toggle of a top-level addon row. */
|
||||
function addonToggle(name: string): HTMLElement {
|
||||
const row = screen.getByText(name).closest('.px-6.py-4') as HTMLElement;
|
||||
return within(row).getByRole('button');
|
||||
}
|
||||
|
||||
/** The pill toggle of an indented sub-row (bag tracking, collab feature, photo provider). */
|
||||
function subToggle(label: string): HTMLElement {
|
||||
const row = screen.getByText(label).closest('.flex.items-center.gap-4') as HTMLElement;
|
||||
return within(row).getByRole('button');
|
||||
}
|
||||
|
||||
function isOn(toggle: HTMLElement): boolean {
|
||||
return toggle.style.background === 'var(--text-primary)';
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
@@ -59,7 +98,7 @@ describe('AddonManager', () => {
|
||||
|
||||
it('FE-ADMIN-ADDON-002: empty state when addons list is empty', async () => {
|
||||
render(<AddonManager />);
|
||||
await screen.findByText('No addons available');
|
||||
expect(await screen.findByText('No addons available')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-003: trip addons section renders with correct section header', async () => {
|
||||
@@ -229,4 +268,360 @@ describe('AddonManager', () => {
|
||||
expect(() => render(<AddonManager />)).not.toThrow();
|
||||
await screen.findByText('Mystery Addon');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-012: a failing load toasts the addon error and shows the empty state', async () => {
|
||||
server.use(http.get('/api/admin/addons', () => HttpResponse.error()));
|
||||
render(<><ToastContainer /><AddonManager /></>);
|
||||
|
||||
await screen.findByText('Failed to update addon');
|
||||
expect(screen.getByText('No addons available')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-013: dark mode swaps the wordmark in the header', async () => {
|
||||
seedStore(useSettingsStore, { settings: { dark_mode: 'dark' } });
|
||||
render(<AddonManager />);
|
||||
|
||||
await screen.findByText('No addons available');
|
||||
expect(screen.getByAltText('TREK')).toHaveAttribute('src', '/text-light.svg');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-014: photo-flavoured trip addons are hidden from the trip section', async () => {
|
||||
server.use(addonsRoute([
|
||||
buildAddon({ id: 'photos', name: 'Memories', icon: 'Image' }),
|
||||
buildAddon({ id: 'gallery', name: 'Trip Photos', icon: 'Puzzle', description: 'Share your photo stream' }),
|
||||
buildAddon({ id: 'todo', name: 'Todo List' }),
|
||||
]));
|
||||
render(<AddonManager />);
|
||||
|
||||
await screen.findByText('Todo List');
|
||||
expect(screen.queryByText('Memories')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Trip Photos')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-015: provider sub-rows carry their vendor icons and toggle state', async () => {
|
||||
server.use(addonsRoute([
|
||||
buildAddon({ id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: true }),
|
||||
buildAddon({ id: 'immich', name: 'Immich', description: 'Self-hosted photos', type: 'photo_provider', enabled: true }),
|
||||
buildAddon({ id: 'synologyphotos', name: 'Synology Photos', description: 'NAS photos', type: 'photo_provider', enabled: false }),
|
||||
buildAddon({ id: 'unsplash', name: 'Unsplash', description: 'Stock photos', type: 'photo_provider', enabled: false }),
|
||||
]));
|
||||
render(<AddonManager />);
|
||||
|
||||
await screen.findByText('Immich');
|
||||
// immich and synologyphotos ship a vendor glyph, unsplash does not
|
||||
const immichRow = screen.getByText('Immich').closest('.flex.items-center.gap-4') as HTMLElement;
|
||||
expect(immichRow.querySelector('svg')).toBeInTheDocument();
|
||||
const synologyRow = screen.getByText('Synology Photos').closest('.flex.items-center.gap-4') as HTMLElement;
|
||||
expect(synologyRow.querySelector('svg')).toBeInTheDocument();
|
||||
const unsplashRow = screen.getByText('Unsplash').closest('.flex.items-center.gap-4') as HTMLElement;
|
||||
expect(unsplashRow.querySelector('svg')).not.toBeInTheDocument();
|
||||
|
||||
expect(isOn(subToggle('Immich'))).toBe(true);
|
||||
expect(isOn(subToggle('Unsplash'))).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-016: toggling a photo provider persists it and refreshes the global addons', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: unknown = null;
|
||||
server.use(
|
||||
addonsRoute([
|
||||
buildAddon({ id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: true }),
|
||||
buildAddon({ id: 'immich', name: 'Immich', description: 'Self-hosted photos', type: 'photo_provider', enabled: false }),
|
||||
]),
|
||||
http.put('/api/admin/addons/immich', async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><AddonManager /></>);
|
||||
await screen.findByText('Immich');
|
||||
|
||||
await user.click(subToggle('Immich'));
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ enabled: true }));
|
||||
await screen.findByText('Addon updated');
|
||||
expect(isOn(subToggle('Immich'))).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-017: a failing photo-provider toggle rolls the sub-row back', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
addonsRoute([
|
||||
buildAddon({ id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: true }),
|
||||
buildAddon({ id: 'unsplash', name: 'Unsplash', description: 'Stock photos', type: 'photo_provider', enabled: true }),
|
||||
]),
|
||||
http.put('/api/admin/addons/unsplash', () => HttpResponse.error()),
|
||||
);
|
||||
render(<><ToastContainer /><AddonManager /></>);
|
||||
await screen.findByText('Unsplash');
|
||||
|
||||
await user.click(subToggle('Unsplash'));
|
||||
|
||||
await screen.findByText('Failed to update addon');
|
||||
await waitFor(() => expect(isOn(subToggle('Unsplash'))).toBe(true));
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-018: the collab sub-features render their state and report the toggled key', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onToggleCollabFeature = vi.fn();
|
||||
server.use(addonsRoute([buildAddon({ id: 'collab', name: 'Collab', enabled: true })]));
|
||||
render(
|
||||
<AddonManager
|
||||
collabFeatures={{ chat: true, notes: false, polls: false, whatsnext: true }}
|
||||
onToggleCollabFeature={onToggleCollabFeature}
|
||||
/>,
|
||||
);
|
||||
|
||||
await screen.findByText('Chat');
|
||||
expect(screen.getByText('Notes')).toBeInTheDocument();
|
||||
expect(screen.getByText('Polls')).toBeInTheDocument();
|
||||
expect(screen.getByText("What's Next")).toBeInTheDocument();
|
||||
expect(isOn(subToggle('Chat'))).toBe(true);
|
||||
expect(isOn(subToggle('Notes'))).toBe(false);
|
||||
|
||||
await user.click(subToggle('Polls'));
|
||||
expect(onToggleCollabFeature).toHaveBeenCalledWith('polls');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-019: collab sub-features stay hidden without the handler props', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'collab', name: 'Collab', enabled: true })]));
|
||||
render(<AddonManager />);
|
||||
|
||||
await screen.findByText('Collab');
|
||||
expect(screen.queryByText('Polls')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-020: a disabled AI-parsing addon renders the row without its config block', async () => {
|
||||
server.use(addonsRoute([{ ...llmAddon({ provider: 'local' }), enabled: false }]));
|
||||
render(<AddonManager />);
|
||||
|
||||
await screen.findByText('AI Parsing');
|
||||
expect(screen.getByText('Extract bookings from files')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Connection')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-021: the local provider lists installed models and a chip fills the model field', async () => {
|
||||
const user = userEvent.setup();
|
||||
const urls: (string | null)[] = [];
|
||||
server.use(addonsRoute([llmAddon({ provider: 'local' })]), modelsRoute(['qwen3:8b', 'llama3:8b'], urls));
|
||||
render(<AddonManager />);
|
||||
|
||||
await screen.findByText('Installed on the server');
|
||||
await screen.findByRole('button', { name: 'llama3:8b' });
|
||||
expect(urls[0]).toBe('http://localhost:11434/v1');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'llama3:8b' }));
|
||||
expect(screen.getByPlaceholderText('select or pull below')).toHaveValue('llama3:8b');
|
||||
|
||||
// qwen3:8b is already installed, so the recommended row offers "Use" instead of "Pull"
|
||||
await user.click(screen.getByRole('button', { name: 'Use' }));
|
||||
expect(screen.getByPlaceholderText('select or pull below')).toHaveValue('qwen3:8b');
|
||||
expect(screen.getByRole('button', { name: 'Selected' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-022: an unreachable Ollama shows the error and Refresh retries', async () => {
|
||||
const user = userEvent.setup();
|
||||
let calls = 0;
|
||||
server.use(
|
||||
addonsRoute([llmAddon({ provider: 'local' })]),
|
||||
http.get('/api/admin/llm/local/models', () => {
|
||||
calls += 1;
|
||||
return calls === 1
|
||||
? HttpResponse.json({ error: 'down' }, { status: 500 })
|
||||
: HttpResponse.json({ models: [] });
|
||||
}),
|
||||
);
|
||||
render(<AddonManager />);
|
||||
|
||||
await screen.findByText(/Request failed with status code 500/);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Refresh' }));
|
||||
await screen.findByText('No models installed yet — pull one below.');
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-023: switching providers swaps the base URL field, the model hint and the Ollama block', async () => {
|
||||
const user = userEvent.setup();
|
||||
const urls: (string | null)[] = [];
|
||||
server.use(addonsRoute([llmAddon({ provider: 'local', apiKey: '••••••••' })]), modelsRoute([], urls));
|
||||
render(<AddonManager />);
|
||||
|
||||
await screen.findByText('Installed on the server');
|
||||
expect(screen.getByPlaceholderText('••••••••')).toBeInTheDocument();
|
||||
|
||||
// A hand-typed base URL is used for the next lookup on blur
|
||||
await user.type(screen.getByPlaceholderText('http://localhost:11434/v1'), 'http://ollama.lan:11434/v1');
|
||||
await user.tab();
|
||||
await waitFor(() => expect(urls).toContain('http://ollama.lan:11434/v1'));
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Local · OpenAI-compatible/ }));
|
||||
await user.click(screen.getByRole('button', { name: 'OpenAI' }));
|
||||
expect(screen.getByPlaceholderText('https://api.openai.com/v1')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('gpt-4o')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Installed on the server')).not.toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'OpenAI' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Anthropic' }));
|
||||
expect(screen.queryByPlaceholderText('https://api.openai.com/v1')).not.toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('claude-opus-4-8')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Anthropic reads PDFs/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-024: pulling a model streams progress and then selects it', async () => {
|
||||
const user = userEvent.setup();
|
||||
let pulled: unknown = null;
|
||||
let modelCalls = 0;
|
||||
server.use(
|
||||
addonsRoute([llmAddon({ provider: 'local' })]),
|
||||
http.get('/api/admin/llm/local/models', () => {
|
||||
modelCalls += 1;
|
||||
return HttpResponse.json({ models: modelCalls === 1 ? [] : [{ name: 'qwen3:8b', size: 1 }] });
|
||||
}),
|
||||
http.post('/api/admin/llm/local/pull', async ({ request }) => {
|
||||
pulled = await request.json();
|
||||
await delay(150);
|
||||
return new HttpResponse(
|
||||
'{"status":"pulling manifest"}\n{"status":"downloading","total":100,"completed":40}\nnot-json\n',
|
||||
{ headers: { 'Content-Type': 'application/x-ndjson' } },
|
||||
);
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><AddonManager /></>);
|
||||
|
||||
await screen.findByText('No models installed yet — pull one below.');
|
||||
await user.click(screen.getByRole('button', { name: 'Pull' }));
|
||||
|
||||
await screen.findByText('Pulling…');
|
||||
expect(screen.getByText('starting…')).toBeInTheDocument();
|
||||
|
||||
await screen.findByText('Model pulled');
|
||||
expect(pulled).toEqual({ baseUrl: 'http://localhost:11434/v1', model: 'qwen3:8b' });
|
||||
expect(screen.getByPlaceholderText('select or pull below')).toHaveValue('qwen3:8b');
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Selected' })).toBeDisabled());
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-025: a failing pull surfaces the server error and saving reports both outcomes', async () => {
|
||||
const user = userEvent.setup();
|
||||
const bodies: unknown[] = [];
|
||||
server.use(
|
||||
addonsRoute([llmAddon({ provider: 'local', model: 'qwen3:8b', baseUrl: '', apiKey: '••••••••', multimodal: true })]),
|
||||
modelsRoute([]),
|
||||
http.post('/api/admin/llm/local/pull', () => HttpResponse.json({ error: 'no disk space' }, { status: 500 })),
|
||||
http.put('/api/admin/addons/llm_parsing', async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
return bodies.length === 1 ? HttpResponse.json({ success: true }) : HttpResponse.error();
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><AddonManager /></>);
|
||||
|
||||
await screen.findByText('No models installed yet — pull one below.');
|
||||
await user.click(screen.getByRole('button', { name: 'Pull' }));
|
||||
await screen.findByText('no disk space');
|
||||
expect(screen.getByRole('button', { name: 'Pull' })).toBeEnabled();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await screen.findByText('Saved');
|
||||
expect(bodies[0]).toEqual({
|
||||
config: { provider: 'local', model: 'qwen3:8b', baseUrl: '', apiKey: '••••••••', multimodal: true },
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await screen.findByText('Failed to save');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-026: model and API key are editable and their hints follow the provider', async () => {
|
||||
const user = userEvent.setup();
|
||||
const bodies: unknown[] = [];
|
||||
server.use(
|
||||
addonsRoute([llmAddon({ provider: 'local' })]),
|
||||
modelsRoute([]),
|
||||
http.put('/api/admin/addons/llm_parsing', async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><AddonManager /></>);
|
||||
|
||||
await screen.findByText('Installed on the server');
|
||||
expect(screen.getByPlaceholderText('(often not required)')).toBeInTheDocument();
|
||||
|
||||
await user.type(screen.getByPlaceholderText('select or pull below'), ' mistral:7b ');
|
||||
await user.type(screen.getByPlaceholderText('(often not required)'), 'sk-live');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Local · OpenAI-compatible/ }));
|
||||
await user.click(screen.getByRole('button', { name: 'OpenAI' }));
|
||||
expect(screen.getByPlaceholderText('sk-…')).toHaveValue('sk-live');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await screen.findByText('Saved');
|
||||
// The model is trimmed before it is stored, the key is sent verbatim
|
||||
expect(bodies[0]).toEqual({
|
||||
config: { provider: 'openai', model: 'mistral:7b', baseUrl: '', apiKey: 'sk-live', multimodal: false },
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-029: switching to Anthropic clears a stale base URL before saving', async () => {
|
||||
const user = userEvent.setup();
|
||||
const bodies: unknown[] = [];
|
||||
server.use(
|
||||
addonsRoute([llmAddon({ provider: 'local', model: '', baseUrl: 'http://ollama.lan:11434/v1', apiKey: '', multimodal: false })]),
|
||||
modelsRoute([]),
|
||||
http.put('/api/admin/addons/llm_parsing', async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><AddonManager /></>);
|
||||
|
||||
await screen.findByText('Installed on the server');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Local · OpenAI-compatible/ }));
|
||||
await user.click(screen.getByRole('button', { name: 'Anthropic' }));
|
||||
await user.type(screen.getByPlaceholderText('claude-opus-4-8'), 'claude-haiku-4-5-20251001');
|
||||
await user.type(screen.getByPlaceholderText('sk-…'), 'sk-ant-live');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await screen.findByText('Saved');
|
||||
// The stale local base URL must not ride along to Anthropic — it would hijack the endpoint.
|
||||
expect(bodies[0]).toEqual({
|
||||
config: { provider: 'anthropic', model: 'claude-haiku-4-5-20251001', baseUrl: '', apiKey: 'sk-ant-live', multimodal: false },
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-027: an error frame in the pull stream aborts the pull and is reported', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
addonsRoute([llmAddon({ provider: 'local' })]),
|
||||
modelsRoute([]),
|
||||
http.post('/api/admin/llm/local/pull', () => new HttpResponse(
|
||||
'{"status":"pulling manifest"}\n{"error":"manifest not found"}\n',
|
||||
{ headers: { 'Content-Type': 'application/x-ndjson' } },
|
||||
)),
|
||||
);
|
||||
render(<><ToastContainer /><AddonManager /></>);
|
||||
|
||||
await screen.findByText('No models installed yet — pull one below.');
|
||||
await user.click(screen.getByRole('button', { name: 'Pull' }));
|
||||
|
||||
await screen.findByText('manifest not found');
|
||||
expect(screen.queryByText('Model pulled')).not.toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Pull' })).toBeEnabled());
|
||||
expect(screen.queryByText('Pulling…')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-028: blurring the base URL under a cloud provider queries no local models', async () => {
|
||||
const user = userEvent.setup();
|
||||
const urls: (string | null)[] = [];
|
||||
server.use(addonsRoute([llmAddon({ provider: 'openai' })]), modelsRoute([], urls));
|
||||
render(<AddonManager />);
|
||||
|
||||
await screen.findByText('Connection');
|
||||
expect(screen.queryByText('Installed on the server')).not.toBeInTheDocument();
|
||||
|
||||
await user.type(screen.getByPlaceholderText('https://api.openai.com/v1'), 'https://proxy.local/v1');
|
||||
await user.tab();
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('https://proxy.local/v1')).toBeInTheDocument());
|
||||
expect(urls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useState, type ComponentType } from 'react'
|
||||
import { adminApi } from '../../api/client'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
@@ -27,7 +27,7 @@ function SynologyIcon({ size = 14 }: { size?: number }) {
|
||||
)
|
||||
}
|
||||
|
||||
const PROVIDER_ICONS: Record<string, React.FC<{ size?: number }>> = {
|
||||
const PROVIDER_ICONS: Record<string, ComponentType<{ size?: number }>> = {
|
||||
immich: ImmichIcon,
|
||||
synologyphotos: SynologyIcon,
|
||||
}
|
||||
@@ -196,7 +196,7 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
<span className={`hidden sm:inline text-xs font-medium ${bagTrackingEnabled ? 'text-content' : 'text-content-faint'}`}>
|
||||
{bagTrackingEnabled ? t('admin.addons.enabled') : t('admin.addons.disabled')}
|
||||
</span>
|
||||
<button onClick={onToggleBagTracking}
|
||||
<button type="button" onClick={onToggleBagTracking}
|
||||
className="relative inline-flex h-6 w-11 items-center rounded-full transition-colors"
|
||||
style={{ background: bagTrackingEnabled ? 'var(--text-primary)' : 'var(--border-primary)' }}>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
@@ -222,7 +222,7 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
<span className={`hidden sm:inline text-xs font-medium ${enabled ? 'text-content' : 'text-content-faint'}`}>
|
||||
{enabled ? t('admin.addons.enabled') : t('admin.addons.disabled')}
|
||||
</span>
|
||||
<button onClick={() => onToggleCollabFeature(feat.key)}
|
||||
<button type="button" onClick={() => onToggleCollabFeature(feat.key)}
|
||||
className="relative inline-flex h-6 w-11 items-center rounded-full transition-colors"
|
||||
style={{ background: enabled ? 'var(--text-primary)' : 'var(--border-primary)' }}>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
@@ -269,7 +269,7 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
<span className={`hidden sm:inline text-xs font-medium ${provider.enabled ? 'text-content' : 'text-content-faint'}`}>
|
||||
{provider.enabled ? t('admin.addons.enabled') : t('admin.addons.disabled')}
|
||||
</span>
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={provider.toggle}
|
||||
className="relative inline-flex h-6 w-11 items-center rounded-full transition-colors"
|
||||
style={{ background: provider.enabled ? 'var(--text-primary)' : 'var(--border-primary)' }}
|
||||
@@ -399,7 +399,7 @@ function LlmParsingConfig({ addon }: { addon: Addon }) {
|
||||
setSaving(true)
|
||||
try {
|
||||
// Send the masked sentinel unchanged so the server keeps the stored key.
|
||||
await adminApi.updateAddon(addon.id, { config: { provider, model: model.trim(), baseUrl: baseUrl.trim(), apiKey, multimodal: cfg.multimodal === true } })
|
||||
await adminApi.updateAddon(addon.id, { config: { provider, model: model.trim(), baseUrl: provider === 'anthropic' ? '' : baseUrl.trim(), apiKey, multimodal: cfg.multimodal === true } })
|
||||
toast.success('Saved')
|
||||
} catch {
|
||||
toast.error('Failed to save')
|
||||
@@ -451,6 +451,7 @@ function LlmParsingConfig({ addon }: { addon: Addon }) {
|
||||
<section className="space-y-3">
|
||||
<div className={sectionCls}>Model</div>
|
||||
<label className="block">
|
||||
<span className="sr-only">Model</span>
|
||||
<input autoComplete="off" className={fieldCls} value={model} onChange={e => setModel(e.target.value)} placeholder={provider === 'anthropic' ? 'claude-opus-4-8' : provider === 'openai' ? 'gpt-4o' : 'select or pull below'} />
|
||||
</label>
|
||||
|
||||
@@ -459,7 +460,7 @@ function LlmParsingConfig({ addon }: { addon: Addon }) {
|
||||
<div className="space-y-3 rounded-lg border border-edge-secondary bg-surface p-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-medium text-content-secondary">Installed on the server</span>
|
||||
<button onClick={loadModels} disabled={loadingModels} className="text-xs text-content-muted underline disabled:opacity-60">
|
||||
<button type="button" onClick={loadModels} disabled={loadingModels} className="text-xs text-content-muted underline disabled:opacity-60">
|
||||
{loadingModels ? 'Loading…' : 'Refresh'}
|
||||
</button>
|
||||
</div>
|
||||
@@ -470,7 +471,7 @@ function LlmParsingConfig({ addon }: { addon: Addon }) {
|
||||
{installed.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{installed.map(name => (
|
||||
<button
|
||||
<button type="button"
|
||||
key={name}
|
||||
title={name}
|
||||
onClick={() => setModel(name)}
|
||||
@@ -509,11 +510,11 @@ function LlmParsingConfig({ addon }: { addon: Addon }) {
|
||||
)}
|
||||
</div>
|
||||
{installedHere ? (
|
||||
<button onClick={() => setModel(m.id)} disabled={active} className={`shrink-0 rounded-md px-3 py-1.5 text-xs font-medium transition-colors ${active ? 'bg-surface-tertiary text-content-muted' : 'border border-edge-secondary text-content-secondary hover:border-edge'}`}>
|
||||
<button type="button" onClick={() => setModel(m.id)} disabled={active} className={`shrink-0 rounded-md px-3 py-1.5 text-xs font-medium transition-colors ${active ? 'bg-surface-tertiary text-content-muted' : 'border border-edge-secondary text-content-secondary hover:border-edge'}`}>
|
||||
{active ? 'Selected' : 'Use'}
|
||||
</button>
|
||||
) : (
|
||||
<button onClick={() => pull(m.id)} disabled={!!pulling} className="shrink-0 rounded-md bg-accent px-3 py-1.5 text-xs font-medium text-accent-text disabled:opacity-60">
|
||||
<button type="button" onClick={() => pull(m.id)} disabled={!!pulling} className="shrink-0 rounded-md bg-accent px-3 py-1.5 text-xs font-medium text-accent-text disabled:opacity-60">
|
||||
{isPulling ? 'Pulling…' : 'Pull'}
|
||||
</button>
|
||||
)}
|
||||
@@ -526,7 +527,7 @@ function LlmParsingConfig({ addon }: { addon: Addon }) {
|
||||
)}
|
||||
</section>
|
||||
|
||||
<button onClick={save} disabled={saving} className="rounded-lg bg-accent px-4 py-2 text-sm font-medium text-accent-text transition-opacity disabled:opacity-60">
|
||||
<button type="button" onClick={save} disabled={saving} className="rounded-lg bg-accent px-4 py-2 text-sm font-medium text-accent-text transition-opacity disabled:opacity-60">
|
||||
{saving ? 'Saving…' : 'Save'}
|
||||
</button>
|
||||
</div>
|
||||
@@ -589,7 +590,7 @@ function AddonRow({ addon, onToggle, t, nameOverride, descriptionOverride, statu
|
||||
{isComingSoon ? t('admin.addons.disabled') : enabledState ? t('admin.addons.enabled') : t('admin.addons.disabled')}
|
||||
</span>
|
||||
{!hideToggle && (
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={() => !isComingSoon && onToggle(addon)}
|
||||
disabled={isComingSoon}
|
||||
className="relative inline-flex h-6 w-11 items-center rounded-full transition-colors"
|
||||
|
||||
@@ -49,7 +49,7 @@ describe('AdminMcpTokensPanel', () => {
|
||||
|
||||
it('FE-ADMIN-MCP-002: empty state rendered when no tokens', async () => {
|
||||
render(<AdminMcpTokensPanel />);
|
||||
await screen.findByText('No MCP tokens have been created yet');
|
||||
expect(await screen.findByText('No MCP tokens have been created yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-MCP-003: token list renders correctly', async () => {
|
||||
@@ -195,7 +195,7 @@ describe('AdminMcpTokensPanel', () => {
|
||||
)
|
||||
);
|
||||
render(<><ToastContainer /><AdminMcpTokensPanel /></>);
|
||||
await screen.findByText('Failed to load tokens');
|
||||
expect(await screen.findByText('Failed to load tokens')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-MCP-011: OAuth sessions loading spinner shown on mount', async () => {
|
||||
@@ -216,7 +216,7 @@ describe('AdminMcpTokensPanel', () => {
|
||||
)
|
||||
);
|
||||
render(<AdminMcpTokensPanel />);
|
||||
await screen.findByText('No active OAuth sessions');
|
||||
expect(await screen.findByText('No active OAuth sessions')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-MCP-013: OAuth sessions list renders with scopes', async () => {
|
||||
@@ -318,6 +318,6 @@ describe('AdminMcpTokensPanel', () => {
|
||||
const deleteBtns = screen.getAllByRole('button', { name: 'Delete' });
|
||||
const confirmBtn = deleteBtns.find(b => !b.title);
|
||||
await user.click(confirmBtn ?? deleteBtns[deleteBtns.length - 1]);
|
||||
await screen.findByText('Failed to revoke session');
|
||||
expect(await screen.findByText('Failed to revoke session')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -126,13 +126,13 @@ export default function AdminMcpTokensPanel() {
|
||||
</span>
|
||||
))}
|
||||
{!expanded && hidden > 0 && (
|
||||
<button onClick={() => toggleScopes(session.id)}
|
||||
<button type="button" onClick={() => toggleScopes(session.id)}
|
||||
className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium transition-colors hover:opacity-80 bg-surface-secondary text-content-secondary border border-edge">
|
||||
+{hidden} more
|
||||
</button>
|
||||
)}
|
||||
{expanded && hidden > 0 && (
|
||||
<button onClick={() => toggleScopes(session.id)}
|
||||
<button type="button" onClick={() => toggleScopes(session.id)}
|
||||
className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium transition-colors hover:opacity-80 bg-surface-secondary text-content-secondary border border-edge">
|
||||
show less
|
||||
</button>
|
||||
@@ -146,7 +146,7 @@ export default function AdminMcpTokensPanel() {
|
||||
<span className="text-xs whitespace-nowrap text-right pt-0.5" style={{ color: 'var(--text-tertiary)' }}>
|
||||
{new Date(session.created_at).toLocaleDateString(locale)}
|
||||
</span>
|
||||
<button onClick={() => setRevokeConfirmId(session.id)}
|
||||
<button type="button" onClick={() => setRevokeConfirmId(session.id)}
|
||||
className="p-1.5 rounded-lg transition-colors hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/20"
|
||||
style={{ color: 'var(--text-tertiary)' }} title={t('common.delete')}>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
@@ -199,7 +199,7 @@ export default function AdminMcpTokensPanel() {
|
||||
<span className="text-xs whitespace-nowrap text-right" style={{ color: 'var(--text-tertiary)' }}>
|
||||
{token.last_used_at ? new Date(token.last_used_at).toLocaleDateString(locale) : t('admin.mcpTokens.never')}
|
||||
</span>
|
||||
<button onClick={() => setDeleteConfirmId(token.id)}
|
||||
<button type="button" onClick={() => setDeleteConfirmId(token.id)}
|
||||
className="p-1.5 rounded-lg transition-colors hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/20"
|
||||
style={{ color: 'var(--text-tertiary)' }} title={t('common.delete')}>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
@@ -214,16 +214,21 @@ export default function AdminMcpTokensPanel() {
|
||||
{/* Revoke OAuth session modal */}
|
||||
{revokeConfirmId !== null && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-[rgba(0,0,0,0.5)]"
|
||||
onClick={e => { if (e.target === e.currentTarget) setRevokeConfirmId(null) }}>
|
||||
role="button" tabIndex={0} aria-label={t('common.close')}
|
||||
onClick={e => { if (e.target === e.currentTarget) setRevokeConfirmId(null) }}
|
||||
onKeyDown={e => {
|
||||
if (e.target !== e.currentTarget) return
|
||||
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setRevokeConfirmId(null) }
|
||||
}}>
|
||||
<div className="rounded-xl shadow-xl w-full max-w-sm p-6 space-y-4 bg-surface-card">
|
||||
<h3 className="text-base font-semibold text-content">{t('admin.oauthSessions.revokeTitle')}</h3>
|
||||
<p className="text-sm text-content-secondary">{t('admin.oauthSessions.revokeMessage')}</p>
|
||||
<div className="flex gap-2 justify-end">
|
||||
<button onClick={() => setRevokeConfirmId(null)}
|
||||
<button type="button" onClick={() => setRevokeConfirmId(null)}
|
||||
className="px-4 py-2 rounded-lg text-sm border border-edge text-content-secondary">
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button onClick={() => handleRevoke(revokeConfirmId)}
|
||||
<button type="button" onClick={() => handleRevoke(revokeConfirmId)}
|
||||
className="px-4 py-2 rounded-lg text-sm font-medium text-white bg-red-600 hover:bg-red-700">
|
||||
{t('common.delete')}
|
||||
</button>
|
||||
@@ -235,16 +240,21 @@ export default function AdminMcpTokensPanel() {
|
||||
{/* Delete MCP token modal */}
|
||||
{deleteConfirmId !== null && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-[rgba(0,0,0,0.5)]"
|
||||
onClick={e => { if (e.target === e.currentTarget) setDeleteConfirmId(null) }}>
|
||||
role="button" tabIndex={0} aria-label={t('common.close')}
|
||||
onClick={e => { if (e.target === e.currentTarget) setDeleteConfirmId(null) }}
|
||||
onKeyDown={e => {
|
||||
if (e.target !== e.currentTarget) return
|
||||
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setDeleteConfirmId(null) }
|
||||
}}>
|
||||
<div className="rounded-xl shadow-xl w-full max-w-sm p-6 space-y-4 bg-surface-card">
|
||||
<h3 className="text-base font-semibold text-content">{t('admin.mcpTokens.deleteTitle')}</h3>
|
||||
<p className="text-sm text-content-secondary">{t('admin.mcpTokens.deleteMessage')}</p>
|
||||
<div className="flex gap-2 justify-end">
|
||||
<button onClick={() => setDeleteConfirmId(null)}
|
||||
<button type="button" onClick={() => setDeleteConfirmId(null)}
|
||||
className="px-4 py-2 rounded-lg text-sm border border-edge text-content-secondary">
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button onClick={() => handleDelete(deleteConfirmId)}
|
||||
<button type="button" onClick={() => handleDelete(deleteConfirmId)}
|
||||
className="px-4 py-2 rounded-lg text-sm font-medium text-white bg-red-600 hover:bg-red-700">
|
||||
{t('common.delete')}
|
||||
</button>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,11 +1,12 @@
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties, type DragEvent } from 'react'
|
||||
import { PLUGIN_PERMISSIONS } from '@trek/shared'
|
||||
import { createPortal } from 'react-dom'
|
||||
import {
|
||||
Blocks, AlertTriangle, PackageOpen, RefreshCw, Trash2, Download, Bug, X, ShieldCheck, UploadCloud,
|
||||
ArrowUpCircle, Github, ExternalLink, ChevronDown, Check, Lock, Search, Link2, KeyRound, ShieldAlert,
|
||||
SlidersHorizontal, ArrowUpDown, CircleDot, MoreHorizontal, RotateCw, ArrowRight, Database, Users, LayoutDashboard,
|
||||
Radio, Luggage, Globe, Image, CalendarDays, Bell,
|
||||
Wallet, Puzzle, MapPin, ListChecks, Pencil, Tag, FileText,
|
||||
Radio, Luggage, Globe, Image, CalendarDays, Bell, Info, History, PauseCircle,
|
||||
Wallet, Puzzle, MapPin, ListChecks, Pencil, Tag, FileText, Route, Navigation, Clock, LocateFixed, Palette,
|
||||
} from 'lucide-react'
|
||||
import PluginIcon from '../shared/PluginIcon'
|
||||
import { adminApi } from '../../api/client'
|
||||
@@ -62,6 +63,8 @@ interface PluginRow {
|
||||
keyFingerprint?: string | null
|
||||
/** Why an update was refused, if one was. `version` is the version that was refused. */
|
||||
updateBlock?: { code: string; detail: string | null; version: string | null } | null
|
||||
/** A deliberate non-latest install paused updates: out of the banner/Update all until resumed. */
|
||||
updateHold?: boolean
|
||||
}
|
||||
interface RegistryItem {
|
||||
id: string
|
||||
@@ -92,19 +95,35 @@ interface RegistryItem {
|
||||
/** The full key — public, and carried in full because re-trust compares it exactly. */
|
||||
authorPublicKey?: string | null
|
||||
}
|
||||
/** One published version, with its SERVER-computed compat verdict (the client has no semver). */
|
||||
interface VersionInfo {
|
||||
version: string
|
||||
publishedAt: string | null
|
||||
size: number | null
|
||||
signed: boolean
|
||||
/** The declared TREK requirement, or null when the entry carries no bounds at all. */
|
||||
trek: string | null
|
||||
compatible: boolean
|
||||
}
|
||||
interface RegistryDetail extends RegistryItem {
|
||||
size: number | null
|
||||
publishedAt: string | null
|
||||
/** Every published version, newest first — the version picker's data. */
|
||||
versions?: VersionInfo[]
|
||||
manifest: {
|
||||
permissions: string[]
|
||||
egress: string[]
|
||||
// Optional because a registry may omit an empty list — the detail view has to
|
||||
// degrade rather than throw halfway through its render.
|
||||
permissions?: string[]
|
||||
egress?: string[]
|
||||
/** The plugin needs OPERATOR-supplied hosts — its egress list is not the whole story. */
|
||||
operatorEgress?: boolean
|
||||
settings: Array<{ key: string; label: string; inputType: string; scope: string; required: boolean }>
|
||||
settings?: Array<{ key: string; label: string; inputType: string; scope: string; required: boolean }>
|
||||
license: string | null
|
||||
icon: string | null
|
||||
requiredAddons?: string[]
|
||||
pluginDependencies?: PluginDep[]
|
||||
/** Display slice of the manifest's capabilities — drives the same chips as an installed row. */
|
||||
capabilities?: { widget?: { slot?: string }; tripPage?: { replaces?: string[] } }
|
||||
} | null
|
||||
}
|
||||
|
||||
@@ -175,26 +194,14 @@ const HEALTH: Record<string, string> = {
|
||||
}
|
||||
|
||||
// Known permissions → human-readable i18n key; unknown ones render as raw code.
|
||||
const PERM_KEYS = [
|
||||
'db:own', 'db:read:trips', 'db:read:users', 'db:read:costs', 'db:read:packing', 'db:read:files', 'db:read:files:content',
|
||||
'db:read:collab', 'db:read:journal', 'db:read:atlas', 'db:read:vacay', 'db:read:daynotes', 'db:read:collections',
|
||||
'db:read:categories', 'db:read:tags', 'db:read:todos', 'weather:read', 'rates:read', 'db:write:costs',
|
||||
'db:write:places', 'db:write:days', 'db:write:itinerary', 'db:write:trips', 'db:write:reservations', 'db:write:accommodations', 'db:write:daynotes', 'db:write:packing',
|
||||
'db:write:tags', 'db:write:todos', 'db:write:atlas', 'db:write:vacay', 'db:write:journal', 'db:write:collections',
|
||||
'db:write:files', 'db:write:collab', 'db:write:members',
|
||||
'db:create:trips',
|
||||
'db:meta',
|
||||
'notify:send', 'ai:invoke', 'oauth:client',
|
||||
'events:subscribe', 'jobs:run',
|
||||
'ws:broadcast:trip', 'ws:broadcast:user',
|
||||
'hook:photo-provider', 'hook:calendar-source', 'hook:place-detail-provider', 'hook:trip-warning-provider', 'hook:table-contributor', 'hook:map-marker-provider',
|
||||
'hook:pdf-section-provider', 'hook:atlas-layer-provider', 'hook:journal-entry-provider', 'hook:trip-card-provider', 'hook:notification-channel', 'hook:user-data', 'http:outbound',
|
||||
]
|
||||
// Generated from the host's protocol/envelope.ts by
|
||||
// server/scripts/gen-plugin-facts.ts - this used to be a hand-kept fourth copy.
|
||||
const PERM_KEYS = PLUGIN_PERMISSIONS
|
||||
|
||||
const KNOWN_TYPES = ['widget', 'page', 'integration', 'trip-page']
|
||||
|
||||
function isNewer(a: string, b: string): boolean {
|
||||
const nums = (v: string) => v.split('-')[0].split('.').map(n => parseInt(n, 10) || 0)
|
||||
const nums = (v: string) => v.split('-')[0].split('.').map(n => Number.parseInt(n, 10) || 0)
|
||||
const pa = nums(a), pb = nums(b)
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const x = pa[i] || 0, y = pb[i] || 0
|
||||
@@ -239,6 +246,11 @@ function deriveCaps(perms: string[], caps: { widget?: { slot?: string }; tripPag
|
||||
if (perms.includes('hook:calendar-source')) out.push({ icon: CalendarDays, label: t('admin.plugins.cap.calendar') })
|
||||
if (perms.includes('hook:place-detail-provider')) out.push({ icon: MapPin, label: t('admin.plugins.cap.placeDetails') })
|
||||
if (perms.includes('hook:trip-warning-provider')) out.push({ icon: AlertTriangle, label: t('admin.plugins.cap.warnings') })
|
||||
if (perms.includes('hook:map-layer-provider')) out.push({ icon: Route, label: t('admin.plugins.cap.mapLayers') })
|
||||
if (perms.includes('hook:route-provider')) out.push({ icon: Navigation, label: t('admin.plugins.cap.routing') })
|
||||
if (perms.includes('hook:day-schedule-provider')) out.push({ icon: Clock, label: t('admin.plugins.cap.daySchedule') })
|
||||
if (perms.includes('hook:day-tint-provider')) out.push({ icon: Palette, label: t('admin.plugins.cap.dayTint') })
|
||||
if (perms.includes('geolocation:read')) out.push({ icon: LocateFixed, label: t('admin.plugins.cap.geolocation') })
|
||||
if (perms.includes('hook:notification-channel')) out.push({ icon: Bell, label: t('admin.plugins.cap.notificationChannel') })
|
||||
if (perms.includes('events:subscribe')) out.push({ icon: Radio, label: t('admin.plugins.cap.events') })
|
||||
for (const h of perms.filter(p => p.startsWith('http:outbound:')).map(p => p.slice('http:outbound:'.length)).filter(Boolean)) {
|
||||
@@ -295,13 +307,8 @@ function installOffer(item: RegistryItem, t: T): { blocked: boolean; version?: s
|
||||
return { blocked: true, label: t('admin.plugins.incompatible'), title }
|
||||
}
|
||||
|
||||
function ReviewedBadge({ t, compact }: { t: T; compact?: boolean }) {
|
||||
if (compact) return <ShieldCheck size={13} className="text-success shrink-0" aria-label={t('admin.plugins.reviewed')} />
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-semibold bg-success-soft text-success">
|
||||
<ShieldCheck size={11} /> {t('admin.plugins.reviewed')}
|
||||
</span>
|
||||
)
|
||||
function ReviewedBadge({ t }: { t: T }) {
|
||||
return <ShieldCheck size={13} className="text-success shrink-0" aria-label={t('admin.plugins.reviewed')} />
|
||||
}
|
||||
|
||||
/** Marks a manually-uploaded (sideloaded) plugin: no registry, unsigned, not reviewed. */
|
||||
@@ -399,6 +406,12 @@ export default function AdminPluginsPanel() {
|
||||
const [egressSaving, setEgressSaving] = useState(false)
|
||||
const [egressError, setEgressError] = useState('')
|
||||
const [confirmUninstall, setConfirmUninstall] = useState<PluginRow | null>(null)
|
||||
// The version picker for an INSTALLED plugin ("Change version…"); versions land async
|
||||
// from the registry detail endpoint, which computes each version's compat verdict.
|
||||
const [versionPicker, setVersionPicker] = useState<{ plugin: PluginRow; versions: VersionInfo[] | null; failed: boolean } | null>(null)
|
||||
// A picked version OLDER than the installed one — held here until the admin consents
|
||||
// to the data risk (the plugin's data dir stays; older code may not understand it).
|
||||
const [confirmDowngrade, setConfirmDowngrade] = useState<{ plugin: PluginRow; version: string } | null>(null)
|
||||
// A QUEUE, not one slot: "Update All" can produce several re-consent prompts —
|
||||
// each must be shown, not silently overwritten by the last one.
|
||||
const [consentQueue, setConsentQueue] = useState<Array<{ plugin: PluginRow; version: string; newPermissions: string[]; newEgress: string[] }>>([])
|
||||
@@ -427,10 +440,13 @@ export default function AdminPluginsPanel() {
|
||||
|
||||
// Index the registry once per fetch: the version map the update badges read, plus the
|
||||
// whole entry (author key + signed flag) the trust badges and re-trust dialog need.
|
||||
// The map holds latestCompatible — the newest version THIS TREK can install (computed
|
||||
// server-side) — not the absolute latest, so the banner never counts an update the
|
||||
// update endpoint would refuse.
|
||||
const indexRegistry = (items: RegistryItem[]) => {
|
||||
const vers: Record<string, string> = {}
|
||||
const byId: Record<string, RegistryItem> = {}
|
||||
items.forEach((i) => { byId[i.id] = i; if (i.latest) vers[i.id] = i.latest })
|
||||
items.forEach((i) => { byId[i.id] = i; if (i.latestCompatible) vers[i.id] = i.latestCompatible })
|
||||
setLatest(vers)
|
||||
setRegById(byId)
|
||||
}
|
||||
@@ -558,7 +574,21 @@ export default function AdminPluginsPanel() {
|
||||
.catch(() => setErrorsFor({ id, rows: [] }))
|
||||
}
|
||||
|
||||
const updateAvailable = (p: PluginRow) => !!(p.version && latest[p.id] && isNewer(latest[p.id], p.version))
|
||||
// A held plugin (deliberate non-latest install) is deliberately NOT an update candidate:
|
||||
// the admin just rolled it back, and the banner nagging them straight back would make
|
||||
// the rollback fight the UI. The row carries its own "paused" marker + resume instead.
|
||||
const updateAvailable = (p: PluginRow) => !!(p.version && !p.updateHold && latest[p.id] && isNewer(latest[p.id], p.version))
|
||||
const resumeUpdates = (p: PluginRow) => act(p.id, () => adminApi.pluginResumeUpdates(p.id), t('admin.plugins.updatesResumed'))
|
||||
// A newer version exists but this TREK can't install it (and it isn't the one on offer):
|
||||
// said passively on the row, so the admin learns a TREK upgrade unlocks it instead of
|
||||
// wondering why no update shows. Null when the registry gives no range to point at.
|
||||
const newerIncompatible = (p: PluginRow): { version: string; range: string } | null => {
|
||||
const reg = regById[p.id]
|
||||
if (!reg?.latest || !p.version || !isNewer(reg.latest, p.version)) return null
|
||||
if (latest[p.id] === reg.latest) return null
|
||||
const range = reg.trek ?? (reg.minTrekVersion ? `>=${reg.minTrekVersion}` : null)
|
||||
return range ? { version: reg.latest, range } : null
|
||||
}
|
||||
const install = (id: string, version?: string) => act(id, () => adminApi.pluginInstall(id, version ? { version } : undefined), t('admin.plugins.installed'))
|
||||
const restart = (id: string) => act(id, async () => { await adminApi.pluginDeactivate(id); await adminApi.pluginActivate(id) }, t('admin.plugins.restarted'))
|
||||
// Dev-link: register a plugin from a local built directory (dev only). Reuses the
|
||||
@@ -646,9 +676,11 @@ export default function AdminPluginsPanel() {
|
||||
.finally(() => { setBusy(null); refresh() })
|
||||
}
|
||||
|
||||
const runUpdate = (p: PluginRow) => {
|
||||
// `version` pins the exact version to install (rollback / explicit switch); omitted,
|
||||
// the server resolves the newest TREK-compatible version itself.
|
||||
const runUpdate = (p: PluginRow, version?: string) => {
|
||||
setBusy(p.id); setMenu(null)
|
||||
adminApi.pluginUpdate(p.id)
|
||||
return adminApi.pluginUpdate(p.id, version)
|
||||
.then((r: { version: string; activated: boolean; newPermissions: string[]; newEgress: string[] }) => {
|
||||
if (r.activated || (r.newPermissions.length === 0 && r.newEgress.length === 0)) toast.success(t('admin.plugins.updated'))
|
||||
else setConsentQueue(qq => [...qq, { plugin: p, version: r.version, newPermissions: r.newPermissions, newEgress: r.newEgress }])
|
||||
@@ -680,9 +712,36 @@ export default function AdminPluginsPanel() {
|
||||
.finally(() => { setRetrusting(false); refresh() })
|
||||
}
|
||||
|
||||
// "Change version…" on an installed row: fetch the per-version list (with the server's
|
||||
// compat verdicts) and open the picker. The fetch is keyed to the plugin so a stale
|
||||
// response can't populate a picker that was reopened for another row.
|
||||
const openVersionPicker = (p: PluginRow) => {
|
||||
setMenu(null)
|
||||
setVersionPicker({ plugin: p, versions: null, failed: false })
|
||||
adminApi.pluginDetail(p.id)
|
||||
.then((d: RegistryDetail) => setVersionPicker(cur => (cur && cur.plugin.id === p.id ? { ...cur, versions: d.versions ?? [] } : cur)))
|
||||
.catch(() => setVersionPicker(cur => (cur && cur.plugin.id === p.id ? { ...cur, failed: true } : cur)))
|
||||
}
|
||||
|
||||
// Switching DOWN keeps the plugin's data dir, which the older code may not understand —
|
||||
// that asks for explicit consent first. Any other switch is the ordinary update path.
|
||||
const pickVersion = (version: string) => {
|
||||
if (!versionPicker) return
|
||||
const p = versionPicker.plugin
|
||||
setVersionPicker(null)
|
||||
if (p.version && isNewer(p.version, version)) setConfirmDowngrade({ plugin: p, version })
|
||||
else void runUpdate(p, version)
|
||||
}
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
const updatable = useMemo(() => plugins.filter(updateAvailable), [plugins, latest])
|
||||
|
||||
// One after another: busy is a single slot, so parallel updates would leave the
|
||||
// other rows clickable mid-install and refresh once per plugin.
|
||||
const updateAll = async () => {
|
||||
for (const p of updatable) await runUpdate(p)
|
||||
}
|
||||
|
||||
// Installed list after search / type / status filters + sort.
|
||||
const shownInstalled = useMemo(() => {
|
||||
const term = q.trim().toLowerCase()
|
||||
@@ -740,7 +799,7 @@ export default function AdminPluginsPanel() {
|
||||
</div>
|
||||
)}
|
||||
{/* Click-away layer for any open dropdown (filters or a row's ⋯ menu). */}
|
||||
{menu && <div className="fixed inset-0 z-20" onClick={() => setMenu(null)} />}
|
||||
{menu && <div role="presentation" className="fixed inset-0 z-20" onClick={() => setMenu(null)} />}
|
||||
{/* Header */}
|
||||
<div className="px-4 sm:px-6 pt-5">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
@@ -796,11 +855,11 @@ export default function AdminPluginsPanel() {
|
||||
<SegBtn active={view === 'discover'} onClick={openDiscover} label={t('admin.plugins.tabDiscover')} count={registry?.length} />
|
||||
</div>
|
||||
<div className="sm:hidden flex items-center gap-2 shrink-0">
|
||||
<button onClick={pickUpload} title={t('admin.plugins.upload')}
|
||||
<button type="button" onClick={pickUpload} title={t('admin.plugins.upload')}
|
||||
className="h-[38px] w-[38px] grid place-items-center rounded-xl border border-edge bg-surface-card text-content-muted hover:text-content hover:border-content-faint transition-colors">
|
||||
<UploadCloud size={15} />
|
||||
</button>
|
||||
<button onClick={rescan} title={t('admin.plugins.rescan')}
|
||||
<button type="button" onClick={rescan} title={t('admin.plugins.rescan')}
|
||||
className="h-[38px] w-[38px] grid place-items-center rounded-xl border border-edge bg-surface-card text-content-muted hover:text-content hover:border-content-faint transition-colors">
|
||||
<RefreshCw size={15} />
|
||||
</button>
|
||||
@@ -843,11 +902,11 @@ export default function AdminPluginsPanel() {
|
||||
valueLabel={sortLabel(sort, t)}
|
||||
onPick={v => setSort(v as SortKey)} />
|
||||
|
||||
<button onClick={pickUpload} title={t('admin.plugins.upload')}
|
||||
<button type="button" onClick={pickUpload} title={t('admin.plugins.upload')}
|
||||
className="hidden sm:grid h-[38px] w-[38px] place-items-center rounded-xl border border-edge bg-surface-card text-content-muted hover:text-content hover:border-content-faint transition-colors">
|
||||
<UploadCloud size={15} />
|
||||
</button>
|
||||
<button onClick={rescan} title={t('admin.plugins.rescan')}
|
||||
<button type="button" onClick={rescan} title={t('admin.plugins.rescan')}
|
||||
className="hidden sm:grid h-[38px] w-[38px] place-items-center rounded-xl border border-edge bg-surface-card text-content-muted hover:text-content hover:border-content-faint transition-colors">
|
||||
<RefreshCw size={15} />
|
||||
</button>
|
||||
@@ -872,7 +931,7 @@ export default function AdminPluginsPanel() {
|
||||
<div className="mx-1.5 sm:mx-3 mb-2 mt-1 flex items-center gap-2.5 px-3.5 py-2.5 rounded-xl bg-warning-soft border border-warning/30">
|
||||
<ArrowUpCircle size={16} className="text-warning shrink-0" />
|
||||
<span className="text-xs text-content-secondary">{t('admin.plugins.updatesAvailable', { count: updatable.length })}</span>
|
||||
<button onClick={() => updatable.forEach(runUpdate)}
|
||||
<button type="button" onClick={() => void updateAll()}
|
||||
className="ml-auto text-xs font-semibold px-3 py-1.5 rounded-lg bg-warning text-white hover:opacity-90 transition-opacity">
|
||||
{t('admin.plugins.updateAll')}
|
||||
</button>
|
||||
@@ -886,9 +945,12 @@ export default function AdminPluginsPanel() {
|
||||
) : shownInstalled.map(p => (
|
||||
<InstalledRow key={p.id} p={p} t={t} busy={busy} menu={menu} setMenu={setMenu}
|
||||
hasUpdate={updateAvailable(p)} latestVer={latest[p.id]}
|
||||
newerIncompatible={newerIncompatible(p)}
|
||||
blocked={blockIsCurrent(p, latest[p.id])}
|
||||
onToggle={() => toggle(p)}
|
||||
onUpdate={() => runUpdate(p)} onRestart={() => restart(p.id)}
|
||||
onChangeVersion={() => openVersionPicker(p)}
|
||||
onResume={() => void resumeUpdates(p)}
|
||||
onReviewBlock={() => setSignatureBlock({
|
||||
subject: { id: p.id, name: p.name, keyFingerprint: p.keyFingerprint ?? null },
|
||||
code: p.updateBlock!.code, detail: p.updateBlock!.detail,
|
||||
@@ -910,11 +972,11 @@ export default function AdminPluginsPanel() {
|
||||
|
||||
{/* Error-log modal */}
|
||||
{errorsFor && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setErrorsFor(null)}>
|
||||
<div className="bg-surface-card border border-edge rounded-2xl w-full max-w-2xl max-h-[70vh] flex flex-col shadow-modal" onClick={e => e.stopPropagation()}>
|
||||
<div role="presentation" className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setErrorsFor(null)}>
|
||||
<div role="presentation" className="bg-surface-card border border-edge rounded-2xl w-full max-w-2xl max-h-[70vh] flex flex-col shadow-modal" onClick={e => e.stopPropagation()}>
|
||||
<div className="px-5 py-3.5 border-b border-edge-secondary flex items-center justify-between">
|
||||
<span className="text-sm font-semibold text-content flex items-center gap-2"><Bug size={15} /> {errorsFor.id} — {t('admin.plugins.errorLog')}</span>
|
||||
<button onClick={() => setErrorsFor(null)} className="text-content-faint hover:text-content"><X size={16} /></button>
|
||||
<button type="button" onClick={() => setErrorsFor(null)} className="text-content-faint hover:text-content"><X size={16} /></button>
|
||||
</div>
|
||||
<div className="p-4 overflow-y-auto text-xs font-mono">
|
||||
{errorsFor.rows.length === 0 ? <p className="text-content-faint py-4 text-center">{t('admin.plugins.noErrors')}</p> :
|
||||
@@ -932,11 +994,11 @@ export default function AdminPluginsPanel() {
|
||||
|
||||
{/* Operator-supplied egress hosts */}
|
||||
{egressFor && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setEgressFor(null)}>
|
||||
<div className="bg-surface-card border border-edge rounded-2xl w-full max-w-lg shadow-modal" onClick={e => e.stopPropagation()}>
|
||||
<div role="presentation" className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setEgressFor(null)}>
|
||||
<div role="presentation" className="bg-surface-card border border-edge rounded-2xl w-full max-w-lg shadow-modal" onClick={e => e.stopPropagation()}>
|
||||
<div className="px-5 py-3.5 border-b border-edge-secondary flex items-center justify-between">
|
||||
<span className="text-sm font-semibold text-content flex items-center gap-2"><Globe size={15} /> {egressFor.id} — {t('admin.plugins.allowedHosts')}</span>
|
||||
<button onClick={() => setEgressFor(null)} className="text-content-faint hover:text-content"><X size={16} /></button>
|
||||
<button type="button" onClick={() => setEgressFor(null)} className="text-content-faint hover:text-content"><X size={16} /></button>
|
||||
</div>
|
||||
<div className="p-5 space-y-3">
|
||||
{!egressFor.supported ? (
|
||||
@@ -950,7 +1012,7 @@ export default function AdminPluginsPanel() {
|
||||
{egressFor.hosts.map(h => (
|
||||
<div key={h} className="flex items-center justify-between gap-2 rounded-lg border border-edge-secondary px-3 py-2">
|
||||
<span className="text-sm font-mono text-content break-all">{h}</span>
|
||||
<button
|
||||
<button type="button"
|
||||
disabled={egressSaving}
|
||||
onClick={() => saveEgress(egressFor.hosts.filter(x => x !== h))}
|
||||
className="text-content-faint hover:text-danger disabled:opacity-50"
|
||||
@@ -965,7 +1027,7 @@ export default function AdminPluginsPanel() {
|
||||
placeholder="gotify.example.com"
|
||||
className="flex-1 rounded-lg border border-edge bg-surface px-3 py-2 text-sm text-content"
|
||||
/>
|
||||
<button
|
||||
<button type="button"
|
||||
disabled={egressSaving || !egressDraft.trim()}
|
||||
onClick={() => saveEgress([...egressFor.hosts, egressDraft.trim()])}
|
||||
className="rounded-lg bg-content px-3 py-2 text-sm text-surface disabled:opacity-50"
|
||||
@@ -991,6 +1053,20 @@ export default function AdminPluginsPanel() {
|
||||
message={t('admin.plugins.uninstallBody')}
|
||||
/>
|
||||
|
||||
{versionPicker && (
|
||||
<VersionPickerDialog plugin={versionPicker.plugin} versions={versionPicker.versions} failed={versionPicker.failed}
|
||||
busy={busy} t={t} locale={locale} onPick={pickVersion} onClose={() => setVersionPicker(null)} />
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={!!confirmDowngrade}
|
||||
onClose={() => setConfirmDowngrade(null)}
|
||||
onConfirm={() => { const d = confirmDowngrade!; setConfirmDowngrade(null); void runUpdate(d.plugin, d.version) }}
|
||||
title={t('admin.plugins.downgradeTitle')}
|
||||
message={t('admin.plugins.downgradeBody', { from: confirmDowngrade?.plugin.version ?? '', to: confirmDowngrade?.version ?? '' })}
|
||||
confirmLabel={t('admin.plugins.downgradeConfirm')}
|
||||
/>
|
||||
|
||||
{signatureBlock && (
|
||||
<SignatureBlockDialog
|
||||
data={signatureBlock} entry={regById[signatureBlock.subject.id]} busy={retrusting} t={t}
|
||||
@@ -1044,7 +1120,7 @@ function sortLabel(s: SortKey, t: T): string {
|
||||
|
||||
function SegBtn({ active, onClick, label, count }: { active: boolean; onClick: () => void; label: string; count?: number }) {
|
||||
return (
|
||||
<button onClick={onClick} role="tab" aria-selected={active}
|
||||
<button type="button" onClick={onClick} role="tab" aria-selected={active}
|
||||
className={`inline-flex items-center gap-2 text-[13px] font-medium px-3.5 py-1.5 rounded-lg transition-colors ${
|
||||
active ? 'bg-surface-card text-content shadow-card' : 'text-content-muted hover:text-content'}`}>
|
||||
{label}
|
||||
@@ -1065,7 +1141,7 @@ function FilterMenu({ id, label, valueLabel, options, onPick, value, menu, setMe
|
||||
const active = value !== options[0]?.[0]
|
||||
return (
|
||||
<div className="relative">
|
||||
<button onClick={() => setMenu(open ? null : id)} title={`${label}: ${valueLabel}`}
|
||||
<button type="button" onClick={() => setMenu(open ? null : id)} title={`${label}: ${valueLabel}`}
|
||||
className={`relative h-[38px] w-[38px] sm:w-auto px-0 sm:px-3 inline-flex items-center justify-center sm:justify-start gap-1.5 rounded-xl border bg-surface-card text-[13px] text-content-secondary transition-colors whitespace-nowrap hover:border-content-faint ${
|
||||
active ? 'border-content-faint' : 'border-edge'}`}>
|
||||
{icon}
|
||||
@@ -1077,7 +1153,7 @@ function FilterMenu({ id, label, valueLabel, options, onPick, value, menu, setMe
|
||||
{open && (
|
||||
<div className="absolute top-11 right-0 z-30 min-w-[180px] max-w-[calc(100vw-2rem)] p-1.5 rounded-xl border border-edge bg-surface-card shadow-elevated">
|
||||
{options.map(([v, lbl]) => (
|
||||
<button key={v} onClick={() => { onPick(v); setMenu(null) }}
|
||||
<button type="button" key={v} onClick={() => { onPick(v); setMenu(null) }}
|
||||
className={`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-[13px] transition-colors hover:bg-surface-tertiary ${
|
||||
value === v ? 'text-content font-semibold' : 'text-content-secondary'}`}>
|
||||
{lbl}<Check size={15} className={`ml-auto text-accent ${value === v ? 'opacity-100' : 'opacity-0'}`} />
|
||||
@@ -1096,17 +1172,17 @@ function EmptyState({ t, onDiscover }: { t: T; onDiscover: () => void }) {
|
||||
<PackageOpen size={26} className="text-content-faint" />
|
||||
</div>
|
||||
<p className="text-sm font-medium text-content-muted">{t('admin.plugins.empty')}</p>
|
||||
<button onClick={onDiscover} className="mt-4 inline-flex items-center gap-1.5 text-xs font-semibold px-4 py-2 rounded-lg bg-accent text-accent-text">
|
||||
<button type="button" onClick={onDiscover} className="mt-4 inline-flex items-center gap-1.5 text-xs font-semibold px-4 py-2 rounded-lg bg-accent text-accent-text">
|
||||
<Download size={14} /> {t('admin.plugins.tabDiscover')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, blocked, onToggle, onUpdate, onRestart, onReviewBlock, onErrors, onEgress, onUninstall }: {
|
||||
function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, newerIncompatible, blocked, onToggle, onUpdate, onRestart, onChangeVersion, onResume, onReviewBlock, onErrors, onEgress, onUninstall }: {
|
||||
p: PluginRow; t: T; busy: string | null; menu: string | null; setMenu: (v: string | null) => void
|
||||
hasUpdate: boolean; latestVer?: string; blocked: boolean
|
||||
onToggle: () => void; onUpdate: () => void; onRestart: () => void; onReviewBlock: () => void
|
||||
hasUpdate: boolean; latestVer?: string; newerIncompatible: { version: string; range: string } | null; blocked: boolean
|
||||
onToggle: () => void; onUpdate: () => void; onRestart: () => void; onChangeVersion: () => void; onResume: () => void; onReviewBlock: () => void
|
||||
onErrors: () => void; onEgress: () => void; onUninstall: () => void
|
||||
}) {
|
||||
const caps = deriveCaps(parseJson<string[]>(p.permissions, []), parseJson<{ widget?: { slot?: string } }>(p.capabilities, {}), t)
|
||||
@@ -1144,7 +1220,7 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, blocked
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-[14.5px] font-semibold tracking-[-.006em] text-content">{p.name}</span>
|
||||
{p.version && <span className="text-[11.5px] text-content-faint font-medium tabular-nums">v{p.version}</span>}
|
||||
{p.reviewed_at && <ReviewedBadge t={t} compact />}
|
||||
{p.reviewed_at && <ReviewedBadge t={t} />}
|
||||
{p.source_repo === 'local:upload' && <SideloadedBadge t={t} />}
|
||||
{p.source_repo === 'local:link' && <DevLinkBadge t={t} />}
|
||||
{/* Registry plugins only — a sideloaded/dev-linked plugin already says something
|
||||
@@ -1159,12 +1235,32 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, blocked
|
||||
<div className="flex items-center gap-1.5 mt-1.5 text-[11.5px] text-warning">
|
||||
<ShieldAlert size={13} className="shrink-0" />
|
||||
<span className="truncate">{t('admin.plugins.updateBlocked', { reason: p.updateBlock.detail ?? p.updateBlock.code })}</span>
|
||||
<button onClick={onReviewBlock}
|
||||
<button type="button" onClick={onReviewBlock}
|
||||
className="shrink-0 font-semibold underline underline-offset-2 hover:opacity-80 transition-opacity">
|
||||
{t('admin.plugins.reviewBlock')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{/* A newer version this TREK can't run — informational, never a button: the fix
|
||||
is a TREK upgrade, so the row must not nag or offer a doomed install. */}
|
||||
{newerIncompatible && (
|
||||
<div className="flex items-center gap-1.5 mt-1.5 text-[11.5px] text-content-faint">
|
||||
<Info size={13} className="shrink-0" />
|
||||
<span className="truncate">{t('admin.plugins.newerNeedsTrek', { version: newerIncompatible.version, range: newerIncompatible.range })}</span>
|
||||
</div>
|
||||
)}
|
||||
{/* Held: the admin deliberately installed a non-latest version, so updates are
|
||||
paused rather than nagged — resuming is one click, right where the pause shows. */}
|
||||
{p.updateHold && (
|
||||
<div className="flex items-center gap-1.5 mt-1.5 text-[11.5px] text-content-faint">
|
||||
<PauseCircle size={13} className="shrink-0" />
|
||||
<span className="truncate">{t('admin.plugins.updatesHeld', { version: p.version ?? '' })}</span>
|
||||
<button type="button" onClick={onResume} disabled={busy === p.id}
|
||||
className="shrink-0 font-semibold underline underline-offset-2 hover:opacity-80 transition-opacity disabled:opacity-50">
|
||||
{t('admin.plugins.resumeUpdates')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{p.status === 'error' && p.last_error ? (
|
||||
<div className="flex items-center gap-1.5 mt-1.5 text-[11.5px] text-danger">
|
||||
<AlertTriangle size={13} className="shrink-0" /><span className="truncate">{p.last_error}</span>
|
||||
@@ -1182,7 +1278,7 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, blocked
|
||||
Actionable, and warning-toned until at least one host exists, because
|
||||
until then the plugin cannot reach anything and looks silently broken. */}
|
||||
{p.operatorEgress && (
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={onEgress}
|
||||
title={t('admin.plugins.allowedHosts.hint')}
|
||||
className={`inline-flex items-center gap-1.5 text-[11px] font-medium px-2 py-[3px] rounded-md border transition-colors ${
|
||||
@@ -1212,7 +1308,7 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, blocked
|
||||
|
||||
<div className="flex items-center gap-1.5 sm:gap-2 shrink-0">
|
||||
{hasUpdate && (
|
||||
<button onClick={onUpdate} disabled={busy === p.id} title={t('admin.plugins.updateTo', { version: latestVer })}
|
||||
<button type="button" onClick={onUpdate} disabled={busy === p.id} title={t('admin.plugins.updateTo', { version: latestVer })}
|
||||
className="inline-flex items-center gap-1.5 text-[11.5px] font-semibold px-2 sm:px-2.5 py-1.5 rounded-full text-warning bg-warning-soft border border-warning/30 hover:opacity-90 transition-opacity disabled:opacity-50">
|
||||
<ArrowUpCircle size={13} /> <span className="hidden sm:inline">{t('admin.plugins.updateTo', { version: latestVer })}</span>
|
||||
</button>
|
||||
@@ -1222,7 +1318,7 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, blocked
|
||||
</span>
|
||||
<ToggleSwitch on={p.enabled === 1} label={t('admin.plugins.enabledToggle')} onToggle={onToggle} />
|
||||
<div className="relative">
|
||||
<button ref={menuBtnRef} data-testid={`plugin-row-menu-btn-${p.id}`} onClick={() => setMenu(menuOpen ? null : `row:${p.id}`)}
|
||||
<button type="button" ref={menuBtnRef} data-testid={`plugin-row-menu-btn-${p.id}`} onClick={() => setMenu(menuOpen ? null : `row:${p.id}`)}
|
||||
className="w-[34px] h-[34px] grid place-items-center rounded-lg text-content-faint hover:text-content hover:bg-surface-tertiary transition-colors">
|
||||
<MoreHorizontal size={17} />
|
||||
</button>
|
||||
@@ -1234,6 +1330,10 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, blocked
|
||||
)}
|
||||
<MenuItem icon={<Bug size={14} />} label={t('admin.plugins.viewErrors')} onClick={onErrors} />
|
||||
<MenuItem icon={<Globe size={14} />} label={t('admin.plugins.allowedHosts')} onClick={onEgress} />
|
||||
{/* Registry plugins only — a sideload/dev-link has no registry versions to pick from. */}
|
||||
{isRegistrySourced(p.source_repo) && (
|
||||
<MenuItem icon={<History size={14} />} label={t('admin.plugins.changeVersion')} onClick={onChangeVersion} />
|
||||
)}
|
||||
{p.source_repo && p.source_repo !== 'local:upload' && p.source_repo !== 'local:link' && (
|
||||
<>
|
||||
<a href={`https://github.com/${p.source_repo}`} target="_blank" rel="noreferrer" onClick={() => setMenu(null)}
|
||||
@@ -1276,7 +1376,7 @@ function anchorMenu(trigger: HTMLElement | null): CSSProperties {
|
||||
|
||||
function MenuItem({ icon, label, onClick, danger }: { icon: React.ReactNode; label: string; onClick: () => void; danger?: boolean }) {
|
||||
return (
|
||||
<button onClick={onClick}
|
||||
<button type="button" onClick={onClick}
|
||||
className={`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-[13px] transition-colors ${
|
||||
danger ? 'text-danger hover:bg-danger-soft' : 'text-content-secondary hover:bg-surface-tertiary'}`}>
|
||||
{icon} {label}
|
||||
@@ -1350,7 +1450,7 @@ function RegistryGrid({ items, onInstall, onOpenDetail, busy, t, installedIds, f
|
||||
<Download size={11} /> {formatCompactCount(item.downloadCount)}
|
||||
</span>
|
||||
)}
|
||||
<button onClick={e => { e.stopPropagation(); onInstall(item.id, offer.version) }}
|
||||
<button type="button" onClick={e => { e.stopPropagation(); onInstall(item.id, offer.version) }}
|
||||
disabled={busy === item.id || installed || offer.blocked}
|
||||
title={installed ? undefined : offer.title}
|
||||
className="ml-auto text-xs font-semibold px-3.5 py-1.5 rounded-lg bg-accent text-accent-text hover:bg-accent-hover disabled:opacity-50 disabled:bg-surface-tertiary disabled:text-content-faint transition-colors">
|
||||
@@ -1396,7 +1496,10 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
}, [item.id])
|
||||
|
||||
const manifest = detail?.manifest ?? null
|
||||
const caps = manifest ? deriveCaps(manifest.permissions, {}, t) : []
|
||||
const permissions = manifest?.permissions ?? []
|
||||
const egress = manifest?.egress ?? []
|
||||
const settings = manifest?.settings ?? []
|
||||
const caps = manifest ? deriveCaps(permissions, manifest.capabilities ?? {}, t) : []
|
||||
const repoUrl = `https://github.com/${item.repo}`
|
||||
const homepage = item.homepage && /^https?:\/\//i.test(item.homepage) && item.homepage !== repoUrl ? item.homepage : null
|
||||
const sizeKb = detail?.size ? Math.max(1, Math.round(detail.size / 1024)) : null
|
||||
@@ -1405,12 +1508,12 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
const offer = installOffer(detail ?? item, t)
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
|
||||
<div className="bg-surface-card border border-edge rounded-2xl w-full max-w-xl max-h-[88vh] overflow-auto shadow-modal" onClick={e => e.stopPropagation()}>
|
||||
<div role="presentation" className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
|
||||
<div role="presentation" className="bg-surface-card border border-edge rounded-2xl w-full max-w-xl max-h-[88vh] overflow-auto shadow-modal" onClick={e => e.stopPropagation()}>
|
||||
<div className="relative">
|
||||
<Screenshot url={item.screenshotUrl} className="w-full aspect-[16/9]" iconSize={36} />
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent" />
|
||||
<button onClick={onClose} className="absolute top-3 right-3 w-8 h-8 grid place-items-center rounded-lg bg-black/40 text-white hover:bg-black/60 transition-colors"><X size={16} /></button>
|
||||
<button type="button" onClick={onClose} className="absolute top-3 right-3 w-8 h-8 grid place-items-center rounded-lg bg-black/40 text-white hover:bg-black/60 transition-colors"><X size={16} /></button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3 sm:gap-3.5 px-4 sm:px-5 -mt-7 relative z-[1]">
|
||||
@@ -1420,11 +1523,11 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
<div className="flex-1 min-w-0 pt-8">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h3 className="text-lg font-semibold tracking-tight text-content">{item.name}</h3>
|
||||
{item.reviewedAt && <ReviewedBadge t={t} compact />}
|
||||
{item.reviewedAt && <ReviewedBadge t={t} />}
|
||||
</div>
|
||||
<p className="text-[12.5px] text-content-faint mt-0.5">{item.author}{item.latest ? ` · v${item.latest}` : ''}</p>
|
||||
</div>
|
||||
<button onClick={() => onInstall(item.id, offer.version)}
|
||||
<button type="button" onClick={() => onInstall(item.id, offer.version)}
|
||||
disabled={busy === item.id || installed || offer.blocked}
|
||||
title={installed ? undefined : offer.title}
|
||||
className="self-end text-[13px] font-semibold px-3 sm:px-4 py-2 rounded-lg bg-accent text-accent-text hover:bg-accent-hover disabled:opacity-50 disabled:bg-surface-tertiary disabled:text-content-faint transition-colors shrink-0">
|
||||
@@ -1446,7 +1549,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
{manifest && (
|
||||
<div className="mt-5">
|
||||
<h4 className="text-[11px] font-semibold uppercase tracking-wider text-content-muted">{t('admin.plugins.accessTitle')}</h4>
|
||||
{caps.filter(c => !c.net).length === 0 && !manifest.permissions.includes('db:own') ? (
|
||||
{caps.filter(c => !c.net).length === 0 && !permissions.includes('db:own') ? (
|
||||
<p className="text-xs text-content-faint mt-2">{t('admin.plugins.noAccess')}</p>
|
||||
) : (
|
||||
<div className="mt-2 space-y-1.5">
|
||||
@@ -1455,7 +1558,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
<c.icon size={15} className="text-accent mt-0.5 shrink-0" /><span>{c.label}</span>
|
||||
</div>
|
||||
))}
|
||||
{manifest.permissions.includes('db:own') && (
|
||||
{permissions.includes('db:own') && (
|
||||
<div className="flex items-start gap-2.5 text-[13px] text-content-secondary py-0.5">
|
||||
<Database size={15} className="text-accent mt-0.5 shrink-0" /><span>{t('admin.plugins.perm.db:own')}</span>
|
||||
</div>
|
||||
@@ -1465,11 +1568,11 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
</div>
|
||||
)}
|
||||
|
||||
{manifest && (manifest.egress.length > 0 || manifest.operatorEgress) && (
|
||||
{manifest && (egress.length > 0 || manifest.operatorEgress) && (
|
||||
<div className="mt-5">
|
||||
<h4 className="text-[11px] font-semibold uppercase tracking-wider text-content-muted">{t('admin.plugins.connectsTitle')}</h4>
|
||||
<div className="flex flex-wrap items-center gap-1.5 mt-2">
|
||||
{manifest.egress.map(h => (
|
||||
{egress.map(h => (
|
||||
<code key={h} className="text-[12px] font-mono text-info bg-info-soft rounded-md px-2 py-1">{h}</code>
|
||||
))}
|
||||
{/* The hosts above are NOT the whole story for this plugin: it talks to a
|
||||
@@ -1488,11 +1591,11 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
</div>
|
||||
)}
|
||||
|
||||
{manifest && manifest.settings.length > 0 && (
|
||||
{manifest && settings.length > 0 && (
|
||||
<div className="mt-5">
|
||||
<h4 className="text-[11px] font-semibold uppercase tracking-wider text-content-muted">{t('admin.plugins.setupTitle')}</h4>
|
||||
<ul className="mt-2 space-y-1.5">
|
||||
{manifest.settings.map(s => (
|
||||
{settings.map(s => (
|
||||
<li key={s.key} className="flex items-center gap-2 text-xs text-content-muted flex-wrap">
|
||||
<span className="font-medium">{s.label}</span>
|
||||
<span className="text-[10px] px-1.5 py-0.5 rounded-full bg-surface-tertiary text-content-faint">{t(`admin.plugins.scope.${s.scope}` as never)}</span>
|
||||
@@ -1507,7 +1610,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
<h4 className="text-[11px] font-semibold uppercase tracking-wider text-content-muted">{t('admin.plugins.detailsTitle')}</h4>
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-3 mt-2.5">
|
||||
{item.latest && <Meta k={t('admin.plugins.metaVersion')} v={`v${item.latest}`} />}
|
||||
{sizeKb && <Meta k={t('admin.plugins.metaSize')} v={`${sizeKb} KB`} />}
|
||||
{sizeKb !== null && <Meta k={t('admin.plugins.metaSize')} v={`${sizeKb} KB`} />}
|
||||
{/* The range, not just its lower bound: "TREK 3.2.0+" reads as "and anything
|
||||
newer", which is exactly the claim a `<4.0.0` upper bound denies. */}
|
||||
{(item.trek || item.minTrekVersion) && (
|
||||
@@ -1519,6 +1622,34 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Every published version, installable individually. The compat verdict per
|
||||
version is SERVER-computed — an incompatible one is explained, never offered. */}
|
||||
{(detail?.versions?.length ?? 0) > 1 && (
|
||||
<div className="mt-5">
|
||||
<h4 className="text-[11px] font-semibold uppercase tracking-wider text-content-muted">{t('admin.plugins.versionsTitle')}</h4>
|
||||
<div className="mt-2 space-y-0.5">
|
||||
{detail!.versions!.map(v => (
|
||||
<div key={v.version} className="flex items-center gap-2.5 py-1">
|
||||
<span className={`text-[12.5px] font-medium tabular-nums ${v.compatible ? 'text-content' : 'text-content-faint'}`}>v{v.version}</span>
|
||||
{v.publishedAt && <span className="text-[11.5px] text-content-faint">{new Date(v.publishedAt).toLocaleDateString(locale)}</span>}
|
||||
{v.signed && <ShieldCheck size={13} className="text-success shrink-0" />}
|
||||
<span className="ml-auto" />
|
||||
{v.compatible ? (
|
||||
!installed && (
|
||||
<button type="button" onClick={() => onInstall(item.id, v.version)} disabled={busy === item.id}
|
||||
className="text-[11.5px] font-semibold px-2.5 py-1 rounded-full border border-edge bg-surface-card text-content-secondary hover:text-content hover:border-content-faint transition-colors disabled:opacity-50">
|
||||
{t('admin.plugins.installCompatible', { version: v.version })}
|
||||
</button>
|
||||
)
|
||||
) : (
|
||||
<span className="text-[11.5px] text-content-faint">{t('admin.plugins.versionNeedsTrek', { range: v.trek ?? '' })}</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 px-4 sm:px-5 py-3.5 border-t border-edge-secondary bg-surface-secondary">
|
||||
@@ -1546,6 +1677,55 @@ function Meta({ k, v }: { k: string; v: string }) {
|
||||
return <div><div className="text-[12px] text-content-faint">{k}</div><div className="text-[12.5px] font-medium text-content mt-0.5">{v}</div></div>
|
||||
}
|
||||
|
||||
/**
|
||||
* "Change version…" for an INSTALLED plugin. Rows render the server's per-version compat
|
||||
* verdict: the installed version is marked, a compatible one gets a Switch action (the
|
||||
* caller routes a DOWNGRADE through the data-risk confirm), an incompatible one is
|
||||
* explained and never offered.
|
||||
*/
|
||||
function VersionPickerDialog({ plugin, versions, failed, busy, t, locale, onPick, onClose }: {
|
||||
plugin: PluginRow; versions: VersionInfo[] | null; failed: boolean; busy: string | null
|
||||
t: T; locale: string; onPick: (version: string) => void; onClose: () => void
|
||||
}) {
|
||||
return (
|
||||
<div role="presentation" className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
|
||||
<div role="presentation" className="bg-surface-card border border-edge rounded-2xl w-full max-w-md max-h-[80vh] overflow-auto shadow-modal" onClick={e => e.stopPropagation()}>
|
||||
<div className="flex items-center justify-between px-4 py-3.5 border-b border-edge-secondary">
|
||||
<h3 className="text-[15px] font-semibold text-content truncate">{t('admin.plugins.versionPickerTitle', { name: plugin.name })}</h3>
|
||||
<button type="button" onClick={onClose} className="w-8 h-8 grid place-items-center rounded-lg text-content-faint hover:text-content hover:bg-surface-tertiary transition-colors shrink-0"><X size={16} /></button>
|
||||
</div>
|
||||
<div className="p-2">
|
||||
{failed && <p className="text-xs text-danger px-2.5 py-2">{t('admin.plugins.detailError')}</p>}
|
||||
{!failed && !versions && <p className="text-xs text-content-faint px-2.5 py-2">{t('common.loading')}</p>}
|
||||
{versions?.length === 0 && <p className="text-xs text-content-faint px-2.5 py-2">{t('admin.plugins.noVersions')}</p>}
|
||||
{versions?.map(v => {
|
||||
const current = v.version === plugin.version
|
||||
return (
|
||||
<div key={v.version} data-testid={`version-row-${v.version}`}
|
||||
className="flex items-center gap-2.5 px-2.5 py-2 rounded-xl hover:bg-surface-secondary transition-colors">
|
||||
<span className={`text-[13px] font-medium tabular-nums ${v.compatible ? 'text-content' : 'text-content-faint'}`}>v{v.version}</span>
|
||||
{v.publishedAt && <span className="text-[11.5px] text-content-faint">{new Date(v.publishedAt).toLocaleDateString(locale)}</span>}
|
||||
{v.signed && <ShieldCheck size={13} className="text-success shrink-0" />}
|
||||
<span className="ml-auto" />
|
||||
{current ? (
|
||||
<span className="text-[11.5px] font-medium text-content-faint">{t('admin.plugins.installed')}</span>
|
||||
) : v.compatible ? (
|
||||
<button type="button" onClick={() => onPick(v.version)} disabled={busy === plugin.id}
|
||||
className="text-[11.5px] font-semibold px-2.5 py-1 rounded-full border border-edge bg-surface-card text-content-secondary hover:text-content hover:border-content-faint transition-colors disabled:opacity-50">
|
||||
{t('admin.plugins.versionSwitch', { version: v.version })}
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-[11.5px] text-content-faint">{t('admin.plugins.versionNeedsTrek', { range: v.trek ?? '' })}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A signature check refused an install/update.
|
||||
*
|
||||
@@ -1580,8 +1760,8 @@ function SignatureBlockDialog({ data, entry, busy, t, onRetrust, onClose }: {
|
||||
: 'admin.plugins.sig.invalidBody'
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
|
||||
<div className="bg-surface-card border border-edge rounded-2xl w-full max-w-md shadow-modal overflow-hidden" onClick={e => e.stopPropagation()}>
|
||||
<div role="presentation" className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
|
||||
<div role="presentation" className="bg-surface-card border border-edge rounded-2xl w-full max-w-md shadow-modal overflow-hidden" onClick={e => e.stopPropagation()}>
|
||||
<div className="px-5 py-4 border-b border-edge-secondary flex items-start gap-3">
|
||||
<div className="w-9 h-9 rounded-lg bg-warning-soft grid place-items-center shrink-0"><ShieldAlert size={18} className="text-warning" /></div>
|
||||
<div>
|
||||
@@ -1604,12 +1784,12 @@ function SignatureBlockDialog({ data, entry, busy, t, onRetrust, onClose }: {
|
||||
)}
|
||||
</div>
|
||||
<div className="px-5 py-3.5 border-t border-edge-secondary bg-surface-secondary flex items-center justify-end gap-2">
|
||||
<button onClick={onClose}
|
||||
<button type="button" onClick={onClose}
|
||||
className="text-xs font-medium px-3.5 py-2 rounded-lg border border-edge text-content-muted hover:text-content hover:bg-surface-tertiary transition-colors">
|
||||
{offerRetrust ? t('admin.plugins.sig.cancel') : t('common.close')}
|
||||
</button>
|
||||
{offerRetrust && (
|
||||
<button onClick={() => onRetrust(version, newKey)} disabled={busy}
|
||||
<button type="button" onClick={() => onRetrust(version, newKey)} disabled={busy}
|
||||
className="text-xs font-semibold px-4 py-2 rounded-lg bg-warning text-white hover:opacity-90 transition-opacity disabled:opacity-50">
|
||||
{t('admin.plugins.sig.retrustConfirm')}
|
||||
</button>
|
||||
@@ -1644,8 +1824,8 @@ function UpdateConsentDialog({ data, unsigned, t, onApprove, onLater }: {
|
||||
t: T; onApprove: () => void; onLater: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onLater}>
|
||||
<div className="bg-surface-card border border-edge rounded-2xl w-full max-w-md shadow-modal overflow-hidden" onClick={e => e.stopPropagation()}>
|
||||
<div role="presentation" className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onLater}>
|
||||
<div role="presentation" className="bg-surface-card border border-edge rounded-2xl w-full max-w-md shadow-modal overflow-hidden" onClick={e => e.stopPropagation()}>
|
||||
<div className="px-5 py-4 border-b border-edge-secondary flex items-start gap-3">
|
||||
<div className="w-9 h-9 rounded-lg bg-warning-soft grid place-items-center shrink-0"><ShieldCheck size={18} className="text-warning" /></div>
|
||||
<div>
|
||||
@@ -1683,8 +1863,8 @@ function UpdateConsentDialog({ data, unsigned, t, onApprove, onLater }: {
|
||||
)}
|
||||
</div>
|
||||
<div className="px-5 py-3.5 border-t border-edge-secondary bg-surface-secondary flex items-center justify-end gap-2">
|
||||
<button onClick={onLater} className="text-xs font-medium px-3.5 py-2 rounded-lg border border-edge text-content-muted hover:text-content hover:bg-surface-tertiary transition-colors">{t('admin.plugins.updateLater')}</button>
|
||||
<button onClick={onApprove} className="text-xs font-semibold px-4 py-2 rounded-lg bg-accent text-accent-text hover:bg-accent-hover transition-colors">{t('admin.plugins.updateApprove')}</button>
|
||||
<button type="button" onClick={onLater} className="text-xs font-medium px-3.5 py-2 rounded-lg border border-edge text-content-muted hover:text-content hover:bg-surface-tertiary transition-colors">{t('admin.plugins.updateLater')}</button>
|
||||
<button type="button" onClick={onApprove} className="text-xs font-semibold px-4 py-2 rounded-lg bg-accent text-accent-text hover:bg-accent-hover transition-colors">{t('admin.plugins.updateApprove')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1704,8 +1884,8 @@ function DependencyResolveDialog({ data, t, busy, installedIds, onDownload, onCl
|
||||
...data.versionMismatch.map(d => ({ id: d.id, constraint: d.wanted, installed: d.installed })),
|
||||
]
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
|
||||
<div className="bg-surface-card border border-edge rounded-2xl w-full max-w-md shadow-modal overflow-hidden" onClick={e => e.stopPropagation()}>
|
||||
<div role="presentation" className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
|
||||
<div role="presentation" className="bg-surface-card border border-edge rounded-2xl w-full max-w-md shadow-modal overflow-hidden" onClick={e => e.stopPropagation()}>
|
||||
<div className="px-5 py-4 border-b border-edge-secondary flex items-start gap-3">
|
||||
<div className="w-9 h-9 rounded-lg bg-warning-soft grid place-items-center shrink-0"><Puzzle size={18} className="text-warning" /></div>
|
||||
<div>
|
||||
@@ -1724,7 +1904,7 @@ function DependencyResolveDialog({ data, t, busy, installedIds, onDownload, onCl
|
||||
: t('admin.plugins.dep.requires', { version: r.constraint })}
|
||||
</div>
|
||||
</div>
|
||||
<button onClick={() => onDownload(r.id, r.constraint)} disabled={busy}
|
||||
<button type="button" onClick={() => onDownload(r.id, r.constraint)} disabled={busy}
|
||||
className="inline-flex items-center gap-1.5 text-[11.5px] font-semibold px-3 py-1.5 rounded-full bg-accent text-accent-text hover:bg-accent-hover transition-colors disabled:opacity-50 shrink-0">
|
||||
<Download size={13} /> {r.installed ? t('admin.plugins.dep.update') : t('admin.plugins.dep.download')}
|
||||
</button>
|
||||
@@ -1735,7 +1915,7 @@ function DependencyResolveDialog({ data, t, busy, installedIds, onDownload, onCl
|
||||
)}
|
||||
</div>
|
||||
<div className="px-5 py-3.5 border-t border-edge-secondary bg-surface-secondary flex items-center justify-end">
|
||||
<button onClick={onClose} className="text-xs font-medium px-3.5 py-2 rounded-lg border border-edge text-content-muted hover:text-content hover:bg-surface-tertiary transition-colors">{t('common.cancel')}</button>
|
||||
<button type="button" onClick={onClose} className="text-xs font-medium px-3.5 py-2 rounded-lg border border-edge text-content-muted hover:text-content hover:bg-surface-tertiary transition-colors">{t('common.cancel')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1761,7 +1941,7 @@ function SecurityInfo({ t }: { t: T }) {
|
||||
<ShieldCheck size={14} className="text-content-faint shrink-0 mt-0.5" />
|
||||
<p className="text-xs text-content-muted">{t('admin.plugins.reviewedMeaning')}</p>
|
||||
</div>
|
||||
<button onClick={() => setOpen(o => !o)}
|
||||
<button type="button" onClick={() => setOpen(o => !o)}
|
||||
className="w-full px-4 sm:px-6 py-2.5 border-t border-edge-secondary flex items-center justify-between gap-2 text-xs font-medium text-content-secondary hover:text-content hover:bg-surface-tertiary transition-colors">
|
||||
<span className="flex items-center gap-2"><Lock size={13} className="shrink-0" /> <span className="text-left">{t('admin.plugins.security.title')}</span></span>
|
||||
<ChevronDown size={15} className={`shrink-0 transition-transform ${open ? 'rotate-180' : ''}`} />
|
||||
|
||||
@@ -310,4 +310,292 @@ describe('BackupPanel', () => {
|
||||
expect(screen.getByRole('button', { name: /^save$/i })).not.toBeDisabled()
|
||||
})
|
||||
})
|
||||
|
||||
// BKP-015: List request fails
|
||||
it('FE-ADMIN-BKP-015: a failing list request toasts and keeps the empty state', async () => {
|
||||
server.use(http.get('/api/backup/list', () => HttpResponse.error()))
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
|
||||
expect(await screen.findByText('Failed to load backups')).toBeInTheDocument()
|
||||
expect(screen.getByText('No backups yet')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
// BKP-016: Create fails
|
||||
it('FE-ADMIN-BKP-016: a failing create toasts the error and re-enables the button', async () => {
|
||||
const user = userEvent.setup()
|
||||
server.use(http.post('/api/backup/create', () => HttpResponse.error()))
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('backup-2025-01-15.zip')
|
||||
|
||||
await user.click(screen.getByTitle('Create Backup'))
|
||||
|
||||
expect(await screen.findByText('Failed to create backup')).toBeInTheDocument()
|
||||
await waitFor(() => expect(screen.getByTitle('Create Backup')).toBeEnabled())
|
||||
})
|
||||
|
||||
// BKP-017: Restore fails
|
||||
it('FE-ADMIN-BKP-017: a failing restore surfaces the server message and clears the spinner', async () => {
|
||||
const user = userEvent.setup()
|
||||
server.use(
|
||||
http.post('/api/backup/restore/:filename', () =>
|
||||
HttpResponse.json({ error: 'archive is corrupt' }, { status: 400 }),
|
||||
),
|
||||
)
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('backup-2025-01-15.zip')
|
||||
|
||||
await user.click(screen.getAllByText('Restore')[0])
|
||||
await user.click(await screen.findByText('Yes, restore'))
|
||||
|
||||
expect(await screen.findByText('archive is corrupt')).toBeInTheDocument()
|
||||
await waitFor(() => expect(screen.getAllByText('Restore')[0].closest('button')).toBeEnabled())
|
||||
})
|
||||
|
||||
// BKP-018: Upload & restore happy path
|
||||
it('FE-ADMIN-BKP-018: picking a file opens the modal and uploads it on confirm', async () => {
|
||||
const user = userEvent.setup()
|
||||
let uploaded = false
|
||||
server.use(
|
||||
http.post('/api/backup/upload-restore', () => {
|
||||
uploaded = true
|
||||
return HttpResponse.json({ success: true })
|
||||
}),
|
||||
)
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('backup-2025-01-15.zip')
|
||||
|
||||
const reloadMock = vi.fn()
|
||||
vi.stubGlobal('location', { ...window.location, reload: reloadMock })
|
||||
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement
|
||||
await user.upload(input, new File(['zip'], 'restore-me.zip', { type: 'application/zip' }))
|
||||
|
||||
expect(await screen.findByText('Restore Backup?')).toBeInTheDocument()
|
||||
expect(screen.getByText('restore-me.zip')).toBeInTheDocument()
|
||||
// The picked file is cleared from the input so the same file can be chosen again
|
||||
expect(input.value).toBe('')
|
||||
|
||||
await user.click(screen.getByText('Yes, restore'))
|
||||
await waitFor(() => expect(uploaded).toBe(true))
|
||||
expect(await screen.findByText('Backup restored. Page will reload…')).toBeInTheDocument()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
// BKP-019: Upload & restore failure
|
||||
it('FE-ADMIN-BKP-019: a failing upload restore toasts and re-enables the upload button', async () => {
|
||||
const user = userEvent.setup()
|
||||
server.use(
|
||||
http.post('/api/backup/upload-restore', () => HttpResponse.json({ error: 'not a backup' }, { status: 400 })),
|
||||
)
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('backup-2025-01-15.zip')
|
||||
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement
|
||||
await user.upload(input, new File(['zip'], 'broken.zip', { type: 'application/zip' }))
|
||||
await user.click(await screen.findByText('Yes, restore'))
|
||||
|
||||
expect(await screen.findByText('not a backup')).toBeInTheDocument()
|
||||
await waitFor(() => expect(screen.getByTitle('Upload Backup')).toBeEnabled())
|
||||
})
|
||||
|
||||
// BKP-020: Upload button forwards the click to the hidden file input
|
||||
it('FE-ADMIN-BKP-020: the Upload button opens the hidden file picker', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<BackupPanel />)
|
||||
await screen.findByText('backup-2025-01-15.zip')
|
||||
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement
|
||||
const clickSpy = vi.spyOn(input, 'click').mockImplementation(() => {})
|
||||
await user.click(screen.getByTitle('Upload Backup'))
|
||||
|
||||
expect(clickSpy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// BKP-021: Delete declined / failing
|
||||
it('FE-ADMIN-BKP-021: declining the confirm keeps the backup, a failing delete toasts', async () => {
|
||||
const user = userEvent.setup()
|
||||
let deleteCalls = 0
|
||||
server.use(
|
||||
http.delete('/api/backup/:filename', () => {
|
||||
deleteCalls += 1
|
||||
return HttpResponse.json({ error: 'file is locked' }, { status: 500 })
|
||||
}),
|
||||
)
|
||||
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false)
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('backup-2025-01-15.zip')
|
||||
|
||||
const trashBtn = Array.from(document.querySelectorAll('button')).find(
|
||||
b => b.querySelector('svg.lucide-trash2'),
|
||||
) as HTMLElement
|
||||
await user.click(trashBtn)
|
||||
expect(deleteCalls).toBe(0)
|
||||
expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument()
|
||||
|
||||
confirmSpy.mockReturnValue(true)
|
||||
await user.click(trashBtn)
|
||||
|
||||
expect(await screen.findByText('Failed to delete')).toBeInTheDocument()
|
||||
expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
// BKP-022: Auto settings save fails
|
||||
it('FE-ADMIN-BKP-022: a failing auto-settings save toasts and keeps the form dirty', async () => {
|
||||
const user = userEvent.setup()
|
||||
server.use(http.put('/api/backup/auto-settings', () => HttpResponse.error()))
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('Enable auto-backup')
|
||||
|
||||
await user.click(getToggleButton())
|
||||
await user.click(screen.getByRole('button', { name: /^save$/i }))
|
||||
|
||||
expect(await screen.findByText('Failed to save settings')).toBeInTheDocument()
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: /^save$/i })).toBeEnabled())
|
||||
})
|
||||
|
||||
// BKP-023: Size/date fallbacks
|
||||
it('FE-ADMIN-BKP-023: missing size and date render as a dash, kilobytes are formatted', async () => {
|
||||
server.use(
|
||||
http.get('/api/backup/list', () =>
|
||||
HttpResponse.json({
|
||||
backups: [
|
||||
{ filename: 'empty.zip', created_at: null, size: 0 },
|
||||
{ filename: 'small.zip', created_at: '2025-03-01T08:00:00Z', size: 5120 },
|
||||
],
|
||||
}),
|
||||
),
|
||||
)
|
||||
render(<BackupPanel />)
|
||||
await screen.findByText('empty.zip')
|
||||
|
||||
expect(screen.getAllByText('-')).toHaveLength(2)
|
||||
expect(screen.getByText('5.0 KB')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
// BKP-024: Invalid server timezone
|
||||
it('FE-ADMIN-BKP-024: an unusable server timezone falls back to the raw timestamp', async () => {
|
||||
server.use(
|
||||
http.get('/api/backup/auto-settings', () =>
|
||||
HttpResponse.json({
|
||||
settings: { enabled: false, interval: 'daily', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 },
|
||||
timezone: 'Not/AZone',
|
||||
}),
|
||||
),
|
||||
)
|
||||
render(<BackupPanel />)
|
||||
await screen.findByText('backup-2025-01-15.zip')
|
||||
|
||||
await waitFor(() => expect(screen.getByText('2025-01-15T10:00:00Z')).toBeInTheDocument())
|
||||
})
|
||||
|
||||
// BKP-025: 12h hour picker
|
||||
it('FE-ADMIN-BKP-025: the hour picker uses AM/PM labels for 12h users and stores the pick', async () => {
|
||||
const user = userEvent.setup()
|
||||
seedStore(useSettingsStore, { settings: { time_format: '12h' } } as any)
|
||||
let saved: Record<string, unknown> | null = null
|
||||
server.use(
|
||||
http.get('/api/backup/auto-settings', () =>
|
||||
HttpResponse.json({
|
||||
settings: { enabled: true, interval: 'daily', keep_days: 7, hour: 0, day_of_week: 0, day_of_month: 1 },
|
||||
timezone: 'UTC',
|
||||
}),
|
||||
),
|
||||
http.put('/api/backup/auto-settings', async ({ request }) => {
|
||||
saved = await request.json() as Record<string, unknown>
|
||||
return HttpResponse.json({ settings: saved })
|
||||
}),
|
||||
)
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('Run at hour')
|
||||
|
||||
expect(screen.getByText('Server local time (12h format) (Timezone: UTC)')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: '12:00 AM' }))
|
||||
await user.click(await screen.findByRole('button', { name: '2:00 PM' }))
|
||||
await user.click(screen.getByRole('button', { name: /^save$/i }))
|
||||
|
||||
await waitFor(() => expect(saved).toMatchObject({ hour: 14 }))
|
||||
})
|
||||
|
||||
// BKP-026: Monthly interval
|
||||
it('FE-ADMIN-BKP-026: the monthly interval offers a day-of-month picker', async () => {
|
||||
const user = userEvent.setup()
|
||||
let saved: Record<string, unknown> | null = null
|
||||
server.use(
|
||||
http.get('/api/backup/auto-settings', () =>
|
||||
HttpResponse.json({
|
||||
settings: { enabled: true, interval: 'monthly', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 },
|
||||
timezone: '',
|
||||
}),
|
||||
),
|
||||
http.put('/api/backup/auto-settings', async ({ request }) => {
|
||||
saved = await request.json() as Record<string, unknown>
|
||||
return HttpResponse.json({ settings: saved })
|
||||
}),
|
||||
)
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('Day of month')
|
||||
|
||||
// No timezone from the server → the hint carries no timezone suffix
|
||||
expect(screen.getByText('Server local time (24h format)')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Sun')).not.toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '1' }))
|
||||
await user.click(await screen.findByRole('button', { name: '15' }))
|
||||
await user.click(screen.getByRole('button', { name: /^save$/i }))
|
||||
|
||||
await waitFor(() => expect(saved).toMatchObject({ day_of_month: 15 }))
|
||||
})
|
||||
|
||||
// BKP-027: Day of week + retention
|
||||
it('FE-ADMIN-BKP-027: day-of-week and retention picks are stored together', async () => {
|
||||
const user = userEvent.setup()
|
||||
let saved: Record<string, unknown> | null = null
|
||||
server.use(
|
||||
http.get('/api/backup/auto-settings', () =>
|
||||
HttpResponse.json({
|
||||
settings: { enabled: true, interval: 'weekly', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 },
|
||||
timezone: 'UTC',
|
||||
}),
|
||||
),
|
||||
http.put('/api/backup/auto-settings', async ({ request }) => {
|
||||
saved = await request.json() as Record<string, unknown>
|
||||
return HttpResponse.json({ settings: saved })
|
||||
}),
|
||||
)
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('Day of week')
|
||||
|
||||
await user.click(screen.getByText('Fri'))
|
||||
await user.click(screen.getByText('Keep forever'))
|
||||
await user.click(screen.getByRole('button', { name: /^save$/i }))
|
||||
|
||||
await waitFor(() => expect(saved).toMatchObject({ day_of_week: 5, keep_days: 0 }))
|
||||
})
|
||||
|
||||
// BKP-028: Download failure
|
||||
it('FE-ADMIN-BKP-028: a failing download toasts the download error', async () => {
|
||||
const user = userEvent.setup()
|
||||
server.use(http.get('/api/backup/download/:filename', () => HttpResponse.error()))
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('backup-2025-01-15.zip')
|
||||
|
||||
await user.click(screen.getByText('Download'))
|
||||
|
||||
expect(await screen.findByText('Download failed')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
// BKP-029: Confirm button hover styling
|
||||
it('FE-ADMIN-BKP-029: the destructive confirm button darkens on hover', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<BackupPanel />)
|
||||
await screen.findByText('backup-2025-01-15.zip')
|
||||
|
||||
await user.click(screen.getAllByText('Restore')[0])
|
||||
const confirmBtn = await screen.findByText('Yes, restore')
|
||||
|
||||
fireEvent.mouseEnter(confirmBtn)
|
||||
expect(confirmBtn.style.background).toBe('rgb(185, 28, 28)')
|
||||
fireEvent.mouseLeave(confirmBtn)
|
||||
expect(confirmBtn.style.background).toBe('rgb(220, 38, 38)')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -191,7 +191,7 @@ export default function BackupPanel() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={loadBackups}
|
||||
disabled={isLoading}
|
||||
className="p-2 text-gray-500 hover:bg-gray-100 rounded-lg transition-colors"
|
||||
@@ -208,7 +208,7 @@ export default function BackupPanel() {
|
||||
className="hidden"
|
||||
onChange={handleUploadRestore}
|
||||
/>
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isUploading}
|
||||
className="flex items-center gap-2 border border-gray-200 text-gray-700 px-3 py-2 rounded-lg hover:bg-gray-50 text-sm font-medium disabled:opacity-60"
|
||||
@@ -222,7 +222,7 @@ export default function BackupPanel() {
|
||||
<span className="hidden sm:inline">{isUploading ? t('backup.uploading') : t('backup.upload')}</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={handleCreate}
|
||||
disabled={isCreating}
|
||||
className="flex items-center gap-2 bg-slate-900 dark:bg-slate-100 text-white dark:text-slate-900 px-3 sm:px-4 py-2 rounded-lg hover:bg-slate-900 text-sm font-medium disabled:opacity-60"
|
||||
@@ -247,7 +247,7 @@ export default function BackupPanel() {
|
||||
<div className="text-center py-12 text-gray-400">
|
||||
<HardDrive className="w-10 h-10 mb-3 mx-auto opacity-40" />
|
||||
<p className="text-sm">{t('backup.empty')}</p>
|
||||
<button onClick={handleCreate} className="mt-4 text-slate-700 text-sm hover:underline">
|
||||
<button type="button" onClick={handleCreate} className="mt-4 text-slate-700 text-sm hover:underline">
|
||||
{t('backup.createFirst')}
|
||||
</button>
|
||||
</div>
|
||||
@@ -274,14 +274,14 @@ export default function BackupPanel() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 flex-shrink-0">
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={() => backupApi.download(backup.filename).catch(() => toast.error(t('backup.toast.downloadError')))}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-slate-700 border border-slate-200 rounded-lg hover:bg-slate-50"
|
||||
>
|
||||
<Download className="w-3.5 h-3.5" />
|
||||
{t('backup.download')}
|
||||
</button>
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={() => handleRestore(backup.filename)}
|
||||
disabled={restoringFile === backup.filename}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-amber-700 border border-amber-200 rounded-lg hover:bg-amber-50 disabled:opacity-60"
|
||||
@@ -292,7 +292,7 @@ export default function BackupPanel() {
|
||||
}
|
||||
{t('backup.restore')}
|
||||
</button>
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={() => handleDelete(backup.filename)}
|
||||
className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg"
|
||||
>
|
||||
@@ -318,11 +318,11 @@ export default function BackupPanel() {
|
||||
<div className="flex flex-col gap-5">
|
||||
{/* Enable toggle */}
|
||||
<label className="flex items-center justify-between gap-4 cursor-pointer">
|
||||
<div className="min-w-0">
|
||||
<span className="text-sm font-medium text-gray-900">{t('backup.auto.enable')}</span>
|
||||
<p className="text-xs text-gray-500 mt-0.5">{t('backup.auto.enableHint')}</p>
|
||||
<div className="min-w-0 text-sm font-medium text-gray-900">
|
||||
{t('backup.auto.enable')}
|
||||
<p className="text-xs font-normal text-gray-500 mt-0.5">{t('backup.auto.enableHint')}</p>
|
||||
</div>
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={() => handleAutoSettingsChange('enabled', !autoSettings.enabled)}
|
||||
className="relative shrink-0 inline-flex h-6 w-11 items-center rounded-full transition-colors"
|
||||
style={{ background: autoSettings.enabled ? 'var(--text-primary)' : 'var(--border-primary)' }}
|
||||
@@ -339,7 +339,7 @@ export default function BackupPanel() {
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">{t('backup.auto.interval')}</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{INTERVAL_OPTIONS.map(opt => (
|
||||
<button
|
||||
<button type="button"
|
||||
key={opt.value}
|
||||
onClick={() => handleAutoSettingsChange('interval', opt.value)}
|
||||
className={`px-4 py-2 rounded-lg text-sm font-medium border transition-colors ${
|
||||
@@ -360,7 +360,7 @@ export default function BackupPanel() {
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">{t('backup.auto.hour')}</label>
|
||||
<CustomSelect
|
||||
value={String(autoSettings.hour)}
|
||||
onChange={v => handleAutoSettingsChange('hour', parseInt(String(v), 10))}
|
||||
onChange={v => handleAutoSettingsChange('hour', Number.parseInt(String(v), 10))}
|
||||
size="sm"
|
||||
options={HOURS.map(h => {
|
||||
let label: string
|
||||
@@ -386,7 +386,7 @@ export default function BackupPanel() {
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">{t('backup.auto.dayOfWeek')}</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{DAYS_OF_WEEK.map(opt => (
|
||||
<button
|
||||
<button type="button"
|
||||
key={opt.value}
|
||||
onClick={() => handleAutoSettingsChange('day_of_week', opt.value)}
|
||||
className={`px-3 py-2 rounded-lg text-sm font-medium border transition-colors ${
|
||||
@@ -408,7 +408,7 @@ export default function BackupPanel() {
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">{t('backup.auto.dayOfMonth')}</label>
|
||||
<CustomSelect
|
||||
value={String(autoSettings.day_of_month)}
|
||||
onChange={v => handleAutoSettingsChange('day_of_month', parseInt(String(v), 10))}
|
||||
onChange={v => handleAutoSettingsChange('day_of_month', Number.parseInt(String(v), 10))}
|
||||
size="sm"
|
||||
options={DAYS_OF_MONTH.map(d => ({ value: String(d), label: String(d) }))}
|
||||
/>
|
||||
@@ -421,7 +421,7 @@ export default function BackupPanel() {
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">{t('backup.auto.keepLabel')}</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{KEEP_OPTIONS.map(opt => (
|
||||
<button
|
||||
<button type="button"
|
||||
key={opt.value}
|
||||
onClick={() => handleAutoSettingsChange('keep_days', opt.value)}
|
||||
className={`px-4 py-2 rounded-lg text-sm font-medium border transition-colors ${
|
||||
@@ -440,7 +440,7 @@ export default function BackupPanel() {
|
||||
|
||||
{/* Save button */}
|
||||
<div className="flex justify-end pt-2 border-t border-gray-100">
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={handleSaveAutoSettings}
|
||||
disabled={autoSettingsSaving || !autoSettingsDirty}
|
||||
className="flex items-center gap-2 bg-slate-900 dark:bg-slate-100 text-white dark:text-slate-900 px-5 py-2 rounded-lg hover:bg-slate-900 text-sm font-medium disabled:opacity-50 transition-colors"
|
||||
@@ -458,11 +458,15 @@ export default function BackupPanel() {
|
||||
{/* Restore Warning Modal */}
|
||||
{restoreConfirm && (
|
||||
<div
|
||||
// Dismiss-on-backdrop is a mouse shortcut for the Cancel button below;
|
||||
// the backdrop itself carries no semantics of its own.
|
||||
role="presentation"
|
||||
className="bg-[rgba(0,0,0,0.5)]"
|
||||
style={{ position: 'fixed', inset: 0, zIndex: 9999, backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}
|
||||
onClick={() => setRestoreConfirm(null)}
|
||||
>
|
||||
<div
|
||||
role="presentation"
|
||||
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"
|
||||
@@ -497,14 +501,14 @@ export default function BackupPanel() {
|
||||
|
||||
{/* Footer */}
|
||||
<div style={{ padding: '0 24px 20px', display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={() => setRestoreConfirm(null)}
|
||||
className="text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700"
|
||||
style={{ padding: '9px 20px', borderRadius: 10, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600, border: 'none', cursor: 'pointer', fontFamily: 'inherit' }}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={executeRestore}
|
||||
className="bg-[#dc2626] text-white"
|
||||
style={{ padding: '9px 20px', borderRadius: 10, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600, border: 'none', cursor: 'pointer', fontFamily: 'inherit' }}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// FE-COMP-CAT-001 to FE-COMP-CAT-012
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
// FE-COMP-CAT-001 to FE-COMP-CAT-020
|
||||
import { render, screen, waitFor, fireEvent, within } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
@@ -27,17 +27,17 @@ describe('CategoryManager', () => {
|
||||
|
||||
it('FE-COMP-CAT-002: shows Categories title', async () => {
|
||||
render(<CategoryManager />);
|
||||
await screen.findByText('Categories');
|
||||
expect(await screen.findByText('Categories')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CAT-003: shows empty state when no categories', async () => {
|
||||
render(<CategoryManager />);
|
||||
await screen.findByText('No categories yet');
|
||||
expect(await screen.findByText('No categories yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CAT-004: shows New Category button', async () => {
|
||||
render(<CategoryManager />);
|
||||
await screen.findByText('New Category');
|
||||
expect(await screen.findByText('New Category')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CAT-005: clicking New Category shows form', async () => {
|
||||
@@ -129,7 +129,7 @@ describe('CategoryManager', () => {
|
||||
|
||||
it('FE-COMP-CAT-010: shows subtitle text', async () => {
|
||||
render(<CategoryManager />);
|
||||
await screen.findByText('Manage categories for places');
|
||||
expect(await screen.findByText('Manage categories for places')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CAT-011: category count is shown', async () => {
|
||||
@@ -156,4 +156,148 @@ describe('CategoryManager', () => {
|
||||
await user.click(screen.getByText('Cancel'));
|
||||
expect(screen.queryByPlaceholderText('Category name')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CAT-013: a failing list request toasts and falls back to the empty state', async () => {
|
||||
server.use(http.get('/api/categories', () => HttpResponse.error()));
|
||||
render(<><ToastContainer /><CategoryManager /></>);
|
||||
|
||||
expect(await screen.findByText('Failed to load categories')).toBeInTheDocument();
|
||||
expect(screen.getByText('No categories yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CAT-014: editing a category sends a PUT and replaces the row', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: Record<string, unknown> | null = null;
|
||||
server.use(
|
||||
http.get('/api/categories', () =>
|
||||
HttpResponse.json({ categories: [buildCategory({ id: 5, name: 'Hotels', color: '#6366f1', icon: 'MapPin' })] })
|
||||
),
|
||||
http.put('/api/categories/5', async ({ request }) => {
|
||||
body = await request.json() as Record<string, unknown>;
|
||||
return HttpResponse.json({ category: buildCategory({ id: 5, name: 'Lodging', color: '#ef4444', icon: 'BedDouble' }) });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><CategoryManager /></>);
|
||||
await screen.findByText('Hotels');
|
||||
|
||||
await user.click(screen.getAllByRole('button').filter(b => !b.textContent?.includes('New Category'))[0]);
|
||||
const nameInput = screen.getByDisplayValue('Hotels');
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'Lodging');
|
||||
await user.click(screen.getByTitle('Hotel'));
|
||||
await user.click(screen.getByText('Update'));
|
||||
|
||||
expect(await screen.findByText('Category updated')).toBeInTheDocument();
|
||||
expect(body).toEqual({ name: 'Lodging', color: '#6366f1', icon: 'BedDouble' });
|
||||
expect(screen.getByText('Lodging')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CAT-015: a failing save surfaces the server message', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('/api/categories', () => HttpResponse.json({ error: 'name already taken' }, { status: 409 })),
|
||||
);
|
||||
render(<><ToastContainer /><CategoryManager /></>);
|
||||
await screen.findByText('New Category');
|
||||
|
||||
await user.click(screen.getByText('New Category'));
|
||||
await user.type(screen.getByPlaceholderText('Category name'), 'Parks');
|
||||
await user.click(screen.getByText('Create'));
|
||||
|
||||
expect(await screen.findByText('name already taken')).toBeInTheDocument();
|
||||
// The form stays open so the name can be corrected
|
||||
expect(screen.getByDisplayValue('Parks')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CAT-016: declining the delete confirm keeps the category', async () => {
|
||||
const user = userEvent.setup();
|
||||
let deleteCalled = false;
|
||||
server.use(
|
||||
http.get('/api/categories', () => HttpResponse.json({ categories: [buildCategory({ id: 9, name: 'Parks' })] })),
|
||||
http.delete('/api/categories/9', () => { deleteCalled = true; return HttpResponse.json({ success: true }); }),
|
||||
);
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(false);
|
||||
render(<CategoryManager />);
|
||||
await screen.findByText('Parks');
|
||||
|
||||
const actionBtns = screen.getAllByRole('button').filter(b => !b.textContent?.includes('New Category'));
|
||||
await user.click(actionBtns[1]);
|
||||
|
||||
expect(deleteCalled).toBe(false);
|
||||
expect(screen.getByText('Parks')).toBeInTheDocument();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('FE-COMP-CAT-017: a failing delete toasts and keeps the row', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/categories', () => HttpResponse.json({ categories: [buildCategory({ id: 9, name: 'Parks' })] })),
|
||||
http.delete('/api/categories/9', () => HttpResponse.json({ error: 'category in use' }, { status: 409 })),
|
||||
);
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
render(<><ToastContainer /><CategoryManager /></>);
|
||||
await screen.findByText('Parks');
|
||||
|
||||
const actionBtns = screen.getAllByRole('button').filter(b => !b.textContent?.includes('New Category'));
|
||||
await user.click(actionBtns[1]);
|
||||
|
||||
expect(await screen.findByText('category in use')).toBeInTheDocument();
|
||||
expect(screen.getByText('Parks')).toBeInTheDocument();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('FE-COMP-CAT-018: picking an icon and a preset colour updates the live preview', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<CategoryManager />);
|
||||
await screen.findByText('New Category');
|
||||
await user.click(screen.getByText('New Category'));
|
||||
|
||||
// Empty name → the preview falls back to the generic label
|
||||
expect(screen.getByText('Category')).toBeInTheDocument();
|
||||
await user.type(screen.getByPlaceholderText('Category name'), 'Beach day');
|
||||
await user.click(screen.getByTitle('Beach'));
|
||||
|
||||
const preview = screen.getByText('Beach day');
|
||||
expect(preview).toHaveStyle({ color: '#6366f1' });
|
||||
|
||||
await user.click(document.querySelectorAll('button[style*="background-color: rgb(239, 68, 68)"]')[0]);
|
||||
expect(screen.getByText('Beach day')).toHaveStyle({ color: '#ef4444' });
|
||||
});
|
||||
|
||||
it('FE-COMP-CAT-019: the custom colour swatch opens the native picker and adopts its value', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<CategoryManager />);
|
||||
await screen.findByText('New Category');
|
||||
await user.click(screen.getByText('New Category'));
|
||||
|
||||
const colorInput = document.querySelector('input[type="color"]') as HTMLInputElement;
|
||||
const clickSpy = vi.spyOn(colorInput, 'click').mockImplementation(() => {});
|
||||
await user.click(screen.getByTitle('Choose custom color'));
|
||||
expect(clickSpy).toHaveBeenCalled();
|
||||
|
||||
fireEvent.change(colorInput, { target: { value: '#123456' } });
|
||||
await waitFor(() => expect(screen.getByText('Category')).toHaveStyle({ color: '#123456' }));
|
||||
// A non-preset colour fills the custom swatch instead of showing the pipette
|
||||
expect(screen.getByTitle('Choose custom color')).toHaveStyle({ backgroundColor: '#123456' });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('FE-COMP-CAT-020: starting an edit closes the create form', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/categories', () => HttpResponse.json({ categories: [buildCategory({ id: 3, name: 'Hotels' })] })),
|
||||
);
|
||||
render(<CategoryManager />);
|
||||
await screen.findByText('Hotels');
|
||||
|
||||
await user.click(screen.getByText('New Category'));
|
||||
expect(screen.getByPlaceholderText('Category name')).toHaveValue('');
|
||||
|
||||
const row = screen.getByText('Hotels').closest('.p-3') as HTMLElement;
|
||||
await user.click(within(row).getAllByRole('button')[0]);
|
||||
|
||||
// Only the inline edit form remains, pre-filled with the row's name
|
||||
expect(screen.getAllByPlaceholderText('Category name')).toHaveLength(1);
|
||||
expect(screen.getByDisplayValue('Hotels')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -56,8 +56,8 @@ export default function CategoryManager() {
|
||||
setEditingId(null)
|
||||
}
|
||||
|
||||
// The Save button carries disabled={… || !form.name.trim()}, so the name is set here.
|
||||
const handleSave = async () => {
|
||||
if (!form.name.trim()) { toast.error(t('categories.toast.nameRequired')); return }
|
||||
setIsSaving(true)
|
||||
try {
|
||||
if (editingId) {
|
||||
@@ -194,7 +194,7 @@ export default function CategoryManager() {
|
||||
<h2 className="font-semibold text-content">{t('categories.title')}</h2>
|
||||
<p className="text-xs mt-1 text-content-muted">{t('categories.subtitle')}</p>
|
||||
</div>
|
||||
<button onClick={handleStartCreate}
|
||||
<button type="button" onClick={handleStartCreate}
|
||||
className="flex items-center gap-2 bg-slate-900 text-white px-3 sm:px-4 py-2 rounded-lg hover:bg-slate-700 text-sm font-medium">
|
||||
<Plus className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">{t('categories.new')}</span>
|
||||
@@ -235,11 +235,11 @@ export default function CategoryManager() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<button onClick={() => handleStartEdit(cat)}
|
||||
<button type="button" onClick={() => handleStartEdit(cat)}
|
||||
className="p-1.5 text-gray-400 hover:text-slate-700 hover:bg-slate-100 rounded-lg">
|
||||
<Edit2 className="w-4 h-4" />
|
||||
</button>
|
||||
<button onClick={() => handleDelete(cat.id)}
|
||||
<button type="button" onClick={() => handleDelete(cat.id)}
|
||||
className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-027
|
||||
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildAdmin } from '../../../tests/helpers/factories';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import DefaultUserSettingsTab from './DefaultUserSettingsTab';
|
||||
|
||||
// The tile preview would pull Leaflet into jsdom; the panel only needs it to render.
|
||||
vi.mock('../Map/MapView', () => ({
|
||||
MapView: ({ tileUrl }: { tileUrl?: string }) => <div data-testid="map-preview" data-tile={tileUrl} />,
|
||||
}));
|
||||
|
||||
const MAPBOX_STANDARD = 'mapbox://styles/mapbox/standard';
|
||||
const MAPBOX_DARK = 'mapbox://styles/mapbox/dark-v11';
|
||||
const MAPBOX_NAV_NIGHT = 'mapbox://styles/mapbox/navigation-night-v1';
|
||||
const OFM_LIBERTY = 'https://tiles.openfreemap.org/styles/liberty';
|
||||
const TILE_PLACEHOLDER = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
|
||||
|
||||
/** Stateful stand-in for the admin defaults endpoint: PUT merges, null deletes. */
|
||||
function stubDefaults(initial: Record<string, unknown> = {}) {
|
||||
const state: Record<string, unknown> = { ...initial };
|
||||
const puts: Record<string, unknown>[] = [];
|
||||
server.use(
|
||||
http.get('/api/admin/default-user-settings', () => HttpResponse.json(state)),
|
||||
http.put('/api/admin/default-user-settings', async ({ request }) => {
|
||||
const body = await request.json() as Record<string, unknown>;
|
||||
puts.push(body);
|
||||
for (const [key, value] of Object.entries(body)) {
|
||||
if (value === null) delete state[key];
|
||||
else state[key] = value;
|
||||
}
|
||||
return HttpResponse.json({ ...state });
|
||||
}),
|
||||
);
|
||||
return { puts, state };
|
||||
}
|
||||
|
||||
function withToast() {
|
||||
return render(<><ToastContainer /><DefaultUserSettingsTab /></>);
|
||||
}
|
||||
|
||||
/** The selected option button is the one drawn with the strong border token. */
|
||||
function isActive(button: HTMLElement): boolean {
|
||||
return (button.style.border || '').includes('var(--text-primary)');
|
||||
}
|
||||
|
||||
/**
|
||||
* The reset link sits inside the field's own <label>; because a button is a labelable
|
||||
* element the wrapping label becomes its accessible name, so it is queried positionally.
|
||||
*/
|
||||
function resetLink(label: string): HTMLElement {
|
||||
const el = screen.getAllByText(label).find(node => node.tagName === 'LABEL');
|
||||
if (!el) throw new Error(`no label found for ${label}`);
|
||||
return within(el).getByRole('button');
|
||||
}
|
||||
|
||||
function hasResetLink(label: string): boolean {
|
||||
const el = screen.getAllByText(label).find(node => node.tagName === 'LABEL');
|
||||
return !!el && within(el).queryByRole('button') !== null;
|
||||
}
|
||||
|
||||
/** The CARTO key input sits under its label inside the field's own wrapper. */
|
||||
function cartoInput(): HTMLInputElement {
|
||||
return within(screen.getByText('Shared CARTO key').closest('div') as HTMLElement).getByRole('textbox');
|
||||
}
|
||||
|
||||
/** Opens a CustomSelect by its trigger label and picks an option from the portal. */
|
||||
async function pickFromSelect(user: ReturnType<typeof userEvent.setup>, trigger: string, option: string) {
|
||||
await user.click(screen.getByRole('button', { name: trigger }));
|
||||
const choices = await screen.findAllByRole('button', { name: option });
|
||||
await user.click(choices[choices.length - 1]);
|
||||
}
|
||||
|
||||
describe('DefaultUserSettingsTab', () => {
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
|
||||
stubDefaults();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-001: shows the loading placeholder until the defaults arrive', async () => {
|
||||
render(<DefaultUserSettingsTab />);
|
||||
expect(screen.getByText('Loading…')).toBeInTheDocument();
|
||||
|
||||
expect(await screen.findByText('Default User Settings')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Loading…')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-002: renders every field with no reset links while nothing is set', async () => {
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
for (const name of ['Light', 'Dark', 'Auto', '°C Celsius', 'km Metric', '24h (14:30)', 'On', 'Off']) {
|
||||
expect(isActive(screen.getByRole('button', { name }))).toBe(false);
|
||||
}
|
||||
for (const label of ['Color Mode', 'Temperature Unit', 'Distance Unit', 'Time Format', 'Display currency', 'Map Template']) {
|
||||
expect(hasResetLink(label)).toBe(false);
|
||||
}
|
||||
expect(screen.getByTestId('map-preview')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-003: a failing load still renders the panel with built-in defaults', async () => {
|
||||
server.use(http.get('/api/admin/default-user-settings', () => HttpResponse.json({}, { status: 500 })));
|
||||
render(<DefaultUserSettingsTab />);
|
||||
|
||||
expect(await screen.findByText('Default User Settings')).toBeInTheDocument();
|
||||
expect(hasResetLink('Map engine')).toBe(false);
|
||||
expect(isActive(screen.getByRole('button', { name: 'Standard (free)' }))).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-004: picking a colour mode saves it and confirms with a toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
withToast();
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Dark' }));
|
||||
|
||||
expect(await screen.findByText('Default saved')).toBeInTheDocument();
|
||||
expect(puts).toEqual([{ dark_mode: 'dark' }]);
|
||||
await waitFor(() => expect(isActive(screen.getByRole('button', { name: 'Dark' }))).toBe(true));
|
||||
expect(resetLink('Color Mode')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-005: a legacy boolean dark_mode still highlights the matching option', async () => {
|
||||
stubDefaults({ dark_mode: true });
|
||||
const { unmount } = render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
expect(isActive(screen.getByRole('button', { name: 'Dark' }))).toBe(true);
|
||||
expect(isActive(screen.getByRole('button', { name: 'Light' }))).toBe(false);
|
||||
unmount();
|
||||
|
||||
stubDefaults({ dark_mode: false });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
expect(isActive(screen.getByRole('button', { name: 'Light' }))).toBe(true);
|
||||
expect(isActive(screen.getByRole('button', { name: 'Auto' }))).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-006: unit and time-format options each save their own key', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '°F Fahrenheit' }));
|
||||
await waitFor(() => expect(resetLink('Temperature Unit')).toBeInTheDocument());
|
||||
await user.click(screen.getByRole('button', { name: 'mi Imperial' }));
|
||||
await waitFor(() => expect(resetLink('Distance Unit')).toBeInTheDocument());
|
||||
await user.click(screen.getByRole('button', { name: '12h (2:30 PM)' }));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([
|
||||
{ temperature_unit: 'fahrenheit' },
|
||||
{ distance_unit: 'imperial' },
|
||||
{ time_format: '12h' },
|
||||
]));
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-007: a set default gets a reset link that clears it server-side', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts, state } = stubDefaults({ temperature_unit: 'celsius' });
|
||||
withToast();
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
expect(isActive(screen.getByRole('button', { name: '°C Celsius' }))).toBe(true);
|
||||
await user.click(resetLink('Temperature Unit'));
|
||||
|
||||
expect(await screen.findByText('Reset to built-in default')).toBeInTheDocument();
|
||||
expect(puts).toEqual([{ temperature_unit: null }]);
|
||||
expect(state.temperature_unit).toBeUndefined();
|
||||
await waitFor(() => expect(hasResetLink('Temperature Unit')).toBe(false));
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-008: the currency picker saves the chosen code and can be reset', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ default_currency: 'USD' });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await pickFromSelect(user, 'USD $', 'EUR €');
|
||||
await waitFor(() => expect(puts).toEqual([{ default_currency: 'EUR' }]));
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'EUR €' })).toBeInTheDocument());
|
||||
|
||||
await user.click(resetLink('Display currency'));
|
||||
await waitFor(() => expect(puts).toHaveLength(2));
|
||||
expect(puts[1]).toEqual({ default_currency: null });
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-009: the blur-booking-codes options save booleans', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'On' }));
|
||||
await waitFor(() => expect(isActive(screen.getByRole('button', { name: 'On' }))).toBe(true));
|
||||
await user.click(screen.getByRole('button', { name: 'Off' }));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([
|
||||
{ blur_booking_codes: true },
|
||||
{ blur_booking_codes: false },
|
||||
]));
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-010: the tile preset dropdown fills the URL field and hands it to the preview', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await pickFromSelect(user, 'Select template...', 'CartoDB Dark');
|
||||
|
||||
const url = 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png';
|
||||
await waitFor(() => expect(puts).toEqual([{ map_tile_url: url }]));
|
||||
expect(screen.getByPlaceholderText(TILE_PLACEHOLDER)).toHaveValue(url);
|
||||
expect(screen.getByTestId('map-preview')).toHaveAttribute('data-tile', url);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-011: a hand-typed tile URL is saved on blur', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
const input = screen.getByPlaceholderText(TILE_PLACEHOLDER);
|
||||
// userEvent reads {...} as key descriptors, so the placeholders are omitted here
|
||||
await user.type(input, 'https://tiles.example.org/tile.png');
|
||||
fireEvent.blur(input);
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ map_tile_url: 'https://tiles.example.org/tile.png' }]));
|
||||
expect(screen.getByTestId('map-preview')).toHaveAttribute('data-tile', 'https://tiles.example.org/tile.png');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-012: resetting the tile URL clears the input too', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
expect(screen.getByRole('button', { name: 'OpenStreetMap DE' })).toBeInTheDocument();
|
||||
await user.click(resetLink('Map Template'));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ map_tile_url: null }]));
|
||||
await waitFor(() => expect(screen.getByPlaceholderText(TILE_PLACEHOLDER)).toHaveValue(''));
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-013: leaflet hides the GL-only token and style fields', async () => {
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
expect(isActive(screen.getByRole('button', { name: 'Standard (free)' }))).toBe(true);
|
||||
expect(screen.queryByText('Map style')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Shared Mapbox token')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-014: switching to Mapbox stores the provider with its own style slot', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Mapbox (3D)' }));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_STANDARD }]));
|
||||
expect(await screen.findByText('Shared Mapbox token')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue(MAPBOX_STANDARD)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-015: switching to MapLibre stores the OpenFreeMap default and hides the token field', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'MapLibre (OpenFreeMap)' }));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ map_provider: 'maplibre-gl', maplibre_style: OFM_LIBERTY }]));
|
||||
expect(await screen.findByText('Map style')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Shared Mapbox token')).not.toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue(OFM_LIBERTY)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-016: switching back to the standard engine only stores the provider', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_STANDARD });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Map style');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Standard (free)' }));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ map_provider: 'leaflet' }]));
|
||||
await waitFor(() => expect(screen.queryByText('Map style')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-017: a Mapbox default holding an OpenFreeMap style falls back to the Mapbox standard', async () => {
|
||||
stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: OFM_LIBERTY });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Map style');
|
||||
|
||||
expect(screen.getByDisplayValue(MAPBOX_STANDARD)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-018: a stored Mapbox style survives while the standard engine is active', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_provider: 'leaflet', mapbox_style: MAPBOX_DARK });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
expect(screen.queryByText('Map style')).not.toBeInTheDocument();
|
||||
// Switching to Mapbox re-uses the stored slot instead of resetting it
|
||||
await user.click(screen.getByRole('button', { name: 'Mapbox (3D)' }));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_DARK }]));
|
||||
expect(screen.getByDisplayValue(MAPBOX_DARK)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-019: the shared Mapbox token is stored on blur and cleared by its reset link', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.old' });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Shared Mapbox token');
|
||||
|
||||
const input = screen.getByPlaceholderText('pk.eyJ…');
|
||||
expect(input).toHaveValue('pk.old');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'pk.new');
|
||||
fireEvent.blur(input);
|
||||
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }]));
|
||||
|
||||
// Clicking the reset link also blurs the field again, so only the last PUT is checked
|
||||
await user.click(resetLink('Shared Mapbox token'));
|
||||
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ mapbox_access_token: null }));
|
||||
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-020: a hand-typed MapLibre style is normalised to OpenFreeMap on blur', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_provider: 'maplibre-gl', maplibre_style: OFM_LIBERTY });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Map style');
|
||||
|
||||
const input = screen.getByDisplayValue(OFM_LIBERTY);
|
||||
await user.clear(input);
|
||||
await user.type(input, 'https://example.com/custom.json');
|
||||
fireEvent.blur(input);
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ maplibre_style: OFM_LIBERTY }]));
|
||||
expect(input).toHaveValue(OFM_LIBERTY);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-021: the style dropdown writes the picked preset into the active provider slot', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_STANDARD });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Map style');
|
||||
|
||||
await pickFromSelect(user, 'Mapbox Standard', 'Navigation Night');
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ mapbox_style: MAPBOX_NAV_NIGHT }]));
|
||||
expect(screen.getByDisplayValue(MAPBOX_NAV_NIGHT)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-022: resetting the style restores the provider default in the field', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_DARK });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Map style');
|
||||
|
||||
await user.click(resetLink('Map style'));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ mapbox_style: null }]));
|
||||
await waitFor(() => expect(screen.getByDisplayValue(MAPBOX_STANDARD)).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-023: the Mapbox 3D and quality options start on their built-in defaults and save their own keys', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_STANDARD });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('3D buildings & terrain');
|
||||
|
||||
// 3D defaults to on, quality mode to off when neither is stored
|
||||
const threeD = within(screen.getByText('3D buildings & terrain').closest('div') as HTMLElement);
|
||||
expect(isActive(threeD.getByRole('button', { name: 'On' }))).toBe(true);
|
||||
const quality = within(screen.getByText('High-quality mode').closest('div') as HTMLElement);
|
||||
expect(isActive(quality.getByRole('button', { name: 'Off' }))).toBe(true);
|
||||
|
||||
await user.click(threeD.getByRole('button', { name: 'Off' }));
|
||||
await waitFor(() => expect(puts).toEqual([{ mapbox_3d_enabled: false }]));
|
||||
await user.click(quality.getByRole('button', { name: 'On' }));
|
||||
await waitFor(() => expect(puts).toHaveLength(2));
|
||||
expect(puts[1]).toEqual({ mapbox_quality_mode: true });
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-024: a rejected save surfaces the request error instead of a success toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/admin/default-user-settings', () => HttpResponse.json({})),
|
||||
http.put('/api/admin/default-user-settings', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
|
||||
);
|
||||
withToast();
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Dark' }));
|
||||
|
||||
expect(await screen.findByText(/Request failed with status code 500/)).toBeInTheDocument();
|
||||
expect(screen.queryByText('Default saved')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-025: a rejected reset surfaces the request error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/admin/default-user-settings', () => HttpResponse.json({ time_format: '12h' })),
|
||||
http.put('/api/admin/default-user-settings', () => HttpResponse.json({ error: 'nope' }, { status: 503 })),
|
||||
);
|
||||
withToast();
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(resetLink('Time Format'));
|
||||
|
||||
expect(await screen.findByText(/Request failed with status code 503/)).toBeInTheDocument();
|
||||
expect(screen.queryByText('Reset to built-in default')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-026: the shared CARTO key is stored on blur and cleared by its reset link', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ carto_api_key: 'ck.old' });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Shared CARTO key');
|
||||
|
||||
const input = cartoInput();
|
||||
expect(input).toHaveValue('ck.old');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'ck.new');
|
||||
fireEvent.blur(input);
|
||||
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }]));
|
||||
|
||||
// Clicking the reset link also blurs the field again, so only the last PUT is checked
|
||||
await user.click(resetLink('Shared CARTO key'));
|
||||
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ carto_api_key: null }));
|
||||
await waitFor(() => expect(cartoInput()).toHaveValue(''));
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-027: a managed instance hides the shared CARTO key field', async () => {
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin(), managed: true });
|
||||
stubDefaults({ carto_api_key: 'ck.hoster' });
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
expect(screen.queryByText('Shared CARTO key')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import CustomSelect from '../shared/CustomSelect'
|
||||
import { MapView } from '../Map/MapView'
|
||||
import { SYMBOLS, currenciesWith } from '../Budget/BudgetPanel.constants'
|
||||
import type { DistanceUnit, Place } from '../../types'
|
||||
import { normalizeTileUrl } from '../../utils/tileUrl'
|
||||
import {
|
||||
MAPBOX_DEFAULT_STYLE,
|
||||
defaultStyleForProvider,
|
||||
@@ -17,9 +18,10 @@ import {
|
||||
styleSettingKey,
|
||||
type GlMapProvider,
|
||||
} from '../Map/glProviders'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
|
||||
const MAP_PRESETS = [
|
||||
{ name: 'OpenStreetMap', url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' },
|
||||
{ name: 'OpenStreetMap', url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png' },
|
||||
{ name: 'OpenStreetMap DE', url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' },
|
||||
{ name: 'CartoDB Light', url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png' },
|
||||
{ name: 'CartoDB Dark', url: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png' },
|
||||
@@ -34,6 +36,7 @@ type Defaults = {
|
||||
default_currency?: string
|
||||
blur_booking_codes?: boolean
|
||||
map_tile_url?: string
|
||||
carto_api_key?: string
|
||||
map_provider?: string
|
||||
mapbox_access_token?: string
|
||||
mapbox_style?: string
|
||||
@@ -48,8 +51,8 @@ function normalizeProvider(value: unknown): MapProvider {
|
||||
return value === 'mapbox-gl' || value === 'maplibre-gl' ? value : 'leaflet'
|
||||
}
|
||||
|
||||
function styleForProvider(provider: MapProvider, style?: string | null): string {
|
||||
if (provider === 'leaflet') return style || MAPBOX_DEFAULT_STYLE
|
||||
/** Only the GL providers keep a style — Leaflet is handled by its callers. */
|
||||
function styleForProvider(provider: GlMapProvider, style?: string | null): string {
|
||||
if (provider === 'mapbox-gl' && isOpenFreeMapStyle(style)) return MAPBOX_DEFAULT_STYLE
|
||||
return normalizeStyleForProvider(provider, style)
|
||||
}
|
||||
@@ -84,7 +87,7 @@ function OptionButton({
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={onClick}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 8,
|
||||
@@ -107,15 +110,18 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
|
||||
const [defaults, setDefaults] = useState<Defaults>({})
|
||||
const [loaded, setLoaded] = useState(false)
|
||||
const [mapTileUrl, setMapTileUrl] = useState('')
|
||||
const managed = useAuthStore((s) => s.managed)
|
||||
const [mapboxToken, setMapboxToken] = useState('')
|
||||
const [cartoKey, setCartoKey] = useState('')
|
||||
const [mapboxStyle, setMapboxStyle] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
adminApi.getDefaultUserSettings().then((data: Defaults) => {
|
||||
const provider = normalizeProvider(data.map_provider)
|
||||
setDefaults(data)
|
||||
setMapTileUrl(data.map_tile_url || '')
|
||||
setMapTileUrl(normalizeTileUrl(data.map_tile_url || ''))
|
||||
setMapboxToken(data.mapbox_access_token || '')
|
||||
setCartoKey(data.carto_api_key || '')
|
||||
setMapboxStyle(provider === 'leaflet' ? (data.mapbox_style || '') : styleForProvider(provider, provider === 'maplibre-gl' ? data.maplibre_style : data.mapbox_style))
|
||||
setLoaded(true)
|
||||
}).catch(() => setLoaded(true))
|
||||
@@ -137,6 +143,7 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
|
||||
setDefaults(updated)
|
||||
if (key === 'map_tile_url') setMapTileUrl('')
|
||||
if (key === 'mapbox_access_token') setMapboxToken('')
|
||||
if (key === 'carto_api_key') setCartoKey('')
|
||||
if (key === 'mapbox_style' || key === 'maplibre_style') {
|
||||
const provider = normalizeProvider(defaults.map_provider)
|
||||
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider))
|
||||
@@ -151,7 +158,7 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
|
||||
|
||||
const ResetButton = ({ field }: { field: keyof Defaults }) =>
|
||||
isSet(field) ? (
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={() => reset(field)}
|
||||
className="text-xs ml-2 text-content-faint underline"
|
||||
style={{ background: 'none', border: 'none', cursor: 'pointer' }}
|
||||
@@ -182,7 +189,7 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
|
||||
transport_mode: null,
|
||||
website: null,
|
||||
phone: null,
|
||||
created_at: Date(),
|
||||
created_at: String(new Date()),
|
||||
}], [])
|
||||
|
||||
if (!loaded) {
|
||||
@@ -328,10 +335,30 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
|
||||
value={mapTileUrl}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMapTileUrl(e.target.value)}
|
||||
onBlur={() => save({ map_tile_url: mapTileUrl })}
|
||||
placeholder="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
|
||||
placeholder="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
|
||||
/>
|
||||
<p className="text-xs mt-1 text-content-faint">{t('settings.mapDefaultHint')}</p>
|
||||
{/* The key comes with the instance on a managed install, injected when the
|
||||
settings are read. A field here would only let somebody save a worse one. */}
|
||||
{!managed && (
|
||||
<div style={{ marginTop: 14 }}>
|
||||
<label className="block text-sm font-medium mb-1.5 text-content-secondary">
|
||||
{t('admin.defaultSettings.cartoKey')}
|
||||
<ResetButton field="carto_api_key" />
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={cartoKey}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setCartoKey(e.target.value)}
|
||||
onBlur={() => save({ carto_api_key: cartoKey })}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
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 mt-1 text-content-faint">{t('admin.defaultSettings.cartoKeyHint')}</p>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ position: 'relative', height: '200px', width: '100%', marginTop: 12 }}>
|
||||
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
|
||||
{React.createElement(MapView as any, {
|
||||
@@ -378,7 +405,9 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
|
||||
|
||||
{mapProvider !== 'leaflet' && (
|
||||
<div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 18 }}>
|
||||
{mapProvider === 'mapbox-gl' && (
|
||||
{/* The token comes with the instance on a managed install, injected when the
|
||||
settings are read. A field here would only let somebody save a worse one. */}
|
||||
{mapProvider === 'mapbox-gl' && !managed && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1.5 text-content-secondary">
|
||||
{t('admin.defaultSettings.mapboxToken')}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// FE-ADMIN-DEVNOTIF-001 to FE-ADMIN-DEVNOTIF-010
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
// FE-ADMIN-DEVNOTIF-001 to FE-ADMIN-DEVNOTIF-016
|
||||
import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
@@ -87,7 +87,7 @@ describe('DevNotificationsPanel', () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
await screen.findByText('Sent: simple-me');
|
||||
expect(await screen.findByText('Sent: simple-me')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-007: all buttons disabled while a send is in-flight', async () => {
|
||||
@@ -101,8 +101,8 @@ describe('DevNotificationsPanel', () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
|
||||
// Fire the click but do not await — handler never resolves so sending stays true
|
||||
void user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
// The request handler never resolves, so sending stays true after the click settles
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
|
||||
await waitFor(() => {
|
||||
const buttons = screen.getAllByRole('button');
|
||||
@@ -110,7 +110,20 @@ describe('DevNotificationsPanel', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-008: error toast shown on API failure', async () => {
|
||||
it('FE-ADMIN-DEVNOTIF-008: the server error field is what the toast shows', async () => {
|
||||
server.use(
|
||||
http.post('/api/admin/dev/test-notification', () =>
|
||||
HttpResponse.json({ error: 'No channel configured' }, { status: 500 }),
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
expect(await screen.findByText('No channel configured')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-008b: a failure without an error field falls back to the generic text', async () => {
|
||||
server.use(
|
||||
http.post('/api/admin/dev/test-notification', () =>
|
||||
HttpResponse.json({ message: 'Server error' }, { status: 500 }),
|
||||
@@ -120,7 +133,7 @@ describe('DevNotificationsPanel', () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
await screen.findByText(/failed|error/i);
|
||||
expect(await screen.findByText('Failed')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-009: changing trip selector updates payload targetId', async () => {
|
||||
@@ -157,4 +170,141 @@ describe('DevNotificationsPanel', () => {
|
||||
await screen.findByText('User-Scoped Events');
|
||||
expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-011: the remaining self/admin type buttons each fire their own event', async () => {
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
server.use(
|
||||
http.post('/api/admin/dev/test-notification', async ({ request }) => {
|
||||
bodies.push(await request.json() as Record<string, unknown>);
|
||||
return HttpResponse.json({ ok: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
|
||||
await user.click(screen.getByText('Boolean → Me').closest('button')!);
|
||||
await screen.findByText('Sent: boolean-me');
|
||||
await user.click(screen.getByText('Navigate → Me').closest('button')!);
|
||||
await screen.findByText('Sent: navigate-me');
|
||||
await user.click(screen.getByText('Simple → All Admins').closest('button')!);
|
||||
await screen.findByText('Sent: simple-admins');
|
||||
await user.click(screen.getByText('version_available').closest('button')!);
|
||||
await screen.findByText('Sent: version_available');
|
||||
|
||||
expect(bodies[0]).toMatchObject({
|
||||
event: 'test_boolean',
|
||||
scope: 'user',
|
||||
targetId: ADMIN_USER.id,
|
||||
inApp: {
|
||||
type: 'boolean',
|
||||
positiveCallback: { action: 'test_approve', payload: {} },
|
||||
negativeCallback: { action: 'test_deny', payload: {} },
|
||||
},
|
||||
});
|
||||
expect(bodies[1]).toMatchObject({ event: 'test_navigate', scope: 'user', targetId: ADMIN_USER.id });
|
||||
expect(bodies[2]).toMatchObject({ event: 'test_simple', scope: 'admin', targetId: 0 });
|
||||
expect(bodies[3]).toMatchObject({ event: 'version_available', scope: 'admin', targetId: 0, params: { version: '9.9.9-test' } });
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-012: every trip-scoped button carries the selected trip and the actor', async () => {
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
server.use(
|
||||
http.post('/api/admin/dev/test-notification', async ({ request }) => {
|
||||
bodies.push(await request.json() as Record<string, unknown>);
|
||||
return HttpResponse.json({ ok: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
|
||||
const [tripSelect] = screen.getAllByRole('combobox');
|
||||
const tripId = Number((tripSelect as HTMLSelectElement).value);
|
||||
|
||||
for (const label of ['trip_reminder', 'photos_shared', 'collab_message', 'packing_tagged']) {
|
||||
await user.click(screen.getByText(label).closest('button')!);
|
||||
await screen.findByText(`Sent: ${label}`);
|
||||
}
|
||||
|
||||
expect(bodies.map(b => b.event)).toEqual(['trip_reminder', 'photos_shared', 'collab_message', 'packing_tagged']);
|
||||
for (const body of bodies) {
|
||||
expect(body.scope).toBe('trip');
|
||||
expect(body.targetId).toBe(tripId);
|
||||
expect(body.params).toMatchObject({ trip: 'Paris Adventure', tripId: String(tripId) });
|
||||
}
|
||||
expect(bodies[1].params).toMatchObject({ actor: 'testadmin', count: '5' });
|
||||
expect(bodies[2].params).toMatchObject({ preview: 'This is a test message preview.' });
|
||||
expect(bodies[3].params).toMatchObject({ category: 'Clothing' });
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-013: user-scoped events target the picked recipient', async () => {
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
server.use(
|
||||
http.post('/api/admin/dev/test-notification', async ({ request }) => {
|
||||
bodies.push(await request.json() as Record<string, unknown>);
|
||||
return HttpResponse.json({ ok: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('User-Scoped Events');
|
||||
|
||||
const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement;
|
||||
const aliceOption = Array.from(userSelect.querySelectorAll('option')).find(
|
||||
o => (o.textContent ?? '').includes('alice'),
|
||||
)!;
|
||||
await user.selectOptions(userSelect, aliceOption.value);
|
||||
const aliceId = Number(aliceOption.value);
|
||||
|
||||
await user.click(screen.getByText('trip_invite').closest('button')!);
|
||||
await screen.findByText(`Sent: trip_invite-${aliceId}`);
|
||||
await user.click(screen.getByText('vacay_invite').closest('button')!);
|
||||
await screen.findByText(`Sent: vacay_invite-${aliceId}`);
|
||||
|
||||
expect(bodies[0]).toMatchObject({
|
||||
event: 'trip_invite',
|
||||
scope: 'user',
|
||||
targetId: aliceId,
|
||||
params: { actor: 'testadmin', invitee: 'alice@example.com' },
|
||||
});
|
||||
expect(bodies[1]).toMatchObject({
|
||||
event: 'vacay_invite',
|
||||
scope: 'user',
|
||||
targetId: aliceId,
|
||||
params: { actor: 'testadmin', planId: '1' },
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-014: the User-Scoped section is hidden when no users come back', async () => {
|
||||
server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [] })));
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-015: failing lookups leave both scoped sections out without crashing', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips', () => HttpResponse.error()),
|
||||
http.get('/api/admin/users', () => HttpResponse.error()),
|
||||
);
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
|
||||
expect(await screen.findByText('Type Testing')).toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument());
|
||||
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Admin-Scoped Events')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-016: hovering a trigger paints and restores its background', async () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
|
||||
const btn = screen.getByText('Simple → Me').closest('button')!;
|
||||
fireEvent.mouseEnter(btn);
|
||||
expect(btn.style.background).toBe('var(--bg-hover)');
|
||||
fireEvent.mouseLeave(btn);
|
||||
expect(btn.style.background).toBe('var(--bg-card)');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { adminApi, tripsApi } from '../../api/client'
|
||||
import { getApiErrorMessage } from '../../utils/apiError'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import {
|
||||
@@ -46,8 +47,8 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
try {
|
||||
await adminApi.sendTestNotification(payload)
|
||||
toast.success(`Sent: ${label}`)
|
||||
} catch (err: any) {
|
||||
toast.error(err.message || 'Failed')
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, 'Failed'))
|
||||
} finally {
|
||||
setSending(null)
|
||||
}
|
||||
@@ -65,7 +66,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
}: {
|
||||
id: string; label: string; sub: string; icon: React.ElementType; color: string; onClick: () => void
|
||||
}) => (
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={onClick}
|
||||
disabled={sending !== null}
|
||||
className="flex items-center gap-3 px-4 py-3 rounded-lg border transition-colors text-left w-full border-edge bg-surface-card"
|
||||
|
||||
@@ -231,7 +231,7 @@ describe('GitHubPanel', () => {
|
||||
render(<GitHubPanel />);
|
||||
await screen.findByText('v1.7.0');
|
||||
await user.click(screen.getByText('Show details'));
|
||||
await screen.findByText('This is a plain paragraph without any markdown syntax.');
|
||||
expect(await screen.findByText('This is a plain paragraph without any markdown syntax.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-GH-014: markdown link with safe href renders as anchor', async () => {
|
||||
|
||||
@@ -461,7 +461,7 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b
|
||||
{/* Expandable body */}
|
||||
{release.body && (
|
||||
<div className="mt-2">
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={() => toggleExpand(release.id)}
|
||||
className="flex items-center gap-1 text-[11px] font-medium text-content-muted transition-colors"
|
||||
>
|
||||
@@ -484,7 +484,7 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b
|
||||
{/* Load more */}
|
||||
{hasMore && (
|
||||
<div className="pt-2 text-center">
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={handleLoadMore}
|
||||
disabled={loadingMore}
|
||||
className="inline-flex items-center gap-2 rounded-lg bg-surface-secondary px-4 py-2 text-xs font-medium text-content-muted transition-colors"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// FE-ADMIN-PKG-001 to FE-ADMIN-PKG-020
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
// FE-ADMIN-PKG-001 to FE-ADMIN-PKG-032
|
||||
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
@@ -18,6 +18,23 @@ beforeEach(() => {
|
||||
resetAllStores();
|
||||
});
|
||||
|
||||
/** Template rows carry [chevron, name, edit, delete]; category headers [add item, edit, delete]. */
|
||||
function rowButtons(name: string, selector: string): HTMLElement[] {
|
||||
const row = screen.getByText(name).closest(selector) as HTMLElement;
|
||||
return within(row).getAllByRole('button');
|
||||
}
|
||||
|
||||
const templateButtons = (name: string) => rowButtons(name, '.px-5.py-3');
|
||||
const categoryButtons = (name: string) => rowButtons(name, '.bg-slate-50');
|
||||
const itemButtons = (name: string) => rowButtons(name, '.group');
|
||||
|
||||
/** Expands the single fixture template and waits for its content. */
|
||||
async function expandBeachTrip(user: ReturnType<typeof userEvent.setup>, firstChild: string) {
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText(firstChild);
|
||||
}
|
||||
|
||||
describe('PackingTemplateManager', () => {
|
||||
it('FE-ADMIN-PKG-001: shows loading spinner on mount', async () => {
|
||||
server.use(
|
||||
@@ -233,7 +250,7 @@ describe('PackingTemplateManager', () => {
|
||||
await user.click(screen.getByText('Add category'));
|
||||
const catInput = screen.getByPlaceholderText('Category name (e.g. Clothing)');
|
||||
await user.type(catInput, 'Electronics{Enter}');
|
||||
await screen.findByText('Electronics');
|
||||
expect(await screen.findByText('Electronics')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-012: adding an item to a category', async () => {
|
||||
@@ -263,7 +280,7 @@ describe('PackingTemplateManager', () => {
|
||||
await user.type(itemInput, 'Sandals');
|
||||
// Submit via Enter key (the input's onKeyDown handler triggers handleAddItem)
|
||||
await user.type(itemInput, '{Enter}');
|
||||
await screen.findByText('Sandals');
|
||||
expect(await screen.findByText('Sandals')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-013: renaming a category inline updates its name', async () => {
|
||||
@@ -295,7 +312,7 @@ describe('PackingTemplateManager', () => {
|
||||
const catInput = screen.getByDisplayValue('Clothing');
|
||||
await user.clear(catInput);
|
||||
await user.type(catInput, 'Shoes{Enter}');
|
||||
await screen.findByText('Shoes');
|
||||
expect(await screen.findByText('Shoes')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-014: deleting a category removes it and its items', async () => {
|
||||
@@ -362,7 +379,7 @@ describe('PackingTemplateManager', () => {
|
||||
const input = screen.getByDisplayValue('T-shirt');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'Tank Top{Enter}');
|
||||
await screen.findByText('Tank Top');
|
||||
expect(await screen.findByText('Tank Top')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-016: deleting an item removes it from the list', async () => {
|
||||
@@ -508,4 +525,296 @@ describe('PackingTemplateManager', () => {
|
||||
expect(screen.queryByPlaceholderText('Template name (e.g. Beach Holiday)')).not.toBeInTheDocument()
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-021: a failing template list toasts and shows the empty state', async () => {
|
||||
server.use(http.get('/api/admin/packing-templates', () => HttpResponse.error()));
|
||||
render(<><ToastContainer /><PackingTemplateManager /></>);
|
||||
|
||||
expect(await screen.findByText('Failed to load templates')).toBeInTheDocument();
|
||||
expect(screen.getByText('No templates created yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-022: a failing expand toasts and leaves the template without content', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),
|
||||
http.get('/api/admin/packing-templates/1', () => HttpResponse.error()),
|
||||
);
|
||||
render(<><ToastContainer /><PackingTemplateManager /></>);
|
||||
await screen.findByText('Beach Trip');
|
||||
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
|
||||
expect(await screen.findByText('Failed to load templates')).toBeInTheDocument();
|
||||
expect(screen.getByText('Add category')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-023: an empty name is not submitted and a failing create toasts', async () => {
|
||||
const user = userEvent.setup();
|
||||
let posts = 0;
|
||||
server.use(
|
||||
http.post('/api/admin/packing-templates', () => {
|
||||
posts += 1;
|
||||
return HttpResponse.json({ error: 'nope' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><PackingTemplateManager /></>);
|
||||
await screen.findByText('No templates created yet');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /new template/i }));
|
||||
const input = screen.getByPlaceholderText('Template name (e.g. Beach Holiday)');
|
||||
await user.type(input, ' {Enter}');
|
||||
expect(posts).toBe(0);
|
||||
|
||||
await user.clear(input);
|
||||
await user.type(input, 'Ski trip{Enter}');
|
||||
expect(await screen.findByText('Failed to create template')).toBeInTheDocument();
|
||||
expect(posts).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-024: deleting the expanded template collapses it, a failing delete toasts', async () => {
|
||||
const user = userEvent.setup();
|
||||
let calls = 0;
|
||||
server.use(
|
||||
http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),
|
||||
http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [item1] })),
|
||||
http.delete('/api/admin/packing-templates/1', () => {
|
||||
calls += 1;
|
||||
return calls === 1
|
||||
? HttpResponse.json({ error: 'in use' }, { status: 500 })
|
||||
: HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><PackingTemplateManager /></>);
|
||||
await expandBeachTrip(user, 'Clothing');
|
||||
|
||||
await user.click(templateButtons('Beach Trip')[3]);
|
||||
expect(await screen.findByText('Failed to delete template')).toBeInTheDocument();
|
||||
expect(screen.getByText('Clothing')).toBeInTheDocument();
|
||||
|
||||
await user.click(templateButtons('Beach Trip')[3]);
|
||||
await screen.findByText('Template deleted');
|
||||
await waitFor(() => expect(screen.queryByText('Clothing')).not.toBeInTheDocument());
|
||||
expect(screen.getByText('No templates created yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-025: a blank rename closes the editor, a failing rename toasts, blur commits', async () => {
|
||||
const user = userEvent.setup();
|
||||
let puts = 0;
|
||||
server.use(
|
||||
http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),
|
||||
http.put('/api/admin/packing-templates/1', () => {
|
||||
puts += 1;
|
||||
return HttpResponse.json({ error: 'nope' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><PackingTemplateManager /></>);
|
||||
await screen.findByText('Beach Trip');
|
||||
|
||||
await user.click(templateButtons('Beach Trip')[2]);
|
||||
await user.clear(screen.getByDisplayValue('Beach Trip'));
|
||||
await user.type(screen.getByRole('textbox'), '{Enter}');
|
||||
await waitFor(() => expect(screen.getByText('Beach Trip')).toBeInTheDocument());
|
||||
expect(puts).toBe(0);
|
||||
|
||||
// Blurring the field commits the pending name — here the request fails
|
||||
await user.click(templateButtons('Beach Trip')[2]);
|
||||
const input = screen.getByDisplayValue('Beach Trip');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'Winter');
|
||||
await user.tab();
|
||||
expect(await screen.findByText('Failed to save')).toBeInTheDocument();
|
||||
expect(puts).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-026: a blank category is not posted, a failing add toasts and X cancels', async () => {
|
||||
const user = userEvent.setup();
|
||||
let posts = 0;
|
||||
server.use(
|
||||
http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),
|
||||
http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [], items: [] })),
|
||||
http.post('/api/admin/packing-templates/1/categories', () => {
|
||||
posts += 1;
|
||||
return HttpResponse.json({ error: 'nope' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><PackingTemplateManager /></>);
|
||||
await expandBeachTrip(user, 'Add category');
|
||||
|
||||
await user.click(screen.getByText('Add category'));
|
||||
const catInput = screen.getByPlaceholderText('Category name (e.g. Clothing)');
|
||||
await user.type(catInput, ' {Enter}');
|
||||
expect(posts).toBe(0);
|
||||
|
||||
await user.clear(catInput);
|
||||
await user.type(catInput, 'Electronics{Enter}');
|
||||
expect(await screen.findByText('Failed to save')).toBeInTheDocument();
|
||||
|
||||
const cancel = within(catInput.parentElement as HTMLElement).getAllByRole('button')[1];
|
||||
await user.click(cancel);
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByPlaceholderText('Category name (e.g. Clothing)')).not.toBeInTheDocument(),
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-027: a blank category rename closes the editor and a failing rename toasts', async () => {
|
||||
const user = userEvent.setup();
|
||||
let puts = 0;
|
||||
server.use(
|
||||
http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),
|
||||
http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [] })),
|
||||
http.put('/api/admin/packing-templates/1/categories/10', () => {
|
||||
puts += 1;
|
||||
return HttpResponse.json({ error: 'nope' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><PackingTemplateManager /></>);
|
||||
await expandBeachTrip(user, 'Clothing');
|
||||
|
||||
await user.click(categoryButtons('Clothing')[1]);
|
||||
await user.clear(screen.getByDisplayValue('Clothing'));
|
||||
await user.tab();
|
||||
await waitFor(() => expect(screen.getByText('Clothing')).toBeInTheDocument());
|
||||
expect(puts).toBe(0);
|
||||
|
||||
await user.click(categoryButtons('Clothing')[1]);
|
||||
const catInput = screen.getByDisplayValue('Clothing');
|
||||
await user.clear(catInput);
|
||||
await user.type(catInput, 'Shoes{Enter}');
|
||||
expect(await screen.findByText('Failed to save')).toBeInTheDocument();
|
||||
expect(puts).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-028: a failing category delete toasts and keeps the category', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),
|
||||
http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [item1] })),
|
||||
http.delete('/api/admin/packing-templates/1/categories/10', () => HttpResponse.error()),
|
||||
);
|
||||
render(<><ToastContainer /><PackingTemplateManager /></>);
|
||||
await expandBeachTrip(user, 'Clothing');
|
||||
|
||||
await user.click(categoryButtons('Clothing')[2]);
|
||||
|
||||
expect(await screen.findByText('Failed to delete category')).toBeInTheDocument();
|
||||
expect(screen.getByText('Clothing')).toBeInTheDocument();
|
||||
expect(screen.getByText('T-shirt')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-029: the add-item button posts the item, a failing add toasts and X closes the row', async () => {
|
||||
const user = userEvent.setup();
|
||||
let posts = 0;
|
||||
server.use(
|
||||
http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),
|
||||
http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [] })),
|
||||
http.post('/api/admin/packing-templates/1/categories/10/items', () => {
|
||||
posts += 1;
|
||||
return posts === 1
|
||||
? HttpResponse.json({ item: { id: 102, category_id: 10, name: 'Sandals', sort_order: 0 } })
|
||||
: HttpResponse.json({ error: 'nope' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><PackingTemplateManager /></>);
|
||||
await expandBeachTrip(user, 'Clothing');
|
||||
|
||||
await user.click(categoryButtons('Clothing')[0]);
|
||||
const itemInput = screen.getByPlaceholderText('Item name');
|
||||
const addRow = itemInput.parentElement as HTMLElement;
|
||||
expect(within(addRow).getAllByRole('button')[0]).toBeDisabled();
|
||||
|
||||
await user.type(itemInput, 'Sandals');
|
||||
await user.click(within(addRow).getAllByRole('button')[0]);
|
||||
await screen.findByText('Sandals');
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Item name'), 'Towel');
|
||||
await user.click(within(addRow).getAllByRole('button')[0]);
|
||||
expect(await screen.findByText('Failed to save')).toBeInTheDocument();
|
||||
|
||||
await user.click(within(addRow).getAllByRole('button')[1]);
|
||||
await waitFor(() => expect(screen.queryByPlaceholderText('Item name')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-030: the item editor commits on the check button, cancels on X and ignores a blank name', async () => {
|
||||
const user = userEvent.setup();
|
||||
let puts = 0;
|
||||
server.use(
|
||||
http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),
|
||||
http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [item1] })),
|
||||
http.put('/api/admin/packing-templates/1/items/100', () => {
|
||||
puts += 1;
|
||||
return puts === 1
|
||||
? HttpResponse.json({ success: true })
|
||||
: HttpResponse.json({ error: 'nope' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><PackingTemplateManager /></>);
|
||||
await expandBeachTrip(user, 'T-shirt');
|
||||
|
||||
// A blank name just closes the editor
|
||||
await user.click(itemButtons('T-shirt')[0]);
|
||||
const blank = screen.getByDisplayValue('T-shirt');
|
||||
await user.clear(blank);
|
||||
await user.click(within(blank.parentElement as HTMLElement).getAllByRole('button')[0]);
|
||||
await waitFor(() => expect(screen.getByText('T-shirt')).toBeInTheDocument());
|
||||
expect(puts).toBe(0);
|
||||
|
||||
// X discards the pending name
|
||||
await user.click(itemButtons('T-shirt')[0]);
|
||||
const editing = screen.getByDisplayValue('T-shirt');
|
||||
await user.clear(editing);
|
||||
await user.type(editing, 'Discarded');
|
||||
await user.click(within(editing.parentElement as HTMLElement).getAllByRole('button')[1]);
|
||||
await waitFor(() => expect(screen.getByText('T-shirt')).toBeInTheDocument());
|
||||
expect(puts).toBe(0);
|
||||
|
||||
// The check button commits
|
||||
await user.click(itemButtons('T-shirt')[0]);
|
||||
const editing2 = screen.getByDisplayValue('T-shirt');
|
||||
await user.clear(editing2);
|
||||
await user.type(editing2, 'Tank Top');
|
||||
await user.click(within(editing2.parentElement as HTMLElement).getAllByRole('button')[0]);
|
||||
await screen.findByText('Tank Top');
|
||||
expect(puts).toBe(1);
|
||||
|
||||
// A failing rename keeps the editor open and toasts
|
||||
await user.click(itemButtons('Tank Top')[0]);
|
||||
const editing3 = screen.getByDisplayValue('Tank Top');
|
||||
await user.clear(editing3);
|
||||
await user.type(editing3, 'Vest{Enter}');
|
||||
expect(await screen.findByText('Failed to save')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('Vest')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-031: a failing item delete toasts and keeps the item', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),
|
||||
http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [item1] })),
|
||||
http.delete('/api/admin/packing-templates/1/items/100', () => HttpResponse.error()),
|
||||
);
|
||||
render(<><ToastContainer /><PackingTemplateManager /></>);
|
||||
await expandBeachTrip(user, 'T-shirt');
|
||||
|
||||
await user.click(itemButtons('T-shirt')[1]);
|
||||
|
||||
expect(await screen.findByText('Failed to delete item')).toBeInTheDocument();
|
||||
expect(screen.getByText('T-shirt')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PKG-032: the chevron button expands and collapses the template', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),
|
||||
http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [item1] })),
|
||||
);
|
||||
render(<PackingTemplateManager />);
|
||||
await screen.findByText('Beach Trip');
|
||||
|
||||
await user.click(templateButtons('Beach Trip')[0]);
|
||||
await screen.findByText('Clothing');
|
||||
|
||||
await user.click(templateButtons('Beach Trip')[0]);
|
||||
await waitFor(() => expect(screen.queryByText('Clothing')).not.toBeInTheDocument());
|
||||
});
|
||||
});
|
||||
|
||||
@@ -115,12 +115,13 @@ export default function PackingTemplateManager() {
|
||||
await adminApi.deleteTemplateCategory(expandedId, catId)
|
||||
setCategories(prev => prev.filter(c => c.id !== catId))
|
||||
setItems(prev => prev.filter(i => i.category_id !== catId))
|
||||
} catch { toast.error(t('admin.packingTemplates.deleteError')) }
|
||||
} catch { toast.error(t('admin.packingTemplates.deleteCategoryError')) }
|
||||
}
|
||||
|
||||
// Item CRUD
|
||||
const handleAddItem = async (catId: number) => {
|
||||
if (!newItemName.trim() || !expandedId) return
|
||||
// The name is already guaranteed non-empty by the button and the Enter handler.
|
||||
if (!expandedId) return
|
||||
try {
|
||||
const data = await adminApi.addTemplateItem(expandedId, catId, { name: newItemName.trim() })
|
||||
setItems(prev => [...prev, data.item])
|
||||
@@ -143,7 +144,7 @@ export default function PackingTemplateManager() {
|
||||
try {
|
||||
await adminApi.deleteTemplateItem(expandedId, itemId)
|
||||
setItems(prev => prev.filter(i => i.id !== itemId))
|
||||
} catch { toast.error(t('admin.packingTemplates.deleteError')) }
|
||||
} catch { toast.error(t('admin.packingTemplates.deleteItemError')) }
|
||||
}
|
||||
|
||||
const inputStyle = 'w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent outline-none'
|
||||
@@ -157,7 +158,7 @@ export default function PackingTemplateManager() {
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.packingTemplates.title')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.packingTemplates.subtitle')}</p>
|
||||
</div>
|
||||
<button onClick={() => setShowCreate(true)}
|
||||
<button type="button" onClick={() => setShowCreate(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" /> <span className="hidden sm:inline">{t('admin.packingTemplates.create')}</span>
|
||||
</button>
|
||||
@@ -170,8 +171,8 @@ export default function PackingTemplateManager() {
|
||||
<input autoFocus value={createName} onChange={e => setCreateName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') handleCreateTemplate(); if (e.key === 'Escape') setShowCreate(false) }}
|
||||
placeholder={t('admin.packingTemplates.namePlaceholder')} className={inputStyle} />
|
||||
<button onClick={handleCreateTemplate} className={`${btnIcon} text-slate-600 hover:text-slate-900`}><Check size={16} /></button>
|
||||
<button onClick={() => setShowCreate(false)} className={`${btnIcon} text-slate-400 hover:text-slate-600`}><X size={16} /></button>
|
||||
<button type="button" onClick={handleCreateTemplate} className={`${btnIcon} text-slate-600 hover:text-slate-900`}><Check size={16} /></button>
|
||||
<button type="button" onClick={() => setShowCreate(false)} className={`${btnIcon} text-slate-400 hover:text-slate-600`}><X size={16} /></button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -186,7 +187,7 @@ export default function PackingTemplateManager() {
|
||||
<div key={tmpl.id}>
|
||||
{/* Template row */}
|
||||
<div className="px-5 py-3 flex items-center gap-3 hover:bg-slate-50 transition-colors">
|
||||
<button onClick={() => toggleExpand(tmpl.id)} className="text-slate-400 flex-shrink-0 p-0 bg-transparent border-none cursor-pointer">
|
||||
<button type="button" onClick={() => toggleExpand(tmpl.id)} className="text-slate-400 flex-shrink-0 p-0 bg-transparent border-none cursor-pointer">
|
||||
{expandedId === tmpl.id ? <ChevronDown size={15} /> : <ChevronRight size={15} />}
|
||||
</button>
|
||||
<Package size={16} className="text-slate-400 flex-shrink-0" />
|
||||
@@ -196,14 +197,14 @@ export default function PackingTemplateManager() {
|
||||
onKeyDown={e => { if (e.key === 'Enter') handleRenameTemplate(tmpl.id); if (e.key === 'Escape') setEditingTemplate(null) }}
|
||||
className="flex-1 px-2 py-0.5 border border-slate-300 rounded text-sm" />
|
||||
) : (
|
||||
<span onClick={() => toggleExpand(tmpl.id)} className="flex-1 text-sm font-medium text-slate-700 cursor-pointer">{tmpl.name}</span>
|
||||
<button type="button" onClick={() => toggleExpand(tmpl.id)} className="flex-1 text-left bg-transparent border-0 p-0 text-sm font-medium text-slate-700 cursor-pointer">{tmpl.name}</button>
|
||||
)}
|
||||
<span className="text-xs text-slate-400 px-2 py-0.5 bg-slate-100 rounded-full">
|
||||
{tmpl.category_count} {t('admin.packingTemplates.categories')} · {tmpl.item_count} {t('admin.packingTemplates.items')}
|
||||
</span>
|
||||
<button onClick={() => { setEditingTemplate(tmpl.id); setEditTemplateName(tmpl.name) }}
|
||||
<button type="button" onClick={() => { setEditingTemplate(tmpl.id); setEditTemplateName(tmpl.name) }}
|
||||
className={`${btnIcon} hover:bg-slate-100 text-slate-400 hover:text-slate-700`}><Edit2 size={14} /></button>
|
||||
<button onClick={() => handleDeleteTemplate(tmpl.id)}
|
||||
<button type="button" onClick={() => handleDeleteTemplate(tmpl.id)}
|
||||
className={`${btnIcon} hover:bg-red-50 text-slate-400 hover:text-red-500`}><Trash2 size={14} /></button>
|
||||
</div>
|
||||
|
||||
@@ -227,11 +228,11 @@ export default function PackingTemplateManager() {
|
||||
<span className="flex-1 text-xs font-bold text-slate-500 uppercase tracking-wider">{cat.name}</span>
|
||||
)}
|
||||
<span className="text-xs text-slate-400">{catItems.length}</span>
|
||||
<button onClick={() => { setAddingItemToCatId(addingItemToCatId === cat.id ? null : cat.id); setNewItemName(''); setTimeout(() => addItemRef.current?.focus(), 30) }}
|
||||
<button type="button" onClick={() => { setAddingItemToCatId(addingItemToCatId === cat.id ? null : cat.id); setNewItemName(''); setTimeout(() => addItemRef.current?.focus(), 30) }}
|
||||
className={`${btnIcon} text-slate-400 hover:text-slate-700`}><Plus size={13} /></button>
|
||||
<button onClick={() => { setEditingCatId(cat.id); setEditCatName(cat.name) }}
|
||||
<button type="button" onClick={() => { setEditingCatId(cat.id); setEditCatName(cat.name) }}
|
||||
className={`${btnIcon} text-slate-400 hover:text-slate-700`}><Edit2 size={13} /></button>
|
||||
<button onClick={() => handleDeleteCategory(cat.id)}
|
||||
<button type="button" onClick={() => handleDeleteCategory(cat.id)}
|
||||
className={`${btnIcon} text-slate-400 hover:text-red-500`}><Trash2 size={13} /></button>
|
||||
</div>
|
||||
|
||||
@@ -245,15 +246,15 @@ export default function PackingTemplateManager() {
|
||||
<input autoFocus value={editItemName} onChange={e => setEditItemName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') handleRenameItem(item.id); if (e.key === 'Escape') setEditingItemId(null) }}
|
||||
className="flex-1 px-2 py-1 border border-slate-200 rounded-lg text-sm" />
|
||||
<button onClick={() => handleRenameItem(item.id)} className="p-1 text-slate-600 hover:text-slate-900"><Check size={13} /></button>
|
||||
<button onClick={() => setEditingItemId(null)} className="p-1 text-slate-400"><X size={13} /></button>
|
||||
<button type="button" onClick={() => handleRenameItem(item.id)} className="p-1 text-slate-600 hover:text-slate-900"><Check size={13} /></button>
|
||||
<button type="button" onClick={() => setEditingItemId(null)} className="p-1 text-slate-400"><X size={13} /></button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="flex-1 text-sm text-slate-700">{item.name}</span>
|
||||
<button onClick={() => { setEditingItemId(item.id); setEditItemName(item.name) }}
|
||||
<button type="button" onClick={() => { setEditingItemId(item.id); setEditItemName(item.name) }}
|
||||
className="p-1 rounded opacity-0 group-hover:opacity-100 text-slate-400 hover:text-slate-700 transition-all"><Edit2 size={12} /></button>
|
||||
<button onClick={() => handleDeleteItem(item.id)}
|
||||
<button type="button" onClick={() => handleDeleteItem(item.id)}
|
||||
className="p-1 rounded opacity-0 group-hover:opacity-100 text-slate-400 hover:text-red-500 transition-all"><Trash2 size={12} /></button>
|
||||
</>
|
||||
)}
|
||||
@@ -267,9 +268,9 @@ export default function PackingTemplateManager() {
|
||||
onKeyDown={e => { if (e.key === 'Enter' && newItemName.trim()) handleAddItem(cat.id); if (e.key === 'Escape') { setAddingItemToCatId(null); setNewItemName('') } }}
|
||||
placeholder={t('admin.packingTemplates.itemName')}
|
||||
className="flex-1 px-2 py-1 border border-slate-200 rounded-lg text-sm" />
|
||||
<button onClick={() => handleAddItem(cat.id)} disabled={!newItemName.trim()}
|
||||
<button type="button" onClick={() => handleAddItem(cat.id)} disabled={!newItemName.trim()}
|
||||
className="p-1.5 rounded-lg bg-slate-900 text-white disabled:bg-slate-300 hover:bg-slate-700 transition-colors"><Plus size={13} /></button>
|
||||
<button onClick={() => { setAddingItemToCatId(null); setNewItemName('') }}
|
||||
<button type="button" onClick={() => { setAddingItemToCatId(null); setNewItemName('') }}
|
||||
className="p-1 text-slate-400 hover:text-slate-600"><X size={13} /></button>
|
||||
</div>
|
||||
)}
|
||||
@@ -286,11 +287,11 @@ export default function PackingTemplateManager() {
|
||||
onKeyDown={e => { if (e.key === 'Enter') handleAddCategory(); if (e.key === 'Escape') { setAddingCategory(false); setNewCatName('') } }}
|
||||
placeholder={t('admin.packingTemplates.categoryName')}
|
||||
className="flex-1 px-3 py-2 border border-slate-200 rounded-lg text-sm" />
|
||||
<button onClick={handleAddCategory} className={`${btnIcon} text-slate-600 hover:text-slate-900`}><Check size={15} /></button>
|
||||
<button onClick={() => { setAddingCategory(false); setNewCatName('') }} className={`${btnIcon} text-slate-400`}><X size={15} /></button>
|
||||
<button type="button" onClick={handleAddCategory} className={`${btnIcon} text-slate-600 hover:text-slate-900`}><Check size={15} /></button>
|
||||
<button type="button" onClick={() => { setAddingCategory(false); setNewCatName('') }} className={`${btnIcon} text-slate-400`}><X size={15} /></button>
|
||||
</div>
|
||||
) : (
|
||||
<button onClick={() => setAddingCategory(true)}
|
||||
<button type="button" onClick={() => setAddingCategory(true)}
|
||||
className="flex items-center gap-2 px-3 py-2.5 w-full text-sm text-slate-400 hover:text-slate-600 border border-dashed border-slate-200 rounded-lg hover:border-slate-400 transition-colors">
|
||||
<FolderPlus size={14} /> {t('admin.packingTemplates.addCategory')}
|
||||
</button>
|
||||
|
||||
@@ -269,6 +269,6 @@ describe('PermissionsPanel', () => {
|
||||
),
|
||||
);
|
||||
renderPanel();
|
||||
await screen.findByText('Error');
|
||||
expect(await screen.findByText('Error')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -104,7 +104,7 @@ export default function PermissionsPanel(): React.ReactElement {
|
||||
<p className="text-xs text-slate-400 mt-0.5">{t('perm.subtitle')}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={handleReset}
|
||||
disabled={saving}
|
||||
title={t('perm.resetDefaults')}
|
||||
@@ -114,7 +114,7 @@ export default function PermissionsPanel(): React.ReactElement {
|
||||
<RotateCcw className="w-3.5 h-3.5" />
|
||||
<span className="hidden sm:inline">{t('perm.resetDefaults')}</span>
|
||||
</button>
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={handleSave}
|
||||
disabled={saving || !dirty}
|
||||
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 disabled:bg-slate-400 transition-colors"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,779 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { Activity, FolderTree, HardDrive } from 'lucide-react'
|
||||
import {
|
||||
STORAGE_CATEGORIES,
|
||||
type StorageBackend,
|
||||
type StorageCategory,
|
||||
type StorageConfig,
|
||||
type StorageMigrationStatus,
|
||||
type StorageTestResponse,
|
||||
} from '@trek/shared'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { formatBytes } from '../../../utils/formatBytes'
|
||||
import { relativeTime } from '../../../utils/relativeTime'
|
||||
import ConfirmDialog from '../../shared/ConfirmDialog'
|
||||
import CustomSelect from '../../shared/CustomSelect'
|
||||
import { useToast } from '../../shared/Toast'
|
||||
import Section from '../../Settings/Section'
|
||||
import BackendForm, { type BackendFormMirrorProps } from './BackendForm'
|
||||
import {
|
||||
CACHE_CATEGORIES,
|
||||
adoptedMirrorFor,
|
||||
computeMigrationCandidates,
|
||||
effectiveCategoryMap,
|
||||
foldBackends,
|
||||
mirrorProbeTargets,
|
||||
primaryNameOf,
|
||||
removeBackend,
|
||||
removeBackendAndMirrors,
|
||||
renameBackendRefs,
|
||||
replicaCandidates,
|
||||
replicaOfPrimaries,
|
||||
settingsDocumentOf,
|
||||
setMirrorTargets,
|
||||
stripCategories,
|
||||
upsertBackend,
|
||||
usageByBackend,
|
||||
type FoldedBackendRow,
|
||||
type MigrationCandidate,
|
||||
} from './storageModel'
|
||||
import { useStorageAdmin } from './useStorageAdmin'
|
||||
|
||||
/** Display-name mapper for joined category lists — the raw id renders only in the badge. */
|
||||
const categoryNames = (t: (key: string) => string, ids: readonly string[]): string =>
|
||||
ids.map((id) => t(`storage.category.${id}`)).join(', ')
|
||||
|
||||
function TestResult({ result, failedLabel, okLabel }: {
|
||||
result: StorageTestResponse | undefined
|
||||
failedLabel: string
|
||||
okLabel: string
|
||||
}): React.ReactElement | null {
|
||||
if (result === undefined) return null
|
||||
return (
|
||||
<div className="mt-2 space-y-0.5">
|
||||
<p className="text-xs font-semibold text-content">{result.ok ? okLabel : failedLabel}</p>
|
||||
{result.targets.map((target) => (
|
||||
<p key={target.name} className="text-xs text-content-faint">
|
||||
{target.ok ? '✓' : '✗'} {target.name}
|
||||
{target.error ? ` — ${target.error}` : ''}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const LINK_BUTTON_STYLE: React.CSSProperties = { background: 'none', border: 'none', cursor: 'pointer' }
|
||||
|
||||
export default function AdminStoragePanel(): React.ReactElement {
|
||||
const { t, locale } = useTranslation()
|
||||
const toast = useToast()
|
||||
const admin = useStorageAdmin(t('common.error'), t('storage.saveConflict'))
|
||||
const [editing, setEditing] = useState<{
|
||||
initial: StorageBackend | null
|
||||
originalName: string | null
|
||||
mirror: BackendFormMirrorProps
|
||||
} | null>(null)
|
||||
const [confirmRemove, setConfirmRemove] = useState<{ name: string; degenerate: boolean } | null>(null)
|
||||
const [syncPrompt, setSyncPrompt] = useState<string | null>(null)
|
||||
// Open/closed only — never a snapshot of candidates. Storing the candidate
|
||||
// array here would go stale the moment the operator edits a category while
|
||||
// the dialog is open; the render below and moveAndSave both recompute
|
||||
// computeMigrationCandidates(draft, state) fresh instead.
|
||||
const [migratePromptOpen, setMigratePromptOpen] = useState(false)
|
||||
const [migrationQueue, setMigrationQueue] = useState<MigrationCandidate[]>([])
|
||||
// Set by `save` right before it calls admin.save(): the pre-save mirror
|
||||
// target count per row name. Consumed (and cleared) by the effect below the
|
||||
// first time `admin.state` changes afterward — never touched otherwise, so
|
||||
// unrelated state changes (the backfill poll included) are no-ops here.
|
||||
const pendingPromptCheck = useRef<Map<string, number> | null>(null)
|
||||
// Synchronous single-flight lock for the queue effect below: `admin.state`
|
||||
// only reflects a just-started migration once startMigration's awaited
|
||||
// refreshState() resolves, so `setMigrationQueue(rest)` re-firing the
|
||||
// effect synchronously (still against the pre-POST `admin.state`) would
|
||||
// otherwise dequeue and POST the next candidate before the server has
|
||||
// confirmed the first — a ref (not state) so the guard is visible on that
|
||||
// very next synchronous re-render, not just after a state-driven one.
|
||||
const migrationStartInFlight = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingPromptCheck.current || !admin.state) return
|
||||
const before = pendingPromptCheck.current
|
||||
pendingPromptCheck.current = null
|
||||
const { rows: afterRows } = foldBackends(admin.state, settingsDocumentOf(admin.state))
|
||||
const grown = afterRows.find((r) => r.mirrorTargets.length > (before.get(r.name) ?? 0))
|
||||
if (grown) setSyncPrompt(grown.name)
|
||||
}, [admin.state])
|
||||
|
||||
// Queued category migrations run strictly sequentially: once a slot opens
|
||||
// (no migration currently running), dequeue the next candidate and start
|
||||
// it. Depends on admin.state so a poll landing a terminal status re-fires
|
||||
// this without any user interaction. The in-flight lock closes the race
|
||||
// where setMigrationQueue(rest) re-fires this effect synchronously while
|
||||
// admin.state still shows the pre-POST world — without it, the next
|
||||
// candidate could dequeue and POST before the first is server-confirmed.
|
||||
// Also waits out a running BACKFILL — the server's one-storage-job-at-a-time
|
||||
// rule spans backfills and migrations alike, so starting while one runs
|
||||
// would 409, and the queued candidate would be lost (no retry).
|
||||
//
|
||||
// A failed startMigration POST would otherwise strand `rest`: it was
|
||||
// already dequeued into local state before the POST, so on failure nothing
|
||||
// ever changes `migrationQueue` or `admin.state` again — the effect never
|
||||
// re-fires and the remaining candidates sit invisibly forever, silently
|
||||
// never migrated. On failure the whole remaining queue is explicitly
|
||||
// cleared (never retried — the operator re-triggers via Save), named in a
|
||||
// toast, and admin.state is refreshed so the panel reflects whatever the
|
||||
// failed attempt's category ended up as server-side.
|
||||
useEffect(() => {
|
||||
if (migrationQueue.length === 0 || !admin.state) return
|
||||
if (migrationStartInFlight.current) return
|
||||
if (admin.state.migrations.some((m) => m.status === 'running')) return
|
||||
if (admin.state.backfills.some((b) => b.status === 'running')) return
|
||||
const [next, ...rest] = migrationQueue
|
||||
migrationStartInFlight.current = true
|
||||
setMigrationQueue(rest)
|
||||
void admin.startMigration(next!.category, next!.toWire).then((error) => {
|
||||
migrationStartInFlight.current = false
|
||||
if (error) {
|
||||
toast.error(error)
|
||||
if (rest.length > 0) {
|
||||
toast.error(t('storage.migrate.queueDropped', { categories: categoryNames(t, rest.map((c) => c.category)) }))
|
||||
setMigrationQueue([])
|
||||
}
|
||||
void admin.refreshState().catch(() => {})
|
||||
}
|
||||
})
|
||||
}, [migrationQueue, admin.state])
|
||||
|
||||
if (admin.loading) {
|
||||
return <p className="text-sm italic p-4 text-content-faint">{t('storage.loading')}</p>
|
||||
}
|
||||
if (!admin.state || !admin.draft) {
|
||||
return (
|
||||
<div role="alert" className="rounded-xl border p-4 text-sm border-edge bg-surface-card text-content">
|
||||
{admin.loadError || t('common.error')}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const { state, draft } = admin
|
||||
|
||||
// Pure/cheap — recomputed every render so the migrate-prompt dialog (below)
|
||||
// never shows a stale candidate set while it's open (fix: migration prompt
|
||||
// staleness). moveAndSave recomputes independently at confirm time rather
|
||||
// than reading this render-scoped value, since the click handler and the
|
||||
// render that produced it are not guaranteed to be the same one.
|
||||
const migrationCandidates = computeMigrationCandidates(draft, state)
|
||||
|
||||
// Duplicate pre-check needs EVERY wire name (hidden mirror names included);
|
||||
// mirror-target candidates are the visible primaries only.
|
||||
const backendNames = [...new Set([...state.backends.map((b) => b.name), ...draft.backends.map((b) => b.name)])]
|
||||
const { rows, degenerate } = foldBackends(state, draft)
|
||||
const effective = effectiveCategoryMap(state, draft)
|
||||
const usageSums = usageByBackend(state, draft)
|
||||
|
||||
const startEdit = (row: FoldedBackendRow) => {
|
||||
// Editing a built-in creates a settings override row bearing its name —
|
||||
// the first-class relocation path (merge-by-name).
|
||||
setEditing({
|
||||
initial: row.backend,
|
||||
originalName: row.name,
|
||||
mirror: {
|
||||
candidates: replicaCandidates(rows, row.name, row.mirrorTargets),
|
||||
initialTargets: row.mirrorTargets,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const commitBackend = (backend: StorageBackend, mirrorTargets?: string[]) => {
|
||||
const renamedFrom =
|
||||
editing?.originalName && editing.originalName !== backend.name ? editing.originalName : null
|
||||
// Widened to StorageConfig: these edit helpers are version-blind (they
|
||||
// return plain StorageConfig), and admin.setDraft re-attaches the
|
||||
// draft's own `version` regardless of what shape it's handed.
|
||||
let next: StorageConfig | null = draft
|
||||
if (renamedFrom) next = renameBackendRefs(removeBackend(next, renamedFrom), renamedFrom, backend.name)
|
||||
next = upsertBackend(next, backend)
|
||||
if (mirrorTargets !== undefined) next = setMirrorTargets(state, next, backend.name, mirrorTargets)
|
||||
admin.setDraft(next)
|
||||
setEditing(null)
|
||||
}
|
||||
|
||||
const removeMessage = (name: string, isDegenerate: boolean): string => {
|
||||
const row = rows.find((r) => r.name === name)
|
||||
const assigned = isDegenerate
|
||||
? degenerate.find((d) => d.backend.name === name)?.categories ?? []
|
||||
: row?.categories ?? []
|
||||
const usedAsReplicaBy = isDegenerate ? [] : replicaOfPrimaries(draft, name)
|
||||
return [
|
||||
t('storage.remove.body', { name }),
|
||||
assigned.length > 0 ? t('storage.remove.stillAssigned', { categories: categoryNames(t, assigned) }) : '',
|
||||
usedAsReplicaBy.length > 0 ? t('storage.remove.usedAsReplicaBy', { primaries: usedAsReplicaBy.join(', ') }) : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
const setCategory = (category: StorageCategory, primaryName: string) => {
|
||||
// Picking a mirrored primary routes through its adopted mirror silently.
|
||||
const target = adoptedMirrorFor(draft, primaryName)?.name ?? primaryName
|
||||
// The admin state's category record is exhaustive by schema contract.
|
||||
const stateEntry = state.categories[category]!
|
||||
const categories = { ...draft.categories }
|
||||
if (stateEntry.source === 'default' && target === stateEntry.backend) {
|
||||
delete categories[category] // back to the default → no longer settings-owned
|
||||
} else {
|
||||
categories[category] = target
|
||||
}
|
||||
admin.setDraft({ ...draft, categories })
|
||||
}
|
||||
|
||||
// Snapshot the LAST-CONFIRMED (pre-save `state`'s own fold, not the
|
||||
// in-progress `draft`) mirror target counts; the effect above compares
|
||||
// them against the fresh post-save state to detect newly-added
|
||||
// replicas. Folding `draft` here would already include the unsaved
|
||||
// edit and mask the very growth this is meant to detect.
|
||||
const snapshotMirrorTargets = (): Map<string, number> => {
|
||||
const { rows: beforeRows } = foldBackends(state, settingsDocumentOf(state))
|
||||
return new Map(beforeRows.map((r) => [r.name, r.mirrorTargets.length]))
|
||||
}
|
||||
|
||||
const doPlainSave = async () => {
|
||||
pendingPromptCheck.current = snapshotMirrorTargets()
|
||||
if (await admin.save()) toast.success(t('storage.saved'))
|
||||
else pendingPromptCheck.current = null
|
||||
}
|
||||
|
||||
// Recomputes the candidate set at confirm time — never trusts whatever was
|
||||
// true when the dialog opened. The operator can edit categories (or a
|
||||
// background poll can land a fresher usage scan) while the dialog is on
|
||||
// screen; the recomputed set is what actually drives both stripCategories
|
||||
// (what gets reverted from the PUT body) and the queue (what gets POSTed),
|
||||
// so the two can never diverge from what the dialog most recently showed.
|
||||
const moveAndSave = async () => {
|
||||
const candidates = computeMigrationCandidates(draft, state)
|
||||
pendingPromptCheck.current = snapshotMirrorTargets()
|
||||
const ok = await admin.save(stripCategories(draft, state, candidates.map((c) => c.category)))
|
||||
if (ok) {
|
||||
setMigrationQueue(candidates)
|
||||
toast.success(t('storage.saved'))
|
||||
} else {
|
||||
pendingPromptCheck.current = null
|
||||
}
|
||||
setMigratePromptOpen(false)
|
||||
}
|
||||
|
||||
const routeOnlySave = async () => {
|
||||
setMigratePromptOpen(false)
|
||||
await doPlainSave()
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
if (migrationCandidates.length > 0) {
|
||||
setMigratePromptOpen(true)
|
||||
return
|
||||
}
|
||||
await doPlainSave()
|
||||
}
|
||||
|
||||
const handleCancelMigration = async (m: StorageMigrationStatus) => {
|
||||
const error = await admin.cancelMigration(m.category)
|
||||
if (error) toast.error(error)
|
||||
}
|
||||
|
||||
const testResultFor = (key: string): StorageTestResponse | 'running' | undefined => admin.testResults[key]
|
||||
|
||||
const handleRefreshStats = async () => {
|
||||
const error = await admin.refreshStats()
|
||||
if (error) toast.error(error)
|
||||
}
|
||||
|
||||
const handleStartBackfill = async (row: FoldedBackendRow) => {
|
||||
if (!row.mirrorName) return
|
||||
setSyncPrompt((prev) => (prev === row.name ? null : prev))
|
||||
const error = await admin.startBackfill(row.mirrorName)
|
||||
if (error) toast.error(error)
|
||||
}
|
||||
|
||||
const handleCancelBackfill = async (row: FoldedBackendRow) => {
|
||||
if (!row.mirrorName) return
|
||||
const error = await admin.cancelBackfill(row.mirrorName)
|
||||
if (error) toast.error(error)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{state.configError && (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-xl border p-3 mb-4 text-sm"
|
||||
style={{ borderColor: 'var(--warning)', background: 'var(--warning-soft)', color: 'var(--text-primary)' }}
|
||||
>
|
||||
{t('storage.configError.banner', { error: state.configError })}
|
||||
</div>
|
||||
)}
|
||||
<Section title={t('storage.health.title')} icon={Activity}>
|
||||
{state.health.replicaFailures.length === 0 ? (
|
||||
<p className="text-sm text-content-faint">{t('storage.health.allClear')}</p>
|
||||
) : (
|
||||
<ul className="space-y-1">
|
||||
{state.health.replicaFailures.map((failure) => (
|
||||
<li key={`${failure.backend}-${failure.key}-${failure.at}`} className="text-sm text-content">
|
||||
{t('storage.health.failureLine', {
|
||||
op: failure.op,
|
||||
key: failure.key,
|
||||
backend: failure.backend,
|
||||
error: failure.error,
|
||||
})}
|
||||
<span className="text-content-faint"> · {relativeTime(failure.at, locale)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{state.seedFilePresent && <p className="text-xs mt-2 text-content-faint">{t('storage.health.seedFile')}</p>}
|
||||
</Section>
|
||||
|
||||
<Section title={t('storage.backends.title')} icon={HardDrive}>
|
||||
<p className="text-sm text-content-faint" style={{ marginTop: -8 }}>{t('storage.description')}</p>
|
||||
<p className="text-xs mb-2 text-content-faint">
|
||||
{state.usage
|
||||
? t('storage.usage.computed', { age: relativeTime(state.usage.computedAt, locale) })
|
||||
: t('storage.usage.never')}
|
||||
{' '}
|
||||
<button type="button" className="text-xs underline text-content-secondary" style={LINK_BUTTON_STYLE} onClick={handleRefreshStats}>
|
||||
{state.usage ? t('storage.usage.refresh') : t('storage.usage.compute')}
|
||||
</button>
|
||||
</p>
|
||||
<div className="space-y-3">
|
||||
{rows.map((row) => {
|
||||
const resultKey = row.mirrorName ?? row.name
|
||||
const result = testResultFor(resultKey)
|
||||
// row.mirrorName only exists when foldBackends adopted a draft mirror
|
||||
// for this row, so the draft lookup below cannot miss.
|
||||
const testCandidate = row.mirrorName
|
||||
? draft.backends.find((b) => b.name === row.mirrorName)!
|
||||
: row.backend
|
||||
const rowUsage = usageSums?.[row.name]
|
||||
const backfill = row.mirrorName ? state.backfills.find((b) => b.backend === row.mirrorName) : undefined
|
||||
return (
|
||||
<div key={row.name} data-testid={`storage-backend-${row.name}`} className="rounded-xl border p-4 border-edge-secondary">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-sm font-semibold text-content">{row.name}</span>
|
||||
<span className="text-xs px-2 py-0.5 rounded-full border border-edge text-content-secondary">
|
||||
{t(`storage.type.${row.type}`)}
|
||||
</span>
|
||||
<span className="text-xs px-2 py-0.5 rounded-full border border-edge text-content-faint">
|
||||
{t(`storage.source.${row.source}`)}
|
||||
</span>
|
||||
<span className="flex-1" />
|
||||
<button type="button"
|
||||
className="text-xs underline text-content-secondary"
|
||||
style={LINK_BUTTON_STYLE}
|
||||
onClick={() =>
|
||||
row.mirrorName
|
||||
? admin.testMirror(resultKey, mirrorProbeTargets(draft, state, testCandidate))
|
||||
: admin.test(testCandidate)
|
||||
}
|
||||
>
|
||||
{t('storage.actions.test')}
|
||||
</button>
|
||||
{row.source !== 'env' && (
|
||||
<button type="button" className="text-xs underline text-content-secondary" style={LINK_BUTTON_STYLE} onClick={() => startEdit(row)}>
|
||||
{t('storage.actions.edit')}
|
||||
</button>
|
||||
)}
|
||||
{row.source === 'settings' && (
|
||||
<button type="button" className="text-xs underline text-content-secondary" style={LINK_BUTTON_STYLE} onClick={() => setConfirmRemove({ name: row.name, degenerate: false })}>
|
||||
{t('storage.actions.remove')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs mt-1 text-content-faint">
|
||||
{row.categories.length > 0
|
||||
? t('storage.backends.usedBy', { categories: categoryNames(t, row.categories) })
|
||||
: t('storage.backends.unused')}
|
||||
</p>
|
||||
{rowUsage && (
|
||||
<p className="text-xs mt-1 text-content-faint">
|
||||
{t('storage.usage.line', { objects: String(rowUsage.objects), size: formatBytes(rowUsage.bytes) })}
|
||||
{row.name === 'uploads-local' && state.usage!.legacyPhotos.objects > 0
|
||||
? ` (${t('storage.usage.legacyNote')})`
|
||||
: ''}
|
||||
</p>
|
||||
)}
|
||||
{row.mirrorTargets.length > 0 && (
|
||||
<p className="text-xs mt-1 text-content-faint">
|
||||
{t('storage.mirror.mirroredTo', { targets: row.mirrorTargets.join(', ') })}
|
||||
</p>
|
||||
)}
|
||||
{row.replicaOf.length > 0 && (
|
||||
<p className="text-xs mt-1 text-content-faint">
|
||||
{t('storage.mirror.replicaOf', { primaries: row.replicaOf.join(', ') })}
|
||||
</p>
|
||||
)}
|
||||
{row.source === 'env' && <p className="text-xs mt-1 text-content-faint">{t('storage.backends.envReadOnly')}</p>}
|
||||
{result === 'running' ? (
|
||||
<p className="text-xs mt-2 text-content-faint">{t('storage.test.running')}</p>
|
||||
) : (
|
||||
<TestResult
|
||||
result={result as StorageTestResponse | undefined}
|
||||
okLabel={t('storage.test.ok')}
|
||||
failedLabel={t('storage.test.failed')}
|
||||
/>
|
||||
)}
|
||||
{row.mirrorTargets.length > 0 && (
|
||||
<div className="mt-2">
|
||||
{backfill?.status === 'running' ? (
|
||||
<>
|
||||
<p className="text-xs text-content-faint">
|
||||
{t('storage.sync.running', { done: String(backfill.done), total: String(backfill.total) })}
|
||||
</p>
|
||||
<p className="text-xs text-content-faint">
|
||||
{t('storage.sync.counts', {
|
||||
copied: String(backfill.copied),
|
||||
skipped: String(backfill.skipped),
|
||||
failed: String(backfill.failed),
|
||||
})}
|
||||
</p>
|
||||
<button type="button"
|
||||
className="text-xs underline text-content-secondary mt-1"
|
||||
style={LINK_BUTTON_STYLE}
|
||||
onClick={() => handleCancelBackfill(row)}
|
||||
>
|
||||
{t('storage.sync.cancel')}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{/* Terminal statuses render ALONGSIDE the button (not instead-of) —
|
||||
a completed/cancelled/errored backfill must stay re-runnable
|
||||
without a page reload. */}
|
||||
{backfill?.status === 'done' && (
|
||||
<p className="text-xs text-content-faint">
|
||||
{t('storage.sync.done', {
|
||||
copied: String(backfill.copied),
|
||||
deleted: String(backfill.deleted),
|
||||
failed: String(backfill.failed),
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
{backfill?.status === 'cancelled' && (
|
||||
<p className="text-xs text-content-faint">{t('storage.sync.cancelled')}</p>
|
||||
)}
|
||||
{backfill?.status === 'error' && (
|
||||
<p className="text-xs text-content-faint">
|
||||
{t('storage.sync.error', { error: backfill.error ?? '' })}
|
||||
</p>
|
||||
)}
|
||||
{syncPrompt !== row.name && (
|
||||
<button type="button"
|
||||
className="text-xs underline text-content-secondary"
|
||||
style={LINK_BUTTON_STYLE}
|
||||
onClick={() => handleStartBackfill(row)}
|
||||
>
|
||||
{t('storage.sync.now')}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{syncPrompt === row.name && (
|
||||
<div className="mt-2 rounded-lg border p-2 border-edge-secondary">
|
||||
<p className="text-xs text-content">{t('storage.sync.prompt')}</p>
|
||||
<div className="flex items-center gap-3 mt-1">
|
||||
<button type="button"
|
||||
className="text-xs underline text-content-secondary"
|
||||
style={LINK_BUTTON_STYLE}
|
||||
onClick={() => handleStartBackfill(row)}
|
||||
>
|
||||
{t('storage.sync.now')}
|
||||
</button>
|
||||
<button type="button"
|
||||
className="text-xs underline text-content-secondary"
|
||||
style={LINK_BUTTON_STYLE}
|
||||
onClick={() => setSyncPrompt(null)}
|
||||
>
|
||||
{t('storage.sync.dismiss')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{degenerate.map(({ backend, reason }) => {
|
||||
const result = testResultFor(backend.name)
|
||||
const primary = backend.type === 'mirror' ? backend.options.primary : ''
|
||||
return (
|
||||
<div key={backend.name} data-testid={`storage-backend-${backend.name}`} className="rounded-xl border p-4 border-edge-secondary">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-sm font-semibold text-content">{backend.name}</span>
|
||||
<span className="text-xs px-2 py-0.5 rounded-full border border-edge text-content-secondary">
|
||||
{t('storage.type.mirror')}
|
||||
</span>
|
||||
<span className="flex-1" />
|
||||
<button type="button" className="text-xs underline text-content-secondary" style={LINK_BUTTON_STYLE} onClick={() => admin.test(backend)}>
|
||||
{t('storage.actions.test')}
|
||||
</button>
|
||||
<button type="button" className="text-xs underline text-content-secondary" style={LINK_BUTTON_STYLE} onClick={() => setConfirmRemove({ name: backend.name, degenerate: true })}>
|
||||
{t('storage.actions.remove')}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs mt-1 text-content-faint">{t(`storage.mirror.degenerate.${reason}`, { primary })}</p>
|
||||
{result === 'running' ? (
|
||||
<p className="text-xs mt-2 text-content-faint">{t('storage.test.running')}</p>
|
||||
) : (
|
||||
<TestResult
|
||||
result={result as StorageTestResponse | undefined}
|
||||
okLabel={t('storage.test.ok')}
|
||||
failedLabel={t('storage.test.failed')}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{state.migrations.length > 0 && (
|
||||
<div className="space-y-3 mt-3">
|
||||
{state.migrations.map((m) => (
|
||||
<div
|
||||
key={m.category}
|
||||
data-testid={`storage-migration-${m.category}`}
|
||||
className="rounded-xl border p-4 border-edge-secondary"
|
||||
>
|
||||
<p className="text-sm font-semibold text-content">{t(`storage.category.${m.category}`)}</p>
|
||||
{m.status === 'running' ? (
|
||||
<>
|
||||
<p className="text-xs mt-1 text-content-faint">
|
||||
{t('storage.migrate.running', {
|
||||
category: t(`storage.category.${m.category}`),
|
||||
done: String(m.done),
|
||||
total: String(m.total),
|
||||
})}
|
||||
</p>
|
||||
<button type="button"
|
||||
className="text-xs underline text-content-secondary mt-1"
|
||||
style={LINK_BUTTON_STYLE}
|
||||
onClick={() => void handleCancelMigration(m)}
|
||||
>
|
||||
{t('storage.migrate.cancel')}
|
||||
</button>
|
||||
</>
|
||||
) : m.status === 'done' ? (
|
||||
<>
|
||||
<p className="text-xs mt-1 text-content-faint">
|
||||
{t('storage.migrate.done', { copied: String(m.copied), skipped: String(m.skipped) })}
|
||||
</p>
|
||||
{m.failed > 0 && (
|
||||
<p className="text-xs mt-1 text-content-faint">
|
||||
{t('storage.migrate.doneFailures', { failed: String(m.failed) })}
|
||||
</p>
|
||||
)}
|
||||
{m.reclaimable && (
|
||||
<p className="text-xs mt-1 text-content-faint">
|
||||
{t('storage.migrate.reclaimable', {
|
||||
objects: String(m.reclaimable.objects),
|
||||
size: formatBytes(m.reclaimable.bytes),
|
||||
from: m.from,
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
) : m.status === 'failed' ? (
|
||||
<p className="text-xs mt-1 text-content-faint">
|
||||
{t('storage.migrate.failed', { error: m.error ?? '' })}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-xs mt-1 text-content-faint">{t('storage.migrate.cancelled')}</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editing ? (
|
||||
<BackendForm
|
||||
initial={editing.initial}
|
||||
backendNames={backendNames}
|
||||
mirror={editing.mirror}
|
||||
onCommit={commitBackend}
|
||||
onCancel={() => setEditing(null)}
|
||||
/>
|
||||
) : (
|
||||
<button type="button"
|
||||
onClick={() =>
|
||||
setEditing({
|
||||
initial: null,
|
||||
originalName: null,
|
||||
mirror: { candidates: replicaCandidates(rows, null), initialTargets: [] },
|
||||
})
|
||||
}
|
||||
style={{
|
||||
padding: '8px 20px', borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit',
|
||||
fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 500,
|
||||
border: '2px solid var(--border-primary)', background: 'var(--bg-card)', color: 'var(--text-primary)',
|
||||
}}
|
||||
>
|
||||
{t('storage.backends.add')}
|
||||
</button>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title={t('storage.categories.title')} icon={FolderTree}>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4">
|
||||
{STORAGE_CATEGORIES.map((category) => {
|
||||
// The admin state's category record is exhaustive by schema contract.
|
||||
const stateEntry = state.categories[category]!
|
||||
const selectedPrimary = primaryNameOf(state, draft, effective[category])
|
||||
const changed = selectedPrimary !== primaryNameOf(state, draft, stateEntry.backend)
|
||||
const viaMirror = effective[category] !== selectedPrimary
|
||||
return (
|
||||
<div key={category} data-testid={`storage-category-${category}`}>
|
||||
<label className="block text-sm font-medium mb-1 text-content-secondary">
|
||||
{t(`storage.category.${category}`)}
|
||||
<span className="ml-2 px-1.5 py-0.5 rounded border font-mono font-normal text-xs border-edge text-content-faint">
|
||||
{category}
|
||||
</span>
|
||||
</label>
|
||||
<p className="text-xs mb-1.5 text-content-faint">{t(`storage.categoryDesc.${category}`)}</p>
|
||||
{state.usage?.categories[category] && (
|
||||
<p className="text-xs mb-1.5 text-content-faint">
|
||||
{t('storage.usage.line', {
|
||||
objects: String(state.usage.categories[category]!.objects),
|
||||
size: formatBytes(state.usage.categories[category]!.bytes),
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
<CustomSelect
|
||||
value={selectedPrimary}
|
||||
onChange={(value) => setCategory(category, String(value))}
|
||||
options={rows.map((row) => ({
|
||||
value: row.name,
|
||||
label:
|
||||
stateEntry.source === 'default' && row.name === stateEntry.backend
|
||||
? `${row.name} (${t('storage.categories.default')})`
|
||||
: row.name,
|
||||
}))}
|
||||
size="sm"
|
||||
style={{ maxWidth: 320 }}
|
||||
/>
|
||||
{changed && (
|
||||
<p role="alert" className="text-xs mt-1 text-content-faint">
|
||||
{t('storage.categories.reassignWarning')}
|
||||
</p>
|
||||
)}
|
||||
{viaMirror && CACHE_CATEGORIES.includes(category) && (
|
||||
<p role="note" className="text-xs mt-1 text-content-faint">
|
||||
{t('storage.mirror.cacheWarning')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<button type="button"
|
||||
onClick={save}
|
||||
disabled={!admin.dirty || admin.saving}
|
||||
style={{
|
||||
padding: '10px 20px', borderRadius: 10, cursor: admin.dirty && !admin.saving ? 'pointer' : 'default',
|
||||
fontFamily: 'inherit', fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600,
|
||||
border: '2px solid var(--text-primary)', background: 'var(--bg-hover)', color: 'var(--text-primary)',
|
||||
opacity: admin.dirty && !admin.saving ? 1 : 0.5,
|
||||
}}
|
||||
>
|
||||
{t('storage.save')}
|
||||
</button>
|
||||
{admin.dirty && <span className="text-xs text-content-faint">{t('storage.unsaved')}</span>}
|
||||
</div>
|
||||
{migrationQueue.length > 0 && (
|
||||
<p className="text-xs mt-2 text-content-faint">
|
||||
{t('storage.migrate.queued', { categories: categoryNames(t, migrationQueue.map((c) => c.category)) })}
|
||||
</p>
|
||||
)}
|
||||
{migratePromptOpen && (
|
||||
<div className="rounded-lg border px-3 py-2 mt-2 border-edge bg-surface-secondary" role="alertdialog">
|
||||
<p className="text-sm text-content">{t('storage.migrate.promptTitle')}</p>
|
||||
{migrationCandidates.map((c) => (
|
||||
<p key={c.category} className="text-xs mt-1 text-content-secondary">
|
||||
{c.objects === null
|
||||
? t('storage.migrate.promptLineUnknown', {
|
||||
category: t(`storage.category.${c.category}`),
|
||||
from: c.from,
|
||||
to: c.to,
|
||||
})
|
||||
: t('storage.migrate.promptLine', {
|
||||
category: t(`storage.category.${c.category}`),
|
||||
objects: String(c.objects),
|
||||
size: formatBytes(c.bytes ?? 0),
|
||||
from: c.from,
|
||||
to: c.to,
|
||||
})}
|
||||
</p>
|
||||
))}
|
||||
<div className="flex items-center gap-3 mt-2">
|
||||
<button type="button"
|
||||
className="text-xs underline text-content-secondary"
|
||||
style={LINK_BUTTON_STYLE}
|
||||
onClick={() => void moveAndSave()}
|
||||
>
|
||||
{t('storage.migrate.move')}
|
||||
</button>
|
||||
<button type="button"
|
||||
className="text-xs underline text-content-secondary"
|
||||
style={LINK_BUTTON_STYLE}
|
||||
onClick={() => void routeOnlySave()}
|
||||
>
|
||||
{t('storage.migrate.routeOnly')}
|
||||
</button>
|
||||
<button type="button"
|
||||
className="text-xs underline text-content-secondary"
|
||||
style={LINK_BUTTON_STYLE}
|
||||
onClick={() => setMigratePromptOpen(false)}
|
||||
>
|
||||
{t('storage.migrate.promptCancel')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{admin.saveError && (
|
||||
<div role="alert" className="text-sm mt-2 text-content">
|
||||
<p>{admin.saveError}</p>
|
||||
{/* A 409 leaves the draft pinned to a version the server has moved
|
||||
past; "save again" can never clear it, so the banner offers the
|
||||
one action that can — see useStorageAdmin.discardDraft. */}
|
||||
{admin.saveConflict && (
|
||||
<button type="button"
|
||||
className="text-xs underline text-content-secondary mt-1"
|
||||
style={LINK_BUTTON_STYLE}
|
||||
onClick={() => void admin.discardDraft()}
|
||||
>
|
||||
{t('storage.discardAndReload')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={confirmRemove !== null}
|
||||
onClose={() => setConfirmRemove(null)}
|
||||
onConfirm={() => {
|
||||
if (confirmRemove) {
|
||||
admin.setDraft(
|
||||
confirmRemove.degenerate
|
||||
? removeBackend(draft, confirmRemove.name)
|
||||
: removeBackendAndMirrors(state, draft, confirmRemove.name),
|
||||
)
|
||||
}
|
||||
setConfirmRemove(null)
|
||||
}}
|
||||
title={t('storage.remove.title')}
|
||||
message={confirmRemove ? removeMessage(confirmRemove.name, confirmRemove.degenerate) : ''}
|
||||
confirmLabel={t('storage.remove.title')}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { MASKED_SETTING_VALUE, type StorageBackend } from '@trek/shared';
|
||||
import { fireEvent, render, screen } from '../../../../tests/helpers/render';
|
||||
import BackendForm from './BackendForm';
|
||||
|
||||
const NAMES = ['uploads-local', 'backups-local', 'off-box'];
|
||||
|
||||
type FormProps = Parameters<typeof BackendForm>[0];
|
||||
|
||||
function renderForm(overrides: Partial<FormProps> = {}) {
|
||||
const onCommit = vi.fn();
|
||||
const onCancel = vi.fn();
|
||||
render(
|
||||
<BackendForm
|
||||
initial={null}
|
||||
backendNames={NAMES}
|
||||
onCommit={onCommit}
|
||||
onCancel={onCancel}
|
||||
{...overrides}
|
||||
/>,
|
||||
);
|
||||
return { onCommit, onCancel };
|
||||
}
|
||||
|
||||
const S3_INITIAL: StorageBackend = {
|
||||
name: 'off-box',
|
||||
type: 's3',
|
||||
options: {
|
||||
endpoint: 'http://127.0.0.1:9000', bucket: 'trek', accessKeyId: 'ak',
|
||||
secretAccessKey: MASKED_SETTING_VALUE, region: 'us-east-1', keyPrefix: '', retries: 1, timeoutMs: 30000,
|
||||
},
|
||||
};
|
||||
|
||||
describe('BackendForm', () => {
|
||||
it('FE-ADMIN-STORF-001: local renders the root path field from the registry', () => {
|
||||
renderForm();
|
||||
expect(screen.getByLabelText(/Root directory/)).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText(/Bucket/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORF-002: s3 renders every field by kind — password secret, number inputs, defaultValue placeholders', () => {
|
||||
renderForm({ initial: S3_INITIAL });
|
||||
expect(screen.getByLabelText(/Endpoint URL/)).toHaveAttribute('type', 'text');
|
||||
expect(screen.getByLabelText(/Secret access key/)).toHaveAttribute('type', 'password');
|
||||
expect(screen.getByLabelText(/Region/)).toHaveAttribute('placeholder', 'us-east-1');
|
||||
expect(screen.getByLabelText(/Retries/)).toHaveAttribute('type', 'number');
|
||||
expect(screen.getByLabelText(/Retries/)).toHaveAttribute('placeholder', '1');
|
||||
expect(screen.getByLabelText(/Timeout \(ms\)/)).toHaveAttribute('placeholder', '30000');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORF-004: the mask echoes back through commit untouched (no-op by contract)', () => {
|
||||
const { onCommit } = renderForm({ initial: S3_INITIAL });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Apply' }));
|
||||
expect(onCommit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: 'off-box',
|
||||
type: 's3',
|
||||
options: expect.objectContaining({ secretAccessKey: MASKED_SETTING_VALUE, retries: 1, timeoutMs: 30000 }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORF-005: a typed plaintext secret keeps Apply offered (no encryption-key gate)', () => {
|
||||
renderForm({ initial: S3_INITIAL });
|
||||
expect(screen.getByRole('button', { name: 'Apply' })).toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText(/Secret access key/), { target: { value: 'sk-new' } });
|
||||
expect(screen.getByRole('button', { name: 'Apply' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORF-006: Apply stays disabled until name and every required field are filled', () => {
|
||||
const { onCommit } = renderForm();
|
||||
const apply = screen.getByRole('button', { name: 'Apply' });
|
||||
expect(apply).toBeDisabled();
|
||||
fireEvent.change(screen.getByLabelText(/Name/), { target: { value: 'nas' } });
|
||||
expect(apply).toBeDisabled(); // root still empty
|
||||
fireEvent.change(screen.getByLabelText(/Root directory/), { target: { value: '/mnt/nas' } });
|
||||
expect(apply).toBeEnabled();
|
||||
fireEvent.click(apply);
|
||||
expect(onCommit).toHaveBeenCalledWith({ name: 'nas', type: 'local', options: { root: '/mnt/nas' } });
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORF-007: a duplicate name on a NEW backend warns and blocks Apply', () => {
|
||||
renderForm();
|
||||
fireEvent.change(screen.getByLabelText(/Name/), { target: { value: 'off-box' } });
|
||||
fireEvent.change(screen.getByLabelText(/Root directory/), { target: { value: '/x' } });
|
||||
expect(screen.getByText(/A backend named off-box already exists/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Apply' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORF-008: empty optional fields are omitted so the shared schema defaults apply', () => {
|
||||
const { onCommit } = renderForm();
|
||||
// Switch to s3 via the type select (CustomSelect renders options into a portal).
|
||||
fireEvent.click(screen.getByText('Local'));
|
||||
fireEvent.click(screen.getByText('S3'));
|
||||
fireEvent.change(screen.getByLabelText(/Name/), { target: { value: 'fresh' } });
|
||||
fireEvent.change(screen.getByLabelText(/Endpoint URL/), { target: { value: 'http://127.0.0.1:9000' } });
|
||||
fireEvent.change(screen.getByLabelText(/Bucket/), { target: { value: 'trek' } });
|
||||
fireEvent.change(screen.getByLabelText(/Access key ID/), { target: { value: 'ak' } });
|
||||
fireEvent.change(screen.getByLabelText(/Secret access key/), { target: { value: 'sk' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Apply' }));
|
||||
const committed = onCommit.mock.calls[0]![0] as StorageBackend;
|
||||
expect(committed.options).toEqual({
|
||||
endpoint: 'http://127.0.0.1:9000', bucket: 'trek', accessKeyId: 'ak', secretAccessKey: 'sk',
|
||||
});
|
||||
expect(committed.options).not.toHaveProperty('region');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORF-009: renaming onto another existing backend warns and blocks Apply', () => {
|
||||
renderForm({ initial: S3_INITIAL });
|
||||
expect(screen.getByRole('button', { name: 'Apply' })).toBeEnabled();
|
||||
fireEvent.change(screen.getByLabelText(/Name/), { target: { value: 'uploads-local' } });
|
||||
expect(screen.getByText(/A backend named uploads-local already exists/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Apply' })).toBeDisabled();
|
||||
// Keeping the original name stays allowed.
|
||||
fireEvent.change(screen.getByLabelText(/Name/), { target: { value: 'off-box' } });
|
||||
expect(screen.getByRole('button', { name: 'Apply' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORF-010: the type select no longer offers Mirror', () => {
|
||||
renderForm();
|
||||
fireEvent.click(screen.getByText('Local')); // open the type select
|
||||
expect(screen.queryByText('Mirror')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('S3')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORF-011: the mirror composer renders candidates minus self and commits targets', () => {
|
||||
const { onCommit } = renderForm({
|
||||
initial: S3_INITIAL,
|
||||
mirror: { candidates: ['uploads-local', 'backups-local', 'off-box'], initialTargets: ['backups-local'] },
|
||||
});
|
||||
expect(screen.getByText('Mirror targets')).toBeInTheDocument();
|
||||
const boxes = screen.getAllByRole('checkbox');
|
||||
expect(boxes).toHaveLength(2); // off-box (self) excluded
|
||||
expect(screen.getByRole('checkbox', { name: 'backups-local' })).toBeChecked();
|
||||
expect(screen.getByRole('note').textContent).toContain('slows every upload');
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'uploads-local' }));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Apply' }));
|
||||
expect(onCommit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 'off-box', type: 's3' }),
|
||||
['backups-local', 'uploads-local'],
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORF-012: unchecking every target commits an empty array (dissolve) and hides the latency note', () => {
|
||||
const { onCommit } = renderForm({
|
||||
initial: S3_INITIAL,
|
||||
mirror: { candidates: ['uploads-local'], initialTargets: ['uploads-local'] },
|
||||
});
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'uploads-local' }));
|
||||
expect(screen.queryByRole('note')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Apply' }));
|
||||
expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ name: 'off-box' }), []);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
import React, { useState } from 'react'
|
||||
import {
|
||||
STORAGE_BACKEND_TYPES,
|
||||
STORAGE_BACKEND_TYPE_IDS,
|
||||
type StorageBackend,
|
||||
type StorageBackendFieldDef,
|
||||
type StorageBackendTypeId,
|
||||
} from '@trek/shared'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import CustomSelect from '../../shared/CustomSelect'
|
||||
|
||||
type FieldValues = Record<string, string | string[]>
|
||||
|
||||
function valuesOf(backend: StorageBackend | null): FieldValues {
|
||||
if (!backend) return {}
|
||||
const values: FieldValues = {}
|
||||
for (const [key, value] of Object.entries(backend.options)) {
|
||||
values[key] = Array.isArray(value) ? value : String(value)
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
export interface BackendFormMirrorProps {
|
||||
/** Selectable replica targets (the form excludes its own name at render). */
|
||||
candidates: string[]
|
||||
initialTargets: string[]
|
||||
}
|
||||
|
||||
interface BackendFormProps {
|
||||
/** null = new backend */
|
||||
initial: StorageBackend | null
|
||||
/** Every defined backend name — mirror-target options and the duplicate pre-check. */
|
||||
backendNames: string[]
|
||||
/**
|
||||
* Present on non-mirror backends: renders the Mirror-targets composer
|
||||
* (replicas-on-primary — panel-supplied chrome, never a registry field).
|
||||
* When present, onCommit's second argument is always an array.
|
||||
*/
|
||||
mirror?: BackendFormMirrorProps
|
||||
onCommit: (backend: StorageBackend, mirrorTargets?: string[]) => void
|
||||
onCancel: () => void
|
||||
}
|
||||
|
||||
const LABEL_CLASS = 'block text-sm font-medium mb-1.5 text-content-secondary'
|
||||
const INPUT_CLASS =
|
||||
'mt-1.5 w-full px-3 py-2 border rounded-lg text-sm border-edge bg-surface-card text-content'
|
||||
|
||||
/**
|
||||
* Renders whatever STORAGE_BACKEND_TYPES declares, by field kind. The raw
|
||||
* `mirror` type is hidden from the type select — mirrors are composed via the
|
||||
* Mirror-targets prop block and synthesized by the panels (the ref-kind
|
||||
* renderers below stay for future registry types).
|
||||
*/
|
||||
export default function BackendForm({
|
||||
initial,
|
||||
backendNames,
|
||||
mirror,
|
||||
onCommit,
|
||||
onCancel,
|
||||
}: BackendFormProps): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const [type, setType] = useState<StorageBackendTypeId>(initial?.type ?? 'local')
|
||||
const [name, setName] = useState(initial?.name ?? '')
|
||||
const [values, setValues] = useState<FieldValues>(() => valuesOf(initial))
|
||||
const [targets, setTargets] = useState<string[]>(mirror?.initialTargets ?? [])
|
||||
|
||||
const fields = STORAGE_BACKEND_TYPES[type].fields as readonly StorageBackendFieldDef[]
|
||||
const refOptions = backendNames.filter((candidate) => candidate !== name.trim())
|
||||
const setValue = (key: string, value: string | string[]) =>
|
||||
setValues((prev) => ({ ...prev, [key]: value }))
|
||||
|
||||
const filled = (field: StorageBackendFieldDef): boolean => {
|
||||
const value = values[field.key]
|
||||
if (field.kind === 'backend-ref-list') return Array.isArray(value) && value.length > 0
|
||||
return typeof value === 'string' && value.trim() !== ''
|
||||
}
|
||||
const duplicate = name.trim() !== (initial?.name ?? '') && backendNames.includes(name.trim())
|
||||
const canApply =
|
||||
name.trim() !== '' && !duplicate && fields.every((f) => !f.required || filled(f))
|
||||
|
||||
const apply = () => {
|
||||
const options: Record<string, unknown> = {}
|
||||
for (const field of fields) {
|
||||
const value = values[field.key]
|
||||
if (field.kind === 'backend-ref-list') {
|
||||
options[field.key] = Array.isArray(value) ? value : []
|
||||
continue
|
||||
}
|
||||
const text = typeof value === 'string' ? value : ''
|
||||
if (text === '' && !field.required) continue // omitted → the shared schema default applies
|
||||
options[field.key] = field.kind === 'number' ? Number(text) : text
|
||||
}
|
||||
// The options were built from the same field defs the schema is generated
|
||||
// from — this is the same sanctioned cast storageModel.asWireBackend makes.
|
||||
const payload = { name: name.trim(), type, options } as StorageBackend
|
||||
// Arity matters: the landed tests pin single-argument calls when no mirror
|
||||
// block is supplied (toHaveBeenCalledWith treats a trailing undefined as a
|
||||
// mismatch), so the second argument exists only when the composer does.
|
||||
if (mirror) onCommit(payload, targets)
|
||||
else onCommit(payload)
|
||||
}
|
||||
|
||||
const renderField = (field: StorageBackendFieldDef): React.ReactElement => {
|
||||
const value = values[field.key]
|
||||
if (field.kind === 'backend-ref') {
|
||||
return (
|
||||
<div key={field.key}>
|
||||
<span className={LABEL_CLASS}>{t(field.labelKey)}</span>
|
||||
<CustomSelect
|
||||
value={typeof value === 'string' ? value : ''}
|
||||
onChange={(next) => setValue(field.key, String(next))}
|
||||
options={refOptions.map((candidate) => ({ value: candidate, label: candidate }))}
|
||||
placeholder={t(field.labelKey)}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (field.kind === 'backend-ref-list') {
|
||||
const selected = Array.isArray(value) ? value : []
|
||||
return (
|
||||
<div key={field.key}>
|
||||
<span className={LABEL_CLASS}>{t(field.labelKey)}</span>
|
||||
<div className="space-y-1">
|
||||
{refOptions.map((candidate) => (
|
||||
<label key={candidate} className="flex items-center gap-2 text-sm text-content">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(candidate)}
|
||||
onChange={(e) =>
|
||||
setValue(
|
||||
field.key,
|
||||
e.target.checked
|
||||
? [...selected, candidate]
|
||||
: selected.filter((existing) => existing !== candidate),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{candidate}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const inputType = field.kind === 'secret' ? 'password' : field.kind === 'number' ? 'number' : 'text'
|
||||
return (
|
||||
<label key={field.key} className={LABEL_CLASS}>
|
||||
{t(field.labelKey)}
|
||||
<input
|
||||
type={inputType}
|
||||
value={typeof value === 'string' ? value : ''}
|
||||
onChange={(e) => setValue(field.key, e.target.value)}
|
||||
placeholder={field.defaultValue !== undefined ? String(field.defaultValue) : ''}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
className={INPUT_CLASS}
|
||||
/>
|
||||
{field.helpKey && <span className="block text-xs mt-1 font-normal text-content-faint">{t(field.helpKey)}</span>}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border p-4 space-y-4 border-edge bg-surface-card">
|
||||
<p className="text-sm font-semibold text-content">
|
||||
{initial ? t('storage.form.editTitle') : t('storage.form.addTitle')}
|
||||
</p>
|
||||
|
||||
<label className={LABEL_CLASS}>
|
||||
{t('storage.form.name')}
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
className={INPUT_CLASS}
|
||||
/>
|
||||
</label>
|
||||
{duplicate && (
|
||||
<p className="text-xs text-content-faint" role="alert">
|
||||
{t('storage.form.duplicateName', { name: name.trim() })}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<span className={LABEL_CLASS}>{t('storage.form.type')}</span>
|
||||
<CustomSelect
|
||||
value={type}
|
||||
onChange={(next) => {
|
||||
setType(next as StorageBackendTypeId)
|
||||
setValues({}) // a different type has different fields
|
||||
}}
|
||||
options={STORAGE_BACKEND_TYPE_IDS.filter((id) => id !== 'mirror').map((id) => ({
|
||||
value: id,
|
||||
label: t(`storage.type.${id}`),
|
||||
}))}
|
||||
size="sm"
|
||||
disabled={initial !== null}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{fields.map(renderField)}
|
||||
|
||||
{mirror && (
|
||||
<div>
|
||||
<span className={LABEL_CLASS}>{t('storage.mirror.targets')}</span>
|
||||
<p className="text-xs mb-1 text-content-faint">{t('storage.mirror.targetsHelp')}</p>
|
||||
<div className="space-y-1">
|
||||
{mirror.candidates
|
||||
.filter((candidate) => candidate !== name.trim())
|
||||
.map((candidate) => (
|
||||
<label key={candidate} className="flex items-center gap-2 text-sm text-content">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={targets.includes(candidate)}
|
||||
onChange={(e) =>
|
||||
setTargets(
|
||||
e.target.checked
|
||||
? [...targets, candidate]
|
||||
: targets.filter((existing) => existing !== candidate),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{candidate}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{targets.length > 0 && (
|
||||
<p className="text-xs mt-1 text-content-faint" role="note">
|
||||
{t('storage.mirror.latencyNote')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<button type="button"
|
||||
onClick={apply}
|
||||
disabled={!canApply}
|
||||
style={{
|
||||
padding: '8px 20px', borderRadius: 10, cursor: canApply ? 'pointer' : 'default',
|
||||
fontFamily: 'inherit', fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600,
|
||||
border: '2px solid var(--text-primary)', background: 'var(--bg-hover)',
|
||||
color: 'var(--text-primary)', opacity: canApply ? 1 : 0.5,
|
||||
}}
|
||||
>
|
||||
{t('storage.form.apply')}
|
||||
</button>
|
||||
<button type="button"
|
||||
onClick={onCancel}
|
||||
style={{
|
||||
padding: '8px 20px', borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit',
|
||||
fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 500,
|
||||
border: '2px solid var(--border-primary)', background: 'var(--bg-card)', color: 'var(--text-primary)',
|
||||
}}
|
||||
>
|
||||
{t('storage.form.cancel')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
MASKED_SETTING_VALUE,
|
||||
STORAGE_CATEGORIES,
|
||||
type StorageAdminState,
|
||||
type StorageBackend,
|
||||
type StorageCategory,
|
||||
type StorageConfig,
|
||||
} from '@trek/shared';
|
||||
import {
|
||||
categoriesPointingAt,
|
||||
computeMigrationCandidates,
|
||||
foldBackends,
|
||||
mirrorProbeTargets,
|
||||
mirrorsReferencing,
|
||||
primaryNameOf,
|
||||
removeBackend,
|
||||
removeBackendAndMirrors,
|
||||
renameBackendRefs,
|
||||
replicaCandidates,
|
||||
replicaOfPrimaries,
|
||||
setMirrorTargets,
|
||||
settingsDocumentOf,
|
||||
stripCategories,
|
||||
upsertBackend,
|
||||
usageByBackend,
|
||||
} from './storageModel';
|
||||
|
||||
const STATE: StorageAdminState = {
|
||||
backends: [
|
||||
{ name: 'uploads-local', type: 'local', source: 'built-in', options: { root: '/data/uploads' }, categories: ['files'] },
|
||||
{ name: 'place-photos-local', type: 'local', source: 'env', options: { root: '/photos' }, categories: ['places'] },
|
||||
{
|
||||
name: 'off-box',
|
||||
type: 's3',
|
||||
source: 'settings',
|
||||
options: {
|
||||
endpoint: 'http://127.0.0.1:9000', bucket: 'trek', accessKeyId: 'ak',
|
||||
secretAccessKey: MASKED_SETTING_VALUE, region: 'us-east-1', keyPrefix: '', retries: 1, timeoutMs: 30000,
|
||||
},
|
||||
categories: ['covers'],
|
||||
},
|
||||
],
|
||||
categories: {
|
||||
files: { backend: 'uploads-local', source: 'default' },
|
||||
journey: { backend: 'uploads-local', source: 'default' },
|
||||
covers: { backend: 'off-box', source: 'settings' },
|
||||
avatars: { backend: 'uploads-local', source: 'default' },
|
||||
places: { backend: 'place-photos-local', source: 'default' },
|
||||
'photos-google': { backend: 'place-photos-local', source: 'default' },
|
||||
'photos-trek': { backend: 'uploads-local', source: 'default' },
|
||||
backups: { backend: 'backups-local', source: 'default' },
|
||||
},
|
||||
health: { replicaFailures: [] },
|
||||
seedFilePresent: false,
|
||||
usage: null,
|
||||
backfills: [],
|
||||
migrations: [],
|
||||
version: 5,
|
||||
configError: null,
|
||||
};
|
||||
|
||||
describe('settingsDocumentOf', () => {
|
||||
it('FE-ADMIN-STORM-001: carries ONLY settings-sourced backends and categories (the PUT contract)', () => {
|
||||
const doc = settingsDocumentOf(STATE);
|
||||
expect(doc.backends.map((b) => b.name)).toEqual(['off-box']);
|
||||
expect(doc.categories).toEqual({ covers: 'off-box' });
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-001b: carries version from state (audit #7 — the PUT body\'s optimistic-concurrency check)', () => {
|
||||
expect(settingsDocumentOf(STATE).version).toBe(5);
|
||||
expect(settingsDocumentOf({ ...STATE, version: 12 }).version).toBe(12);
|
||||
});
|
||||
});
|
||||
|
||||
describe('remove pre-check helpers', () => {
|
||||
const draft: StorageConfig = {
|
||||
backends: [
|
||||
{ name: 'nas', type: 'local', options: { root: '/mnt/nas' } },
|
||||
{ name: 'mir', type: 'mirror', options: { primary: 'backups-local', replicas: ['nas'] } },
|
||||
],
|
||||
categories: { covers: 'nas', backups: 'mir' },
|
||||
};
|
||||
|
||||
it('FE-ADMIN-STORM-002: lists categories pointing at a backend', () => {
|
||||
expect(categoriesPointingAt(draft, 'nas')).toEqual(['covers']);
|
||||
expect(categoriesPointingAt(draft, 'unused')).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-003: lists mirrors referencing a backend (primary or replica)', () => {
|
||||
expect(mirrorsReferencing(draft, 'nas')).toEqual(['mir']);
|
||||
expect(mirrorsReferencing(draft, 'backups-local')).toEqual(['mir']);
|
||||
expect(mirrorsReferencing(draft, 'unused')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('draft edits', () => {
|
||||
const draft: StorageConfig = {
|
||||
backends: [{ name: 'nas', type: 'local', options: { root: '/mnt/nas' } }],
|
||||
categories: {},
|
||||
};
|
||||
|
||||
it('FE-ADMIN-STORM-005: upsert replaces by name in place, appends new ones, never mutates', () => {
|
||||
const edited = upsertBackend(draft, { name: 'nas', type: 'local', options: { root: '/mnt/nas2' } });
|
||||
expect(edited.backends).toEqual([{ name: 'nas', type: 'local', options: { root: '/mnt/nas2' } }]);
|
||||
const added = upsertBackend(draft, { name: 'other', type: 'local', options: { root: '/o' } });
|
||||
expect(added.backends.map((b) => b.name)).toEqual(['nas', 'other']);
|
||||
expect(draft.backends).toHaveLength(1); // untouched
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-006: removeBackend filters by name', () => {
|
||||
expect(removeBackend(draft, 'nas').backends).toEqual([]);
|
||||
expect(removeBackend(draft, 'ghost').backends).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
// Hoisted to module scope (not just the mirror-fold describe below) so the
|
||||
// usageByBackend suite can reuse the same mirrored fixture the brief's test
|
||||
// snippet assumes is in scope.
|
||||
const MIRRORED_STATE: StorageAdminState = {
|
||||
...STATE,
|
||||
backends: [
|
||||
...STATE.backends,
|
||||
{
|
||||
name: 'mirror', type: 'mirror', source: 'settings',
|
||||
options: { primary: 'backups-local', replicas: ['off-box'] }, categories: ['backups'],
|
||||
},
|
||||
{ name: 'backups-local', type: 'local', source: 'built-in', options: { root: '/data/backups' }, categories: [] },
|
||||
],
|
||||
categories: { ...STATE.categories, backups: { backend: 'mirror', source: 'settings' } },
|
||||
};
|
||||
const mirroredDraft = (): StorageConfig => settingsDocumentOf(MIRRORED_STATE);
|
||||
|
||||
describe('mirror fold/synthesize (replicas-on-primary)', () => {
|
||||
it('FE-ADMIN-STORM-007: foldBackends hides the mirror, decorates primary and replica, unions categories', () => {
|
||||
const { rows, degenerate } = foldBackends(MIRRORED_STATE, mirroredDraft());
|
||||
expect(degenerate).toEqual([]);
|
||||
expect(rows.map((r) => r.name)).not.toContain('mirror');
|
||||
const primary = rows.find((r) => r.name === 'backups-local')!;
|
||||
expect(primary.mirrorTargets).toEqual(['off-box']);
|
||||
expect(primary.mirrorName).toBe('mirror');
|
||||
expect(primary.categories).toContain('backups'); // via the mirror
|
||||
const replica = rows.find((r) => r.name === 'off-box')!;
|
||||
expect(replica.replicaOf).toEqual(['backups-local']);
|
||||
expect(replica.categories).toContain('covers'); // its own direct assignment survives
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-008: setMirrorTargets synthesizes a mirror and reroutes ALL effective categories of the primary, defaults included', () => {
|
||||
const draft = settingsDocumentOf(STATE); // no mirror yet; backups is default → backups-local
|
||||
const next = setMirrorTargets(STATE, draft, 'backups-local', ['off-box']);
|
||||
const mirror = next.backends.find((b) => b.type === 'mirror')!;
|
||||
expect(mirror.name).toBe('backups-local-mirror');
|
||||
expect(mirror.options).toEqual({ primary: 'backups-local', replicas: ['off-box'] });
|
||||
expect(next.categories.backups).toBe('backups-local-mirror'); // default-sourced category rewritten
|
||||
expect(next.categories.covers).toBe('off-box'); // categories of OTHER backends untouched
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-009: setMirrorTargets adopts a foreign-named mirror in place', () => {
|
||||
const next = setMirrorTargets(MIRRORED_STATE, mirroredDraft(), 'backups-local', ['off-box', 'uploads-local']);
|
||||
const mirrors = next.backends.filter((b) => b.type === 'mirror');
|
||||
expect(mirrors).toHaveLength(1);
|
||||
expect(mirrors[0]!.name).toBe('mirror'); // adopted, not renamed
|
||||
expect(mirrors[0]!.options).toEqual({ primary: 'backups-local', replicas: ['off-box', 'uploads-local'] });
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-010: empty targets dissolve the mirror and revert default-sourced categories', () => {
|
||||
// Build the synthesized state locally: default backups routed via a fresh mirror…
|
||||
const withMirror = setMirrorTargets(STATE, settingsDocumentOf(STATE), 'backups-local', ['off-box']);
|
||||
// …then dissolve it: the backups entry must DROP (state says its default is backups-local).
|
||||
const dissolved = setMirrorTargets(STATE, withMirror, 'backups-local', []);
|
||||
expect(dissolved.backends.some((b) => b.type === 'mirror')).toBe(false);
|
||||
expect(dissolved.categories).not.toHaveProperty('backups');
|
||||
// Against MIRRORED_STATE (backups already settings-sourced at the mirror), dissolve re-points instead of dropping.
|
||||
const repointed = setMirrorTargets(MIRRORED_STATE, mirroredDraft(), 'backups-local', []);
|
||||
expect(repointed.categories.backups).toBe('backups-local');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-011: degenerate mirrors are classified, never hidden', () => {
|
||||
const draft: StorageConfig = {
|
||||
backends: [
|
||||
{ name: 'off-box', type: 's3', options: STATE.backends[2]!.options } as StorageBackend,
|
||||
{ name: 'm1', type: 'mirror', options: { primary: 'uploads-local', replicas: ['off-box'] } },
|
||||
{ name: 'm2', type: 'mirror', options: { primary: 'uploads-local', replicas: ['off-box'] } },
|
||||
{ name: 'm-env', type: 'mirror', options: { primary: 'place-photos-local', replicas: ['off-box'] } },
|
||||
{ name: 'm-ghost', type: 'mirror', options: { primary: 'nope', replicas: [] } },
|
||||
],
|
||||
categories: {},
|
||||
};
|
||||
const { rows, degenerate } = foldBackends(STATE, draft);
|
||||
expect(rows.find((r) => r.name === 'uploads-local')!.mirrorName).toBe('m1'); // first wins
|
||||
expect(degenerate.map((d) => [d.backend.name, d.reason])).toEqual([
|
||||
['m2', 'duplicate-mirror'],
|
||||
['m-env', 'env-primary'],
|
||||
['m-ghost', 'missing-primary'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-012: renameBackendRefs rewrites mirror primaries, replicas, and category entries', () => {
|
||||
const draft: StorageConfig = {
|
||||
backends: [
|
||||
{ name: 'nas', type: 'local', options: { root: '/mnt/nas' } },
|
||||
{ name: 'm', type: 'mirror', options: { primary: 'nas', replicas: ['nas'] } },
|
||||
],
|
||||
categories: { covers: 'nas' },
|
||||
};
|
||||
const renamed = renameBackendRefs(draft, 'nas', 'nas2');
|
||||
const mirror = renamed.backends.find((b) => b.type === 'mirror')!;
|
||||
expect(mirror.options).toEqual({ primary: 'nas2', replicas: ['nas2'] });
|
||||
expect(renamed.categories.covers).toBe('nas2');
|
||||
expect(renamed.backends[0]!.name).toBe('nas'); // the backend row itself is the caller's job
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-013: removeBackendAndMirrors cascades; replicaOfPrimaries phrases in primary names', () => {
|
||||
const draft = mirroredDraft();
|
||||
expect(replicaOfPrimaries(draft, 'off-box')).toEqual(['backups-local']);
|
||||
const removed = removeBackendAndMirrors(MIRRORED_STATE, draft, 'backups-local');
|
||||
expect(removed.backends.some((b) => b.name === 'mirror')).toBe(false);
|
||||
expect(removed.backends.some((b) => b.name === 'backups-local')).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-015: removing a replica strips it from remaining mirrors; a mirror stripped empty dissolves', () => {
|
||||
// Single-replica mirror: stripping off-box empties it → dissolve + re-point
|
||||
// (backups is settings-sourced at the mirror in MIRRORED_STATE, so it re-points, not drops).
|
||||
const dissolved = removeBackendAndMirrors(MIRRORED_STATE, mirroredDraft(), 'off-box');
|
||||
expect(dissolved.backends.some((b) => b.name === 'off-box')).toBe(false);
|
||||
expect(dissolved.backends.some((b) => b.type === 'mirror')).toBe(false);
|
||||
expect(dissolved.categories.backups).toBe('backups-local');
|
||||
// Multi-replica mirror: stripping one target keeps the mirror alive with the rest.
|
||||
const twoTargets = setMirrorTargets(MIRRORED_STATE, mirroredDraft(), 'backups-local', ['off-box', 'uploads-local']);
|
||||
const survived = removeBackendAndMirrors(MIRRORED_STATE, twoTargets, 'off-box');
|
||||
const mirror = survived.backends.find((b) => b.type === 'mirror')!;
|
||||
expect(mirror.options).toEqual({ primary: 'backups-local', replicas: ['uploads-local'] });
|
||||
expect(survived.categories.backups).toBe('mirror'); // still routed via the surviving mirror
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-014: primaryNameOf maps mirror names (draft or state) to their primary; others pass through', () => {
|
||||
expect(primaryNameOf(MIRRORED_STATE, mirroredDraft(), 'mirror')).toBe('backups-local');
|
||||
expect(primaryNameOf(MIRRORED_STATE, { backends: [], categories: {} }, 'mirror')).toBe('backups-local'); // state fallback
|
||||
expect(primaryNameOf(STATE, settingsDocumentOf(STATE), 'uploads-local')).toBe('uploads-local');
|
||||
});
|
||||
});
|
||||
|
||||
describe('replicaCandidates', () => {
|
||||
it('FE-ADMIN-STORM-020: offers only rows that serve no category, never the row being edited', () => {
|
||||
const { rows } = foldBackends(MIRRORED_STATE, mirroredDraft());
|
||||
// uploads-local/place-photos-local serve categories directly;
|
||||
// backups-local serves backups through the mirror it is the primary of;
|
||||
// off-box carries a direct `covers` assignment. Nothing is offerable.
|
||||
expect(replicaCandidates(rows, 'backups-local')).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-021: keeps an already-selected target listed so it can be unchecked', () => {
|
||||
const { rows } = foldBackends(MIRRORED_STATE, mirroredDraft());
|
||||
expect(replicaCandidates(rows, 'backups-local', ['off-box'])).toEqual(['off-box']);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-022: an unassigned row is offered', () => {
|
||||
const state: StorageAdminState = {
|
||||
...MIRRORED_STATE,
|
||||
backends: [
|
||||
...MIRRORED_STATE.backends,
|
||||
{ name: 'cold-store', type: 'local', source: 'settings', options: { root: '/data/cold' }, categories: [] },
|
||||
],
|
||||
};
|
||||
const { rows } = foldBackends(state, settingsDocumentOf(state));
|
||||
expect(replicaCandidates(rows, 'backups-local')).toEqual(['cold-store']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('usageByBackend', () => {
|
||||
it('FE-ADMIN-STORM-016: sums categories onto their effective backend rows, mirrors onto the primary, legacy onto uploads-local', () => {
|
||||
const usage = {
|
||||
computedAt: 1,
|
||||
categories: Object.fromEntries(
|
||||
STORAGE_CATEGORIES.map((c) => [c, { objects: 1, bytes: 10 }]),
|
||||
) as Record<StorageCategory, { objects: number; bytes: number }>,
|
||||
legacyPhotos: { objects: 5, bytes: 50 },
|
||||
};
|
||||
const state = { ...MIRRORED_STATE, usage };
|
||||
const sums = usageByBackend(state, mirroredDraft())!;
|
||||
// backups routes via the mirror → attributed to backups-local (the primary row).
|
||||
expect(sums['backups-local']).toEqual({ objects: 1, bytes: 10 });
|
||||
// uploads-local serves 4 direct categories (files, journey, avatars, photos-trek —
|
||||
// this fixture's `places` and `photos-google` default to the env-sourced
|
||||
// place-photos-local backend, not uploads-local) + legacy photos.
|
||||
expect(sums['uploads-local']).toEqual({ objects: 4 + 5, bytes: 40 + 50 });
|
||||
// places + photos-google both default to place-photos-local.
|
||||
expect(sums['place-photos-local']).toEqual({ objects: 2, bytes: 20 });
|
||||
// covers routes to off-box directly.
|
||||
expect(sums['off-box']).toEqual({ objects: 1, bytes: 10 });
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-017: null usage yields null', () => {
|
||||
expect(usageByBackend({ ...STATE, usage: null }, settingsDocumentOf(STATE))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('computeMigrationCandidates', () => {
|
||||
it('FE-ADMIN-STORM-018: lists changed categories with usage counts; zero-object ones are excluded; null usage keeps them with null counts', () => {
|
||||
const state: StorageAdminState = {
|
||||
...STATE,
|
||||
usage: {
|
||||
computedAt: 1,
|
||||
categories: {
|
||||
files: { objects: 3, bytes: 300 },
|
||||
journey: { objects: 0, bytes: 0 },
|
||||
} as Record<StorageCategory, { objects: number; bytes: number }>,
|
||||
legacyPhotos: { objects: 0, bytes: 0 },
|
||||
},
|
||||
};
|
||||
const base = settingsDocumentOf(state);
|
||||
const draft: StorageConfig = {
|
||||
...base,
|
||||
categories: { ...base.categories, files: 'off-box', journey: 'off-box', avatars: 'off-box' },
|
||||
};
|
||||
const candidates = computeMigrationCandidates(draft, state);
|
||||
expect(candidates).toEqual([
|
||||
{ category: 'files', from: 'uploads-local', to: 'off-box', toWire: 'off-box', objects: 3, bytes: 300 },
|
||||
{ category: 'avatars', from: 'uploads-local', to: 'off-box', toWire: 'off-box', objects: null, bytes: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-018b: reassigning onto a mirrored primary yields toWire = the mirror wire name while `to` stays the display primary', () => {
|
||||
const state: StorageAdminState = {
|
||||
...STATE,
|
||||
backends: [
|
||||
...STATE.backends,
|
||||
{ name: 'nas', type: 'local', source: 'settings', options: { root: '/mnt/nas' }, categories: [] },
|
||||
{
|
||||
name: 'off-box-mirror',
|
||||
type: 'mirror',
|
||||
source: 'settings',
|
||||
options: { primary: 'off-box', replicas: ['nas'] },
|
||||
categories: [],
|
||||
},
|
||||
],
|
||||
usage: {
|
||||
computedAt: 1,
|
||||
categories: { files: { objects: 3, bytes: 300 } } as Record<StorageCategory, { objects: number; bytes: number }>,
|
||||
legacyPhotos: { objects: 0, bytes: 0 },
|
||||
},
|
||||
};
|
||||
const base = settingsDocumentOf(state);
|
||||
// Reassign 'files' to the mirrored primary's WIRE name — the same value
|
||||
// setCategory() writes into the draft when the operator picks a mirrored
|
||||
// primary in the UI (adoptedMirrorFor(draft, 'off-box')?.name).
|
||||
const draft: StorageConfig = { ...base, categories: { ...base.categories, files: 'off-box-mirror' } };
|
||||
const candidates = computeMigrationCandidates(draft, state);
|
||||
expect(candidates).toEqual([
|
||||
{ category: 'files', from: 'uploads-local', to: 'off-box', toWire: 'off-box-mirror', objects: 3, bytes: 300 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-019: stripCategories restores the saved assignment for exactly the named categories', () => {
|
||||
const base = settingsDocumentOf(STATE);
|
||||
const draft: StorageConfig = {
|
||||
...base,
|
||||
categories: { ...base.categories, files: 'off-box', covers: 'uploads-local' },
|
||||
};
|
||||
|
||||
const strippedFiles = stripCategories(draft, STATE, ['files']);
|
||||
expect(strippedFiles.categories.files).toBeUndefined(); // default-sourced: saved value is "no override"
|
||||
expect(strippedFiles.categories.covers).toBe('uploads-local'); // untouched — not in the strip list
|
||||
|
||||
const strippedCovers = stripCategories(draft, STATE, ['covers']);
|
||||
expect(strippedCovers.categories.covers).toBe('off-box'); // settings-sourced saved value restored explicitly
|
||||
expect(strippedCovers.categories.files).toBe('off-box'); // untouched — not in the strip list
|
||||
});
|
||||
});
|
||||
|
||||
describe('mirrorProbeTargets', () => {
|
||||
it('FE-ADMIN-STORM-020: a non-mirror candidate passes through unchanged', () => {
|
||||
const local: StorageBackend = { name: 'uploads-local', type: 'local', options: { root: '/data/uploads' } };
|
||||
expect(mirrorProbeTargets(settingsDocumentOf(STATE), STATE, local)).toEqual([local]);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-021: expands primary + replicas — draft override wins per name, falling back to state for names the draft never touched', () => {
|
||||
const mirror: StorageBackend = {
|
||||
name: 'mirror', type: 'mirror',
|
||||
options: { primary: 'uploads-local', replicas: ['off-box'] },
|
||||
};
|
||||
// The draft carries an EDITED off-box (unsaved endpoint change) but never
|
||||
// touches uploads-local (a built-in, never draft-owned).
|
||||
const editedOffBox = {
|
||||
name: 'off-box', type: 's3',
|
||||
options: { ...(STATE.backends[2]!.options as Record<string, unknown>), endpoint: 'http://edited:9000' },
|
||||
} as StorageBackend;
|
||||
const draft: StorageConfig = { backends: [editedOffBox, mirror], categories: {} };
|
||||
|
||||
const targets = mirrorProbeTargets(draft, STATE, mirror);
|
||||
expect(targets.map((t) => t.name)).toEqual(['uploads-local', 'off-box']);
|
||||
// Primary: no draft entry — resolved from state (the live built-in).
|
||||
expect(targets[0]).toEqual({ name: 'uploads-local', type: 'local', options: { root: '/data/uploads' } });
|
||||
// Replica: draft override wins — the unsaved edit, not the saved options.
|
||||
expect((targets[1]!.options as Record<string, unknown>).endpoint).toBe('http://edited:9000');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-STORM-022: a name resolving to neither draft nor state is dropped, not thrown', () => {
|
||||
const mirror: StorageBackend = {
|
||||
name: 'mirror', type: 'mirror',
|
||||
options: { primary: 'uploads-local', replicas: ['ghost'] },
|
||||
};
|
||||
const targets = mirrorProbeTargets(settingsDocumentOf(STATE), STATE, mirror);
|
||||
expect(targets.map((t) => t.name)).toEqual(['uploads-local']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,440 @@
|
||||
import {
|
||||
STORAGE_CATEGORIES,
|
||||
type StorageAdminState,
|
||||
type StorageBackend,
|
||||
type StorageCategory,
|
||||
type StorageConfig,
|
||||
type StorageConfigPut,
|
||||
} from '@trek/shared'
|
||||
|
||||
/** One entry of the effective world (GET state), as the panels render it. */
|
||||
export type StateBackend = StorageAdminState['backends'][number]
|
||||
|
||||
/**
|
||||
* The settings-owned document the PUT carries: settings-sourced backends and
|
||||
* settings-sourced category assignments ONLY — built-ins and env backends are
|
||||
* never in the body unless the operator overrides one by name (in which case
|
||||
* the override already reports source 'settings'). Carries `version` from
|
||||
* the state it was built at (audit #7 — optimistic concurrency): the hook
|
||||
* re-attaches this same version on every subsequent local edit, so a PUT
|
||||
* always submits the version the operator's form was loaded at, not
|
||||
* whatever the server currently holds.
|
||||
*/
|
||||
export function settingsDocumentOf(state: StorageAdminState): StorageConfigPut {
|
||||
return {
|
||||
backends: state.backends.filter((b) => b.source === 'settings').map(asWireBackend),
|
||||
categories: Object.fromEntries(
|
||||
Object.entries(state.categories)
|
||||
.filter(([, entry]) => entry.source === 'settings')
|
||||
.map(([category, entry]) => [category, entry.backend]),
|
||||
) as StorageConfig['categories'],
|
||||
version: state.version,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* State options are already schema-shaped (the wire contract guarantees it;
|
||||
* secret fields carry the mask, which the server unmasks by name on PUT/test) —
|
||||
* the cast re-attaches the discriminated-union type the loose state record dropped.
|
||||
*/
|
||||
export function asWireBackend(backend: Pick<StateBackend, 'name' | 'type' | 'options'>): StorageBackend {
|
||||
return { name: backend.name, type: backend.type, options: backend.options } as StorageBackend
|
||||
}
|
||||
|
||||
/** Draft categories pointing at a backend name (the friendly remove pre-check). */
|
||||
export function categoriesPointingAt(draft: StorageConfig, name: string): StorageCategory[] {
|
||||
return (Object.entries(draft.categories) as Array<[StorageCategory, string]>)
|
||||
.filter(([, backend]) => backend === name)
|
||||
.map(([category]) => category)
|
||||
}
|
||||
|
||||
/** Draft mirrors referencing a backend name as primary or replica (remove pre-check). */
|
||||
export function mirrorsReferencing(draft: StorageConfig, name: string): string[] {
|
||||
return draft.backends
|
||||
.filter((b) => b.type === 'mirror' && (b.options.primary === name || b.options.replicas.includes(name)))
|
||||
.map((b) => b.name)
|
||||
}
|
||||
|
||||
/** Replace by name in place, or append. Never mutates. */
|
||||
export function upsertBackend(draft: StorageConfig, backend: StorageBackend): StorageConfig {
|
||||
const exists = draft.backends.some((b) => b.name === backend.name)
|
||||
return {
|
||||
...draft,
|
||||
backends: exists
|
||||
? draft.backends.map((b) => (b.name === backend.name ? backend : b))
|
||||
: [...draft.backends, backend],
|
||||
}
|
||||
}
|
||||
|
||||
export function removeBackend(draft: StorageConfig, name: string): StorageConfig {
|
||||
return { ...draft, backends: draft.backends.filter((b) => b.name !== name) }
|
||||
}
|
||||
|
||||
// ── Mirror fold/synthesize (replicas-on-primary spec) ─────────────────────────
|
||||
// The draft stays the wire document; folding is a view rule, synthesis a set
|
||||
// of pure draft operations. Mirror NAMES never reach the UI — every helper
|
||||
// that renders phrases mirrors as their primary.
|
||||
|
||||
type MirrorBackend = Extract<StorageBackend, { type: 'mirror' }>
|
||||
const isMirror = (b: StorageBackend): b is MirrorBackend => b.type === 'mirror'
|
||||
|
||||
export interface FoldedBackendRow {
|
||||
name: string
|
||||
type: 'local' | 's3'
|
||||
source: 'built-in' | 'env' | 'settings'
|
||||
backend: StorageBackend
|
||||
/** Direct assignments ∪ assignments routed via the adopted mirror. */
|
||||
categories: StorageCategory[]
|
||||
/** Adopted mirror's replicas — [] when unmirrored. */
|
||||
mirrorTargets: string[]
|
||||
/** Adopted mirror's wire name — needed by draft ops, hidden from the UI. */
|
||||
mirrorName: string | null
|
||||
/** Primaries whose adopted mirror lists this backend as a replica. */
|
||||
replicaOf: string[]
|
||||
}
|
||||
|
||||
export interface DegenerateMirror {
|
||||
backend: StorageBackend
|
||||
reason: 'duplicate-mirror' | 'env-primary' | 'missing-primary'
|
||||
categories: StorageCategory[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-fetchable content — replicating it is usually wasteful. photos-google is
|
||||
* the Google photo cache (place-photo-cache.service.ts); places is mostly
|
||||
* provider-derived imagery.
|
||||
*/
|
||||
export const CACHE_CATEGORIES: readonly StorageCategory[] = ['photos-google', 'places']
|
||||
|
||||
/** The configurable categories resolved draft-over-state (draft entries win; defaults fill the rest). */
|
||||
export function effectiveCategoryMap(state: StorageAdminState, draft: StorageConfig): Record<StorageCategory, string> {
|
||||
const map = {} as Record<StorageCategory, string>
|
||||
for (const category of STORAGE_CATEGORIES) {
|
||||
// The admin state's category record is exhaustive by schema contract.
|
||||
map[category] = draft.categories[category] ?? state.categories[category]!.backend
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
/** First draft mirror wrapping the named primary — the one the UI manages. */
|
||||
export function adoptedMirrorFor(draft: StorageConfig, primaryName: string): MirrorBackend | undefined {
|
||||
return draft.backends.filter(isMirror).find((m) => m.options.primary === primaryName)
|
||||
}
|
||||
|
||||
/**
|
||||
* Client-side mirror expansion for the test probe (audit fix — the server's
|
||||
* `testBackend` resolves a mirror candidate's primary/replicas against its
|
||||
* OWN live snapshot by name, so probing a mirrored row with unsaved draft
|
||||
* edits to those targets would silently test the SAVED options instead of
|
||||
* what's on the form). Draft overrides win per name, falling back to state
|
||||
* (built-in/env); a name that resolves to neither is dropped — that
|
||||
* primary/replica no longer exists, and the row already renders as
|
||||
* degenerate in that case.
|
||||
*/
|
||||
export function mirrorProbeTargets(
|
||||
draft: StorageConfig,
|
||||
state: StorageAdminState,
|
||||
mirror: StorageBackend,
|
||||
): StorageBackend[] {
|
||||
if (mirror.type !== 'mirror') return [mirror]
|
||||
const names = [mirror.options.primary, ...mirror.options.replicas]
|
||||
return names
|
||||
.map((name): StorageBackend | null => {
|
||||
const draftMatch = draft.backends.find((b) => b.name === name)
|
||||
if (draftMatch) return draftMatch
|
||||
const stateMatch = state.backends.find((b) => b.name === name)
|
||||
return stateMatch ? asWireBackend(stateMatch) : null
|
||||
})
|
||||
.filter((b): b is StorageBackend => b !== null)
|
||||
}
|
||||
|
||||
export function foldBackends(
|
||||
state: StorageAdminState,
|
||||
draft: StorageConfig,
|
||||
): { rows: FoldedBackendRow[]; degenerate: DegenerateMirror[] } {
|
||||
const draftNames = draft.backends.map((b) => b.name)
|
||||
const effective = effectiveCategoryMap(state, draft)
|
||||
const categoriesOf = (name: string): StorageCategory[] =>
|
||||
STORAGE_CATEGORIES.filter((category) => effective[category] === name)
|
||||
|
||||
// Base (non-mirror) rows, slice-2 precedence: built-ins/env from the state
|
||||
// unless a draft row overrides the name; settings rows from the draft.
|
||||
const base: Array<Pick<FoldedBackendRow, 'name' | 'type' | 'source' | 'backend'>> = []
|
||||
for (const b of state.backends) {
|
||||
if (b.type === 'mirror') continue // mirrors fold below; the draft owns them
|
||||
if (draftNames.includes(b.name)) continue
|
||||
if (b.source === 'settings') continue // removed from the draft, pending save
|
||||
base.push({ name: b.name, type: b.type, source: b.source, backend: asWireBackend(b) })
|
||||
}
|
||||
for (const b of draft.backends) {
|
||||
if (isMirror(b)) continue
|
||||
base.push({ name: b.name, type: b.type, source: 'settings', backend: b })
|
||||
}
|
||||
|
||||
// Adoption: the first mirror per editable primary; the rest are degenerate —
|
||||
// rendered unfolded with a reason, never silently dropped.
|
||||
const adopted = new Map<string, MirrorBackend>()
|
||||
const degenerate: DegenerateMirror[] = []
|
||||
for (const mirror of draft.backends.filter(isMirror)) {
|
||||
const primary = base.find((row) => row.name === mirror.options.primary)
|
||||
if (!primary) degenerate.push({ backend: mirror, reason: 'missing-primary', categories: categoriesOf(mirror.name) })
|
||||
else if (primary.source === 'env') degenerate.push({ backend: mirror, reason: 'env-primary', categories: categoriesOf(mirror.name) })
|
||||
else if (adopted.has(primary.name)) degenerate.push({ backend: mirror, reason: 'duplicate-mirror', categories: categoriesOf(mirror.name) })
|
||||
else adopted.set(primary.name, mirror)
|
||||
}
|
||||
|
||||
const rows = base.map((row): FoldedBackendRow => {
|
||||
const mirror = adopted.get(row.name)
|
||||
return {
|
||||
...row,
|
||||
categories: [...categoriesOf(row.name), ...(mirror ? categoriesOf(mirror.name) : [])],
|
||||
mirrorTargets: mirror ? [...mirror.options.replicas] : [],
|
||||
mirrorName: mirror?.name ?? null,
|
||||
replicaOf: [...adopted.values()]
|
||||
.filter((m) => m.options.replicas.includes(row.name))
|
||||
.map((m) => m.options.primary),
|
||||
}
|
||||
})
|
||||
return { rows, degenerate }
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows offerable as mirror replicas (the "Mirror targets" picker).
|
||||
*
|
||||
* A backend that already serves a category — directly, or as the primary of a
|
||||
* mirror a category routes to, which is exactly what `row.categories` unions —
|
||||
* can never also be a replica: the mirror's sync sweep makes each replica
|
||||
* MATCH the primary, deleting whatever the primary doesn't hold, and `backups`
|
||||
* sweeps the replica's entire root. The server refuses such a config outright
|
||||
* (storage-registry.service.ts, assertNoSharedReplicas); the picker simply
|
||||
* never offers one, so the operator can't walk into the refusal.
|
||||
*
|
||||
* Targets already selected on this mirror stay listed regardless — they must
|
||||
* remain visible to be unchecked (and a config that predates this rule is
|
||||
* repaired here, not hidden).
|
||||
*/
|
||||
export function replicaCandidates(
|
||||
rows: FoldedBackendRow[],
|
||||
selfName: string | null,
|
||||
currentTargets: readonly string[] = [],
|
||||
): string[] {
|
||||
return rows
|
||||
.filter((row) => row.name !== selfName)
|
||||
.filter((row) => row.categories.length === 0 || currentTargets.includes(row.name))
|
||||
.map((row) => row.name)
|
||||
}
|
||||
|
||||
function uniqueMirrorName(state: StorageAdminState, draft: StorageConfig, primaryName: string): string {
|
||||
const taken = new Set([...draft.backends.map((b) => b.name), ...state.backends.map((b) => b.name)])
|
||||
const base = `${primaryName}-mirror`
|
||||
if (!taken.has(base)) return base
|
||||
for (let n = 2; ; n++) {
|
||||
if (!taken.has(`${base}-${n}`)) return `${base}-${n}`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* targets non-empty: update the adopted mirror in place (or synthesize one)
|
||||
* and route every category that effectively resolves to the primary —
|
||||
* default-sourced included — through it. targets empty: dissolve, re-pointing
|
||||
* the mirror's categories at the primary and dropping entries that revert to
|
||||
* their built-in default.
|
||||
*/
|
||||
export function setMirrorTargets(
|
||||
state: StorageAdminState,
|
||||
draft: StorageConfig,
|
||||
primaryName: string,
|
||||
targets: string[],
|
||||
): StorageConfig {
|
||||
const adopted = adoptedMirrorFor(draft, primaryName)
|
||||
|
||||
if (targets.length === 0) {
|
||||
if (!adopted) return draft
|
||||
const categories = { ...draft.categories }
|
||||
for (const category of STORAGE_CATEGORIES) {
|
||||
if (categories[category] !== adopted.name) continue
|
||||
const stateEntry = state.categories[category]! // exhaustive by schema contract
|
||||
if (stateEntry.source === 'default' && stateEntry.backend === primaryName) delete categories[category]
|
||||
else categories[category] = primaryName
|
||||
}
|
||||
return { backends: draft.backends.filter((b) => b.name !== adopted.name), categories }
|
||||
}
|
||||
|
||||
const effective = effectiveCategoryMap(state, draft)
|
||||
const mirror: StorageBackend = {
|
||||
name: adopted?.name ?? uniqueMirrorName(state, draft, primaryName),
|
||||
type: 'mirror',
|
||||
options: { primary: primaryName, replicas: [...targets] },
|
||||
}
|
||||
const backends = adopted
|
||||
? draft.backends.map((b) => (b.name === adopted.name ? mirror : b))
|
||||
: [...draft.backends, mirror]
|
||||
const categories = { ...draft.categories }
|
||||
for (const category of STORAGE_CATEGORIES) {
|
||||
if (effective[category] === primaryName) categories[category] = mirror.name
|
||||
}
|
||||
return { backends, categories }
|
||||
}
|
||||
|
||||
/** Rewrite every reference to a renamed backend: mirror primaries, replicas, category entries. */
|
||||
export function renameBackendRefs(draft: StorageConfig, oldName: string, newName: string): StorageConfig {
|
||||
return {
|
||||
backends: draft.backends.map((b) => {
|
||||
if (!isMirror(b)) return b
|
||||
return {
|
||||
...b,
|
||||
options: {
|
||||
primary: b.options.primary === oldName ? newName : b.options.primary,
|
||||
replicas: b.options.replicas.map((r) => (r === oldName ? newName : r)),
|
||||
},
|
||||
}
|
||||
}),
|
||||
categories: Object.fromEntries(
|
||||
Object.entries(draft.categories).map(([category, backend]) => [category, backend === oldName ? newName : backend]),
|
||||
) as StorageConfig['categories'],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a backend, every mirror wrapping it as primary, and every replica
|
||||
* reference to it in the remaining mirrors — a mirror stripped of its last
|
||||
* replica dissolves (with the same category re-pointing as an explicit
|
||||
* dissolve), so the draft never carries a phantom reference the composer
|
||||
* cannot render or repair.
|
||||
*/
|
||||
export function removeBackendAndMirrors(
|
||||
state: StorageAdminState,
|
||||
draft: StorageConfig,
|
||||
name: string,
|
||||
): StorageConfig {
|
||||
const stripped = draft.backends
|
||||
.filter((b) => b.name !== name && !(isMirror(b) && b.options.primary === name))
|
||||
.map((b) =>
|
||||
isMirror(b) && b.options.replicas.includes(name)
|
||||
? { ...b, options: { ...b.options, replicas: b.options.replicas.filter((r) => r !== name) } }
|
||||
: b,
|
||||
)
|
||||
let next: StorageConfig = { ...draft, backends: stripped }
|
||||
for (const mirror of stripped.filter(isMirror)) {
|
||||
if (mirror.options.replicas.length > 0) continue
|
||||
if (adoptedMirrorFor(next, mirror.options.primary)?.name === mirror.name) {
|
||||
next = setMirrorTargets(state, next, mirror.options.primary, [])
|
||||
} else {
|
||||
// A degenerate duplicate stripped empty: drop it and re-point its categories.
|
||||
const categories = { ...next.categories }
|
||||
for (const category of STORAGE_CATEGORIES) {
|
||||
if (categories[category] === mirror.name) categories[category] = mirror.options.primary
|
||||
}
|
||||
next = { backends: next.backends.filter((b) => b.name !== mirror.name), categories }
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
/** Primaries whose mirrors use the named backend as a replica — pre-check copy stays in primary names. */
|
||||
export function replicaOfPrimaries(draft: StorageConfig, name: string): string[] {
|
||||
return draft.backends
|
||||
.filter(isMirror)
|
||||
.filter((m) => m.options.replicas.includes(name))
|
||||
.map((m) => m.options.primary)
|
||||
}
|
||||
|
||||
/** Map a mirror name (draft first, then state) to its primary; anything else passes through. */
|
||||
export function primaryNameOf(state: StorageAdminState, draft: StorageConfig, backendName: string): string {
|
||||
const draftMirror = draft.backends.filter(isMirror).find((m) => m.name === backendName)
|
||||
if (draftMirror) return draftMirror.options.primary
|
||||
const stateMirror = state.backends.find((b) => b.name === backendName && b.type === 'mirror')
|
||||
if (stateMirror) return String((stateMirror.options as Record<string, unknown>).primary)
|
||||
return backendName
|
||||
}
|
||||
|
||||
/**
|
||||
* Usage sums per VISIBLE backend row: each category's numbers land on the row
|
||||
* that serves it (a mirror-routed category on the mirror's PRIMARY row), and
|
||||
* the legacy photos directory lands on uploads-local — the only backend the
|
||||
* served-legacy `photos` category ever resolves to.
|
||||
*/
|
||||
export function usageByBackend(
|
||||
state: StorageAdminState,
|
||||
draft: StorageConfig,
|
||||
): Record<string, { objects: number; bytes: number }> | null {
|
||||
if (!state.usage) return null
|
||||
const sums: Record<string, { objects: number; bytes: number }> = {}
|
||||
const add = (row: string, entry: { objects: number; bytes: number }) => {
|
||||
const current = (sums[row] ??= { objects: 0, bytes: 0 })
|
||||
current.objects += entry.objects
|
||||
current.bytes += entry.bytes
|
||||
}
|
||||
const effective = effectiveCategoryMap(state, draft)
|
||||
for (const category of STORAGE_CATEGORIES) {
|
||||
const entry = state.usage.categories[category]
|
||||
if (entry) add(primaryNameOf(state, draft, effective[category]), entry)
|
||||
}
|
||||
// The served-legacy `photos` directory always resolves to uploads-local —
|
||||
// hardcoded, not derived, because it is not one of the configurable categories.
|
||||
add(primaryNameOf(state, draft, 'uploads-local'), state.usage.legacyPhotos)
|
||||
return sums
|
||||
}
|
||||
|
||||
// ── Category migration (copy → flip → delta sweep) ────────────────────────────
|
||||
|
||||
/** One reassigned category the operator might want to move existing objects for. */
|
||||
export interface MigrationCandidate {
|
||||
category: StorageCategory
|
||||
from: string
|
||||
/** Display primary — never a hidden mirror name; used by the prompt lines and comparisons. */
|
||||
to: string
|
||||
/**
|
||||
* The RAW effective draft backend name for this category — possibly a
|
||||
* mirror's wire name when `to` is a mirrored primary. The migration POST
|
||||
* must carry this, not `to`: posting the bare primary would silently drop
|
||||
* replication for a category that was just routed onto a mirror.
|
||||
*/
|
||||
toWire: string
|
||||
/** null when usage was never scanned — the prompt still fires, with an unknown-size line. */
|
||||
objects: number | null
|
||||
bytes: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Every category whose effective (draft-over-state) PRIMARY backend differs
|
||||
* from what's currently saved — normalized through `primaryNameOf` so simply
|
||||
* wrapping (or unwrapping) a mirror around the same primary never counts as
|
||||
* a candidate; mirroring is the existing sync/backfill flow, not a category
|
||||
* migration. Zero-object categories (usage present, 0 objects) are excluded —
|
||||
* nothing to move; null usage (never scanned) keeps the category as a
|
||||
* candidate with null counts, per spec ("unknown still prompts").
|
||||
*/
|
||||
export function computeMigrationCandidates(draft: StorageConfig, state: StorageAdminState): MigrationCandidate[] {
|
||||
const effective = effectiveCategoryMap(state, draft)
|
||||
const candidates: MigrationCandidate[] = []
|
||||
for (const category of STORAGE_CATEGORIES) {
|
||||
const from = primaryNameOf(state, draft, state.categories[category]!.backend) // exhaustive by schema contract
|
||||
const toWire = effective[category]
|
||||
const to = primaryNameOf(state, draft, toWire)
|
||||
if (from === to) continue
|
||||
const usage = state.usage?.categories[category]
|
||||
candidates.push({ category, from, to, toWire, objects: usage ? usage.objects : null, bytes: usage ? usage.bytes : null })
|
||||
}
|
||||
return candidates.filter((c) => c.objects !== 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* Revert exactly the named categories in `draft` back to what's currently
|
||||
* saved in `saved` — same default/settings convention as the rest of this
|
||||
* file (drop the override when the saved entry is default-sourced, write the
|
||||
* explicit backend name otherwise). Every other draft edit is untouched.
|
||||
*/
|
||||
export function stripCategories(
|
||||
draft: StorageConfig,
|
||||
saved: StorageAdminState,
|
||||
categories: StorageCategory[],
|
||||
): StorageConfig {
|
||||
const next = { ...draft.categories }
|
||||
for (const category of categories) {
|
||||
const savedEntry = saved.categories[category]! // exhaustive by schema contract
|
||||
if (savedEntry.source === 'default') delete next[category]
|
||||
else next[category] = savedEntry.backend
|
||||
}
|
||||
return { ...draft, categories: next }
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { StorageAdminState, StorageBackend, StorageConfig, StorageConfigPut, StorageTestResponse } from '@trek/shared'
|
||||
import { adminApi } from '../../../api/client'
|
||||
import { getApiErrorMessage, type ApiError } from '../../../types'
|
||||
import { settingsDocumentOf } from './storageModel'
|
||||
|
||||
export type StorageTestResults = Record<string, StorageTestResponse | 'running'>
|
||||
|
||||
/** 50ms under vitest so poll tests run on real timers (MSW + fake timers don't mix). */
|
||||
export const BACKFILL_POLL_MS = import.meta.env.MODE === 'test' ? 50 : 5000
|
||||
|
||||
/** True for a 409 response — the version this draft was built at is no longer current (audit #7). */
|
||||
function isConflictError(err: unknown): boolean {
|
||||
return typeof err === 'object' && err !== null && 'response' in err && (err as ApiError).response?.status === 409
|
||||
}
|
||||
|
||||
export interface StorageAdmin {
|
||||
state: StorageAdminState | null
|
||||
/** The settings-owned document (the PUT body), with local edits layered in. Carries the version the draft was built at. */
|
||||
draft: StorageConfigPut | null
|
||||
dirty: boolean
|
||||
loading: boolean
|
||||
loadError: string | null
|
||||
/** Server 400s/409s land here VERBATIM (400) or as the distinct conflict copy (409) — long registry messages outlive a toast. */
|
||||
saveError: string | null
|
||||
/** True while `saveError` is the 409 copy — the panels render the discard-and-reload escape next to it. */
|
||||
saveConflict: boolean
|
||||
saving: boolean
|
||||
testResults: StorageTestResults
|
||||
setDraft: (next: StorageConfig) => void
|
||||
/** PUTs `overrideDraft ?? draft` — an override lets a caller strip categories from the wire body without staging them (and marking dirty) via setDraft. */
|
||||
save: (overrideDraft?: StorageConfig) => Promise<boolean>
|
||||
test: (backend: StorageBackend) => Promise<void>
|
||||
/**
|
||||
* Probe each target individually (client-expanded mirror primary +
|
||||
* replicas — see `mirrorProbeTargets`) and merge the results into one
|
||||
* `StorageTestResponse` under `key` (the row's mirror wire name). Never
|
||||
* sends the mirror stub itself — each call probes a concrete backend.
|
||||
*/
|
||||
testMirror: (key: string, targets: StorageBackend[]) => Promise<void>
|
||||
/** null on success; the verbatim server error otherwise. */
|
||||
startBackfill: (mirrorName: string) => Promise<string | null>
|
||||
cancelBackfill: (mirrorName: string) => Promise<string | null>
|
||||
startMigration: (category: string, to: string) => Promise<string | null>
|
||||
cancelMigration: (category: string) => Promise<string | null>
|
||||
refreshStats: () => Promise<string | null>
|
||||
/** Re-GETs admin state (poll-safe — see the implementation comment below). Exposed for the panel's failed-queue recovery path. */
|
||||
refreshState: () => Promise<void>
|
||||
/**
|
||||
* The 409's only exit: throw the local edits away and reload the saved
|
||||
* settings (fresh GET → fresh draft → fresh version), clearing dirty and
|
||||
* saveError. See the implementation comment for why refreshState can't do
|
||||
* this itself.
|
||||
*/
|
||||
discardDraft: () => Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared by the desktop and phone storage panels (DefaultUserSettingsTab
|
||||
* model: self-contained, adminApi directly, deliberately no offline core —
|
||||
* hoster-level config is online-only).
|
||||
*/
|
||||
export function useStorageAdmin(genericError: string, conflictError: string): StorageAdmin {
|
||||
const [state, setState] = useState<StorageAdminState | null>(null)
|
||||
const [draft, setDraftState] = useState<StorageConfigPut | null>(null)
|
||||
const [dirty, setDirty] = useState(false)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
const [saveError, setSaveError] = useState<string | null>(null)
|
||||
const [saveConflict, setSaveConflict] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [testResults, setTestResults] = useState<StorageTestResults>({})
|
||||
|
||||
// Read imperatively from the poll effect/refreshState so a stale closure
|
||||
// never re-derives the draft out from under an in-flight edit.
|
||||
const dirtyRef = useRef(dirty)
|
||||
useEffect(() => {
|
||||
dirtyRef.current = dirty
|
||||
}, [dirty])
|
||||
|
||||
// Read imperatively at refreshState's resolve time so a poll GET that was
|
||||
// in flight when a save started never applies after the save's own state.
|
||||
const savingRef = useRef(saving)
|
||||
useEffect(() => {
|
||||
savingRef.current = saving
|
||||
}, [saving])
|
||||
|
||||
// Bumped by every deliberate state application (initial load, save
|
||||
// success). A refreshState() call captures the seq before its GET and
|
||||
// drops the response if the seq moved on — i.e. a save applied its own
|
||||
// fresher state — while that GET was in flight.
|
||||
const stateSeq = useRef(0)
|
||||
|
||||
const applyState = useCallback((next: StorageAdminState) => {
|
||||
stateSeq.current += 1
|
||||
setState(next)
|
||||
setDraftState(settingsDocumentOf(next))
|
||||
setDirty(false)
|
||||
setSaveError(null)
|
||||
setSaveConflict(false)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
adminApi
|
||||
.getStorage()
|
||||
.then((data) => {
|
||||
if (!cancelled) applyState(data)
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelled) setLoadError(getApiErrorMessage(err, genericError))
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [applyState, genericError])
|
||||
|
||||
// Re-attaches the CURRENT draft's version onto whatever shape the caller
|
||||
// hands in (the storageModel edit helpers are version-blind — they operate
|
||||
// on plain StorageConfig — so this is the one place that keeps `version`
|
||||
// pinned to what the operator's form was loaded at, no matter how many
|
||||
// local edits run in between).
|
||||
const setDraft = useCallback((next: StorageConfig) => {
|
||||
setDraftState((prev) => ({ ...next, version: prev?.version ?? 0 }))
|
||||
setDirty(true)
|
||||
}, [])
|
||||
|
||||
// Poll-safe refresh: replaces `state` unconditionally, but only re-derives
|
||||
// `draft` when the operator has no unsaved edits in flight — never touches
|
||||
// `dirty`/`saveError`, so a running poll cannot clobber a dirty draft or
|
||||
// mask a pending save error.
|
||||
//
|
||||
// Race guard: a poll GET issued before a save's PUT resolves can resolve
|
||||
// AFTER the save applied its own (fresher) response, overwriting it with
|
||||
// the pre-save world. Capture the state-application sequence number before
|
||||
// the await and drop the response if it moved on, or if a save is
|
||||
// in-flight/just landed (read via a ref so it's current at resolve time).
|
||||
//
|
||||
// Declared before `save` (which calls it on a 409) — a hook's `const`s
|
||||
// must exist before another callback's dependency array references them.
|
||||
const refreshState = useCallback(async (): Promise<void> => {
|
||||
const seq = stateSeq.current
|
||||
const next = await adminApi.getStorage()
|
||||
if (stateSeq.current !== seq || savingRef.current) return
|
||||
setState(next)
|
||||
if (!dirtyRef.current) setDraftState(settingsDocumentOf(next))
|
||||
}, [])
|
||||
|
||||
const save = useCallback(
|
||||
async (overrideDraft?: StorageConfig): Promise<boolean> => {
|
||||
if (!draft) return false
|
||||
// Always the DRAFT's own version, even for an overrideDraft (a variant
|
||||
// of the same draft with categories stripped, per stripCategories) —
|
||||
// both share the same version basis: what the operator's form was
|
||||
// loaded/refreshed at, never re-read from `state` here (that would
|
||||
// defeat the whole check — see setDraft's re-attach comment above).
|
||||
const body: StorageConfigPut = { ...(overrideDraft ?? draft), version: draft.version }
|
||||
setSaving(true)
|
||||
setSaveError(null)
|
||||
setSaveConflict(false)
|
||||
try {
|
||||
// The response is the fresh effective world, never the request echo.
|
||||
applyState(await adminApi.updateStorage(body))
|
||||
return true
|
||||
} catch (err: unknown) {
|
||||
if (isConflictError(err)) {
|
||||
// Something else (another admin's save, or a category migration's
|
||||
// flip) wrote since this draft's version was captured. Refresh
|
||||
// `state` so the operator sees the fresh world, but the dirty
|
||||
// draft itself is left untouched for review (dirty is never
|
||||
// cleared here) — refreshState() already respects dirtyRef.
|
||||
setSaveError(conflictError)
|
||||
setSaveConflict(true)
|
||||
void refreshState().catch(() => {})
|
||||
} else {
|
||||
setSaveError(getApiErrorMessage(err, genericError))
|
||||
}
|
||||
return false
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
},
|
||||
[draft, applyState, genericError, conflictError, refreshState],
|
||||
)
|
||||
|
||||
/**
|
||||
* Conflict recovery (final-review fix): after a 409 the dirty draft keeps
|
||||
* the version it was built at. refreshState deliberately leaves a dirty
|
||||
* draft's version alone — bumping it there would resurrect audit #7, where
|
||||
* the background poll floats a mid-edit draft past a migration flip it
|
||||
* never carried — so nothing else can ever move it, and every retry 409s
|
||||
* again. The operator's way out is to say so explicitly: discard the local
|
||||
* edits, reload the saved settings, and start over from the fresh version.
|
||||
* A fresh GET (not the possibly-dropped post-409 refresh) guarantees that
|
||||
* version is current, and applyState clears dirty/saveError with it.
|
||||
*/
|
||||
const discardDraft = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
applyState(await adminApi.getStorage())
|
||||
} catch (err: unknown) {
|
||||
setSaveError(getApiErrorMessage(err, genericError))
|
||||
setSaveConflict(false)
|
||||
}
|
||||
}, [applyState, genericError])
|
||||
|
||||
const test = useCallback(
|
||||
async (backend: StorageBackend): Promise<void> => {
|
||||
setTestResults((prev) => ({ ...prev, [backend.name]: 'running' }))
|
||||
try {
|
||||
const result = await adminApi.testStorageBackend(backend)
|
||||
setTestResults((prev) => ({ ...prev, [backend.name]: result }))
|
||||
} catch (err: unknown) {
|
||||
const error = getApiErrorMessage(err, genericError)
|
||||
setTestResults((prev) => ({
|
||||
...prev,
|
||||
[backend.name]: { ok: false, targets: [{ name: backend.name, ok: false, error }] },
|
||||
}))
|
||||
}
|
||||
},
|
||||
[genericError],
|
||||
)
|
||||
|
||||
const testMirror = useCallback(
|
||||
async (key: string, targets: StorageBackend[]): Promise<void> => {
|
||||
setTestResults((prev) => ({ ...prev, [key]: 'running' }))
|
||||
const settled = await Promise.all(
|
||||
targets.map(async (target) => {
|
||||
try {
|
||||
const result = await adminApi.testStorageBackend(target)
|
||||
return result.targets[0] ?? { name: target.name, ok: result.ok }
|
||||
} catch (err: unknown) {
|
||||
return { name: target.name, ok: false, error: getApiErrorMessage(err, genericError) }
|
||||
}
|
||||
}),
|
||||
)
|
||||
setTestResults((prev) => ({ ...prev, [key]: { ok: settled.every((r) => r.ok), targets: settled } }))
|
||||
},
|
||||
[genericError],
|
||||
)
|
||||
|
||||
// While any backfill or category migration is running, poll GET state so
|
||||
// progress/counts advance without the operator refreshing the page.
|
||||
useEffect(() => {
|
||||
if (
|
||||
!state?.backfills.some((b) => b.status === 'running') &&
|
||||
!state?.migrations.some((m) => m.status === 'running')
|
||||
)
|
||||
return
|
||||
const iv = setInterval(() => {
|
||||
// A transient poll failure is retried on the next tick — it must never
|
||||
// surface as a toast or interrupt the operator's in-progress edit.
|
||||
void refreshState().catch(() => {})
|
||||
}, BACKFILL_POLL_MS)
|
||||
return () => clearInterval(iv)
|
||||
}, [state, refreshState])
|
||||
|
||||
const startBackfill = useCallback(
|
||||
async (mirrorName: string): Promise<string | null> => {
|
||||
try {
|
||||
await adminApi.startStorageBackfill(mirrorName)
|
||||
void refreshState().catch(() => {})
|
||||
return null
|
||||
} catch (err: unknown) {
|
||||
return getApiErrorMessage(err, genericError)
|
||||
}
|
||||
},
|
||||
[refreshState, genericError],
|
||||
)
|
||||
|
||||
const cancelBackfill = useCallback(
|
||||
async (mirrorName: string): Promise<string | null> => {
|
||||
try {
|
||||
await adminApi.cancelStorageBackfill(mirrorName)
|
||||
void refreshState().catch(() => {})
|
||||
return null
|
||||
} catch (err: unknown) {
|
||||
return getApiErrorMessage(err, genericError)
|
||||
}
|
||||
},
|
||||
[refreshState, genericError],
|
||||
)
|
||||
|
||||
const startMigration = useCallback(
|
||||
async (category: string, to: string): Promise<string | null> => {
|
||||
try {
|
||||
await adminApi.startStorageMigration(category, to)
|
||||
// Awaited (unlike cancelMigration/startBackfill/cancelBackfill): the
|
||||
// queue effect's in-flight lock releases as soon as this promise
|
||||
// resolves, so admin.state must already reflect the just-started
|
||||
// migration by then — otherwise the next queued candidate can
|
||||
// dequeue and POST before the server has confirmed this one.
|
||||
await refreshState().catch(() => {})
|
||||
return null
|
||||
} catch (err: unknown) {
|
||||
return getApiErrorMessage(err, genericError)
|
||||
}
|
||||
},
|
||||
[refreshState, genericError],
|
||||
)
|
||||
|
||||
const cancelMigration = useCallback(
|
||||
async (category: string): Promise<string | null> => {
|
||||
try {
|
||||
await adminApi.cancelStorageMigration(category)
|
||||
void refreshState().catch(() => {})
|
||||
return null
|
||||
} catch (err: unknown) {
|
||||
return getApiErrorMessage(err, genericError)
|
||||
}
|
||||
},
|
||||
[refreshState, genericError],
|
||||
)
|
||||
|
||||
const refreshStats = useCallback(async (): Promise<string | null> => {
|
||||
try {
|
||||
const usage = await adminApi.refreshStorageStats()
|
||||
setState((prev) => (prev ? { ...prev, usage } : prev))
|
||||
return null
|
||||
} catch (err: unknown) {
|
||||
return getApiErrorMessage(err, genericError)
|
||||
}
|
||||
}, [genericError])
|
||||
|
||||
return {
|
||||
state,
|
||||
draft,
|
||||
dirty,
|
||||
loading,
|
||||
loadError,
|
||||
saveError,
|
||||
saveConflict,
|
||||
saving,
|
||||
testResults,
|
||||
setDraft,
|
||||
save,
|
||||
test,
|
||||
testMirror,
|
||||
startBackfill,
|
||||
cancelBackfill,
|
||||
startMigration,
|
||||
cancelMigration,
|
||||
refreshStats,
|
||||
refreshState,
|
||||
discardDraft,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
// FE-W4BGT-001 to FE-W4BGT-022
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { screen, act, waitFor } from '@testing-library/react'
|
||||
import { render, fireEvent } from '../../../tests/helpers/render'
|
||||
import { reservationsApi, healthApi } from '../../api/client'
|
||||
import { addListener } from '../../api/websocket'
|
||||
import { useBackgroundTasksStore, type BackgroundImportTask } from '../../store/backgroundTasksStore'
|
||||
import BackgroundTasksWidget from './BackgroundTasksWidget'
|
||||
|
||||
const navigate = vi.fn()
|
||||
vi.mock('react-router', async () => {
|
||||
const actual = await vi.importActual<typeof import('react-router')>('react-router')
|
||||
return { ...actual, useNavigate: () => navigate }
|
||||
})
|
||||
vi.mock('../../api/websocket', () => ({ addListener: vi.fn(), removeListener: vi.fn() }))
|
||||
vi.mock('../../api/client', () => ({
|
||||
reservationsApi: { importJobStatus: vi.fn(), importBookingAsync: vi.fn() },
|
||||
healthApi: { features: vi.fn() },
|
||||
}))
|
||||
vi.mock('../../db/offlineDb', () => ({ saveImportFiles: vi.fn(() => Promise.resolve()) }))
|
||||
|
||||
const task = (overrides: Partial<BackgroundImportTask> = {}): BackgroundImportTask => ({
|
||||
id: 'j1', tripId: 't1', label: 'voucher.pdf', status: 'done', done: 0, total: 1, items: [], warnings: [],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
type WsHandler = (e: Record<string, unknown>) => void
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(healthApi.features).mockReturnValue(new Promise(() => {}))
|
||||
vi.mocked(reservationsApi.importJobStatus).mockReturnValue(new Promise(() => {}))
|
||||
useBackgroundTasksStore.setState({ tasks: [] })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('BackgroundTasksWidget — rendering', () => {
|
||||
it('FE-W4BGT-001: renders nothing without tasks', () => {
|
||||
const { container, baseElement } = render(<BackgroundTasksWidget />)
|
||||
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
expect(baseElement.querySelectorAll('button')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-W4BGT-002: a running job shows the spinner, the parsing note and no close button', () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', done: 1, total: 3 })] })
|
||||
const { baseElement } = render(<BackgroundTasksWidget />)
|
||||
|
||||
expect(screen.getByText('voucher.pdf')).toBeInTheDocument()
|
||||
expect(screen.getByText(/· 1\/3$/)).toBeInTheDocument()
|
||||
expect(baseElement.querySelector('.animate-spin')).not.toBeNull()
|
||||
expect(screen.queryByLabelText('Close')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4BGT-003: a single-file job omits the counter', () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', done: 0, total: 1 })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
expect(screen.queryByText(/·/)).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4BGT-004: a restored done job without items still reads as parsing', () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'done', items: undefined })] })
|
||||
const { baseElement } = render(<BackgroundTasksWidget />)
|
||||
|
||||
expect(baseElement.querySelector('.animate-spin')).not.toBeNull()
|
||||
expect(screen.getByLabelText('Close')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BGT-005: a finished job with items offers the review action', () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ items: [{ id: 1 }] as never })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Import' }))
|
||||
|
||||
expect(useBackgroundTasksStore.getState().tasks[0].reviewRequested).toBe(true)
|
||||
expect(navigate).toHaveBeenCalledWith('/trips/t1')
|
||||
})
|
||||
|
||||
it('FE-W4BGT-006: a failed job shows the error message', () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'error', error: 'AI quota exhausted' })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
expect(screen.getByText('AI quota exhausted')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BGT-007: the close button drops the card', () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task()] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Close'))
|
||||
|
||||
expect(useBackgroundTasksStore.getState().tasks).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('BackgroundTasksWidget — websocket', () => {
|
||||
it('FE-W4BGT-008: import:progress updates the running card', () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', total: 4 })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
const handler = vi.mocked(addListener).mock.calls[0][0] as WsHandler
|
||||
|
||||
act(() => { handler({ type: 'import:progress', jobId: 'j1', tripId: 't1', done: 2, total: 4 }) })
|
||||
|
||||
expect(screen.getByText(/· 2\/4$/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BGT-009: import:done attaches the parsed items', () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', items: undefined })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
const handler = vi.mocked(addListener).mock.calls[0][0] as WsHandler
|
||||
|
||||
act(() => { handler({ type: 'import:done', jobId: 'j1', tripId: 't1', result: { items: [{ id: 1 }], warnings: [] } }) })
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Import' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BGT-010: import:error surfaces the message', () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'running' })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
const handler = vi.mocked(addListener).mock.calls[0][0] as WsHandler
|
||||
|
||||
act(() => { handler({ type: 'import:error', jobId: 'j1', tripId: 't1', message: 'boom' }) })
|
||||
|
||||
expect(screen.getByText('boom')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BGT-011: unrelated events and events without a job id are ignored', () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', total: 4 })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
const handler = vi.mocked(addListener).mock.calls[0][0] as WsHandler
|
||||
|
||||
act(() => {
|
||||
handler({ type: 'place:updated', jobId: 'j1' })
|
||||
handler({ type: 'import:progress', done: 3, total: 4 })
|
||||
handler({ done: 3 })
|
||||
})
|
||||
|
||||
expect(screen.getByText(/· 0\/4$/)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('BackgroundTasksWidget — rehydrate', () => {
|
||||
it('FE-W4BGT-012: a restored job that the server finished gets its items back', async () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', items: undefined })] })
|
||||
vi.mocked(reservationsApi.importJobStatus).mockResolvedValue({
|
||||
status: 'done', done: 1, total: 1, result: { items: [{ id: 1 }], warnings: [] },
|
||||
} as never)
|
||||
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
expect(await screen.findByRole('button', { name: 'Import' })).toBeInTheDocument()
|
||||
expect(reservationsApi.importJobStatus).toHaveBeenCalledWith('t1', 'j1')
|
||||
})
|
||||
|
||||
it('FE-W4BGT-013: a restored job the server reports as failed shows the error', async () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', items: undefined })] })
|
||||
vi.mocked(reservationsApi.importJobStatus).mockResolvedValue({ status: 'error', error: 'expired', done: 0, total: 1 } as never)
|
||||
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
expect(await screen.findByText('expired')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BGT-014: a restored job the server has dropped is removed', async () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', items: undefined })] })
|
||||
vi.mocked(reservationsApi.importJobStatus).mockRejectedValue({ response: { status: 404 } })
|
||||
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
await waitFor(() => expect(useBackgroundTasksStore.getState().tasks).toHaveLength(0))
|
||||
})
|
||||
|
||||
it('FE-W4BGT-015: a non-404 failure keeps the card', async () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', items: undefined })] })
|
||||
vi.mocked(reservationsApi.importJobStatus).mockRejectedValue({ response: { status: 500 } })
|
||||
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
await waitFor(() => expect(reservationsApi.importJobStatus).toHaveBeenCalled())
|
||||
expect(useBackgroundTasksStore.getState().tasks).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('BackgroundTasksWidget — poll backstop', () => {
|
||||
it('FE-W4BGT-021: a job the server drops mid-poll ends as an error instead of spinning on', async () => {
|
||||
vi.useFakeTimers()
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', items: undefined })] })
|
||||
vi.mocked(reservationsApi.importJobStatus)
|
||||
.mockResolvedValueOnce({ status: 'running', done: 0, total: 1 } as never)
|
||||
.mockRejectedValue({ response: { status: 404 } })
|
||||
|
||||
render(<BackgroundTasksWidget />)
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5000) })
|
||||
|
||||
expect(useBackgroundTasksStore.getState().tasks[0].status).toBe('error')
|
||||
// The file parsed fine — blaming it would send the user looking for a problem
|
||||
// that isn't there.
|
||||
expect(useBackgroundTasksStore.getState().tasks[0].error).toBe('Unknown error')
|
||||
})
|
||||
|
||||
it('FE-W4BGT-022: a transient poll failure leaves the job running', async () => {
|
||||
vi.useFakeTimers()
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', items: undefined })] })
|
||||
vi.mocked(reservationsApi.importJobStatus)
|
||||
.mockResolvedValueOnce({ status: 'running', done: 0, total: 1 } as never)
|
||||
.mockRejectedValue({ response: { status: 500 } })
|
||||
|
||||
render(<BackgroundTasksWidget />)
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5000) })
|
||||
|
||||
expect(useBackgroundTasksStore.getState().tasks[0].status).toBe('running')
|
||||
})
|
||||
})
|
||||
|
||||
describe('BackgroundTasksWidget — AI retry', () => {
|
||||
const withFiles = () => task({
|
||||
items: [], sourceFiles: [new File(['%PDF'], 'voucher.pdf', { type: 'application/pdf' })],
|
||||
})
|
||||
|
||||
it('FE-W4BGT-016: offers the AI retry only when the feature is on', async () => {
|
||||
vi.mocked(healthApi.features).mockResolvedValue({ aiParsing: true } as never)
|
||||
useBackgroundTasksStore.setState({ tasks: [withFiles()] })
|
||||
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
expect(await screen.findByRole('button', { name: /AI/i })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BGT-017: hides the retry when the feature probe fails', async () => {
|
||||
vi.mocked(healthApi.features).mockRejectedValue(new Error('down'))
|
||||
useBackgroundTasksStore.setState({ tasks: [withFiles()] })
|
||||
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
await waitFor(() => expect(healthApi.features).toHaveBeenCalled())
|
||||
expect(screen.queryByRole('button', { name: /AI/i })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4BGT-018: hides the retry on a job that already ran with force-ai', async () => {
|
||||
vi.mocked(healthApi.features).mockResolvedValue({ aiParsing: true } as never)
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ items: [], mode: 'force-ai', sourceFiles: [new File([''], 'a.pdf')] })] })
|
||||
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
await waitFor(() => expect(healthApi.features).toHaveBeenCalled())
|
||||
expect(screen.queryByRole('button', { name: /AI/i })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4BGT-019: retrying swaps the card for the new force-ai job', async () => {
|
||||
vi.mocked(healthApi.features).mockResolvedValue({ aiParsing: true } as never)
|
||||
vi.mocked(reservationsApi.importBookingAsync).mockResolvedValue({ jobId: 'j2' } as never)
|
||||
useBackgroundTasksStore.setState({ tasks: [withFiles()] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /AI/i }))
|
||||
|
||||
await waitFor(() => {
|
||||
const tasks = useBackgroundTasksStore.getState().tasks
|
||||
expect(tasks).toHaveLength(1)
|
||||
expect(tasks[0]).toMatchObject({ id: 'j2', mode: 'force-ai', tripId: 't1' })
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-W4BGT-020: a refused retry surfaces the server error on the original card', async () => {
|
||||
vi.mocked(healthApi.features).mockResolvedValue({ aiParsing: true } as never)
|
||||
vi.mocked(reservationsApi.importBookingAsync).mockRejectedValue({ response: { data: { error: 'No model configured' } } })
|
||||
useBackgroundTasksStore.setState({ tasks: [withFiles()] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /AI/i }))
|
||||
|
||||
expect(await screen.findByText('No model configured')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,14 +1,19 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { screen } from '@testing-library/react'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { render } from '../../../tests/helpers/render'
|
||||
import { reservationsApi, healthApi } from '../../api/client'
|
||||
import { saveImportFiles } from '../../db/offlineDb'
|
||||
import { useBackgroundTasksStore, type BackgroundImportTask } from '../../store/backgroundTasksStore'
|
||||
import BackgroundTasksWidget from './BackgroundTasksWidget'
|
||||
|
||||
vi.mock('../../api/websocket', () => ({ addListener: vi.fn(), removeListener: vi.fn() }))
|
||||
vi.mock('../../api/client', () => ({
|
||||
// Keep the rehydrate/poll backstops pending so the seeded state is what renders.
|
||||
reservationsApi: { importJobStatus: vi.fn(() => new Promise(() => {})) },
|
||||
reservationsApi: { importJobStatus: vi.fn(() => new Promise(() => {})), importBookingAsync: vi.fn() },
|
||||
healthApi: { features: vi.fn() },
|
||||
}))
|
||||
vi.mock('../../db/offlineDb', () => ({ saveImportFiles: vi.fn(() => Promise.resolve()) }))
|
||||
|
||||
const task = (overrides: Partial<BackgroundImportTask> = {}): BackgroundImportTask => ({
|
||||
id: 'j1',
|
||||
@@ -22,8 +27,14 @@ const task = (overrides: Partial<BackgroundImportTask> = {}): BackgroundImportTa
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const pdf = () => new File(['%PDF'], 'voucher.pdf', { type: 'application/pdf' })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// Like the poll backstop above: leave the feature probe pending so tests that don't care
|
||||
// about the AI retry render the same widget they did before the button existed.
|
||||
vi.mocked(healthApi.features).mockReturnValue(new Promise(() => {}))
|
||||
vi.mocked(saveImportFiles).mockResolvedValue(undefined)
|
||||
useBackgroundTasksStore.setState({ tasks: [] })
|
||||
})
|
||||
|
||||
@@ -42,4 +53,101 @@ describe('BackgroundTasksWidget', () => {
|
||||
expect(screen.getByText('No reservations could be extracted from the uploaded files.')).toBeInTheDocument()
|
||||
expect(screen.queryByText(/AI parsing failed/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
describe('AI retry', () => {
|
||||
it('offers the retry on an empty result once the addon reports AI parsing', async () => {
|
||||
vi.mocked(healthApi.features).mockResolvedValue({ bookingImport: true, aiParsing: true })
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ sourceFiles: [pdf()] })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
expect(await screen.findByRole('button', { name: 'Try AI parsing' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('stays hidden when the addon is off, the files are gone, or the run was already force-ai', async () => {
|
||||
vi.mocked(healthApi.features).mockResolvedValue({ bookingImport: true, aiParsing: false })
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ sourceFiles: [pdf()] })] })
|
||||
const { unmount } = render(<BackgroundTasksWidget />)
|
||||
await waitFor(() => expect(healthApi.features).toHaveBeenCalled())
|
||||
expect(screen.queryByRole('button', { name: 'Try AI parsing' })).not.toBeInTheDocument()
|
||||
unmount()
|
||||
|
||||
vi.mocked(healthApi.features).mockResolvedValue({ bookingImport: true, aiParsing: true })
|
||||
// Rehydrated from storage: sourceFiles can't survive a reload, so there is nothing to resend.
|
||||
useBackgroundTasksStore.setState({ tasks: [task()] })
|
||||
const withoutFiles = render(<BackgroundTasksWidget />)
|
||||
await waitFor(() => expect(healthApi.features).toHaveBeenCalledTimes(2))
|
||||
expect(screen.queryByRole('button', { name: 'Try AI parsing' })).not.toBeInTheDocument()
|
||||
withoutFiles.unmount()
|
||||
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ sourceFiles: [pdf()], mode: 'force-ai' })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
await waitFor(() => expect(healthApi.features).toHaveBeenCalledTimes(3))
|
||||
expect(screen.queryByRole('button', { name: 'Try AI parsing' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('re-submits the files with force-ai, keeps them for the review and replaces the task', async () => {
|
||||
const file = pdf()
|
||||
vi.mocked(healthApi.features).mockResolvedValue({ bookingImport: true, aiParsing: true })
|
||||
vi.mocked(reservationsApi.importBookingAsync).mockResolvedValue({ jobId: 'j2' })
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ sourceFiles: [file] })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Try AI parsing' }))
|
||||
|
||||
expect(reservationsApi.importBookingAsync).toHaveBeenCalledWith('t1', [file], 'force-ai')
|
||||
// Without this the reviewed bookings lose their source document after a reload.
|
||||
await waitFor(() => expect(saveImportFiles).toHaveBeenCalledWith('j2', [file]))
|
||||
await waitFor(() => {
|
||||
const tasks = useBackgroundTasksStore.getState().tasks
|
||||
expect(tasks).toHaveLength(1)
|
||||
expect(tasks[0]).toMatchObject({ id: 'j2', tripId: 't1', status: 'running', mode: 'force-ai' })
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the task and surfaces the server error when the retry is rejected', async () => {
|
||||
vi.mocked(healthApi.features).mockResolvedValue({ bookingImport: true, aiParsing: true })
|
||||
vi.mocked(reservationsApi.importBookingAsync).mockRejectedValue({ response: { data: { error: 'No AI model configured' } } })
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ sourceFiles: [pdf()] })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Try AI parsing' }))
|
||||
|
||||
expect(await screen.findByText('No AI model configured')).toBeInTheDocument()
|
||||
const tasks = useBackgroundTasksStore.getState().tasks
|
||||
expect(tasks).toHaveLength(1)
|
||||
expect(tasks[0]).toMatchObject({ id: 'j1', status: 'error' })
|
||||
expect(saveImportFiles).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignores a second click while the first retry is still in flight', async () => {
|
||||
vi.mocked(healthApi.features).mockResolvedValue({ bookingImport: true, aiParsing: true })
|
||||
// Never settles: the retry stays in flight for the whole test.
|
||||
vi.mocked(reservationsApi.importBookingAsync).mockReturnValue(new Promise<{ jobId: string }>(() => {}))
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ sourceFiles: [pdf()] })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
|
||||
const button = await screen.findByRole('button', { name: 'Try AI parsing' })
|
||||
await userEvent.click(button)
|
||||
await waitFor(() => expect(button).toBeDisabled())
|
||||
await userEvent.click(button)
|
||||
|
||||
expect(reservationsApi.importBookingAsync).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
/*
|
||||
* Warnings used to appear only when nothing at all was found, so a partly
|
||||
* understood import dropped whatever it could not place without a word — a
|
||||
* station the geocoder could not locate, say (#1969), whose endpoint then
|
||||
* disappeared on save.
|
||||
*/
|
||||
it('shows the warnings on a job that did produce items', () => {
|
||||
const warning = 'voucher.pdf: could not locate "Curbside Pickup Counter 7" — set it manually before saving'
|
||||
useBackgroundTasksStore.setState({
|
||||
tasks: [task({ items: [{ id: 1 } as never], warnings: [warning] })],
|
||||
})
|
||||
render(<BackgroundTasksWidget />)
|
||||
expect(screen.getByText(new RegExp('Curbside Pickup Counter 7'))).toBeInTheDocument()
|
||||
// and the import button is still there — the job did find something
|
||||
expect(screen.getByRole('button', { name: /import/i })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import ReactDOM from 'react-dom'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { Loader2, CheckCircle2, AlertCircle, X } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { addListener, removeListener } from '../../api/websocket'
|
||||
import { reservationsApi } from '../../api/client'
|
||||
import { reservationsApi, healthApi } from '../../api/client'
|
||||
import { saveImportFiles } from '../../db/offlineDb'
|
||||
import { useBackgroundTasksStore, type BackgroundImportTask } from '../../store/backgroundTasksStore'
|
||||
|
||||
/**
|
||||
@@ -23,6 +24,34 @@ export default function BackgroundTasksWidget() {
|
||||
const setError = useBackgroundTasksStore((s) => s.setError)
|
||||
const requestReview = useBackgroundTasksStore((s) => s.requestReview)
|
||||
const dismiss = useBackgroundTasksStore((s) => s.dismiss)
|
||||
const addTask = useBackgroundTasksStore((s) => s.addTask)
|
||||
|
||||
const [aiParsing, setAiParsing] = useState(false)
|
||||
useEffect(() => {
|
||||
healthApi.features().then((f) => setAiParsing(!!f.aiParsing)).catch(() => setAiParsing(false))
|
||||
}, [])
|
||||
|
||||
// Re-runs the same files with force-ai: the LLM sees every file, kitinerary is skipped.
|
||||
const [retrying, setRetrying] = useState<string | null>(null)
|
||||
const retryWithAi = async (task: BackgroundImportTask) => {
|
||||
const files = task.sourceFiles
|
||||
if (!files || files.length === 0 || retrying === task.id) return
|
||||
setRetrying(task.id)
|
||||
try {
|
||||
const { jobId } = await reservationsApi.importBookingAsync(task.tripId, files, 'force-ai')
|
||||
// Same as the modal's first submit: the review attaches each source document to the
|
||||
// booking it created, and only IndexedDB survives a reload mid-parse.
|
||||
await saveImportFiles(jobId, files)
|
||||
dismiss(task.id)
|
||||
addTask({ id: jobId, tripId: task.tripId, label: task.label, total: files.length, files, mode: 'force-ai' })
|
||||
} catch (err) {
|
||||
// 409 when the addon is enabled but this user has no model configured.
|
||||
const message = (err as { response?: { data?: { error?: string } } })?.response?.data?.error
|
||||
setError(task.id, task.tripId, message ?? t('reservations.import.error'))
|
||||
} finally {
|
||||
setRetrying(null)
|
||||
}
|
||||
}
|
||||
|
||||
// On (re)load, reconcile tasks restored from localStorage with the server: a parse
|
||||
// that was still running when the page reloaded must keep its widget, so re-fetch each
|
||||
@@ -82,11 +111,16 @@ export default function BackgroundTasksWidget() {
|
||||
else if (s.status === 'error') setError(task.id, task.tripId, s.error ?? 'error')
|
||||
else setProgress(task.id, task.tripId, s.done, s.total)
|
||||
})
|
||||
.catch(() => {})
|
||||
.catch((err: { response?: { status?: number } }) => {
|
||||
// The server 404s a job once it has expired (or after a restart). Nothing is
|
||||
// ever coming, so end the card instead of spinning and re-polling forever.
|
||||
// Not the parse-failure message — the file was fine, the job is just gone.
|
||||
if (err?.response?.status === 404) setError(task.id, task.tripId, t('common.unknownError'))
|
||||
})
|
||||
}
|
||||
}, 5000)
|
||||
return () => clearInterval(iv)
|
||||
}, [tasks, setProgress, setDone, setError])
|
||||
}, [tasks, setProgress, setDone, setError, t])
|
||||
|
||||
if (tasks.length === 0) return null
|
||||
|
||||
@@ -95,7 +129,7 @@ export default function BackgroundTasksWidget() {
|
||||
navigate(`/trips/${task.tripId}`)
|
||||
}
|
||||
|
||||
return ReactDOM.createPortal(
|
||||
return createPortal(
|
||||
<div
|
||||
style={{ position: 'fixed', right: 16, bottom: 16, zIndex: 50000, display: 'flex', flexDirection: 'column', gap: 8, width: 380, maxWidth: 'calc(100vw - 32px)', fontFamily: 'var(--font-system)' }}
|
||||
>
|
||||
@@ -128,22 +162,46 @@ export default function BackgroundTasksWidget() {
|
||||
// Restored from a reload; items are being re-fetched (see the poll backstop).
|
||||
<div style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', marginTop: 1 }}>{t('reservations.import.parsing')}</div>
|
||||
) : task.items.length > 0 ? (
|
||||
<button
|
||||
onClick={() => review(task)}
|
||||
className="bg-accent text-accent-text"
|
||||
style={{ marginTop: 4, border: 'none', borderRadius: 8, padding: '4px 12px', fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
|
||||
>
|
||||
{t('common.import')}
|
||||
</button>
|
||||
) : (
|
||||
<div style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', marginTop: 1 }}>
|
||||
{t('reservations.import.previewEmpty')}
|
||||
<div>
|
||||
<button type="button"
|
||||
onClick={() => review(task)}
|
||||
className="bg-accent text-accent-text"
|
||||
style={{ marginTop: 4, border: 'none', borderRadius: 8, padding: '4px 12px', fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
|
||||
>
|
||||
{t('common.import')}
|
||||
</button>
|
||||
{/* A partly-understood import warns too. Warnings used to be
|
||||
shown only when nothing at all was found, so anything the
|
||||
parse could not place — a station it could not locate, say
|
||||
(#1969) — was dropped without a word on exactly the imports
|
||||
that did produce something. */}
|
||||
{(task.warnings?.length ?? 0) > 0 && (
|
||||
<div style={{ color: '#b45309', marginTop: 3, whiteSpace: 'pre-wrap', wordBreak: 'break-word', maxHeight: 96, overflowY: 'auto' }}>
|
||||
<div style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: '#b45309', marginTop: 3, whiteSpace: 'pre-wrap', wordBreak: 'break-word', maxHeight: 96, overflowY: 'auto' }}>
|
||||
{task.warnings!.join('\n')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', marginTop: 1 }}>
|
||||
{t('reservations.import.previewEmpty')}
|
||||
{(task.warnings?.length ?? 0) > 0 && (
|
||||
<div style={{ color: '#b45309', marginTop: 3, whiteSpace: 'pre-wrap', wordBreak: 'break-word', maxHeight: 96, overflowY: 'auto' }}>
|
||||
{task.warnings!.join('\n')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{aiParsing && task.mode !== 'force-ai' && task.sourceFiles && task.sourceFiles.length > 0 && (
|
||||
<button type="button"
|
||||
onClick={() => retryWithAi(task)}
|
||||
disabled={retrying === task.id}
|
||||
className="bg-surface-tertiary text-content"
|
||||
style={{ marginTop: 4, border: 'none', borderRadius: 8, padding: '4px 12px', fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 600, cursor: retrying === task.id ? 'default' : 'pointer', opacity: retrying === task.id ? 0.6 : 1, fontFamily: 'inherit' }}
|
||||
>
|
||||
{t('reservations.import.tryAi')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
@@ -153,7 +211,7 @@ export default function BackgroundTasksWidget() {
|
||||
</div>
|
||||
|
||||
{task.status !== 'running' && (
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={() => dismiss(task.id)}
|
||||
className="bg-transparent text-content-faint"
|
||||
style={{ flexShrink: 0, border: 'none', cursor: 'pointer', padding: 2, borderRadius: 6, display: 'flex', alignItems: 'center' }}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { calcPP, hasCustomMemberSplit } from './BudgetPanel.helpers'
|
||||
import { calcPP, hasCustomMemberSplit, normalizePastedAmount } from './BudgetPanel.helpers'
|
||||
|
||||
describe('BudgetPanel.helpers', () => {
|
||||
describe('hasCustomMemberSplit (#1458)', () => {
|
||||
@@ -25,4 +25,18 @@ describe('BudgetPanel.helpers', () => {
|
||||
expect(calcPP(100, 0)).toBeNull()
|
||||
expect(calcPP(100, null)).toBeNull()
|
||||
})
|
||||
|
||||
describe('normalizePastedAmount', () => {
|
||||
it('keeps the last separator as the decimal point', () => {
|
||||
expect(normalizePastedAmount('1.234,56 €')).toBe('1234.56')
|
||||
expect(normalizePastedAmount('$1,234.56')).toBe('1234.56')
|
||||
expect(normalizePastedAmount(' -12,5 ')).toBe('-12.5')
|
||||
})
|
||||
|
||||
it('drops everything that is not part of the number', () => {
|
||||
expect(normalizePastedAmount('EUR 1 234 567')).toBe('1234567')
|
||||
expect(normalizePastedAmount('42')).toBe('42')
|
||||
expect(normalizePastedAmount('abc')).toBe('')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -48,12 +48,12 @@ export function hexLighten(hex: string, amount: number): string {
|
||||
const m = hex.replace('#', '').match(/.{2}/g)
|
||||
if (!m || m.length !== 3) return hex
|
||||
const mix = (c: number) => Math.min(255, Math.round(c + (255 - c) * amount))
|
||||
const [r, g, b] = m.map(x => parseInt(x, 16))
|
||||
const [r, g, b] = m.map(x => Number.parseInt(x, 16))
|
||||
return `#${[mix(r), mix(g), mix(b)].map(v => v.toString(16).padStart(2, '0')).join('')}`
|
||||
}
|
||||
|
||||
export const fmtNum = (v: number | null | undefined, locale: string, cur: string) => {
|
||||
if (v == null || isNaN(v)) return '-'
|
||||
if (v == null || Number.isNaN(v)) return '-'
|
||||
const d = currencyDecimals(cur)
|
||||
return Number(v).toLocaleString(locale, { minimumFractionDigits: d, maximumFractionDigits: d }) + ' ' + (SYMBOLS[cur] || cur)
|
||||
}
|
||||
@@ -75,5 +75,18 @@ export function splitColorFor(userId: number, order: number) {
|
||||
}
|
||||
|
||||
export function colorForUserId(userId: number) {
|
||||
return SPLIT_COLORS[((userId | 0) - 1 + SPLIT_COLORS.length * 1000) % SPLIT_COLORS.length]
|
||||
const id = Number.isFinite(userId) ? Math.trunc(userId) : 0
|
||||
return SPLIT_COLORS[(id - 1 + SPLIT_COLORS.length * 1000) % SPLIT_COLORS.length]
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalises a pasted amount to a plain `1234.56` string: drops currency
|
||||
* symbols and spaces, treats the last comma/dot as the decimal separator and
|
||||
* removes every thousand separator before it.
|
||||
*/
|
||||
export function normalizePastedAmount(raw: string): string {
|
||||
const text = raw.trim().replace(/[^\d.,-]/g, '')
|
||||
const decimalPos = Math.max(text.lastIndexOf(','), text.lastIndexOf('.'))
|
||||
if (decimalPos === -1) return text.replace(/[.,]/g, '')
|
||||
return text.substring(0, decimalPos).replace(/[.,]/g, '') + '.' + text.substring(decimalPos + 1)
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ describe('BudgetPanel', () => {
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] }))
|
||||
);
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
await screen.findByText('No budget created yet');
|
||||
expect(await screen.findByText('No budget created yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-002: shows empty state text body', async () => {
|
||||
@@ -40,7 +40,7 @@ describe('BudgetPanel', () => {
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] }))
|
||||
);
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
await screen.findByText(/Create categories and entries/i);
|
||||
expect(await screen.findByText(/Create categories and entries/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-003: shows category input in empty state when user can edit', async () => {
|
||||
@@ -48,7 +48,7 @@ describe('BudgetPanel', () => {
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] }))
|
||||
);
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
await screen.findByPlaceholderText('Enter category name...');
|
||||
expect(await screen.findByPlaceholderText('Enter category name...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-004: renders budget items from store after load', async () => {
|
||||
@@ -57,7 +57,7 @@ describe('BudgetPanel', () => {
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [item] }))
|
||||
);
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
await screen.findByText('Hotel Paris');
|
||||
expect(await screen.findByText('Hotel Paris')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-005: renders category section header', async () => {
|
||||
@@ -87,7 +87,7 @@ describe('BudgetPanel', () => {
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [item] }))
|
||||
);
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
await screen.findByText('Budget');
|
||||
expect(await screen.findByText('Budget')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-008: shows CSV export button', async () => {
|
||||
@@ -96,7 +96,7 @@ describe('BudgetPanel', () => {
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [item] }))
|
||||
);
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
await screen.findByText('CSV');
|
||||
expect(await screen.findByText('CSV')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-009: add item row visible in table', async () => {
|
||||
@@ -105,7 +105,7 @@ describe('BudgetPanel', () => {
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [item] }))
|
||||
);
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
await screen.findByPlaceholderText('New Entry');
|
||||
expect(await screen.findByPlaceholderText('New Entry')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-010: adding new item via form calls POST and shows item', async () => {
|
||||
@@ -124,7 +124,7 @@ describe('BudgetPanel', () => {
|
||||
await user.type(nameInput, 'Restaurant Dinner');
|
||||
const addBtn = screen.getByTitle('Add Reservation');
|
||||
await user.click(addBtn);
|
||||
await screen.findByText('Restaurant Dinner');
|
||||
expect(await screen.findByText('Restaurant Dinner')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-011: delete button present for items when user can edit', async () => {
|
||||
@@ -161,7 +161,7 @@ describe('BudgetPanel', () => {
|
||||
);
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
await screen.findByText('Hotel A');
|
||||
await screen.findByText('Hotel B');
|
||||
expect(await screen.findByText('Hotel B')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-014: items from different categories render separate sections', async () => {
|
||||
@@ -183,7 +183,7 @@ describe('BudgetPanel', () => {
|
||||
);
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
// Component renders even in empty state
|
||||
await screen.findByText('No budget created yet');
|
||||
expect(await screen.findByText('No budget created yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-016: trip currency EUR is shown in header for item rows', async () => {
|
||||
@@ -193,7 +193,7 @@ describe('BudgetPanel', () => {
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [item] }))
|
||||
);
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
await screen.findByText('Misc');
|
||||
expect(await screen.findByText('Misc')).toBeInTheDocument();
|
||||
// Row exists - EUR formatting would appear in values
|
||||
});
|
||||
|
||||
@@ -233,7 +233,7 @@ describe('BudgetPanel', () => {
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
const nameInput = await screen.findByPlaceholderText('New Entry');
|
||||
await user.type(nameInput, 'Pizza{Enter}');
|
||||
await screen.findByText('Pizza');
|
||||
expect(await screen.findByText('Pizza')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-020: component renders without crashing with empty tripMembers', async () => {
|
||||
@@ -241,7 +241,7 @@ describe('BudgetPanel', () => {
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] }))
|
||||
);
|
||||
render(<BudgetPanel tripId={1} tripMembers={[]} />);
|
||||
await screen.findByText('No budget created yet');
|
||||
expect(await screen.findByText('No budget created yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-021: inline edit name cell — clicking a name cell makes it editable', async () => {
|
||||
@@ -342,7 +342,7 @@ describe('BudgetPanel', () => {
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] }))
|
||||
);
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
await screen.findByPlaceholderText('Enter category name...');
|
||||
expect(await screen.findByPlaceholderText('Enter category name...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-028: creating a new category via input calls POST and adds a section', async () => {
|
||||
@@ -356,7 +356,7 @@ describe('BudgetPanel', () => {
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
const input = await screen.findByPlaceholderText('Enter category name...');
|
||||
await user.type(input, 'Souvenirs{Enter}');
|
||||
await screen.findByText('Souvenirs');
|
||||
expect(await screen.findByText('Souvenirs')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-029: settlement section renders flows with usernames', async () => {
|
||||
@@ -371,7 +371,7 @@ describe('BudgetPanel', () => {
|
||||
{ user_id: 2, username: 'bob', balance: 10, avatar_url: null },
|
||||
],
|
||||
flows: [
|
||||
{ from: { username: 'alice', avatar_url: null }, to: { username: 'bob', avatar_url: null }, amount: 10 },
|
||||
{ from: { user_id: 1, username: 'alice', avatar_url: null }, to: { user_id: 2, username: 'bob', avatar_url: null }, amount: 10 },
|
||||
],
|
||||
})
|
||||
)
|
||||
@@ -387,7 +387,7 @@ describe('BudgetPanel', () => {
|
||||
await user.click(settlementBtn);
|
||||
// alice and bob should appear in balances section
|
||||
await screen.findByText('alice');
|
||||
await screen.findByText('bob');
|
||||
expect(await screen.findByText('bob')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-030: per-person summary renders usernames', async () => {
|
||||
@@ -408,7 +408,7 @@ describe('BudgetPanel', () => {
|
||||
];
|
||||
render(<BudgetPanel tripId={1} tripMembers={tripMembers} />);
|
||||
await screen.findByText('Shared Dinner');
|
||||
await screen.findByText('testuser');
|
||||
expect(await screen.findByText('testuser')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-032: grand total row shows sum across all categories', async () => {
|
||||
@@ -451,7 +451,7 @@ describe('BudgetPanel', () => {
|
||||
render(<BudgetPanel tripId={1} />);
|
||||
await screen.findByText('Train');
|
||||
// expense_date is rendered as plain text in read-only mode
|
||||
await screen.findByText('2025-06-15');
|
||||
expect(await screen.findByText('2025-06-15')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-BUDGET-035: settlement section with avatar renders user avatar image', async () => {
|
||||
@@ -465,7 +465,7 @@ describe('BudgetPanel', () => {
|
||||
{ user_id: 1, username: 'alice', avatar_url: '/uploads/avatars/alice.jpg', balance: -30 },
|
||||
{ user_id: 2, username: 'bob', avatar_url: null, balance: 30 },
|
||||
],
|
||||
flows: [{ from: { username: 'alice', avatar_url: '/uploads/avatars/alice.jpg' }, to: { username: 'bob', avatar_url: null }, amount: 30 }]
|
||||
flows: [{ from: { user_id: 1, username: 'alice', avatar_url: '/uploads/avatars/alice.jpg' }, to: { user_id: 2, username: 'bob', avatar_url: null }, amount: 30 }]
|
||||
})
|
||||
),
|
||||
http.get('/api/trips/1/budget/per-person', () => HttpResponse.json({ summary: [] })),
|
||||
|
||||
@@ -46,7 +46,7 @@ export default function BudgetPanel({ tripId, tripMembers = [] }: BudgetPanelPro
|
||||
onKeyDown={e => e.key === 'Enter' && handleAddCategory()}
|
||||
placeholder={t('budget.emptyPlaceholder')}
|
||||
style={{ flex: 1, padding: '9px 14px', borderRadius: 10, border: '1px solid var(--border-primary)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontFamily: 'inherit', outline: 'none', background: 'var(--bg-input)', color: 'var(--text-primary)', minWidth: 0 }} />
|
||||
<button onClick={handleAddCategory} disabled={!newCategoryName.trim()}
|
||||
<button type="button" onClick={handleAddCategory} disabled={!newCategoryName.trim()}
|
||||
style={{ background: 'var(--accent)', color: 'var(--accent-text)', border: 'none', borderRadius: 10, padding: '0 12px', cursor: 'pointer', display: 'flex', alignItems: 'center', opacity: newCategoryName.trim() ? 1 : 0.5, flexShrink: 0 }}>
|
||||
<Plus size={16} />
|
||||
</button>
|
||||
@@ -87,7 +87,7 @@ export default function BudgetPanel({ tripId, tripMembers = [] }: BudgetPanelPro
|
||||
placeholder={t('budget.categoryName')}
|
||||
style={{ flex: 1, minWidth: 0, border: '1px solid var(--border-primary)', borderRadius: 10, padding: '9px 14px', fontSize: 'calc(13px * var(--fs-scale-body, 1))', outline: 'none', fontFamily: 'inherit', background: 'var(--bg-card)', color: 'var(--text-primary)' }}
|
||||
/>
|
||||
<button onClick={handleAddCategory} disabled={!newCategoryName.trim()}
|
||||
<button type="button" onClick={handleAddCategory} disabled={!newCategoryName.trim()}
|
||||
title={t('budget.addCategory')}
|
||||
style={{
|
||||
appearance: 'none', border: 'none', cursor: newCategoryName.trim() ? 'pointer' : 'default', fontFamily: 'inherit',
|
||||
@@ -101,7 +101,7 @@ export default function BudgetPanel({ tripId, tripMembers = [] }: BudgetPanelPro
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<button onClick={handleExportCsv} title={t('budget.exportCsv')}
|
||||
<button type="button" onClick={handleExportCsv} title={t('budget.exportCsv')}
|
||||
style={{
|
||||
appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
// FE-W4AIR-001 to FE-W4AIR-009
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, fireEvent } from '../../../tests/helpers/render'
|
||||
import AddItemRow from './BudgetPanelAddItemRow'
|
||||
|
||||
const t = (key: string) => key
|
||||
|
||||
function setup() {
|
||||
const onAdd = vi.fn()
|
||||
const utils = render(<table><tbody><AddItemRow onAdd={onAdd} t={t} /></tbody></table>)
|
||||
return { onAdd, ...utils }
|
||||
}
|
||||
|
||||
const nameInput = () => screen.getByPlaceholderText('budget.newEntry')
|
||||
const priceInput = () => screen.getByPlaceholderText('0,00')
|
||||
const noteInput = () => screen.getByPlaceholderText('budget.table.note')
|
||||
const numberInputs = () => screen.getAllByPlaceholderText('-')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('BudgetPanelAddItemRow', () => {
|
||||
it('FE-W4AIR-001: the add button stays disabled until a name is typed', () => {
|
||||
setup()
|
||||
const button = screen.getByRole('button', { name: 'reservations.add' })
|
||||
|
||||
expect(button).toBeDisabled()
|
||||
fireEvent.change(nameInput(), { target: { value: 'Ferry' } })
|
||||
expect(button).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-W4AIR-002: submits the trimmed name with parsed numbers', () => {
|
||||
const { onAdd } = setup()
|
||||
|
||||
fireEvent.change(nameInput(), { target: { value: ' Ferry ' } })
|
||||
fireEvent.change(priceInput(), { target: { value: '129,90' } })
|
||||
fireEvent.change(numberInputs()[0], { target: { value: '2' } })
|
||||
fireEvent.change(numberInputs()[1], { target: { value: '3' } })
|
||||
fireEvent.change(noteInput(), { target: { value: ' one way ' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'reservations.add' }))
|
||||
|
||||
expect(onAdd).toHaveBeenCalledWith({
|
||||
name: 'Ferry', total_price: 129.9, persons: 2, days: 3, note: 'one way', expense_date: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-W4AIR-003: falls back to zero price and null optionals', () => {
|
||||
const { onAdd } = setup()
|
||||
|
||||
fireEvent.change(nameInput(), { target: { value: 'Ferry' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'reservations.add' }))
|
||||
|
||||
expect(onAdd).toHaveBeenCalledWith({
|
||||
name: 'Ferry', total_price: 0, persons: null, days: null, note: null, expense_date: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-W4AIR-004: ignores a whitespace-only name', () => {
|
||||
const { onAdd } = setup()
|
||||
|
||||
fireEvent.change(nameInput(), { target: { value: ' ' } })
|
||||
fireEvent.keyDown(nameInput(), { key: 'Enter' })
|
||||
|
||||
expect(onAdd).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W4AIR-005: Enter in any field submits the row', () => {
|
||||
const { onAdd } = setup()
|
||||
fireEvent.change(nameInput(), { target: { value: 'Ferry' } })
|
||||
|
||||
fireEvent.keyDown(priceInput(), { key: 'Enter' })
|
||||
expect(onAdd).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-W4AIR-006: a non-Enter key does not submit', () => {
|
||||
const { onAdd } = setup()
|
||||
fireEvent.change(nameInput(), { target: { value: 'Ferry' } })
|
||||
|
||||
fireEvent.keyDown(nameInput(), { key: 'a' })
|
||||
|
||||
expect(onAdd).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W4AIR-007: clears the row and refocuses the name field after adding', () => {
|
||||
setup()
|
||||
fireEvent.change(nameInput(), { target: { value: 'Ferry' } })
|
||||
fireEvent.change(priceInput(), { target: { value: '12' } })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'reservations.add' }))
|
||||
|
||||
expect(nameInput()).toHaveValue('')
|
||||
expect(priceInput()).toHaveValue('')
|
||||
vi.advanceTimersByTime(60)
|
||||
expect(nameInput()).toHaveFocus()
|
||||
})
|
||||
|
||||
it('FE-W4AIR-008: pasting a formatted amount normalizes the separators', () => {
|
||||
setup()
|
||||
|
||||
fireEvent.paste(priceInput(), { clipboardData: { getData: () => '1.234,56 EUR' } })
|
||||
expect(priceInput()).toHaveValue('1234.56')
|
||||
|
||||
fireEvent.paste(priceInput(), { clipboardData: { getData: () => '$2,345.67' } })
|
||||
expect(priceInput()).toHaveValue('2345.67')
|
||||
})
|
||||
|
||||
it('FE-W4AIR-009: pasting a separator-free amount keeps the digits', () => {
|
||||
setup()
|
||||
|
||||
fireEvent.paste(priceInput(), { clipboardData: { getData: () => 'EUR 4200' } })
|
||||
|
||||
expect(priceInput()).toHaveValue('4200')
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useRef } from 'react'
|
||||
import { Plus } from 'lucide-react'
|
||||
import { CustomDatePicker } from '../shared/CustomDateTimePicker'
|
||||
import { normalizePastedAmount } from './BudgetPanel.helpers'
|
||||
|
||||
interface AddItemRowProps {
|
||||
onAdd: (data: { name: string; total_price: number; persons: number | null; days: number | null; note: string | null; expense_date: string | null }) => void
|
||||
@@ -18,7 +19,7 @@ export default function AddItemRow({ onAdd, t }: AddItemRowProps) {
|
||||
|
||||
const handleAdd = () => {
|
||||
if (!name.trim()) return
|
||||
onAdd({ name: name.trim(), total_price: parseFloat(String(price).replace(',', '.')) || 0, persons: parseInt(persons) || null, days: parseInt(days) || null, note: note.trim() || null, expense_date: expenseDate || null })
|
||||
onAdd({ name: name.trim(), total_price: Number.parseFloat(String(price).replace(',', '.')) || 0, persons: Number.parseInt(persons) || null, days: Number.parseInt(days) || null, note: note.trim() || null, expense_date: expenseDate || null })
|
||||
setName(''); setPrice(''); setPersons(''); setDays(''); setNote(''); setExpenseDate('')
|
||||
setTimeout(() => nameRef.current?.focus(), 50)
|
||||
}
|
||||
@@ -33,7 +34,7 @@ export default function AddItemRow({ onAdd, t }: AddItemRowProps) {
|
||||
</td>
|
||||
<td style={{ padding: '4px 6px' }}>
|
||||
<input value={price} onChange={e => setPrice(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleAdd()}
|
||||
onPaste={e => { e.preventDefault(); let t = e.clipboardData.getData('text').trim().replace(/[^\d.,-]/g, ''); const lc = t.lastIndexOf(','), ld = t.lastIndexOf('.'), dp = Math.max(lc, ld); if (dp > -1) { t = t.substring(0, dp).replace(/[.,]/g, '') + '.' + t.substring(dp + 1) } else { t = t.replace(/[.,]/g, '') } setPrice(t) }}
|
||||
onPaste={e => { e.preventDefault(); setPrice(normalizePastedAmount(e.clipboardData.getData('text'))) }}
|
||||
placeholder="0,00" inputMode="decimal" style={{ ...inp, textAlign: 'center' }} />
|
||||
</td>
|
||||
<td className="hidden sm:table-cell" style={{ padding: '4px 6px', textAlign: 'center' }}>
|
||||
@@ -56,7 +57,7 @@ export default function AddItemRow({ onAdd, t }: AddItemRowProps) {
|
||||
<input value={note} onChange={e => setNote(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleAdd()} placeholder={t('budget.table.note')} style={inp} />
|
||||
</td>
|
||||
<td style={{ padding: '4px 6px', textAlign: 'center' }}>
|
||||
<button onClick={handleAdd} disabled={!name.trim()} title={t('reservations.add')}
|
||||
<button type="button" onClick={handleAdd} disabled={!name.trim()} title={t('reservations.add')}
|
||||
style={{ background: name.trim() ? 'var(--text-primary)' : 'var(--border-primary)', border: 'none', borderRadius: 4, color: 'var(--bg-primary)',
|
||||
cursor: name.trim() ? 'pointer' : 'default', padding: '4px 8px', display: 'inline-flex', alignItems: 'center' }}>
|
||||
<Plus size={14} />
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
// FE-W4BCT-001 to FE-W4BCT-053
|
||||
import type { CSSProperties } from 'react'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { BudgetItem } from '../../types'
|
||||
import { render, screen, fireEvent, createEvent, within } from '../../../tests/helpers/render'
|
||||
import BudgetCategoryTable from './BudgetPanelCategoryTable'
|
||||
import type { TripMember } from './BudgetPanelMemberChips'
|
||||
|
||||
const contribFor = vi.fn((_id: number) => [] as unknown[])
|
||||
|
||||
vi.mock('../Plugins/PluginContributions', () => ({
|
||||
usePluginViewContributions: () => contribFor,
|
||||
PluginCardFooter: ({ items }: { items: unknown[] }) => <div data-testid="plugin-footer">{items.length}</div>,
|
||||
}))
|
||||
|
||||
const TRIP_MEMBERS: TripMember[] = [
|
||||
{ id: 1, username: 'ada', avatar_url: null },
|
||||
{ id: 2, username: 'bob', avatar_url: null },
|
||||
]
|
||||
|
||||
function budgetItem(overrides: Partial<BudgetItem> = {}): BudgetItem {
|
||||
return {
|
||||
id: 1, trip_id: 7, category: 'Food', name: 'Ferry', total_price: 100,
|
||||
persons: 2, days: 5, note: null, expense_date: null, reservation_id: null, members: [],
|
||||
...overrides,
|
||||
} as unknown as BudgetItem
|
||||
}
|
||||
|
||||
type Props = Parameters<typeof BudgetCategoryTable>[0]
|
||||
|
||||
function setup(overrides: Partial<Props> = {}, items: BudgetItem[] = [budgetItem()]) {
|
||||
const spies = {
|
||||
setEditingCat: vi.fn(),
|
||||
setDragCat: vi.fn(),
|
||||
setDragOverCat: vi.fn(),
|
||||
setDragItem: vi.fn(),
|
||||
setDragOverItem: vi.fn(),
|
||||
setDragItemCat: vi.fn(),
|
||||
reorderBudgetCategories: vi.fn(async () => {}),
|
||||
reorderBudgetItems: vi.fn(async () => {}),
|
||||
handleRenameCategory: vi.fn(async () => {}),
|
||||
handleDeleteCategory: vi.fn(async () => {}),
|
||||
handleDeleteItem: vi.fn(async () => {}),
|
||||
handleUpdateField: vi.fn(async () => {}),
|
||||
handleAddItem: vi.fn(async () => {}),
|
||||
setBudgetItemMembers: vi.fn(async () => ({ members: [], item: {} })),
|
||||
toggleBudgetMemberPaid: vi.fn(async () => {}),
|
||||
}
|
||||
const props = {
|
||||
cat: 'Food',
|
||||
grouped: new Map([['Food', items]]),
|
||||
categoryColor: () => '#ef4444',
|
||||
canEdit: true,
|
||||
editingCat: null,
|
||||
dragCat: null,
|
||||
dragOverCat: null,
|
||||
dragItem: null,
|
||||
dragOverItem: null,
|
||||
dragItemCat: null,
|
||||
categoryNames: ['Transport', 'Food', 'Hotels'],
|
||||
tripId: 7,
|
||||
currency: 'EUR',
|
||||
locale: 'en-US',
|
||||
t: (key: string) => key,
|
||||
fmt: (v: number | null | undefined, cur: string) => `${v ?? '-'} ${cur}`,
|
||||
hasMultipleMembers: false,
|
||||
tripMembers: TRIP_MEMBERS,
|
||||
th: {} as CSSProperties,
|
||||
td: {} as CSSProperties,
|
||||
...spies,
|
||||
...overrides,
|
||||
} as unknown as Props
|
||||
|
||||
const utils = render(<BudgetCategoryTable {...props} />)
|
||||
return { ...spies, ...utils }
|
||||
}
|
||||
|
||||
/** dragleave carrying a relatedTarget — jsdom lacks DragEvent, so fireEvent drops it. */
|
||||
function dragLeaveInto(target: Element, relatedTarget: Element) {
|
||||
const event = createEvent.dragLeave(target)
|
||||
Object.defineProperty(event, 'relatedTarget', { value: relatedTarget })
|
||||
fireEvent(target, event)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
contribFor.mockReset()
|
||||
contribFor.mockReturnValue([])
|
||||
})
|
||||
|
||||
describe('BudgetCategoryTable — header', () => {
|
||||
it('FE-W4BCT-001: shows the category name and the summed subtotal', () => {
|
||||
setup({}, [budgetItem(), budgetItem({ id: 2, total_price: 50 })])
|
||||
|
||||
expect(screen.getByText('Food')).toBeInTheDocument()
|
||||
expect(screen.getByText('150 EUR')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BCT-002: treats a priceless item as zero in the subtotal', () => {
|
||||
const { container } = setup({}, [budgetItem({ total_price: null } as Partial<BudgetItem>)])
|
||||
|
||||
// The subtotal sits in the black category header, before the table.
|
||||
expect(container.querySelectorAll('span')[1]).toHaveTextContent('0 EUR')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-003: renders an empty category with only the add row', () => {
|
||||
setup({ grouped: new Map() } as Partial<Props>)
|
||||
|
||||
expect(screen.getByPlaceholderText('budget.newEntry')).toBeInTheDocument()
|
||||
expect(screen.queryByDisplayValue('Ferry')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4BCT-004: the pencil starts renaming the category', () => {
|
||||
const { setEditingCat } = setup()
|
||||
|
||||
fireEvent.click(screen.getAllByRole('button')[0])
|
||||
|
||||
expect(setEditingCat).toHaveBeenCalledWith({ name: 'Food', value: 'Food' })
|
||||
})
|
||||
|
||||
it('FE-W4BCT-005: Enter in the rename input commits and closes the editor', () => {
|
||||
const { handleRenameCategory, setEditingCat } = setup({ editingCat: { name: 'Food', value: 'Groceries' } })
|
||||
const input = screen.getByDisplayValue('Groceries')
|
||||
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
|
||||
expect(handleRenameCategory).toHaveBeenCalledWith('Food', 'Groceries')
|
||||
expect(setEditingCat).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-006: blurring the rename input commits it', () => {
|
||||
const { handleRenameCategory } = setup({ editingCat: { name: 'Food', value: 'Groceries' } })
|
||||
|
||||
fireEvent.blur(screen.getByDisplayValue('Groceries'))
|
||||
|
||||
expect(handleRenameCategory).toHaveBeenCalledWith('Food', 'Groceries')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-007: Escape abandons the rename', () => {
|
||||
const { handleRenameCategory, setEditingCat } = setup({ editingCat: { name: 'Food', value: 'Groceries' } })
|
||||
|
||||
fireEvent.keyDown(screen.getByDisplayValue('Groceries'), { key: 'Escape' })
|
||||
|
||||
expect(handleRenameCategory).not.toHaveBeenCalled()
|
||||
expect(setEditingCat).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-008: typing updates the pending rename value', () => {
|
||||
const { setEditingCat } = setup({ editingCat: { name: 'Food', value: 'Food' } })
|
||||
|
||||
fireEvent.change(screen.getByDisplayValue('Food'), { target: { value: 'Fuel' } })
|
||||
|
||||
expect(setEditingCat).toHaveBeenCalledWith({ name: 'Food', value: 'Fuel' })
|
||||
})
|
||||
|
||||
it('FE-W4BCT-009: the trash button deletes the category', () => {
|
||||
const { handleDeleteCategory } = setup()
|
||||
|
||||
fireEvent.click(screen.getByTitle('budget.deleteCategory'))
|
||||
|
||||
expect(handleDeleteCategory).toHaveBeenCalledWith('Food')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-010: a read-only table hides every editing affordance', () => {
|
||||
setup({ canEdit: false })
|
||||
|
||||
expect(screen.queryByTitle('budget.deleteCategory')).toBeNull()
|
||||
expect(screen.queryByTitle('common.delete')).toBeNull()
|
||||
expect(screen.queryByPlaceholderText('budget.newEntry')).toBeNull()
|
||||
expect(document.querySelectorAll('[draggable="true"]')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('BudgetCategoryTable — rows', () => {
|
||||
it('FE-W4BCT-011: derives the per-person, per-day and per-person-day figures', () => {
|
||||
setup({}, [budgetItem({ total_price: 100, persons: 2, days: 5 })])
|
||||
|
||||
expect(screen.getByText('50 EUR')).toBeInTheDocument()
|
||||
expect(screen.getByText('20 EUR')).toBeInTheDocument()
|
||||
expect(screen.getByText('10 EUR')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BCT-012: blanks the per-person columns for a custom member split', () => {
|
||||
setup({}, [budgetItem({
|
||||
total_price: 100, persons: 2, days: 5,
|
||||
members: [{ user_id: 1, username: 'ada', amount: 70 }, { user_id: 2, username: 'bob', amount: 30 }],
|
||||
} as unknown as Partial<BudgetItem>)])
|
||||
|
||||
// per-day still resolves; per-person and per-person-day are dashed out.
|
||||
expect(screen.getByText('20 EUR')).toBeInTheDocument()
|
||||
expect(screen.getAllByText('-').length).toBeGreaterThanOrEqual(2)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-013: deleting a row reports its id', () => {
|
||||
const { handleDeleteItem } = setup()
|
||||
|
||||
fireEvent.click(screen.getByTitle('common.delete'))
|
||||
|
||||
expect(handleDeleteItem).toHaveBeenCalledWith(1)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-014: editing the name cell saves through handleUpdateField', () => {
|
||||
const { handleUpdateField } = setup()
|
||||
|
||||
fireEvent.click(screen.getByText('Ferry'))
|
||||
const input = screen.getByDisplayValue('Ferry')
|
||||
fireEvent.change(input, { target: { value: 'Bus' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
|
||||
expect(handleUpdateField).toHaveBeenCalledWith(1, 'name', 'Bus')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-015: a reservation-linked row locks the name cell', () => {
|
||||
setup({}, [budgetItem({ reservation_id: 42 } as Partial<BudgetItem>)])
|
||||
|
||||
fireEvent.click(screen.getByText('Ferry'))
|
||||
|
||||
expect(screen.queryByDisplayValue('Ferry')).toBeNull()
|
||||
expect(screen.getByText('Ferry')).not.toHaveAttribute('title')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-016: the persons cell coerces the entry to an integer', () => {
|
||||
const { handleUpdateField } = setup()
|
||||
|
||||
fireEvent.click(screen.getByText('2'))
|
||||
const input = screen.getByDisplayValue('2')
|
||||
fireEvent.change(input, { target: { value: '4.7' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
|
||||
expect(handleUpdateField).toHaveBeenCalledWith(1, 'persons', 4)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-017: clearing the days cell stores null', () => {
|
||||
const { handleUpdateField } = setup()
|
||||
|
||||
fireEvent.click(screen.getByText('5'))
|
||||
const input = screen.getByDisplayValue('5')
|
||||
fireEvent.change(input, { target: { value: '' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
|
||||
expect(handleUpdateField).toHaveBeenCalledWith(1, 'days', null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-018: swaps the persons cell for member chips on a multi-member trip', () => {
|
||||
setup({ hasMultipleMembers: true }, [budgetItem({ members: [{ user_id: 1, username: 'ada', paid: 0 }] } as unknown as Partial<BudgetItem>)])
|
||||
|
||||
// One chip in the persons column and one in the mobile stack under the name.
|
||||
expect(screen.getAllByText('A')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-019: shows the raw expense date instead of a picker when read-only', () => {
|
||||
setup({ canEdit: false }, [budgetItem({ expense_date: '2026-06-15' } as Partial<BudgetItem>)])
|
||||
|
||||
expect(screen.getByText('2026-06-15')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BCT-020: falls back to an em dash for a read-only row without a date', () => {
|
||||
setup({ canEdit: false })
|
||||
|
||||
expect(screen.getByText('—')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BCT-021: appends a plugin footer row when a plugin contributes', () => {
|
||||
contribFor.mockReturnValue([{ kind: 'column' }])
|
||||
setup()
|
||||
|
||||
expect(screen.getByTestId('plugin-footer')).toHaveTextContent('1')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-022: adding an item routes the payload into the category', () => {
|
||||
const { handleAddItem } = setup()
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('budget.newEntry'), { target: { value: 'Taxi' } })
|
||||
fireEvent.click(screen.getByTitle('reservations.add'))
|
||||
|
||||
expect(handleAddItem).toHaveBeenCalledWith('Food', expect.objectContaining({ name: 'Taxi' }))
|
||||
})
|
||||
})
|
||||
|
||||
describe('BudgetCategoryTable — drag and drop', () => {
|
||||
it('FE-W4BCT-023: the category handle starts and ends a category drag', () => {
|
||||
const { setDragCat, setDragOverCat, container } = setup()
|
||||
const handle = container.querySelectorAll('[draggable="true"]')[0] as HTMLElement
|
||||
|
||||
fireEvent.dragStart(handle, { dataTransfer: { effectAllowed: '', setData: vi.fn() } })
|
||||
expect(setDragCat).toHaveBeenCalledWith('Food')
|
||||
|
||||
fireEvent.dragEnd(handle)
|
||||
expect(setDragCat).toHaveBeenLastCalledWith(null)
|
||||
expect(setDragOverCat).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-024: dragging another category over this one marks the drop line', () => {
|
||||
const { setDragOverCat, container } = setup({ dragCat: 'Transport' })
|
||||
|
||||
fireEvent.dragOver(container.firstElementChild!, { dataTransfer: { dropEffect: '' } })
|
||||
|
||||
expect(setDragOverCat).toHaveBeenCalledWith('Food')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-025: ignores a drag-over from the same category or from an item', () => {
|
||||
const same = setup({ dragCat: 'Food' })
|
||||
fireEvent.dragOver(same.container.firstElementChild!, { dataTransfer: { dropEffect: '' } })
|
||||
expect(same.setDragOverCat).not.toHaveBeenCalled()
|
||||
|
||||
const item = setup({ dragCat: 'Transport', dragItem: 5 })
|
||||
fireEvent.dragOver(item.container.firstElementChild!, { dataTransfer: { dropEffect: '' } })
|
||||
expect(item.setDragOverCat).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W4BCT-026: dropping a category reorders the list around this one', () => {
|
||||
const { reorderBudgetCategories, setDragCat, container } = setup({ dragCat: 'Hotels' })
|
||||
|
||||
fireEvent.drop(container.firstElementChild!)
|
||||
|
||||
expect(reorderBudgetCategories).toHaveBeenCalledWith(7, ['Transport', 'Hotels', 'Food'])
|
||||
expect(setDragCat).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-027: dropping a category on itself only clears the drag state', () => {
|
||||
const { reorderBudgetCategories, setDragOverCat, container } = setup({ dragCat: 'Food' })
|
||||
|
||||
fireEvent.drop(container.firstElementChild!)
|
||||
|
||||
expect(reorderBudgetCategories).not.toHaveBeenCalled()
|
||||
expect(setDragOverCat).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-028: leaving the category clears the drop marker', () => {
|
||||
const { setDragOverCat, container } = setup({ dragCat: 'Transport' })
|
||||
|
||||
fireEvent.dragLeave(container.firstElementChild!, { relatedTarget: document.body })
|
||||
|
||||
expect(setDragOverCat).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-029: dragging a row over a sibling marks it as the target', () => {
|
||||
const rows = [budgetItem(), budgetItem({ id: 2, name: 'Bus' })]
|
||||
const { setDragOverItem, container } = setup({ dragItem: 2, dragItemCat: 'Food' }, rows)
|
||||
|
||||
fireEvent.dragOver(container.querySelectorAll('tbody tr')[0], { dataTransfer: { dropEffect: '' } })
|
||||
|
||||
expect(setDragOverItem).toHaveBeenCalledWith(1)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-030: dropping a row reorders the ids inside the category', () => {
|
||||
const rows = [budgetItem(), budgetItem({ id: 2, name: 'Bus' }), budgetItem({ id: 3, name: 'Taxi' })]
|
||||
const { reorderBudgetItems, setDragItem, container } = setup({ dragItem: 3, dragItemCat: 'Food' }, rows)
|
||||
|
||||
fireEvent.drop(container.querySelectorAll('tbody tr')[0])
|
||||
|
||||
expect(reorderBudgetItems).toHaveBeenCalledWith(7, [3, 1, 2])
|
||||
expect(setDragItem).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-031: a row from another category is not reordered here', () => {
|
||||
const { reorderBudgetItems, container } = setup({ dragItem: 9, dragItemCat: 'Transport' })
|
||||
|
||||
fireEvent.drop(container.querySelectorAll('tbody tr')[0])
|
||||
|
||||
expect(reorderBudgetItems).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W4BCT-032: the row handle starts and ends an item drag', () => {
|
||||
const { setDragItem, setDragItemCat, container } = setup()
|
||||
const handle = container.querySelectorAll('[draggable="true"]')[1] as HTMLElement
|
||||
|
||||
fireEvent.dragStart(handle, { dataTransfer: { effectAllowed: '' } })
|
||||
expect(setDragItem).toHaveBeenCalledWith(1)
|
||||
expect(setDragItemCat).toHaveBeenCalledWith('Food')
|
||||
|
||||
fireEvent.dragEnd(handle)
|
||||
expect(setDragItem).toHaveBeenLastCalledWith(null)
|
||||
expect(setDragItemCat).toHaveBeenLastCalledWith(null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-033: leaving a row clears the item drop marker', () => {
|
||||
const { setDragOverItem, container } = setup()
|
||||
|
||||
fireEvent.dragLeave(container.querySelectorAll('tbody tr')[0], { relatedTarget: document.body })
|
||||
|
||||
expect(setDragOverItem).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-034: dims the dragged category and marks the drop line', () => {
|
||||
const dragged = setup({ dragCat: 'Food' })
|
||||
expect((dragged.container.firstElementChild as HTMLElement).style.opacity).toBe('0.4')
|
||||
|
||||
const over = setup({ dragCat: 'Transport', dragOverCat: 'Food' })
|
||||
const marker = within(over.container.firstElementChild as HTMLElement).getAllByRole('generic')
|
||||
expect(marker.length).toBeGreaterThan(0)
|
||||
expect((over.container.firstElementChild as HTMLElement).firstElementChild).toHaveStyle({ height: '4px' })
|
||||
})
|
||||
|
||||
it('FE-W4BCT-035: dims the dragged row and outlines the drop target', () => {
|
||||
const dragged = setup({ dragItem: 1 })
|
||||
expect((dragged.container.querySelector('tbody tr') as HTMLElement).style.opacity).toBe('0.4')
|
||||
|
||||
const over = setup({ dragOverItem: 1 })
|
||||
expect((over.container.querySelector('tbody tr') as HTMLElement).style.boxShadow).toBe('inset 4px 0 0 0 var(--accent)')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-036: the table body accepts a category drop only while one is being dragged', () => {
|
||||
const dragging = setup({ dragCat: 'Transport' })
|
||||
const activeTransfer = { dropEffect: '' }
|
||||
fireEvent.dragOver(dragging.container.querySelector('table')!.parentElement!, { dataTransfer: activeTransfer })
|
||||
expect(activeTransfer.dropEffect).toBe('move')
|
||||
|
||||
const idle = setup()
|
||||
const idleTransfer = { dropEffect: '' }
|
||||
fireEvent.dragOver(idle.container.querySelector('table')!.parentElement!, { dataTransfer: idleTransfer })
|
||||
expect(idleTransfer.dropEffect).toBe('')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-037: a row accepts a dragged category without becoming an item drop target', () => {
|
||||
const { setDragOverItem, container } = setup({ dragCat: 'Transport' })
|
||||
const transfer = { dropEffect: '' }
|
||||
|
||||
fireEvent.dragOver(container.querySelectorAll('tbody tr')[0], { dataTransfer: transfer })
|
||||
|
||||
expect(transfer.dropEffect).toBe('move')
|
||||
expect(setDragOverItem).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W4BCT-038: moving between a row and its own cells keeps the drop marker', () => {
|
||||
const { setDragOverItem, setDragOverCat, container } = setup({ dragCat: 'Transport', dragItem: 2, dragItemCat: 'Food' })
|
||||
const row = container.querySelectorAll('tbody tr')[0]
|
||||
|
||||
// jsdom has no DragEvent, so relatedTarget has to be attached by hand.
|
||||
dragLeaveInto(row, row.querySelector('td')!)
|
||||
dragLeaveInto(container.firstElementChild as HTMLElement, container.querySelector('table')!)
|
||||
|
||||
expect(setDragOverItem).not.toHaveBeenCalled()
|
||||
expect(setDragOverCat).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('BudgetCategoryTable — hover affordances', () => {
|
||||
it('FE-W4BCT-039: the rename pencil brightens while hovered', () => {
|
||||
setup()
|
||||
const pencil = screen.getAllByRole('button')[0]
|
||||
|
||||
fireEvent.mouseEnter(pencil)
|
||||
expect(pencil.style.color).toBe('rgb(255, 255, 255)')
|
||||
|
||||
fireEvent.mouseLeave(pencil)
|
||||
expect(pencil.style.color).toBe('rgba(255, 255, 255, 0.4)')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-040: the delete-category button fades in while hovered', () => {
|
||||
setup()
|
||||
const trash = screen.getByTitle('budget.deleteCategory')
|
||||
|
||||
fireEvent.mouseEnter(trash)
|
||||
expect(trash.style.opacity).toBe('1')
|
||||
|
||||
fireEvent.mouseLeave(trash)
|
||||
expect(trash.style.opacity).toBe('0.6')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-041: a row highlights while hovered', () => {
|
||||
const { container } = setup()
|
||||
const row = container.querySelector('tbody tr') as HTMLElement
|
||||
|
||||
fireEvent.mouseEnter(row)
|
||||
expect(row.style.background).toBe('var(--bg-hover)')
|
||||
|
||||
fireEvent.mouseLeave(row)
|
||||
expect(row.style.background).toBe('transparent')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-042: the delete-row button turns red while hovered', () => {
|
||||
setup()
|
||||
const trash = screen.getByTitle('common.delete')
|
||||
|
||||
fireEvent.mouseEnter(trash)
|
||||
expect(trash.style.color).toBe('rgb(239, 68, 68)')
|
||||
|
||||
fireEvent.mouseLeave(trash)
|
||||
expect(trash.style.color).toBe('rgb(209, 213, 219)')
|
||||
})
|
||||
})
|
||||
|
||||
describe('BudgetCategoryTable — remaining cells', () => {
|
||||
it('FE-W4BCT-043: editing the total saves the parsed number', () => {
|
||||
const { handleUpdateField } = setup()
|
||||
|
||||
fireEvent.click(screen.getByText('100.00'))
|
||||
const input = screen.getByDisplayValue('100')
|
||||
fireEvent.change(input, { target: { value: '120,50' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
|
||||
expect(handleUpdateField).toHaveBeenCalledWith(1, 'total_price', 120.5)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-044: a zero-decimal currency drops the decimals from the amount placeholder', () => {
|
||||
setup({ currency: 'JPY' }, [budgetItem({ total_price: null } as Partial<BudgetItem>)])
|
||||
|
||||
expect(screen.getByText('0')).toBeInTheDocument()
|
||||
expect(screen.queryByText('0,00')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4BCT-045: editing the note saves it', () => {
|
||||
const { handleUpdateField } = setup({}, [budgetItem({ note: 'Return trip' } as Partial<BudgetItem>)])
|
||||
|
||||
fireEvent.click(screen.getByText('Return trip'))
|
||||
const input = screen.getByDisplayValue('Return trip')
|
||||
fireEvent.change(input, { target: { value: 'One way' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
|
||||
expect(handleUpdateField).toHaveBeenCalledWith(1, 'note', 'One way')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-046: picking a day from the date cell stores the ISO date', () => {
|
||||
const { handleUpdateField, container } = setup({}, [budgetItem({ expense_date: '2026-06-15' } as Partial<BudgetItem>)])
|
||||
const dateCell = container.querySelectorAll('tbody tr')[0].querySelectorAll('td')[7]
|
||||
|
||||
fireEvent.click(dateCell.querySelector('button')!)
|
||||
const day20 = screen.getAllByRole('button').find(b => b.textContent?.trim() === '20')
|
||||
fireEvent.click(day20!)
|
||||
|
||||
expect(handleUpdateField).toHaveBeenCalledWith(1, 'expense_date', '2026-06-20')
|
||||
})
|
||||
|
||||
it('FE-W4BCT-047: clearing the date cell stores null', () => {
|
||||
const { handleUpdateField, container } = setup({}, [budgetItem({ expense_date: '2026-06-15' } as Partial<BudgetItem>)])
|
||||
const dateCell = container.querySelectorAll('tbody tr')[0].querySelectorAll('td')[7]
|
||||
|
||||
fireEvent.click(dateCell.querySelector('button')!)
|
||||
fireEvent.click(screen.getByLabelText('Clear date'))
|
||||
|
||||
expect(handleUpdateField).toHaveBeenCalledWith(1, 'expense_date', null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-048: a non-numeric persons entry stores null', () => {
|
||||
const { handleUpdateField } = setup()
|
||||
|
||||
fireEvent.click(screen.getByText('2'))
|
||||
const input = screen.getByDisplayValue('2')
|
||||
fireEvent.change(input, { target: { value: 'abc' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
|
||||
expect(handleUpdateField).toHaveBeenCalledWith(1, 'persons', null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-049: zero days is stored as null rather than 0', () => {
|
||||
const { handleUpdateField } = setup()
|
||||
|
||||
fireEvent.click(screen.getByText('5'))
|
||||
const input = screen.getByDisplayValue('5')
|
||||
fireEvent.change(input, { target: { value: '0' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
|
||||
expect(handleUpdateField).toHaveBeenCalledWith(1, 'days', null)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-050: an item without persons, days or members dashes out every derived column', () => {
|
||||
const { container } = setup({}, [budgetItem({ persons: null, days: null, members: undefined } as unknown as Partial<BudgetItem>)])
|
||||
const cells = container.querySelectorAll('tbody tr')[0].querySelectorAll('td')
|
||||
|
||||
// per person, per day, per person-day — none of them is derivable.
|
||||
expect(cells[4]).toHaveTextContent('-')
|
||||
expect(cells[5]).toHaveTextContent('-')
|
||||
expect(cells[6]).toHaveTextContent('-')
|
||||
expect(screen.queryByText('100.00 EUR')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('BudgetCategoryTable — member chips', () => {
|
||||
const withMembers = () => setup(
|
||||
{ hasMultipleMembers: true },
|
||||
[budgetItem({ members: [{ user_id: 1, username: 'ada', paid: 0 }] } as unknown as Partial<BudgetItem>)],
|
||||
)
|
||||
|
||||
it('FE-W4BCT-051: tapping a chip toggles that member’s paid flag', () => {
|
||||
const { toggleBudgetMemberPaid } = withMembers()
|
||||
|
||||
// The chip is rendered twice: the mobile stack under the name and the persons column.
|
||||
const chips = screen.getAllByText('A')
|
||||
fireEvent.click(chips[0])
|
||||
fireEvent.click(chips[1])
|
||||
|
||||
expect(toggleBudgetMemberPaid).toHaveBeenCalledTimes(2)
|
||||
expect(toggleBudgetMemberPaid).toHaveBeenCalledWith(7, 1, 1, true)
|
||||
})
|
||||
|
||||
it('FE-W4BCT-052: picking a member from either chip dropdown sets the item members', () => {
|
||||
const { setBudgetItemMembers, container } = withMembers()
|
||||
// The mobile stack under the name and the persons column both carry an editor.
|
||||
// Assigned chips are buttons of their own, so the editors are the two that
|
||||
// carry the picker icon.
|
||||
const editors = Array.from(container.querySelectorAll('td button'))
|
||||
.filter(b => b.querySelector('.lucide-pencil, .lucide-users'))
|
||||
|
||||
fireEvent.click(editors[0])
|
||||
fireEvent.click(screen.getByText('bob'))
|
||||
fireEvent.click(editors[0]) // picking an option leaves the dropdown open
|
||||
fireEvent.click(editors[1])
|
||||
fireEvent.click(screen.getByText('bob'))
|
||||
|
||||
expect(setBudgetItemMembers).toHaveBeenCalledTimes(2)
|
||||
expect(setBudgetItemMembers).toHaveBeenCalledWith(7, 1, [1, 2])
|
||||
})
|
||||
|
||||
it('FE-W4BCT-053: read-only member chips expose no editing controls', () => {
|
||||
setup(
|
||||
{ hasMultipleMembers: true, canEdit: false },
|
||||
[budgetItem({ members: [{ user_id: 1, username: 'ada', paid: 1 }] } as unknown as Partial<BudgetItem>)],
|
||||
)
|
||||
|
||||
expect(screen.getAllByText('A')).toHaveLength(2)
|
||||
expect(document.querySelectorAll('table button')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -111,7 +111,7 @@ export default function BudgetCategoryTable({ cat, grouped, categoryColor, canEd
|
||||
<>
|
||||
<span style={{ fontWeight: 600, fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{cat}</span>
|
||||
{canEdit && (
|
||||
<button onClick={() => setEditingCat({ name: cat, value: cat })}
|
||||
<button type="button" onClick={() => setEditingCat({ name: cat, value: cat })}
|
||||
style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'rgba(255,255,255,0.4)', display: 'flex', padding: 1 }}
|
||||
onMouseEnter={e => e.currentTarget.style.color = '#fff'} onMouseLeave={e => e.currentTarget.style.color = 'rgba(255,255,255,0.4)'}>
|
||||
<Pencil size={10} />
|
||||
@@ -123,7 +123,7 @@ export default function BudgetCategoryTable({ cat, grouped, categoryColor, canEd
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
<span style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, opacity: 0.9 }}>{fmt(subtotal, currency)}</span>
|
||||
{canEdit && (
|
||||
<button onClick={() => handleDeleteCategory(cat)} title={t('budget.deleteCategory')}
|
||||
<button type="button" onClick={() => handleDeleteCategory(cat)} title={t('budget.deleteCategory')}
|
||||
style={{ background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: 4, color: '#fff', cursor: 'pointer', padding: '3px 6px', display: 'flex', alignItems: 'center', opacity: 0.6 }}
|
||||
onMouseEnter={e => e.currentTarget.style.opacity = '1'} onMouseLeave={e => e.currentTarget.style.opacity = '0.6'}>
|
||||
<Trash2 size={13} />
|
||||
@@ -225,11 +225,11 @@ export default function BudgetCategoryTable({ cat, grouped, categoryColor, canEd
|
||||
readOnly={!canEdit}
|
||||
/>
|
||||
) : (
|
||||
<InlineEditCell value={item.persons} type="number" decimals={0} onSave={v => handleUpdateField(item.id, 'persons', v != null ? parseInt(v as string) || null : null)} style={{ textAlign: 'center' }} placeholder="-" locale={locale} editTooltip={t('budget.editTooltip')} readOnly={!canEdit} />
|
||||
<InlineEditCell value={item.persons} type="number" decimals={0} onSave={v => handleUpdateField(item.id, 'persons', v != null ? Number.parseInt(v as string) || null : null)} style={{ textAlign: 'center' }} placeholder="-" locale={locale} editTooltip={t('budget.editTooltip')} readOnly={!canEdit} />
|
||||
)}
|
||||
</td>
|
||||
<td className="hidden sm:table-cell" style={{ ...td, textAlign: 'center' }}>
|
||||
<InlineEditCell value={item.days} type="number" decimals={0} onSave={v => handleUpdateField(item.id, 'days', v != null ? parseInt(v as string) || null : null)} style={{ textAlign: 'center' }} placeholder="-" locale={locale} editTooltip={t('budget.editTooltip')} readOnly={!canEdit} />
|
||||
<InlineEditCell value={item.days} type="number" decimals={0} onSave={v => handleUpdateField(item.id, 'days', v != null ? Number.parseInt(v as string) || null : null)} style={{ textAlign: 'center' }} placeholder="-" locale={locale} editTooltip={t('budget.editTooltip')} readOnly={!canEdit} />
|
||||
</td>
|
||||
<td className="hidden md:table-cell" style={{ ...td, textAlign: 'center', color: pp != null ? 'var(--text-secondary)' : 'var(--text-faint)' }}>{pp != null ? fmt(pp, currency) : '-'}</td>
|
||||
<td className="hidden md:table-cell" style={{ ...td, textAlign: 'center', color: pd != null ? 'var(--text-secondary)' : 'var(--text-faint)' }}>{pd != null ? fmt(pd, currency) : '-'}</td>
|
||||
@@ -246,7 +246,7 @@ export default function BudgetCategoryTable({ cat, grouped, categoryColor, canEd
|
||||
<td className="hidden sm:table-cell" style={td}><InlineEditCell value={item.note} onSave={v => handleUpdateField(item.id, 'note', v)} placeholder={t('budget.table.note')} locale={locale} editTooltip={t('budget.editTooltip')} readOnly={!canEdit} /></td>
|
||||
<td style={{ ...td, textAlign: 'center' }}>
|
||||
{canEdit && (
|
||||
<button onClick={() => handleDeleteItem(item.id)} title={t('common.delete')}
|
||||
<button type="button" onClick={() => handleDeleteItem(item.id)} title={t('common.delete')}
|
||||
style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4, color: 'var(--text-faint)', borderRadius: 4, display: 'inline-flex', transition: 'color 0.15s' }}
|
||||
onMouseEnter={e => e.currentTarget.style.color = '#ef4444'} onMouseLeave={e => e.currentTarget.style.color = '#d1d5db'}>
|
||||
<Trash2 size={14} />
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
// FE-W4IEC-001 to FE-W4IEC-016
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '../../../tests/helpers/render'
|
||||
import InlineEditCell from './BudgetPanelInlineEditCell'
|
||||
|
||||
function setup(props: Partial<Parameters<typeof InlineEditCell>[0]> = {}) {
|
||||
const onSave = vi.fn()
|
||||
const utils = render(<InlineEditCell value="Ferry" onSave={onSave} locale="en-US" {...props} />)
|
||||
return { onSave, ...utils }
|
||||
}
|
||||
|
||||
function paste(input: HTMLElement, text: string) {
|
||||
fireEvent.paste(input, { clipboardData: { getData: () => text } })
|
||||
}
|
||||
|
||||
describe('InlineEditCell — display', () => {
|
||||
it('FE-W4IEC-001: shows the raw text value', () => {
|
||||
setup()
|
||||
expect(screen.getByText('Ferry')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4IEC-002: formats a number with the given decimals and locale', () => {
|
||||
setup({ value: 1234.5, type: 'number' })
|
||||
expect(screen.getByText('1,234.50')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4IEC-003: honours a custom decimal count', () => {
|
||||
setup({ value: 12, type: 'number', decimals: 0 })
|
||||
expect(screen.getByText('12')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4IEC-004: falls back to the placeholder, then to a dash', () => {
|
||||
const { unmount } = setup({ value: null, placeholder: 'Add note' })
|
||||
expect(screen.getByText('Add note')).toBeInTheDocument()
|
||||
unmount()
|
||||
|
||||
setup({ value: null })
|
||||
expect(screen.getByText('-')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4IEC-005: exposes the edit tooltip and hover feedback when editable', () => {
|
||||
const { container } = setup({ editTooltip: 'Click to edit' })
|
||||
const cell = container.firstElementChild as HTMLElement
|
||||
|
||||
expect(cell).toHaveAttribute('title', 'Click to edit')
|
||||
fireEvent.mouseEnter(cell)
|
||||
expect(cell.style.background).toBe('var(--bg-hover)')
|
||||
fireEvent.mouseLeave(cell)
|
||||
expect(cell.style.background).toBe('transparent')
|
||||
})
|
||||
|
||||
it('FE-W4IEC-006: a read-only cell has no tooltip, no hover and cannot be opened', () => {
|
||||
const { container } = setup({ readOnly: true, editTooltip: 'Click to edit' })
|
||||
const cell = container.firstElementChild as HTMLElement
|
||||
|
||||
expect(cell).not.toHaveAttribute('title')
|
||||
fireEvent.mouseEnter(cell)
|
||||
expect(cell.style.background).toBe('')
|
||||
|
||||
fireEvent.click(cell)
|
||||
expect(screen.queryByRole('textbox')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4IEC-007: centres the content when the caller centres the text', () => {
|
||||
const { container } = setup({ style: { textAlign: 'center' } })
|
||||
|
||||
expect((container.firstElementChild as HTMLElement).style.justifyContent).toBe('center')
|
||||
})
|
||||
})
|
||||
|
||||
describe('InlineEditCell — editing', () => {
|
||||
it('FE-W4IEC-008: clicking opens a focused, pre-selected input', () => {
|
||||
const { container } = setup()
|
||||
fireEvent.click(container.firstElementChild!)
|
||||
|
||||
const input = screen.getByRole('textbox') as HTMLInputElement
|
||||
expect(input).toHaveValue('Ferry')
|
||||
expect(input).toHaveFocus()
|
||||
})
|
||||
|
||||
it('FE-W4IEC-009: Enter saves the changed value', () => {
|
||||
const { onSave, container } = setup()
|
||||
fireEvent.click(container.firstElementChild!)
|
||||
|
||||
const input = screen.getByRole('textbox')
|
||||
fireEvent.change(input, { target: { value: 'Bus' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith('Bus')
|
||||
expect(screen.queryByRole('textbox')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4IEC-010: blur saves and an unchanged value does not fire onSave', () => {
|
||||
const { onSave, container } = setup()
|
||||
fireEvent.click(container.firstElementChild!)
|
||||
|
||||
fireEvent.blur(screen.getByRole('textbox'))
|
||||
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W4IEC-011: Escape restores the original value without saving', () => {
|
||||
const { onSave, container } = setup()
|
||||
fireEvent.click(container.firstElementChild!)
|
||||
|
||||
const input = screen.getByRole('textbox')
|
||||
fireEvent.change(input, { target: { value: 'Bus' } })
|
||||
fireEvent.keyDown(input, { key: 'Escape' })
|
||||
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
expect(screen.getByText('Ferry')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4IEC-012: a numeric cell parses a comma decimal and uses a decimal keypad', () => {
|
||||
const { onSave, container } = setup({ value: 10, type: 'number' })
|
||||
fireEvent.click(container.firstElementChild!)
|
||||
|
||||
const input = screen.getByRole('textbox')
|
||||
expect(input).toHaveAttribute('inputmode', 'decimal')
|
||||
fireEvent.change(input, { target: { value: '12,50' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith(12.5)
|
||||
})
|
||||
|
||||
it('FE-W4IEC-013: an unparseable numeric entry saves null', () => {
|
||||
const { onSave, container } = setup({ value: 10, type: 'number' })
|
||||
fireEvent.click(container.firstElementChild!)
|
||||
|
||||
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'abc' } })
|
||||
fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' })
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it('FE-W4IEC-014: pasting a formatted amount normalizes separators', () => {
|
||||
const { container } = setup({ value: 0, type: 'number' })
|
||||
fireEvent.click(container.firstElementChild!)
|
||||
const input = screen.getByRole('textbox')
|
||||
|
||||
paste(input, '1.234,56 EUR')
|
||||
expect(input).toHaveValue('1234.56')
|
||||
|
||||
paste(input, '$2,345.67')
|
||||
expect(input).toHaveValue('2345.67')
|
||||
})
|
||||
|
||||
it('FE-W4IEC-015: pasting a separator-free amount keeps the digits', () => {
|
||||
const { container } = setup({ value: 0, type: 'number' })
|
||||
fireEvent.click(container.firstElementChild!)
|
||||
const input = screen.getByRole('textbox')
|
||||
|
||||
paste(input, 'EUR 4200')
|
||||
expect(input).toHaveValue('4200')
|
||||
})
|
||||
|
||||
it('FE-W4IEC-016: a text cell leaves pasted content to the browser', () => {
|
||||
const { container } = setup()
|
||||
fireEvent.click(container.firstElementChild!)
|
||||
const input = screen.getByRole('textbox')
|
||||
|
||||
paste(input, '1.234,56')
|
||||
|
||||
expect(input).toHaveValue('Ferry')
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { normalizePastedAmount } from './BudgetPanel.helpers'
|
||||
|
||||
interface InlineEditCellProps {
|
||||
value: string | number | null | undefined
|
||||
@@ -22,28 +23,14 @@ export default function InlineEditCell({ value, onSave, type = 'text', style = {
|
||||
const save = () => {
|
||||
setEditing(false)
|
||||
let v: string | number | null = editValue
|
||||
if (type === 'number') { const p = parseFloat(String(editValue).replace(',', '.')); v = isNaN(p) ? null : p }
|
||||
if (type === 'number') { const p = Number.parseFloat(String(editValue).replace(',', '.')); v = Number.isNaN(p) ? null : p }
|
||||
if (v !== value) onSave(v)
|
||||
}
|
||||
|
||||
const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
|
||||
if (type !== 'number') return
|
||||
e.preventDefault()
|
||||
let text = e.clipboardData.getData('text').trim()
|
||||
// Strip everything except digits, dots, commas, minus
|
||||
text = text.replace(/[^\d.,-]/g, '')
|
||||
// Remove all thousand separators (dots or commas before 3-digit groups), keep last separator as decimal
|
||||
const lastComma = text.lastIndexOf(',')
|
||||
const lastDot = text.lastIndexOf('.')
|
||||
const decimalPos = Math.max(lastComma, lastDot)
|
||||
if (decimalPos > -1) {
|
||||
const intPart = text.substring(0, decimalPos).replace(/[.,]/g, '')
|
||||
const decPart = text.substring(decimalPos + 1)
|
||||
text = intPart + '.' + decPart
|
||||
} else {
|
||||
text = text.replace(/[.,]/g, '')
|
||||
}
|
||||
setEditValue(text)
|
||||
setEditValue(normalizePastedAmount(e.clipboardData.getData('text')))
|
||||
}
|
||||
|
||||
if (editing) {
|
||||
@@ -58,14 +45,27 @@ export default function InlineEditCell({ value, onSave, type = 'text', style = {
|
||||
? Number(value).toLocaleString(locale, { minimumFractionDigits: decimals, maximumFractionDigits: decimals })
|
||||
: (value || '')
|
||||
|
||||
// Editable cells are real buttons so they can be tabbed to and pressed. A
|
||||
// read-only cell renders no control at all rather than a disabled one: it is
|
||||
// plain text, and a disabled button would be announced as an unavailable
|
||||
// control that never becomes available. Same split the member chips use.
|
||||
const cellStyle: React.CSSProperties = {
|
||||
padding: '2px 4px', borderRadius: 4, minHeight: 22, display: 'flex', alignItems: 'center',
|
||||
justifyContent: style?.textAlign === 'center' ? 'center' : 'flex-start', transition: 'background 0.15s',
|
||||
color: display ? 'var(--text-primary)' : 'var(--text-faint)', fontSize: 'calc(13px * var(--fs-scale-body, 1))',
|
||||
width: '100%', textAlign: 'left', ...style,
|
||||
}
|
||||
const content = display || placeholder || '-'
|
||||
|
||||
if (readOnly) return <div style={{ ...cellStyle, cursor: 'default' }}>{content}</div>
|
||||
|
||||
return (
|
||||
<div onClick={() => { if (readOnly) return; setEditValue(value ?? ''); setEditing(true) }} title={readOnly ? undefined : editTooltip}
|
||||
style={{ cursor: readOnly ? 'default' : 'pointer', padding: '2px 4px', borderRadius: 4, minHeight: 22, display: 'flex', alignItems: 'center',
|
||||
justifyContent: style?.textAlign === 'center' ? 'center' : 'flex-start', transition: 'background 0.15s',
|
||||
color: display ? 'var(--text-primary)' : 'var(--text-faint)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', ...style }}
|
||||
onMouseEnter={e => { if (!readOnly) e.currentTarget.style.background = 'var(--bg-hover)' }}
|
||||
onMouseLeave={e => { if (!readOnly) e.currentTarget.style.background = 'transparent' }}>
|
||||
{display || placeholder || '-'}
|
||||
</div>
|
||||
<button type="button"
|
||||
onClick={() => { setEditValue(value ?? ''); setEditing(true) }} title={editTooltip}
|
||||
style={{ ...cellStyle, cursor: 'pointer' }}
|
||||
onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-hover)' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.background = 'transparent' }}>
|
||||
{content}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
// FE-W4BMC-001 to FE-W4BMC-016
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import type { BudgetItemMember } from '../../types'
|
||||
import { render, screen, fireEvent } from '../../../tests/helpers/render'
|
||||
import BudgetMemberChips, { ChipWithTooltip, type TripMember } from './BudgetPanelMemberChips'
|
||||
|
||||
const TRIP_MEMBERS: TripMember[] = [
|
||||
{ id: 1, username: 'ada', avatar_url: '/uploads/avatars/ada.png' },
|
||||
{ id: 2, username: 'bob', avatar_url: null },
|
||||
]
|
||||
|
||||
function member(overrides: Partial<BudgetItemMember> = {}): BudgetItemMember {
|
||||
return { user_id: 1, username: 'ada', avatar_url: null, paid: 0, ...overrides } as unknown as BudgetItemMember
|
||||
}
|
||||
|
||||
function setup(props: Partial<Parameters<typeof BudgetMemberChips>[0]> = {}) {
|
||||
const onSetMembers = vi.fn()
|
||||
const onTogglePaid = vi.fn()
|
||||
const utils = render(
|
||||
<BudgetMemberChips members={[member()]} tripMembers={TRIP_MEMBERS} onSetMembers={onSetMembers} onTogglePaid={onTogglePaid} {...props} />,
|
||||
)
|
||||
return { onSetMembers, onTogglePaid, ...utils }
|
||||
}
|
||||
|
||||
/**
|
||||
* The member picker trigger. A chip that can be clicked is a real button too,
|
||||
* so it is the icon that tells the trigger apart from the chips before it.
|
||||
*/
|
||||
function picker(): HTMLElement {
|
||||
const trigger = screen.getAllByRole('button').find(b => b.querySelector('.lucide-pencil, .lucide-users'))
|
||||
if (!trigger) throw new Error('no picker trigger rendered')
|
||||
return trigger
|
||||
}
|
||||
|
||||
describe('ChipWithTooltip', () => {
|
||||
it('FE-W4BMC-001: falls back to the uppercased initial', () => {
|
||||
const { container } = render(<ChipWithTooltip label="ada" avatarUrl={null} />)
|
||||
|
||||
expect(container.firstElementChild).toHaveTextContent('A')
|
||||
})
|
||||
|
||||
it('FE-W4BMC-002: renders the avatar when one is given', () => {
|
||||
const { container } = render(<ChipWithTooltip label="ada" avatarUrl="/uploads/avatars/ada.png" />)
|
||||
|
||||
expect(container.querySelector('img')).toHaveAttribute('src', '/uploads/avatars/ada.png')
|
||||
})
|
||||
|
||||
it('FE-W4BMC-003: hovering portals a name tooltip and leaving removes it', () => {
|
||||
const { container } = render(<ChipWithTooltip label="Ada Lovelace" avatarUrl={null} />)
|
||||
const chip = container.firstElementChild as HTMLElement
|
||||
|
||||
fireEvent.mouseEnter(chip)
|
||||
expect(screen.getByText('Ada Lovelace')).toBeInTheDocument()
|
||||
|
||||
fireEvent.mouseLeave(chip)
|
||||
expect(screen.queryByText('Ada Lovelace')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4BMC-004: a paid chip turns green and the tooltip carries a Paid tag', () => {
|
||||
const { container } = render(<ChipWithTooltip label="ada" avatarUrl={null} paid />)
|
||||
const chip = container.firstElementChild as HTMLElement
|
||||
|
||||
expect(chip.style.border).toBe('2px solid rgb(34, 197, 94)')
|
||||
fireEvent.mouseEnter(chip)
|
||||
expect(screen.getByText('Paid')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BMC-005: only a clickable chip gets the pointer cursor', () => {
|
||||
const onClick = vi.fn()
|
||||
const { container, unmount } = render(<ChipWithTooltip label="ada" avatarUrl={null} onClick={onClick} />)
|
||||
const chip = container.firstElementChild as HTMLElement
|
||||
|
||||
expect(chip.style.cursor).toBe('pointer')
|
||||
fireEvent.click(chip)
|
||||
expect(onClick).toHaveBeenCalledOnce()
|
||||
unmount()
|
||||
|
||||
const plain = render(<ChipWithTooltip label="ada" avatarUrl={null} />)
|
||||
expect((plain.container.firstElementChild as HTMLElement).style.cursor).toBe('default')
|
||||
})
|
||||
})
|
||||
|
||||
describe('BudgetMemberChips', () => {
|
||||
it('FE-W4BMC-006: renders one chip per assigned member plus the picker button', () => {
|
||||
setup({ members: [member(), member({ user_id: 2, username: 'bob' })] })
|
||||
|
||||
expect(screen.getByText('A')).toBeInTheDocument()
|
||||
expect(screen.getByText('B')).toBeInTheDocument()
|
||||
expect(picker()).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4BMC-007: uses the people icon while nobody is assigned and the pencil afterwards', () => {
|
||||
const { container, unmount } = setup({ members: [] })
|
||||
expect(container.querySelector('.lucide-users')).not.toBeNull()
|
||||
unmount()
|
||||
|
||||
const withMembers = setup()
|
||||
expect(withMembers.container.querySelector('.lucide-pencil')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4BMC-008: clicking a chip toggles that member paid flag', () => {
|
||||
const { onTogglePaid } = setup()
|
||||
|
||||
fireEvent.click(screen.getByText('A'))
|
||||
|
||||
expect(onTogglePaid).toHaveBeenCalledWith(1, true)
|
||||
})
|
||||
|
||||
it('FE-W4BMC-009: clicking an already-paid chip clears the flag', () => {
|
||||
const { onTogglePaid } = setup({ members: [member({ paid: 1 })] })
|
||||
|
||||
fireEvent.click(screen.getByText('A'))
|
||||
|
||||
expect(onTogglePaid).toHaveBeenCalledWith(1, false)
|
||||
})
|
||||
|
||||
it('FE-W4BMC-010: a read-only strip has no picker and no paid toggling', () => {
|
||||
const { onTogglePaid } = setup({ readOnly: true })
|
||||
|
||||
expect(screen.queryByRole('button')).toBeNull()
|
||||
fireEvent.click(screen.getByText('A'))
|
||||
expect(onTogglePaid).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W4BMC-011: the picker lists every trip member and marks the assigned ones', () => {
|
||||
setup()
|
||||
fireEvent.click(picker())
|
||||
|
||||
const rows = screen.getAllByRole('button').slice(2)
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(rows[0]).toHaveTextContent('ada')
|
||||
expect(rows[0].querySelector('.lucide-check')).not.toBeNull()
|
||||
expect(rows[1].querySelector('.lucide-check')).toBeNull()
|
||||
expect(rows[0].querySelector('img')).toHaveAttribute('src', '/uploads/avatars/ada.png')
|
||||
expect(rows[1]).toHaveTextContent('B')
|
||||
})
|
||||
|
||||
it('FE-W4BMC-012: picking an unassigned member adds them', () => {
|
||||
const { onSetMembers } = setup()
|
||||
fireEvent.click(picker())
|
||||
|
||||
fireEvent.click(screen.getAllByRole('button')[3])
|
||||
|
||||
expect(onSetMembers).toHaveBeenCalledWith([1, 2])
|
||||
})
|
||||
|
||||
it('FE-W4BMC-013: picking an assigned member removes them', () => {
|
||||
const { onSetMembers } = setup()
|
||||
fireEvent.click(picker())
|
||||
|
||||
fireEvent.click(screen.getAllByRole('button')[2])
|
||||
|
||||
expect(onSetMembers).toHaveBeenCalledWith([])
|
||||
})
|
||||
|
||||
it('FE-W4BMC-014: a mousedown outside closes the picker, inside keeps it', () => {
|
||||
setup()
|
||||
const trigger = picker()
|
||||
fireEvent.click(trigger)
|
||||
|
||||
fireEvent.mouseDown(screen.getAllByRole('button')[2])
|
||||
expect(screen.getAllByRole('button')).toHaveLength(4)
|
||||
|
||||
fireEvent.mouseDown(trigger)
|
||||
expect(screen.getAllByRole('button')).toHaveLength(4)
|
||||
|
||||
fireEvent.mouseDown(document.body)
|
||||
expect(screen.getAllByRole('button')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-W4BMC-015: the trigger toggles the picker closed again', () => {
|
||||
setup()
|
||||
const trigger = picker()
|
||||
|
||||
fireEvent.click(trigger)
|
||||
expect(screen.getAllByRole('button')).toHaveLength(4)
|
||||
|
||||
fireEvent.click(trigger)
|
||||
expect(screen.getAllByRole('button')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-W4BMC-016: the non-compact variant renders larger chips', () => {
|
||||
setup({ compact: false })
|
||||
|
||||
expect(screen.getByText('A')).toHaveStyle({ width: '30px' })
|
||||
expect(picker().style.width).toBe('28px')
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import ReactDOM from 'react-dom'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { Pencil, Users, Check } from 'lucide-react'
|
||||
import type { BudgetItemMember } from '../../types'
|
||||
@@ -22,7 +22,7 @@ interface ChipWithTooltipProps {
|
||||
export function ChipWithTooltip({ label, avatarUrl, size = 20, paid, onClick }: ChipWithTooltipProps) {
|
||||
const [hover, setHover] = useState(false)
|
||||
const [pos, setPos] = useState({ top: 0, left: 0 })
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const ref = useRef<HTMLElement | null>(null)
|
||||
|
||||
const onEnter = () => {
|
||||
if (ref.current) {
|
||||
@@ -35,23 +35,35 @@ export function ChipWithTooltip({ label, avatarUrl, size = 20, paid, onClick }:
|
||||
const borderColor = paid ? '#22c55e' : 'var(--border-primary)'
|
||||
const bg = paid ? 'rgba(34,197,94,0.15)' : 'var(--bg-tertiary)'
|
||||
|
||||
// Identical for both shells — a clickable chip is a real button so it can be
|
||||
// tabbed to and pressed, a decorative one stays a plain div.
|
||||
const chipStyle = {
|
||||
width: size, height: size, borderRadius: '50%', border: `2px solid ${borderColor}`,
|
||||
background: bg, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
fontSize: size * 0.4, fontWeight: 700, color: paid ? '#16a34a' : 'var(--text-muted)',
|
||||
overflow: 'hidden', flexShrink: 0, cursor: onClick ? 'pointer' : 'default',
|
||||
transition: 'border-color 0.15s, background 0.15s',
|
||||
padding: 0, fontFamily: 'inherit',
|
||||
}
|
||||
const inner = avatarUrl
|
||||
? <img src={avatarUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
|
||||
: label?.[0]?.toUpperCase()
|
||||
|
||||
return (
|
||||
<>
|
||||
<div ref={ref} onMouseEnter={onEnter} onMouseLeave={() => setHover(false)}
|
||||
onClick={onClick}
|
||||
style={{
|
||||
width: size, height: size, borderRadius: '50%', border: `2px solid ${borderColor}`,
|
||||
background: bg, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
fontSize: size * 0.4, fontWeight: 700, color: paid ? '#16a34a' : 'var(--text-muted)',
|
||||
overflow: 'hidden', flexShrink: 0, cursor: onClick ? 'pointer' : 'default',
|
||||
transition: 'border-color 0.15s, background 0.15s',
|
||||
}}>
|
||||
{avatarUrl
|
||||
? <img src={avatarUrl} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
|
||||
: label?.[0]?.toUpperCase()
|
||||
}
|
||||
</div>
|
||||
{hover && ReactDOM.createPortal(
|
||||
{onClick ? (
|
||||
<button type="button" ref={el => { ref.current = el }} aria-label={label}
|
||||
onMouseEnter={onEnter} onMouseLeave={() => setHover(false)}
|
||||
onClick={onClick} style={chipStyle}>
|
||||
{inner}
|
||||
</button>
|
||||
) : (
|
||||
<div ref={el => { ref.current = el }} onMouseEnter={onEnter} onMouseLeave={() => setHover(false)}
|
||||
style={chipStyle}>
|
||||
{inner}
|
||||
</div>
|
||||
)}
|
||||
{hover && createPortal(
|
||||
<div style={{
|
||||
position: 'fixed', top: pos.top, left: pos.left, transform: 'translate(-50%, -100%)',
|
||||
pointerEvents: 'none', zIndex: 10000, whiteSpace: 'nowrap',
|
||||
@@ -131,7 +143,7 @@ export default function BudgetMemberChips({ members = [], tripMembers = [], onSe
|
||||
/>
|
||||
))}
|
||||
{!readOnly && (
|
||||
<button ref={btnRef} onClick={openDropdown}
|
||||
<button type="button" ref={btnRef} onClick={openDropdown}
|
||||
style={{
|
||||
width: btnSize, height: btnSize, borderRadius: '50%', border: '1.5px dashed var(--border-primary)',
|
||||
background: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
@@ -140,7 +152,7 @@ export default function BudgetMemberChips({ members = [], tripMembers = [], onSe
|
||||
{members.length > 0 ? <Pencil size={iconSize} /> : <Users size={iconSize} />}
|
||||
</button>
|
||||
)}
|
||||
{showDropdown && ReactDOM.createPortal(
|
||||
{showDropdown && createPortal(
|
||||
<div ref={dropRef} style={{
|
||||
position: 'fixed', top: dropPos.top, left: dropPos.left, transform: 'translateX(-50%)', zIndex: 10000,
|
||||
background: 'var(--bg-card)', border: '1px solid var(--border-primary)', borderRadius: 10,
|
||||
@@ -149,7 +161,7 @@ export default function BudgetMemberChips({ members = [], tripMembers = [], onSe
|
||||
{tripMembers.map(tm => {
|
||||
const isActive = memberIds.includes(tm.id)
|
||||
return (
|
||||
<button key={tm.id} onClick={() => toggleMember(tm.id)} style={{
|
||||
<button type="button" key={tm.id} onClick={() => toggleMember(tm.id)} style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, width: '100%', padding: '5px 8px',
|
||||
borderRadius: 6, border: 'none', background: isActive ? 'var(--bg-hover)' : 'none', cursor: 'pointer',
|
||||
fontFamily: 'inherit', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-primary)', textAlign: 'left',
|
||||
@@ -163,7 +175,7 @@ export default function BudgetMemberChips({ members = [], tripMembers = [], onSe
|
||||
color: 'var(--text-muted)', overflow: 'hidden', flexShrink: 0,
|
||||
}}>
|
||||
{tm.avatar_url
|
||||
? <img src={tm.avatar_url} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
|
||||
? <img src={tm.avatar_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
|
||||
: tm.username?.[0]?.toUpperCase()
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// FE-W4PIE-001 to FE-W4PIE-006
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { render, screen } from '../../../tests/helpers/render'
|
||||
import PieChart from './BudgetPanelPieChart'
|
||||
|
||||
const SEGMENTS = [
|
||||
{ label: 'Food', value: 300, color: '#ef4444' },
|
||||
{ label: 'Hotels', value: 100, color: '#3b82f6' },
|
||||
]
|
||||
|
||||
describe('BudgetPanelPieChart', () => {
|
||||
it('FE-W4PIE-001: renders nothing without segments', () => {
|
||||
const { container } = render(<PieChart segments={[]} totalLabel="1.200 €" />)
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('FE-W4PIE-002: renders nothing when every segment is zero', () => {
|
||||
const { container } = render(
|
||||
<PieChart segments={[{ label: 'Food', value: 0, color: '#ef4444' }]} totalLabel="0 €" />,
|
||||
)
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('FE-W4PIE-003: turns the segment shares into consecutive conic-gradient stops', () => {
|
||||
const { container } = render(<PieChart segments={SEGMENTS} totalLabel="400 €" />)
|
||||
const pie = container.querySelector('.trek-pie-reveal') as HTMLElement
|
||||
|
||||
expect(pie.style.background).toBe('conic-gradient(rgb(239, 68, 68) 0deg 270deg, rgb(59, 130, 246) 270deg 360deg)')
|
||||
})
|
||||
|
||||
it('FE-W4PIE-004: shows the total label in the donut hole', () => {
|
||||
render(<PieChart segments={SEGMENTS} totalLabel="400 €" />)
|
||||
|
||||
expect(screen.getByText('400 €')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4PIE-005: defaults to a 200px pie with a 55% hole', () => {
|
||||
const { container } = render(<PieChart segments={SEGMENTS} totalLabel="400 €" />)
|
||||
const root = container.firstElementChild as HTMLElement
|
||||
const hole = screen.getByText('400 €').parentElement as HTMLElement
|
||||
|
||||
expect(root.style.width).toBe('200px')
|
||||
expect(Math.round(parseFloat(hole.style.width))).toBe(110)
|
||||
})
|
||||
|
||||
it('FE-W4PIE-006: scales pie and hole from the size prop', () => {
|
||||
const { container } = render(<PieChart segments={SEGMENTS} size={120} totalLabel="400 €" />)
|
||||
const root = container.firstElementChild as HTMLElement
|
||||
const hole = screen.getByText('400 €').parentElement as HTMLElement
|
||||
|
||||
expect(root.style.height).toBe('120px')
|
||||
expect(Math.round(parseFloat(hole.style.height))).toBe(66)
|
||||
})
|
||||
})
|
||||
@@ -15,7 +15,7 @@ export default function RingAvatar({ userId, username, avatarUrl, size = 34, inn
|
||||
overflow: 'hidden',
|
||||
fontSize: size < 28 ? 10 : 12, fontWeight: 600, color: textColor,
|
||||
}}>
|
||||
{avatarUrl ? <img src={avatarUrl} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : username?.[0]?.toUpperCase()}
|
||||
{avatarUrl ? <img src={avatarUrl} alt={username || ''} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : username?.[0]?.toUpperCase()}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -75,7 +75,7 @@ export default function BudgetSummary({ theme, currency, locale, grandTotal, has
|
||||
{/* Settlement dropdown inside the total card */}
|
||||
{hasMultipleMembers && settlement && settlement.flows.length > 0 && (
|
||||
<div style={{ marginTop: 16, borderTop: `1px solid ${theme.divider}`, paddingTop: 12 }}>
|
||||
<button onClick={() => setSettlementOpen(v => !v)} style={{
|
||||
<button type="button" onClick={() => setSettlementOpen(v => !v)} style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, width: '100%',
|
||||
background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontFamily: 'inherit',
|
||||
color: theme.sub, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600, letterSpacing: 0.5,
|
||||
@@ -83,7 +83,12 @@ export default function BudgetSummary({ theme, currency, locale, grandTotal, has
|
||||
{settlementOpen ? <ChevronDown size={13} /> : <ChevronRight size={13} />}
|
||||
{t('budget.settlement')}
|
||||
<span style={{ position: 'relative', display: 'inline-flex', marginLeft: 2 }}>
|
||||
{/* Decoration inside the settlement toggle: the hint hangs off
|
||||
hover, and the click only keeps the toggle from firing. A
|
||||
role of its own would give the toggle a second name and a
|
||||
nested control, so it declares itself presentational. */}
|
||||
<span style={{ display: 'flex', cursor: 'help' }}
|
||||
role="presentation"
|
||||
onMouseEnter={e => { const tip = e.currentTarget.nextElementSibling as HTMLElement; if (tip) tip.style.display = 'block' }}
|
||||
onMouseLeave={e => { const tip = e.currentTarget.nextElementSibling as HTMLElement; if (tip) tip.style.display = 'none' }}
|
||||
onClick={e => e.stopPropagation()}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { splitCents, payerSum, payersBalanced, rebalancePayers } from './CostsPanel.helpers'
|
||||
import { calculateTicketShares, hasTicketSplit, payerSum, payersBalanced, readTicketItems, readUserNote, rebalancePayers, splitCents, writeTicketItems, type TicketItem } from './CostsPanel.helpers'
|
||||
|
||||
describe('splitCents', () => {
|
||||
it('splits evenly when it divides cleanly', () => {
|
||||
@@ -76,3 +76,103 @@ describe('rebalancePayers', () => {
|
||||
expect(payersBalanced(next, new Set([1, 2, 3]), 100)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
// ── Notes vs. itemized receipts (#1658) ──────────────────────────────────────
|
||||
|
||||
describe('readTicketItems', () => {
|
||||
const receipt = '{"items":[{"name":"Bread","price":"3.50","parts":[1,2]},{"name":"Wine","price":"12","parts":[2]}]}'
|
||||
|
||||
it('reads the receipt out of its own column', () => {
|
||||
const items = readTicketItems({ ticket_json: receipt })
|
||||
expect(items.map(i => i.name)).toEqual(['Bread', 'Wine'])
|
||||
expect(items[0].participants).toEqual(new Set([1, 2]))
|
||||
expect(items[1].price).toBe('12')
|
||||
})
|
||||
|
||||
it('still reads a response cached before the column existed', () => {
|
||||
const items = readTicketItems({ note: 'TICKETJSON:' + receipt })
|
||||
expect(items).toHaveLength(2)
|
||||
expect(items[1].participants).toEqual(new Set([2]))
|
||||
})
|
||||
|
||||
it('prefers the column over the legacy note when both are present', () => {
|
||||
const items = readTicketItems({ ticket_json: '{"items":[{"name":"Only","price":"1","parts":[]}]}', note: 'TICKETJSON:' + receipt })
|
||||
expect(items.map(i => i.name)).toEqual(['Only'])
|
||||
})
|
||||
|
||||
it('is empty for an expense with neither, and for malformed JSON', () => {
|
||||
expect(readTicketItems({ note: 'just a note' })).toEqual([])
|
||||
expect(readTicketItems(null)).toEqual([])
|
||||
expect(readTicketItems({ ticket_json: '{oops' })).toEqual([])
|
||||
})
|
||||
|
||||
it('round-trips through writeTicketItems', () => {
|
||||
const items = readTicketItems({ ticket_json: receipt })
|
||||
expect(readTicketItems({ ticket_json: writeTicketItems(items) })).toEqual(items)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasTicketSplit', () => {
|
||||
it('recognises both storage shapes and nothing else', () => {
|
||||
expect(hasTicketSplit({ ticket_json: '{"items":[]}' })).toBe(true)
|
||||
expect(hasTicketSplit({ note: 'TICKETJSON:{"items":[]}' })).toBe(true)
|
||||
expect(hasTicketSplit({ note: 'dinner with Ben' })).toBe(false)
|
||||
expect(hasTicketSplit(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('readUserNote', () => {
|
||||
it('returns what the user typed', () => {
|
||||
expect(readUserNote({ note: 'Lisa pays half back' })).toBe('Lisa pays half back')
|
||||
})
|
||||
|
||||
it('never returns a receipt blob as if it were a note', () => {
|
||||
expect(readUserNote({ note: 'TICKETJSON:{"items":[]}' })).toBe('')
|
||||
expect(readUserNote({ note: null })).toBe('')
|
||||
expect(readUserNote(null)).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
// ── Receipt splits have to reconcile (#1382) ─────────────────────────────────
|
||||
|
||||
describe('calculateTicketShares', () => {
|
||||
const line = (price: string, parts: number[]): TicketItem =>
|
||||
({ id: price + parts.join(), name: 'Line', price, participants: new Set(parts) })
|
||||
const shareSum = (shares: Record<number, number>) =>
|
||||
Object.values(shares).reduce((a, v) => a + Math.round(v * 100), 0)
|
||||
|
||||
it('splits each line among the people on it', () => {
|
||||
const { shares, total } = calculateTicketShares([line('10', [1, 2]), line('6', [2])])
|
||||
expect(shares).toEqual({ 1: 5, 2: 11 })
|
||||
expect(total).toBe(16)
|
||||
})
|
||||
|
||||
it('spreads a line nobody was ticked for across everyone on the receipt', () => {
|
||||
// The service charge used to count toward the total and toward nobody's share,
|
||||
// so the expense carried a permanent difference no settle-up could clear.
|
||||
const { shares, total } = calculateTicketShares([
|
||||
line('10', [1, 2]),
|
||||
line('5', []),
|
||||
line('x', [2]),
|
||||
])
|
||||
expect(shares).toEqual({ 1: 7.5, 2: 7.5 })
|
||||
expect(total).toBe(15)
|
||||
expect(shareSum(shares)).toBe(Math.round(total * 100))
|
||||
})
|
||||
|
||||
it('hands out the remainder cents so the shares add back up to the total', () => {
|
||||
const { shares, total } = calculateTicketShares([line('10', [1, 2, 3]), line('0.01', [])])
|
||||
expect(shareSum(shares)).toBe(Math.round(total * 100))
|
||||
expect(total).toBe(10.01)
|
||||
})
|
||||
|
||||
it('splits nothing when the receipt has no participants anywhere', () => {
|
||||
const { shares, total } = calculateTicketShares([line('10', []), line('5', [])])
|
||||
expect(shares).toEqual({})
|
||||
expect(total).toBe(15)
|
||||
})
|
||||
|
||||
it('is empty for an empty receipt', () => {
|
||||
expect(calculateTicketShares([])).toEqual({ shares: {}, total: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -22,7 +22,7 @@ export function splitCents(amount: number, n: number): number[] {
|
||||
|
||||
/** Sum the amounts of the selected payers. */
|
||||
export function payerSum(amounts: Record<number, string>, ids: Set<number>): number {
|
||||
return [...ids].reduce((a, id) => a + (parseFloat(amounts[id]) || 0), 0)
|
||||
return [...ids].reduce((a, id) => a + (Number.parseFloat(amounts[id]) || 0), 0)
|
||||
}
|
||||
|
||||
/** True when the payer amounts add up to the expense total, to the cent. */
|
||||
@@ -45,9 +45,139 @@ export function rebalancePayers(
|
||||
if (free.length === 0) return amounts
|
||||
const pinnedSum = all
|
||||
.filter(id => pinned.has(id))
|
||||
.reduce((a, id) => a + (parseFloat(amounts[id]) || 0), 0)
|
||||
.reduce((a, id) => a + (Number.parseFloat(amounts[id]) || 0), 0)
|
||||
const shares = splitCents(total - pinnedSum, free.length)
|
||||
const next = { ...amounts }
|
||||
free.forEach((id, i) => { next[id] = shares[i] ? shares[i].toFixed(2) : '' })
|
||||
return next
|
||||
}
|
||||
|
||||
/**
|
||||
* Split `total` equally across `members`, in whole cents.
|
||||
*
|
||||
* The remainder cent rotates with the item id rather than always landing on the
|
||||
* first member, so across several expenses the rounding evens out instead of
|
||||
* always favouring the same person.
|
||||
*/
|
||||
export function splitEqualShares(total: number, members: { user_id: number }[], itemId: number): Record<number, number> {
|
||||
const n = members.length
|
||||
if (n === 0) return {}
|
||||
|
||||
const totalCents = Math.round(total * 100)
|
||||
const baseCents = Math.floor(totalCents / n)
|
||||
const remainder = totalCents % n
|
||||
|
||||
const shares: Record<number, number> = {}
|
||||
const sortedMembers = [...members].sort((a, b) => a.user_id - b.user_id)
|
||||
const startIndex = itemId % n
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
const member = sortedMembers[i]
|
||||
const hasExtraCent = ((i - startIndex + n) % n) < remainder
|
||||
shares[member.user_id] = (baseCents + (hasExtraCent ? 1 : 0)) / 100
|
||||
}
|
||||
|
||||
return shares
|
||||
}
|
||||
|
||||
/** One line of a receipt: what it cost and who is in on it. */
|
||||
export interface TicketItem {
|
||||
id: string
|
||||
name: string
|
||||
price: string
|
||||
participants: Set<number>
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the itemized receipt off an expense (#1658).
|
||||
*
|
||||
* It lives in `ticket_json` since migration 186. Before that it was smuggled
|
||||
* through `note` behind a `TICKETJSON:` prefix, which is why an expense split by
|
||||
* receipt could never carry a written note. The old shape is still read here so
|
||||
* a response cached before the migration keeps rendering its split.
|
||||
*/
|
||||
export function readTicketItems(item: { ticket_json?: string | null; note?: string | null } | null | undefined): TicketItem[] {
|
||||
const raw = item?.ticket_json ?? (item?.note?.startsWith('TICKETJSON:') ? item.note.slice(11) : null)
|
||||
if (!raw) return []
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
return (parsed.items || []).map((line: { name?: string; price?: unknown; parts?: number[] }, i: number) => ({
|
||||
id: `${i}`,
|
||||
name: String(line.name ?? ''),
|
||||
price: String(line.price ?? ''),
|
||||
participants: new Set(line.parts || []),
|
||||
}))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** True when this expense is split line by line rather than equally or by amount. */
|
||||
export function hasTicketSplit(item: { ticket_json?: string | null; note?: string | null } | null | undefined): boolean {
|
||||
return Boolean(item?.ticket_json || item?.note?.startsWith('TICKETJSON:'))
|
||||
}
|
||||
|
||||
/** Serialize the receipt lines for storage in `ticket_json`. */
|
||||
export function writeTicketItems(items: TicketItem[]): string {
|
||||
return JSON.stringify({ items: items.map(i => ({ name: i.name, price: i.price, parts: [...i.participants] })) })
|
||||
}
|
||||
|
||||
/** Long enough for a receipt discrepancy or a reimbursement reminder, short
|
||||
* enough that the row stays a row. */
|
||||
export const NOTE_MAX = 500
|
||||
|
||||
/**
|
||||
* The note a user actually typed, which is never the receipt blob. Only matters
|
||||
* for data written before migration 186 moved the receipt out of the field.
|
||||
*/
|
||||
export function readUserNote(item: { note?: string | null } | null | undefined): string {
|
||||
const note = item?.note
|
||||
return note && !note.startsWith('TICKETJSON:') ? note : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-person totals for a receipt split line by line, plus the receipt total.
|
||||
*
|
||||
* Every cent on the receipt lands on somebody: a line nobody was ticked for is
|
||||
* carried by everyone who appears on the receipt, so the shares add back up to
|
||||
* the total. They used to count toward the total only, which left the expense
|
||||
* with member debits that could never cancel the payer's credit — a permanent
|
||||
* difference the settle-up view showed as debt but had no flow to clear (#1382).
|
||||
* A receipt with no participants at all splits nothing; it is not saveable
|
||||
* anyway, since every line needs someone on it.
|
||||
*/
|
||||
export function calculateTicketShares(items: TicketItem[]): { shares: Record<number, number>; total: number } {
|
||||
const shares: Record<number, number> = {}
|
||||
let totalCents = 0
|
||||
|
||||
const everyone = [...new Set(items.flatMap(i => [...i.participants]))].sort((a, b) => a - b)
|
||||
|
||||
for (const item of items) {
|
||||
const priceNum = Number.parseFloat(item.price) || 0
|
||||
const priceCents = Math.round(priceNum * 100)
|
||||
totalCents += priceCents
|
||||
|
||||
const sortedPartIds = item.participants.size > 0
|
||||
? [...item.participants].sort((a, b) => a - b)
|
||||
: everyone
|
||||
const n = sortedPartIds.length
|
||||
if (n === 0) continue
|
||||
|
||||
const baseCents = Math.floor(priceCents / n)
|
||||
const remainder = priceCents - baseCents * n
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
const id = sortedPartIds[i]
|
||||
const hasExtraCent = i < remainder
|
||||
const shareCents = baseCents + (hasExtraCent ? 1 : 0)
|
||||
shares[id] = (shares[id] || 0) + shareCents
|
||||
}
|
||||
}
|
||||
|
||||
const finalShares: Record<number, number> = {}
|
||||
for (const id of Object.keys(shares)) {
|
||||
finalShares[Number(id)] = shares[Number(id)] / 100
|
||||
}
|
||||
|
||||
return { shares: finalShares, total: totalCents / 100 }
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useMemo, useCallback } from 'react'
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
import { ArrowDown, ArrowUp, BarChart3, Plus, Search, ArrowRight, ArrowLeftRight, Check, RotateCcw, Pencil, Trash2, AlertCircle, Download } from 'lucide-react'
|
||||
import { Fragment, useState, useEffect, useMemo, useCallback } from 'react'
|
||||
import { useSearchParams } from 'react-router'
|
||||
import { ArrowDown, ArrowUp, BarChart3, Plus, Search, ArrowRight, ArrowLeftRight, Check, RotateCcw, Pencil, Trash2, AlertCircle, Download, StickyNote, ChevronDown } from 'lucide-react'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
@@ -10,79 +10,20 @@ import { useTranslation } from '../../i18n'
|
||||
import { budgetApi } from '../../api/client'
|
||||
import { useExchangeRates } from '../../hooks/useExchangeRates'
|
||||
import { useIsMobile } from '../../hooks/useIsMobile'
|
||||
import { formatMoney, currencyDecimals, currencyLocale } from '../../utils/formatters'
|
||||
import { formatMoney, currencyDecimals, currencyLocale, localizeAmountInput, cleanAmount } from '../../utils/formatters'
|
||||
import { downloadBlob } from '../../utils/fileDownload'
|
||||
import Modal from '../shared/Modal'
|
||||
import CustomSelect from '../shared/CustomSelect'
|
||||
import { CustomDatePicker } from '../shared/CustomDateTimePicker'
|
||||
import { localToday } from '../Planner/today'
|
||||
import { SYMBOLS, currenciesWith, SPLIT_COLORS } from './BudgetPanel.constants'
|
||||
import { payersBalanced, rebalancePayers } from './CostsPanel.helpers'
|
||||
import { calculateTicketShares, hasTicketSplit, NOTE_MAX, payersBalanced, readTicketItems, readUserNote, rebalancePayers, splitEqualShares, writeTicketItems, type TicketItem } from './CostsPanel.helpers'
|
||||
import { COST_CATEGORY_LIST, catMeta } from './costsCategories'
|
||||
import type { BudgetItem } from '../../types'
|
||||
import type { TripMember } from './BudgetPanelMemberChips'
|
||||
import GuestBadge from '../shared/GuestBadge'
|
||||
import { NumericInput } from '../shared/NumericInput'
|
||||
|
||||
export function splitEqualShares(total: number, members: { user_id: number }[], itemId: number): Record<number, number> {
|
||||
const n = members.length
|
||||
if (n === 0) return {}
|
||||
|
||||
const totalCents = Math.round(total * 100)
|
||||
const baseCents = Math.floor(totalCents / n)
|
||||
const remainder = totalCents % n
|
||||
|
||||
const shares: Record<number, number> = {}
|
||||
const sortedMembers = [...members].sort((a, b) => a.user_id - b.user_id)
|
||||
const startIndex = itemId % n
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
const member = sortedMembers[i]
|
||||
const hasExtraCent = ((i - startIndex + n) % n) < remainder
|
||||
shares[member.user_id] = (baseCents + (hasExtraCent ? 1 : 0)) / 100
|
||||
}
|
||||
|
||||
return shares
|
||||
}
|
||||
|
||||
export interface TicketItem {
|
||||
id: string
|
||||
name: string
|
||||
price: string
|
||||
participants: Set<number>
|
||||
}
|
||||
|
||||
export function calculateTicketShares(items: TicketItem[]): { shares: Record<number, number>; total: number } {
|
||||
const shares: Record<number, number> = {}
|
||||
let totalCents = 0
|
||||
|
||||
for (const item of items) {
|
||||
const priceNum = parseFloat(item.price) || 0
|
||||
const priceCents = Math.round(priceNum * 100)
|
||||
totalCents += priceCents
|
||||
|
||||
const partIds = [...item.participants]
|
||||
const n = partIds.length
|
||||
if (n === 0) continue
|
||||
|
||||
const baseCents = Math.floor(priceCents / n)
|
||||
const remainder = priceCents % n
|
||||
|
||||
const sortedPartIds = [...partIds].sort((a, b) => a - b)
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
const id = sortedPartIds[i]
|
||||
const hasExtraCent = i < remainder
|
||||
const shareCents = baseCents + (hasExtraCent ? 1 : 0)
|
||||
shares[id] = (shares[id] || 0) + shareCents
|
||||
}
|
||||
}
|
||||
|
||||
const finalShares: Record<number, number> = {}
|
||||
for (const id of Object.keys(shares)) {
|
||||
finalShares[Number(id)] = shares[Number(id)] / 100
|
||||
}
|
||||
|
||||
return { shares: finalShares, total: totalCents / 100 }
|
||||
}
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
|
||||
interface CostsPanelProps {
|
||||
tripId: number
|
||||
@@ -134,12 +75,18 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const { convert } = useExchangeRates(base)
|
||||
const curOf = useCallback((e: BudgetItem) => (e.currency || tripCurrency), [tripCurrency])
|
||||
const [settlement, setSettlement] = useState<SettlementData | null>(null)
|
||||
// A failed settlement read leaves `settlement` null, which the empty views would
|
||||
// otherwise present as "everyone is square", a balance claim we cannot make.
|
||||
const [settlementError, setSettlementError] = useState(false)
|
||||
const [filter, setFilter] = useState<'all' | 'mine' | 'owed'>('all')
|
||||
const [search, setSearch] = useState('')
|
||||
const [catFilter, setCatFilter] = useState('') // '' = all categories
|
||||
const [dayFilter, setDayFilter] = useState('') // '' = all days, else YYYY-MM-DD
|
||||
const [modalOpen, setModalOpen] = useState(false)
|
||||
const [editing, setEditing] = useState<BudgetItem | null>(null)
|
||||
// One note open at a time: two expanded rows next to each other read as a mess,
|
||||
// and the point of the collapse is that the list stays scannable.
|
||||
const [expandedNoteId, setExpandedNoteId] = useState<number | null>(null)
|
||||
const [editingSettlement, setEditingSettlement] = useState<Settlement | null>(null)
|
||||
const [addingPayment, setAddingPayment] = useState(false)
|
||||
|
||||
@@ -156,7 +103,9 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const fmt0 = useCallback((v: number, c = base) => formatMoney(v, c, locale, { decimals: 0 }), [base, locale])
|
||||
|
||||
const loadSettlement = useCallback(() => {
|
||||
budgetApi.settlement(tripId, base).then(setSettlement).catch(() => {})
|
||||
budgetApi.settlement(tripId, base)
|
||||
.then(s => { setSettlement(s); setSettlementError(false) })
|
||||
.catch(() => setSettlementError(true))
|
||||
}, [tripId, base])
|
||||
|
||||
useEffect(() => { loadBudgetItems(tripId); loadSettlement() }, [tripId])
|
||||
@@ -276,8 +225,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
if (!flows.length) return
|
||||
try {
|
||||
for (const f of flows) await budgetApi.createSettlement(tripId, { from_user_id: f.from.user_id, to_user_id: f.to.user_id, amount: f.amount, currency: base })
|
||||
loadSettlement()
|
||||
} catch { toast.error(t('common.unknownError')) }
|
||||
// Refresh even when one transfer failed: the ones created before it are real,
|
||||
// and leaving them in the flow list invites a second, doubled settle-up.
|
||||
finally { loadSettlement() }
|
||||
}
|
||||
|
||||
const dateMeta = useMemo(() => {
|
||||
@@ -298,7 +249,13 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
// Costs rework (#1500). One row per expense, oldest first.
|
||||
const handleExportCsv = () => {
|
||||
const sep = ';'
|
||||
const esc = (v: unknown) => { const s = String(v ?? ''); return s.includes(sep) || s.includes('"') || s.includes('\n') ? '"' + s.replace(/"/g, '""') + '"' : s }
|
||||
// A cell starting with =, +, -, @, TAB or CR is evaluated as a formula by Excel
|
||||
// and Sheets, and the name/note columns are free text any trip member can write.
|
||||
const esc = (v: unknown) => {
|
||||
let s = String(v ?? '')
|
||||
if (/^[=+\-@\t\r]/.test(s)) s = "'" + s
|
||||
return s.includes(sep) || s.includes('"') || s.includes('\n') ? '"' + s.replace(/"/g, '""') + '"' : s
|
||||
}
|
||||
const fmtDate = (iso: string) => { if (!iso) return ''; try { return new Date(iso + 'T00:00:00Z').toLocaleDateString(locale, { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' }) } catch { return iso } }
|
||||
|
||||
const header = ['Date', 'Name', 'Category', 'Amount', 'Currency', 'Amount (' + base + ')', 'Note']
|
||||
@@ -306,8 +263,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const items = budgetItems.slice().sort((a, b) => (a.expense_date || '').localeCompare(b.expense_date || ''))
|
||||
for (const e of items) {
|
||||
const cur = curOf(e)
|
||||
// Ticket notes carry the itemized-receipt JSON, not a human note.
|
||||
const note = e.note && !e.note.startsWith('TICKETJSON:') ? e.note : ''
|
||||
const note = readUserNote(e)
|
||||
rows.push([
|
||||
esc(fmtDate(e.expense_date || '')), esc(e.name), esc(t(catMeta(e.category).labelKey)),
|
||||
(e.total_price || 0).toFixed(currencyDecimals(cur)), cur,
|
||||
@@ -318,13 +274,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
|
||||
const bom = ''
|
||||
const blob = new Blob([bom + rows.join('\r\n')], { type: 'text/csv;charset=utf-8;' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
const safeName = (trip?.title || 'trip').replace(/[^a-zA-Z0-9À-ɏ _-]/g, '').trim()
|
||||
a.download = `costs-${safeName}.csv`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
downloadBlob(blob, `costs-${safeName}.csv`)
|
||||
}
|
||||
|
||||
// ── small presentational helpers ────────────────────────────────────────
|
||||
@@ -373,7 +324,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
|
||||
return (
|
||||
<div className="costs-root" style={{ minHeight: '100%', background: 'var(--c-bg)', padding: isMobile ? '6px 14px 28px' : '40px 24px 48px' }}>
|
||||
{isMobile ? <MobileBody /> : (
|
||||
{isMobile ? MobileBody() : (
|
||||
<div style={{ maxWidth: '100%', margin: '0 auto' }}>
|
||||
{/* ── Header bar ── */}
|
||||
<div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, marginBottom: 28, flexWrap: 'wrap' }}>
|
||||
@@ -397,12 +348,12 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</div>
|
||||
{canEdit && (
|
||||
<div style={{ display: 'flex', gap: 10 }}>
|
||||
<button onClick={settleAll} disabled={!(settlement?.flows || []).length}
|
||||
<button type="button" onClick={settleAll} disabled={!(settlement?.flows || []).length}
|
||||
className="bg-surface-card border border-edge text-content disabled:opacity-40"
|
||||
style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '10px 16px', borderRadius: 12, fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
<Check size={16} /> {t('costs.settleUp')}
|
||||
</button>
|
||||
<button onClick={() => { setEditing(null); setModalOpen(true) }}
|
||||
<button type="button" onClick={() => { setEditing(null); setModalOpen(true) }}
|
||||
className="bg-[var(--text-primary)] text-[var(--bg-primary)]"
|
||||
style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '10px 18px', borderRadius: 12, fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, border: 0, cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
<Plus size={16} /> {t('costs.addExpense')}
|
||||
@@ -450,14 +401,14 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
{filterControls}
|
||||
<div className="bg-surface-secondary" style={{ display: 'flex', borderRadius: 9, padding: 3 }}>
|
||||
{(['all', 'mine', 'owed'] as const).map(f => (
|
||||
<button key={f} onClick={() => setFilter(f)}
|
||||
<button type="button" key={f} onClick={() => setFilter(f)}
|
||||
className={filter === f ? 'bg-surface-card text-content' : 'text-content-muted'}
|
||||
style={{ padding: '6px 11px', fontSize: 'calc(12px * var(--fs-scale-body, 1))', borderRadius: 7, fontWeight: 500, border: 0, cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
{t('costs.filter.' + f)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button onClick={handleExportCsv} title={t('budget.exportCsv')} disabled={!budgetItems.length}
|
||||
<button type="button" onClick={handleExportCsv} title={t('budget.exportCsv')} disabled={!budgetItems.length}
|
||||
className="bg-surface-input border border-edge text-content-muted disabled:opacity-40"
|
||||
style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 34, height: 34, borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0 }}>
|
||||
<Download size={15} />
|
||||
@@ -467,9 +418,13 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
|
||||
{dayBanner}
|
||||
{dayGroups.length === 0 ? (
|
||||
<div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>
|
||||
{search ? t('costs.noMatch') : t('costs.emptyText')}
|
||||
</div>
|
||||
search ? (
|
||||
<div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>
|
||||
{t('costs.noMatch')}
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState scene="costs" title={t('costs.emptyText')} />
|
||||
)
|
||||
) : dayGroups.map(g => {
|
||||
const dtot = g.entries.reduce((a, en) => en.kind === 'expense' ? a + baseTotal(en.e) : a, 0)
|
||||
return (
|
||||
@@ -481,8 +436,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
)}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{g.entries.map(en => en.kind === 'expense'
|
||||
? <ExpenseRow key={'e' + en.e.id} e={en.e} />
|
||||
: <SettlementRow key={'s' + en.s.id} s={en.s} />)}
|
||||
? <Fragment key={'e' + en.e.id}>{ExpenseRow({ e: en.e })}</Fragment>
|
||||
: <Fragment key={'s' + en.s.id}>{SettlementRow({ s: en.s })}</Fragment>)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -496,26 +451,26 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
|
||||
<div className={labelCls}>{t('costs.settleUp')} · <span className="text-content">{(settlement?.flows || []).length}</span></div>
|
||||
{canEdit && (
|
||||
<button onClick={() => setAddingPayment(true)}
|
||||
<button type="button" onClick={() => setAddingPayment(true)}
|
||||
className="text-content-muted bg-surface-secondary border border-edge"
|
||||
style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '5px 9px', borderRadius: 8, fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
<Plus size={13} /> {t('costs.addPayment')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<SettleFlows />
|
||||
{SettleFlows()}
|
||||
</div>
|
||||
|
||||
{/* balances */}
|
||||
<div className={cardCls} style={{ borderRadius: 22, padding: '22px 24px' }}>
|
||||
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.balances')}</div>
|
||||
<BalancesList balances={settlement?.balances || []} />
|
||||
{BalancesList({ balances: settlement?.balances || [] })}
|
||||
</div>
|
||||
|
||||
{/* by category */}
|
||||
<div className={cardCls} style={{ borderRadius: 22, padding: '22px 24px' }}>
|
||||
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.byCategory')}</div>
|
||||
<CategoryBreakdown />
|
||||
{CategoryBreakdown()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -563,6 +518,11 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
.costs-root .text-content-muted { color: var(--c-ink2) !important; }
|
||||
.costs-root .text-content-faint { color: var(--c-ink3) !important; }
|
||||
.costs-root .exp-actions { opacity: 1; }
|
||||
.costs-root .exp-actions button { background: none; }
|
||||
.costs-root .exp-actions button:hover { background: var(--bg-secondary); color: var(--c-ink); }
|
||||
/* Destructive actions keep their own tint: the neutral one would read as
|
||||
"safe" on the button that deletes the expense. */
|
||||
.costs-root .exp-actions .exp-action-danger:hover { background: rgba(220,38,38,0.14); color: #dc2626; }
|
||||
@media (max-width: 1100px) {
|
||||
.costs-root .costs-summary { grid-template-columns: 1fr 1fr !important; }
|
||||
.costs-root .costs-grid { grid-template-columns: 1fr !important; }
|
||||
@@ -574,8 +534,15 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</div>
|
||||
)
|
||||
|
||||
// Settle-up and Balances both come from the one settlement request, so they
|
||||
// share the notice that says the numbers are missing rather than zero.
|
||||
function loadFailed() {
|
||||
return <div className="text-content-muted" style={{ textAlign: 'center', padding: '14px 8px', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))' }}>{t('common.unknownError')}</div>
|
||||
}
|
||||
|
||||
// ── shared settle-flow list ──────────────────────────────────────────────
|
||||
function SettleFlows() {
|
||||
if (settlementError) return loadFailed()
|
||||
const flows = settlement?.flows || []
|
||||
if (flows.length === 0) return (
|
||||
<div style={{ textAlign: 'center', padding: '14px 8px' }}>
|
||||
@@ -593,7 +560,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
|
||||
<span className="text-content" style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 700 }}>{fmt(f.amount)}</span>
|
||||
{canEdit && <button onClick={() => settleFlow(f.from.user_id, f.to.user_id, f.amount)} className="bg-[var(--text-primary)] text-[var(--bg-primary)]" style={{ padding: '7px 12px', borderRadius: 9, fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, border: 0, cursor: 'pointer', fontFamily: 'inherit' }}>{t('costs.settle')}</button>}
|
||||
{canEdit && <button type="button" onClick={() => settleFlow(f.from.user_id, f.to.user_id, f.amount)} className="bg-[var(--text-primary)] text-[var(--bg-primary)]" style={{ padding: '7px 12px', borderRadius: 9, fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, border: 0, cursor: 'pointer', fontFamily: 'inherit' }}>{t('costs.settle')}</button>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
@@ -602,6 +569,14 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
}
|
||||
|
||||
// ── mobile layout (Budget1Mobile.html): single flat column, total card on top ──
|
||||
//
|
||||
// Called as a plain function — `{MobileBody()}`, not `<MobileBody />` — and the
|
||||
// same goes for ExpenseRow, SettleFlows, BalancesList and CategoryBreakdown.
|
||||
// A component declared inside this one is a fresh component type on every
|
||||
// render, so React tears the old subtree down and mounts a new one instead of
|
||||
// updating it; the search box then loses focus after every keystroke. Calling
|
||||
// them keeps the markup inline where it always was. Do not "tidy" these back
|
||||
// into elements.
|
||||
function MobileBody() {
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, paddingTop: 8 }}>
|
||||
@@ -614,7 +589,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
<span>{t('costs.youPaid')} · <b style={{ color: '#fff', fontWeight: 600 }}>{fmt0(totals.myPaid)}</b></span>
|
||||
</div>
|
||||
{canEdit && (
|
||||
<button onClick={() => { setEditing(null); setModalOpen(true) }} style={{ marginTop: 16, width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, background: 'rgba(255,255,255,0.14)', border: '1px solid rgba(255,255,255,0.16)', color: '#fff', padding: 13, borderRadius: 14, fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
<button type="button" onClick={() => { setEditing(null); setModalOpen(true) }} style={{ marginTop: 16, width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, background: 'rgba(255,255,255,0.14)', border: '1px solid rgba(255,255,255,0.16)', color: '#fff', padding: 13, borderRadius: 14, fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
<Plus size={17} /> {t('costs.addExpense')}
|
||||
</button>
|
||||
)}
|
||||
@@ -653,17 +628,17 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14, gap: 8 }}>
|
||||
<div className="text-content" style={{ fontSize: 'calc(19px * var(--fs-scale-subtitle, 1))', fontWeight: 700, letterSpacing: '-0.02em', display: 'flex', alignItems: 'baseline', gap: 8 }}>{t('costs.settleUp')} <span className="text-content-faint" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 500 }}>{(settlement?.flows || []).length}</span></div>
|
||||
{canEdit && (
|
||||
<button onClick={() => setAddingPayment(true)} className="text-content-muted bg-surface-card border border-edge" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '6px 10px', borderRadius: 9, fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}><Plus size={13} /> {t('costs.addPayment')}</button>
|
||||
<button type="button" onClick={() => setAddingPayment(true)} className="text-content-muted bg-surface-card border border-edge" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '6px 10px', borderRadius: 9, fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}><Plus size={13} /> {t('costs.addPayment')}</button>
|
||||
)}
|
||||
</div>
|
||||
<SettleFlows />
|
||||
{SettleFlows()}
|
||||
</div>
|
||||
|
||||
{/* Expenses */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
|
||||
<div className="text-content" style={{ fontSize: 'calc(19px * var(--fs-scale-subtitle, 1))', fontWeight: 700, letterSpacing: '-0.02em' }}>{t('costs.expenses')}</div>
|
||||
<button onClick={handleExportCsv} title={t('budget.exportCsv')} disabled={!budgetItems.length}
|
||||
<button type="button" onClick={handleExportCsv} title={t('budget.exportCsv')} disabled={!budgetItems.length}
|
||||
className="bg-surface-card border border-edge text-content-muted disabled:opacity-40"
|
||||
style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 34, height: 34, borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0 }}>
|
||||
<Download size={15} />
|
||||
@@ -675,7 +650,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</div>
|
||||
<div className="bg-surface-secondary" style={{ display: 'flex', borderRadius: 11, padding: 3, gap: 2 }}>
|
||||
{(['all', 'mine', 'owed'] as const).map(f => (
|
||||
<button key={f} onClick={() => setFilter(f)} className={filter === f ? 'bg-surface-card text-content' : 'text-content-muted'} style={{ flex: 1, padding: '8px 6px', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 500, borderRadius: 8, border: 0, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}>{t('costs.filter.' + f)}</button>
|
||||
<button type="button" key={f} onClick={() => setFilter(f)} className={filter === f ? 'bg-surface-card text-content' : 'text-content-muted'} style={{ flex: 1, padding: '8px 6px', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 500, borderRadius: 8, border: 0, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}>{t('costs.filter.' + f)}</button>
|
||||
))}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
@@ -691,8 +666,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
<div key={g.day} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{!dayFilter && <div className={labelCls} style={{ display: 'flex', alignItems: 'center', padding: '0 2px' }}>{g.day}<span className="text-content-muted" style={{ marginLeft: 'auto', textTransform: 'none', letterSpacing: 0, fontWeight: 500, fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))' }}>{t('costs.spent', { amount: fmt(dtot) })}</span></div>}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{g.entries.map(en => en.kind === 'expense'
|
||||
? <ExpenseRow key={'e' + en.e.id} e={en.e} />
|
||||
: <SettlementRow key={'s' + en.s.id} s={en.s} />)}</div>
|
||||
? <Fragment key={'e' + en.e.id}>{ExpenseRow({ e: en.e })}</Fragment>
|
||||
: <Fragment key={'s' + en.s.id}>{SettlementRow({ s: en.s })}</Fragment>)}</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
@@ -701,19 +676,43 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
{/* Balances */}
|
||||
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
|
||||
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.balances')}</div>
|
||||
<BalancesList balances={settlement?.balances || []} />
|
||||
{BalancesList({ balances: settlement?.balances || [] })}
|
||||
</div>
|
||||
|
||||
{/* By category */}
|
||||
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
|
||||
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.byCategory')}</div>
|
||||
<CategoryBreakdown />
|
||||
{CategoryBreakdown()}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── inline subcomponents (close over helpers) ────────────────────────────
|
||||
/**
|
||||
* Edit and delete, in a capsule beside the row rather than inside it — the
|
||||
* mobile card has always done it this way, and out here the buttons stop
|
||||
* competing with the amount for the right edge of the card.
|
||||
*/
|
||||
function RowActions({ onEdit, onDelete, deleteLabel }: { onEdit: () => void; onDelete: () => void; deleteLabel: string }) {
|
||||
// No `background` here on purpose: an inline value would beat the :hover
|
||||
// rule in the stylesheet block below, which is how the first attempt at
|
||||
// this silently did nothing.
|
||||
const btn: React.CSSProperties = {
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: 30, height: 30, borderRadius: 999, border: 0,
|
||||
cursor: 'pointer', padding: 0,
|
||||
}
|
||||
return (
|
||||
<div className="exp-actions bg-surface-card border border-edge" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 3, flexShrink: 0, borderRadius: 999, padding: 5 }}>
|
||||
<button type="button" title={t('common.edit')} onClick={onEdit} className="text-content-muted transition-colors" style={btn}><Pencil size={13} /></button>
|
||||
<button type="button" title={deleteLabel} onClick={onDelete} className="exp-action-danger transition-colors" style={{ ...btn, color: '#dc2626' }}><Trash2 size={13} /></button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Called, not rendered — see MobileBody: an element here would remount the
|
||||
// list on every keystroke in the search box.
|
||||
function ExpenseRow({ e }: { e: BudgetItem }) {
|
||||
const c = catMeta(e.category)
|
||||
const Icon = c.Icon
|
||||
@@ -721,17 +720,38 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const payers = (e.payers || []).filter(p => p.amount > 0)
|
||||
const net = round2(myPaidOf(e) - myShareOf(e))
|
||||
const unfinished = isUnfinished(e)
|
||||
const note = readUserNote(e)
|
||||
const open = expandedNoteId === e.id
|
||||
|
||||
// Fixed columns, identical on every row, so the eye can run down the list
|
||||
// instead of re-finding each field on each line. A row without a note leaves
|
||||
// its column empty rather than letting everything after it drift left, which
|
||||
// is what made the list read as unstructured.
|
||||
const cols = isMobile ? '46px 1fr auto' : '46px minmax(200px, 1fr) minmax(0, 1.5fr) auto'
|
||||
|
||||
return (
|
||||
<div className="bg-surface-card border border-edge exp-row" style={{ display: 'grid', gridTemplateColumns: '46px 1fr auto', gap: 16, alignItems: 'center', borderRadius: 18, padding: '16px 20px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'stretch', gap: 8 }}>
|
||||
<div className="bg-surface-card border border-edge exp-row" style={{ position: 'relative', flex: 1, minWidth: 0, display: 'grid', gridTemplateColumns: cols, gap: 18, alignItems: 'center', borderRadius: 18, padding: isMobile ? '16px 20px' : '20px 20px 16px' }}>
|
||||
{/* The category rides the card edge as a tab, the way the mobile card
|
||||
does, so it stops taking up a slot inside the row itself. */}
|
||||
{!isMobile && (
|
||||
<span aria-hidden="true" style={{ position: 'absolute', left: -1, top: -1, display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 11px 4px 10px', borderRadius: '17px 0 12px 0', background: c.color, color: '#fff', fontSize: 'calc(9.5px * var(--fs-scale-caption, 1))', fontWeight: 800, letterSpacing: '0.05em', textTransform: 'uppercase', lineHeight: 1.2 }}>
|
||||
<Icon size={10} strokeWidth={2.4} />
|
||||
{t(c.labelKey)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
<span style={{ position: 'relative', width: 46, height: 46, borderRadius: 13, display: 'grid', placeItems: 'center', background: c.color + '22', color: c.color }}>
|
||||
<Icon size={21} />
|
||||
{isMobile && unfinished && (
|
||||
<span title={t('costs.unfinishedHint')} style={{ position: 'absolute', bottom: -4, right: -4, width: 20, height: 20, borderRadius: '50%', background: '#d97706', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 800, lineHeight: 1, border: '2px solid var(--bg-card)' }}>!</span>
|
||||
)}
|
||||
</span>
|
||||
|
||||
{/* What it was. */}
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 6 }}>
|
||||
<span className="text-content" style={{ fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 600 }}>{e.name}</span>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 7, minWidth: 0 }}>
|
||||
<span className="text-content" style={{ fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.name}</span>
|
||||
{unfinished && !isMobile && (
|
||||
<span title={t('costs.unfinishedHint')} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 8px 2px 6px', borderRadius: 999, background: 'rgba(217,119,6,0.14)', color: '#d97706', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700, flexShrink: 0 }}>
|
||||
<span style={{ width: 14, height: 14, borderRadius: '50%', background: '#d97706', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 800 }}>!</span>
|
||||
@@ -739,8 +759,15 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{cur !== base && (
|
||||
<div className="text-content-faint" style={{ marginTop: 4, fontSize: 'calc(12px * var(--fs-scale-body, 1))', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{fmt(e.total_price, cur)} {'→'} {fmt(baseTotal(e))}
|
||||
</div>
|
||||
)}
|
||||
{/* Under the name, because a chip reading "Y 122,00" says nothing on
|
||||
its own — the name above it is what gives it a meaning. */}
|
||||
{payers.length > 0 && (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginBottom: 5 }}>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 6 }}>
|
||||
{payers.map(p => (
|
||||
<span key={p.user_id} className="bg-surface-secondary border border-edge" title={personName(p.user_id)} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 10px 3px 3px', borderRadius: 999, fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))' }}>
|
||||
<Avatar id={p.user_id} size={18} />
|
||||
@@ -749,29 +776,38 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{!isMobile && (
|
||||
<div className="text-content-faint" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{t(c.labelKey)}{cur !== base ? ` · ${fmt(e.total_price, cur)} → ${fmt(baseTotal(e))}` : ''}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* The note, marked by a rule in the category colour instead of a box, so
|
||||
it reads as part of the row rather than something dropped onto it. */}
|
||||
{!isMobile && (
|
||||
note ? (
|
||||
<button type="button" onClick={() => setExpandedNoteId(open ? null : e.id)}
|
||||
aria-expanded={open} title={open ? t('costs.hideNote') : t('costs.showNote')}
|
||||
className="bg-surface-secondary border border-edge text-content-muted hover:text-content hover:border-content-faint transition-colors exp-note-btn"
|
||||
style={{ display: 'flex', alignItems: open ? 'flex-start' : 'center', gap: 9, minWidth: 0, width: '100%', padding: open ? '10px 14px 11px 13px' : '7px 12px 7px 11px', borderRadius: open ? 14 : 999, borderLeft: '3px solid ' + c.color, cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', lineHeight: 1.5, textAlign: 'left' }}>
|
||||
<span style={open
|
||||
? { whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', minWidth: 0, flex: 1 }
|
||||
: { whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', minWidth: 0, flex: 1 }}>{note}</span>
|
||||
<ChevronDown size={13} style={{ flexShrink: 0, marginTop: open ? 3 : 0, transition: 'transform .18s ease', transform: open ? 'rotate(180deg)' : 'none' }} />
|
||||
</button>
|
||||
) : <span />
|
||||
)}
|
||||
|
||||
{/* The money, and what to do with it. */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, alignSelf: 'center' }}>
|
||||
<div style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
|
||||
<div className="text-content" style={{ fontSize: 'calc(18px * var(--fs-scale-subtitle, 1))', fontWeight: 600 }}>{fmt(baseTotal(e))}</div>
|
||||
{!isUnfinished && (e.members || []).length > 0 && Math.abs(net) > 0.01 && (
|
||||
<div style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', marginTop: 2, fontWeight: 500, whiteSpace: 'nowrap', color: net > 0 ? '#16a34a' : '#dc2626' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4, whiteSpace: 'nowrap' }}>
|
||||
<span className="bg-surface-secondary border border-edge text-content" style={{ display: 'inline-flex', alignItems: 'center', padding: isMobile ? '0' : '6px 13px', borderRadius: 999, border: isMobile ? 0 : undefined, background: isMobile ? 'none' : undefined, fontSize: isMobile ? 'calc(18px * var(--fs-scale-subtitle, 1))' : 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{fmt(baseTotal(e))}</span>
|
||||
{!unfinished && (e.members || []).length > 0 && Math.abs(net) > 0.01 && (
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', padding: isMobile ? 0 : '2px 9px', borderRadius: 999, background: isMobile ? 'none' : (net > 0 ? 'rgba(22,163,74,0.13)' : 'rgba(220,38,38,0.13)'), fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 600, color: net > 0 ? '#16a34a' : '#dc2626' }}>
|
||||
{net > 0 ? t('costs.youLent', { amount: fmt(net) }) : t('costs.youBorrowed', { amount: fmt(-net) })}
|
||||
</div>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{canEdit && (
|
||||
<div className="exp-actions" style={{ display: 'flex', flexDirection: 'column', gap: 6, flexShrink: 0 }}>
|
||||
<button title={t('common.edit')} onClick={() => { setEditing(e); setModalOpen(true) }} className="bg-surface-secondary border border-edge text-content-muted" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 28, height: 28, borderRadius: 999, cursor: 'pointer' }}><Pencil size={13} /></button>
|
||||
<button title={t('common.delete')} onClick={() => handleDelete(e.id)} className="bg-surface-secondary border border-edge" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 28, height: 28, borderRadius: 999, cursor: 'pointer', color: '#dc2626' }}><Trash2 size={13} /></button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{canEdit && RowActions({ onEdit: () => { setEditing(e); setModalOpen(true) }, onDelete: () => handleDelete(e.id), deleteLabel: t('common.delete') })}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -781,7 +817,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
// Legacy transfers carry no currency and were entered in the display base.
|
||||
const cur = (s.currency || base).toUpperCase()
|
||||
return (
|
||||
<div className="bg-surface-card border border-edge exp-row" style={{ display: 'grid', gridTemplateColumns: '46px 1fr auto', gap: 16, alignItems: 'center', borderRadius: 18, padding: '16px 20px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'stretch', gap: 8 }}>
|
||||
<div className="bg-surface-card border border-edge exp-row" style={{ flex: 1, minWidth: 0, display: 'grid', gridTemplateColumns: isMobile ? '46px 1fr auto' : '46px minmax(200px, 1fr) minmax(0, 1.5fr) auto', gap: isMobile ? 16 : 18, alignItems: 'center', borderRadius: 18, padding: '16px 20px' }}>
|
||||
<span style={{ width: 46, height: 46, borderRadius: 13, display: 'grid', placeItems: 'center', background: 'rgba(22,163,74,0.12)', color: '#16a34a' }}><ArrowLeftRight size={21} /></span>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<div className="text-content" style={{ fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 600, marginBottom: 6 }}>
|
||||
@@ -793,20 +830,25 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
<span className="text-content-faint" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{personName(s.from_user_id)} → {personName(s.to_user_id)}</span>
|
||||
</div>
|
||||
</div>
|
||||
{/* A payment carries no note, but it keeps the column so its amount lands
|
||||
on the same axis as every expense above it. */}
|
||||
{!isMobile && <span />}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, alignSelf: 'center' }}>
|
||||
<div className="text-content" style={{ fontSize: 'calc(18px * var(--fs-scale-subtitle, 1))', fontWeight: 600, whiteSpace: 'nowrap' }}>{fmt(convert(s.amount, cur))}</div>
|
||||
{canEdit && (
|
||||
<div className="exp-actions" style={{ display: 'flex', flexDirection: 'column', gap: 6, flexShrink: 0 }}>
|
||||
<button title={t('common.edit')} onClick={() => setEditingSettlement(s)} className="bg-surface-secondary border border-edge text-content-muted" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 28, height: 28, borderRadius: 999, cursor: 'pointer' }}><Pencil size={13} /></button>
|
||||
<button title={t('costs.undo')} onClick={() => undoSettlement(s.id)} className="bg-surface-secondary border border-edge" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 28, height: 28, borderRadius: 999, cursor: 'pointer', color: '#dc2626' }}><RotateCcw size={13} /></button>
|
||||
</div>
|
||||
)}
|
||||
<span className="bg-surface-secondary border border-edge text-content" style={{ display: 'inline-flex', alignItems: 'center', padding: '6px 13px', borderRadius: 999, fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 700, whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' }}>{fmt(convert(s.amount, cur))}</span>
|
||||
</div>
|
||||
</div>
|
||||
{canEdit && (
|
||||
<div className="exp-actions bg-surface-card border border-edge" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 3, flexShrink: 0, borderRadius: 999, padding: 5 }}>
|
||||
<button type="button" title={t('common.edit')} onClick={() => setEditingSettlement(s)} className="text-content-muted transition-colors" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 30, height: 30, borderRadius: 999, border: 0, cursor: 'pointer', padding: 0 }}><Pencil size={13} /></button>
|
||||
<button type="button" title={t('costs.undo')} onClick={() => undoSettlement(s.id)} className="exp-action-danger transition-colors" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 30, height: 30, borderRadius: 999, border: 0, cursor: 'pointer', padding: 0, color: '#dc2626' }}><RotateCcw size={13} /></button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function BalancesList({ balances }: { balances: SettlementData['balances'] }) {
|
||||
if (settlementError) return loadFailed()
|
||||
const rows = people.map(p => balances.find(b => b.user_id === p.id) || { user_id: p.id, username: p.username, avatar_url: null, balance: 0 })
|
||||
const max = Math.max(1, ...rows.map(r => Math.abs(r.balance)))
|
||||
return (
|
||||
@@ -928,7 +970,7 @@ function SettlementModal({ tripId, people, me, editing, currency, onClose, onSav
|
||||
const [cur, setCur] = useState<string>((editing?.currency || currency).toUpperCase())
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
const amt = parseFloat(amount) || 0
|
||||
const amt = Number.parseFloat(amount) || 0
|
||||
const valid = amt > 0 && fromId !== toId
|
||||
const opts = people.map(p => ({ value: String(p.id), label: p.id === me ? t('costs.you') : p.username }))
|
||||
|
||||
@@ -949,8 +991,8 @@ function SettlementModal({ tripId, people, me, editing, currency, onClose, onSav
|
||||
<Modal isOpen onClose={onClose} title={editing ? t('costs.editPayment') : t('costs.addPayment')} size="md"
|
||||
footer={
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
|
||||
<button onClick={onClose} className="text-content-muted border border-edge" style={{ padding: '8px 16px', borderRadius: 10, background: 'none', fontSize: 'calc(13px * var(--fs-scale-body, 1))', cursor: 'pointer', fontFamily: 'inherit' }}>{t('common.cancel')}</button>
|
||||
<button onClick={save} disabled={!valid || saving} className="bg-[var(--text-primary)] text-[var(--bg-primary)]" style={{ padding: '8px 20px', borderRadius: 10, border: 0, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', opacity: !valid || saving ? 0.5 : 1 }}>{editing ? t('common.save') : t('costs.addPayment')}</button>
|
||||
<button type="button" onClick={onClose} className="text-content-muted border border-edge" style={{ padding: '8px 16px', borderRadius: 10, background: 'none', fontSize: 'calc(13px * var(--fs-scale-body, 1))', cursor: 'pointer', fontFamily: 'inherit' }}>{t('common.cancel')}</button>
|
||||
<button type="button" onClick={save} disabled={!valid || saving} className="bg-[var(--text-primary)] text-[var(--bg-primary)]" style={{ padding: '8px 20px', borderRadius: 10, border: 0, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', opacity: !valid || saving ? 0.5 : 1 }}>{editing ? t('common.save') : t('costs.addPayment')}</button>
|
||||
</div>
|
||||
}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
|
||||
@@ -990,6 +1032,8 @@ export interface ExpensePrefill {
|
||||
category?: string
|
||||
amount?: number
|
||||
reservationId?: number
|
||||
/** Set when the expense is being created from a place (#1298). */
|
||||
placeId?: number
|
||||
}
|
||||
|
||||
export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClose, onSaved }: {
|
||||
@@ -997,6 +1041,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
}) {
|
||||
const { t, locale } = useTranslation()
|
||||
const toast = useToast()
|
||||
const isMobile = useIsMobile()
|
||||
const { addBudgetItem, updateBudgetItem } = useTripStore()
|
||||
const { convert } = useExchangeRates(base)
|
||||
const sym = (c: string) => SYMBOLS[c] || (c + ' ')
|
||||
@@ -1004,9 +1049,10 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
const [name, setName] = useState(editing?.name || prefill?.name || '')
|
||||
const [cat, setCat] = useState<string>(editing ? catMeta(editing.category).key : (prefill?.category || 'food'))
|
||||
const [currency, setCurrency] = useState((editing?.currency || base).toUpperCase())
|
||||
const [day, setDay] = useState(editing?.expense_date || new Date().toISOString().slice(0, 10))
|
||||
const [day, setDay] = useState(editing?.expense_date || localToday())
|
||||
const [note, setNote] = useState(() => readUserNote(editing))
|
||||
const [total, setTotal] = useState<string>(() => {
|
||||
if (editing) return editing.total_price ? String(editing.total_price) : ''
|
||||
if (editing) return editing.total_price ? String(cleanAmount(editing.total_price)) : ''
|
||||
if (prefill?.amount != null) return String(prefill.amount)
|
||||
return ''
|
||||
})
|
||||
@@ -1038,7 +1084,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
const [pinnedPayers, setPinnedPayers] = useState<Set<number>>(() => new Set(initialPayers.map(p => p.user_id)))
|
||||
|
||||
const [splitMode, setSplitMode] = useState<'equally' | 'custom' | 'ticket'>(() => {
|
||||
if (editing?.note && editing.note.startsWith('TICKETJSON:')) {
|
||||
if (hasTicketSplit(editing)) {
|
||||
return 'ticket'
|
||||
}
|
||||
if (editing && editing.members && editing.members.length > 0) {
|
||||
@@ -1048,22 +1094,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
return 'equally'
|
||||
})
|
||||
|
||||
const [ticketItems, setTicketItems] = useState<TicketItem[]>(() => {
|
||||
if (editing?.note && editing.note.startsWith('TICKETJSON:')) {
|
||||
try {
|
||||
const parsed = JSON.parse(editing.note.slice(11))
|
||||
return (parsed.items || []).map((item: any) => ({
|
||||
id: String(Math.random()),
|
||||
name: item.name,
|
||||
price: String(item.price),
|
||||
participants: new Set(item.parts || [])
|
||||
}))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
return []
|
||||
})
|
||||
const [ticketItems, setTicketItems] = useState<TicketItem[]>(() => readTicketItems(editing))
|
||||
|
||||
const [customAmounts, setCustomAmounts] = useState<Record<number, string>>(() => {
|
||||
const m: Record<number, string> = {}
|
||||
@@ -1085,8 +1116,8 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
return calculateTicketShares(ticketItems)
|
||||
}, [ticketItems])
|
||||
|
||||
const totalNum = isTicketMode ? ticketInfo.total : (parseFloat(total) || 0)
|
||||
const splitSum = [...participants].reduce((sum, id) => sum + (parseFloat(customAmounts[id]) || 0), 0)
|
||||
const totalNum = isTicketMode ? ticketInfo.total : (Number.parseFloat(total) || 0)
|
||||
const splitSum = [...participants].reduce((sum, id) => sum + (Number.parseFloat(customAmounts[id]) || 0), 0)
|
||||
const customBalanced = Math.round(splitSum * 100) === Math.round(totalNum * 100)
|
||||
const each = participants.size > 0 ? totalNum / participants.size : 0
|
||||
const equalShares = useMemo(() => {
|
||||
@@ -1099,13 +1130,13 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
|
||||
const enteredSum = [...participants]
|
||||
.filter(id => customAmounts[id])
|
||||
.reduce((sum, id) => sum + (parseFloat(customAmounts[id]) || 0), 0)
|
||||
.reduce((sum, id) => sum + (Number.parseFloat(customAmounts[id]) || 0), 0)
|
||||
const remaining = Math.max(0, totalNum - enteredSum)
|
||||
|
||||
return splitEqualShares(remaining, emptyParts.map(id => ({ user_id: id })), editing?.id || 0)
|
||||
}, [totalNum, participants, customAmounts, editing])
|
||||
|
||||
const ticketValid = ticketItems.length > 0 && ticketItems.every(item => item.name.trim().length > 0 && (parseFloat(item.price) || 0) > 0 && item.participants.size > 0)
|
||||
const ticketValid = ticketItems.length > 0 && ticketItems.every(item => item.name.trim().length > 0 && (Number.parseFloat(item.price) || 0) > 0 && item.participants.size > 0)
|
||||
const payersOk = !multiPayer || (payerIds.size > 0 && payersBalanced(payerAmounts, payerIds, totalNum))
|
||||
const valid = name.trim().length > 0 && payersOk && (
|
||||
isTicketMode
|
||||
@@ -1227,15 +1258,24 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
const save = async () => {
|
||||
if (!valid) return
|
||||
setSaving(true)
|
||||
// A picked payer always goes out, even when nobody shares the expense: the
|
||||
// server re-derives total_price from the payer sum (CostsPanel.helpers), so
|
||||
// dropping the payer would store the entry with a total of 0.
|
||||
const payerList = multiPayer
|
||||
? [...payerIds]
|
||||
.map(id => ({ user_id: id, amount: parseFloat(payerAmounts[id]) || 0 }))
|
||||
.map(id => ({ user_id: id, amount: Number.parseFloat(payerAmounts[id]) || 0 }))
|
||||
.filter(p => p.amount > 0)
|
||||
: (payerId > 0 && participants.size > 0) ? [{ user_id: payerId, amount: totalNum }] : []
|
||||
const memberList = [...participants].map(id => ({
|
||||
: payerId > 0 ? [{ user_id: payerId, amount: totalNum }] : []
|
||||
// A receipt line can name somebody who is not ticked as a participant. Sending
|
||||
// only the ticked set would drop their share, leaving the member sum short of
|
||||
// total_price and handing the settlement a difference it can never clear (#1382).
|
||||
const memberIds = splitMode === 'ticket'
|
||||
? [...new Set([...participants, ...Object.keys(ticketInfo.shares).map(Number)])].sort((a, b) => a - b)
|
||||
: [...participants]
|
||||
const memberList = memberIds.map(id => ({
|
||||
user_id: id,
|
||||
amount: splitMode === 'custom'
|
||||
? (parseFloat(customAmounts[id]) || 0)
|
||||
? (Number.parseFloat(customAmounts[id]) || 0)
|
||||
: splitMode === 'ticket'
|
||||
? (ticketInfo.shares[id] || 0)
|
||||
: null
|
||||
@@ -1246,17 +1286,13 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
currency,
|
||||
payers: payerList,
|
||||
members: memberList,
|
||||
member_ids: [...participants],
|
||||
member_ids: memberIds,
|
||||
expense_date: day || null,
|
||||
total_price: totalNum,
|
||||
note: splitMode === 'ticket' ? 'TICKETJSON:' + JSON.stringify({
|
||||
items: ticketItems.map(item => ({
|
||||
name: item.name,
|
||||
price: item.price,
|
||||
parts: [...item.participants]
|
||||
}))
|
||||
}) : null,
|
||||
note: note.trim() || null,
|
||||
ticket_json: splitMode === 'ticket' ? writeTicketItems(ticketItems) : null,
|
||||
...(!editing && prefill?.reservationId ? { reservation_id: prefill.reservationId } : {}),
|
||||
...(!editing && prefill?.placeId ? { place_id: prefill.placeId } : {}),
|
||||
}
|
||||
try {
|
||||
if (editing) await updateBudgetItem(tripId, editing.id, data)
|
||||
@@ -1270,17 +1306,25 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
}
|
||||
|
||||
const inputCls = 'w-full bg-surface-input border border-edge text-content'
|
||||
const labelCls = 'block text-[11px] font-semibold uppercase tracking-[0.08em] text-content-faint mb-[6px]'
|
||||
const labelCls = 'block text-caption font-semibold uppercase tracking-[0.14em] text-content-faint mb-2'
|
||||
// Borrowed from the trip dialog (TripFormModal): related fields sit together in
|
||||
// a panel instead of running as one undifferentiated column of inputs.
|
||||
const panelCls = 'rounded-2xl border border-edge bg-surface-secondary p-4'
|
||||
|
||||
return (
|
||||
<Modal isOpen onClose={onClose} title={editing ? t('costs.editExpense') : t('costs.addExpense')} size="2xl"
|
||||
<Modal isOpen onClose={onClose} title={editing ? t('costs.editExpense') : t('costs.addExpense')} size={isMobile ? '2xl' : '5xl'}
|
||||
footer={
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
|
||||
<button onClick={onClose} className="text-content-muted border border-edge" style={{ padding: '8px 16px', borderRadius: 10, background: 'none', fontSize: 'calc(13px * var(--fs-scale-body, 1))', cursor: 'pointer', fontFamily: 'inherit' }}>{t('common.cancel')}</button>
|
||||
<button onClick={save} disabled={!valid || saving} className="bg-[var(--text-primary)] text-[var(--bg-primary)]" style={{ padding: '8px 20px', borderRadius: 10, border: 0, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', opacity: !valid || saving ? 0.5 : 1 }}>{editing ? t('common.save') : t('costs.addExpense')}</button>
|
||||
<button type="button" onClick={onClose} className="text-content-muted border border-edge" style={{ padding: '8px 16px', borderRadius: 10, background: 'none', fontSize: 'calc(13px * var(--fs-scale-body, 1))', cursor: 'pointer', fontFamily: 'inherit' }}>{t('common.cancel')}</button>
|
||||
<button type="button" onClick={save} disabled={!valid || saving} className="bg-[var(--text-primary)] text-[var(--bg-primary)]" style={{ padding: '8px 20px', borderRadius: 10, border: 0, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', opacity: !valid || saving ? 0.5 : 1 }}>{editing ? t('common.save') : t('costs.addExpense')}</button>
|
||||
</div>
|
||||
}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
|
||||
{/* Two columns on desktop: what the expense was on the left, how it is
|
||||
shared on the right. The split follows the two questions the dialog
|
||||
actually asks, so neither side is a leftovers pile. */}
|
||||
<div style={{ display: isMobile ? 'flex' : 'grid', flexDirection: 'column', gridTemplateColumns: '1fr 1fr', alignItems: 'start', gap: isMobile ? 14 : 28 }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 14, minWidth: 0 }}>
|
||||
<div className={panelCls} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
|
||||
<div>
|
||||
<label className={labelCls}>{t('costs.whatFor')}</label>
|
||||
<input value={name} onChange={e => setName(e.target.value)} placeholder={t('costs.namePlaceholder')} className={inputCls} style={{ borderRadius: 10, padding: '11px 13px', fontSize: 'calc(14px * var(--fs-scale-body, 1))', outline: 'none' }} />
|
||||
@@ -1290,7 +1334,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
<label className={labelCls}>{t('costs.totalAmount')}</label>
|
||||
<div className="bg-surface-input border border-edge" style={{ height: FIELD_H, boxSizing: 'border-box', display: 'flex', alignItems: 'center', borderRadius: 10, padding: '0 12px', opacity: isTicketMode ? 0.6 : 1 }}>
|
||||
<span className="text-content-faint" style={{ fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))' }}>{sym(currency)}</span>
|
||||
<NumericInput mode="decimal" placeholder="0.00" value={isTicketMode ? ticketInfo.total.toFixed(2) : total}
|
||||
<NumericInput mode="decimal" placeholder={localizeAmountInput('0.00', currency)} value={localizeAmountInput(isTicketMode ? ticketInfo.total.toFixed(2) : total, currency)}
|
||||
onValueChange={onTotalChange}
|
||||
disabled={isTicketMode}
|
||||
className="text-content" style={{ flex: 1, border: 0, background: 'none', outline: 'none', fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 600, paddingLeft: 6, width: '100%' }} />
|
||||
@@ -1318,13 +1362,15 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
</div>
|
||||
|
||||
<div className={panelCls}>
|
||||
<label className={labelCls}>{t('costs.category')}</label>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
|
||||
{COST_CATEGORY_LIST.map(c => {
|
||||
const Icon = c.Icon; const on = cat === c.key
|
||||
return (
|
||||
<button key={c.key} onClick={() => setCat(c.key)}
|
||||
<button type="button" key={c.key} onClick={() => setCat(c.key)}
|
||||
className={on ? 'bg-surface-card text-content border' : 'bg-surface-secondary text-content-muted border border-edge'}
|
||||
style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 11px 6px 7px', borderRadius: 999, fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit', borderColor: on ? 'var(--text-primary)' : undefined }}>
|
||||
<span style={{ width: 20, height: 20, borderRadius: 6, display: 'grid', placeItems: 'center', background: c.color + '22', color: c.color }}><Icon size={12} /></span>
|
||||
@@ -1335,8 +1381,11 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 14, minWidth: 0 }}>
|
||||
<div className={panelCls}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
|
||||
<label className={labelCls} style={{ marginBottom: 0 }}>{t('costs.whoPaid')}</label>
|
||||
<button type="button" onClick={() => (multiPayer ? disableMultiPayer() : enableMultiPayer())}
|
||||
className="text-content-muted"
|
||||
@@ -1373,8 +1422,8 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
{on ? (
|
||||
<div className="bg-surface-input border border-edge" style={{ display: 'flex', alignItems: 'center', gap: 4, borderRadius: 8, padding: '0 10px' }}>
|
||||
<span className="text-content-faint" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{sym(currency)}</span>
|
||||
<NumericInput mode="decimal" placeholder="0.00" data-testid="payer-amount"
|
||||
value={payerAmounts[p.id] || ''}
|
||||
<NumericInput mode="decimal" placeholder={localizeAmountInput('0.00', currency)} data-testid="payer-amount"
|
||||
value={localizeAmountInput(payerAmounts[p.id] || '', currency)}
|
||||
onValueChange={v => onPayerAmountChange(p.id, v)}
|
||||
className="text-content"
|
||||
style={{ width: '100%', border: 0, background: 'none', outline: 'none', fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, padding: '8px 0', textAlign: 'right' }} />
|
||||
@@ -1398,23 +1447,23 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className={panelCls}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
|
||||
<label className={labelCls}>{t('costs.split') || 'Split'}</label>
|
||||
<div className="bg-surface-secondary" style={{ display: 'flex', borderRadius: 8, padding: 2 }}>
|
||||
<label className={labelCls} style={{ marginBottom: 0 }}>{t('costs.split') || 'Split'}</label>
|
||||
<div className="bg-surface-card border border-edge" style={{ display: 'flex', borderRadius: 999, padding: 2 }}>
|
||||
<button type="button" onClick={() => setSplitMode('equally')}
|
||||
className={splitMode === 'equally' ? 'bg-surface-card text-content' : 'text-content-muted'}
|
||||
style={{ padding: '4px 10px', fontSize: 11.5, borderRadius: 6, fontWeight: 600, border: 0, cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
className={splitMode === 'equally' ? 'bg-surface-secondary text-content' : 'text-content-muted'}
|
||||
style={{ padding: '4px 12px', fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', borderRadius: 999, fontWeight: 600, border: 0, background: splitMode === 'equally' ? undefined : 'none', cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
{t('costs.splitEqually') || 'Equally'}
|
||||
</button>
|
||||
<button type="button" onClick={() => setSplitMode('custom')}
|
||||
className={splitMode === 'custom' ? 'bg-surface-card text-content' : 'text-content-muted'}
|
||||
style={{ padding: '4px 10px', fontSize: 11.5, borderRadius: 6, fontWeight: 600, border: 0, cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
className={splitMode === 'custom' ? 'bg-surface-secondary text-content' : 'text-content-muted'}
|
||||
style={{ padding: '4px 12px', fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', borderRadius: 999, fontWeight: 600, border: 0, background: splitMode === 'custom' ? undefined : 'none', cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
{t('costs.splitCustom') || 'Custom'}
|
||||
</button>
|
||||
<button type="button" onClick={() => setSplitMode('ticket')}
|
||||
className={splitMode === 'ticket' ? 'bg-surface-card text-content' : 'text-content-muted'}
|
||||
style={{ padding: '4px 10px', fontSize: 11.5, borderRadius: 6, fontWeight: 600, border: 0, cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
className={splitMode === 'ticket' ? 'bg-surface-secondary text-content' : 'text-content-muted'}
|
||||
style={{ padding: '4px 12px', fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', borderRadius: 999, fontWeight: 600, border: 0, background: splitMode === 'ticket' ? undefined : 'none', cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
{t('costs.splitTicket') || 'Ticket'}
|
||||
</button>
|
||||
</div>
|
||||
@@ -1428,7 +1477,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 130px auto', gap: 8, alignItems: 'center' }}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Item name"
|
||||
placeholder={t('costs.ticketItemName')}
|
||||
value={item.name}
|
||||
onChange={e => handleUpdateItemName(item.id, e.target.value)}
|
||||
className="bg-surface-input border border-edge text-content"
|
||||
@@ -1438,8 +1487,8 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
<span className="text-content-faint" style={{ fontSize: 12 }}>{sym(currency)}</span>
|
||||
<NumericInput
|
||||
mode="decimal"
|
||||
placeholder="0.00"
|
||||
value={item.price}
|
||||
placeholder={localizeAmountInput('0.00', currency)}
|
||||
value={localizeAmountInput(item.price, currency)}
|
||||
onValueChange={v => handleUpdateItemPrice(item.id, v)}
|
||||
className="text-content"
|
||||
style={{ width: '100%', border: 0, background: 'none', outline: 'none', fontSize: 13, fontWeight: 600, textAlign: 'right', padding: '6px 0' }}
|
||||
@@ -1451,7 +1500,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, alignItems: 'center' }}>
|
||||
<span className="text-content-faint" style={{ fontSize: 10.5, fontWeight: 600, textTransform: 'uppercase', marginRight: 4 }}>Splitting:</span>
|
||||
<span className="text-content-faint" style={{ fontSize: 10.5, fontWeight: 600, textTransform: 'uppercase', marginRight: 4 }}>{t('costs.ticketSplitting')}</span>
|
||||
{people.map((p, pIdx) => {
|
||||
const active = item.participants.has(p.id)
|
||||
return (
|
||||
@@ -1475,12 +1524,12 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
</div>
|
||||
|
||||
<button type="button" onClick={handleAddEmptyItem} className="border border-dashed border-edge text-content-muted" style={{ padding: '8px 12px', borderRadius: 10, background: 'none', fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
|
||||
<Plus size={14} /> Add item
|
||||
<Plus size={14} /> {t('costs.ticketAddItem')}
|
||||
</button>
|
||||
|
||||
{ticketItems.length > 0 && (
|
||||
<div className="bg-surface-secondary border border-edge" style={{ padding: 12, borderRadius: 10 }}>
|
||||
<div className="text-content" style={{ fontSize: 12, fontWeight: 600, marginBottom: 8 }}>Individual Shares Summary</div>
|
||||
<div className="text-content" style={{ fontSize: 12, fontWeight: 600, marginBottom: 8 }}>{t('costs.ticketShares')}</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
{people.map(p => {
|
||||
const share = ticketInfo.shares[p.id] || 0
|
||||
@@ -1515,13 +1564,13 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
{sym(currency)}{(equalShares[p.id] || 0).toFixed(2)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-content-faint" style={{ fontSize: 12, textAlign: 'right', paddingRight: 10 }}>Excluded</span>
|
||||
<span className="text-content-faint" style={{ fontSize: 12, textAlign: 'right', paddingRight: 10 }}>{t('costs.excluded')}</span>
|
||||
)
|
||||
) : (
|
||||
on ? (
|
||||
<div className="bg-surface-input border border-edge" style={{ display: 'flex', alignItems: 'center', gap: 4, borderRadius: 8, padding: '0 10px' }}>
|
||||
<span className="text-content-faint" style={{ fontSize: 13 }}>{sym(currency)}</span>
|
||||
<input type="text" inputMode="decimal" placeholder={(placeholderShares[p.id] || 0).toFixed(2)} value={customAmounts[p.id] || ''}
|
||||
<input type="text" inputMode="decimal" placeholder={localizeAmountInput((placeholderShares[p.id] || 0).toFixed(2), currency)} value={localizeAmountInput(customAmounts[p.id] || '', currency)}
|
||||
onChange={e => handleCustomAmountChange(p.id, e.target.value)}
|
||||
className="text-content" style={{ width: '100%', border: 0, background: 'none', outline: 'none', fontSize: 14, fontWeight: 600, padding: '8px 0', textAlign: 'right' }} />
|
||||
</div>
|
||||
@@ -1540,15 +1589,27 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
</span>
|
||||
) : (
|
||||
<span style={{ fontWeight: 600, color: customBalanced ? '#16a34a' : '#dc2626' }}>
|
||||
{customBalanced
|
||||
? 'Split matches total'
|
||||
: `Sum of splits: ${sym(currency)}${splitSum.toFixed(2)} of ${sym(currency)}${totalNum.toFixed(2)} (${(totalNum - splitSum) > 0 ? 'under by' : 'over by'} ${sym(currency)}${Math.abs(totalNum - splitSum).toFixed(2)})`}
|
||||
{customBalanced
|
||||
? t('costs.splitBalanced')
|
||||
: t(totalNum - splitSum > 0 ? 'costs.splitSumUnder' : 'costs.splitSumOver', {
|
||||
sum: sym(currency) + splitSum.toFixed(2),
|
||||
total: sym(currency) + totalNum.toFixed(2),
|
||||
diff: sym(currency) + Math.abs(totalNum - splitSum).toFixed(2),
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={panelCls}>
|
||||
<label className={labelCls} htmlFor="expense-note">{t('costs.note')}</label>
|
||||
<textarea id="expense-note" value={note} onChange={e => setNote(e.target.value)} rows={2}
|
||||
placeholder={t('costs.notePlaceholder')} maxLength={NOTE_MAX}
|
||||
className={inputCls} style={{ borderRadius: 10, padding: '10px 13px', fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', outline: 'none', resize: 'vertical', minHeight: 68, width: '100%', boxSizing: 'border-box', fontFamily: 'inherit', lineHeight: 1.5 }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { COST_CATEGORIES, typeToCostCategory } from '@trek/shared'
|
||||
import { COST_CAT_META, COST_CATEGORY_LIST, catMeta } from './costsCategories'
|
||||
|
||||
describe('COST_CAT_META', () => {
|
||||
it('has metadata for every fixed category, including fuel and parking', () => {
|
||||
for (const key of COST_CATEGORIES) {
|
||||
expect(COST_CAT_META[key]).toBeDefined()
|
||||
expect(COST_CAT_META[key].key).toBe(key)
|
||||
}
|
||||
})
|
||||
|
||||
it('derives COST_CATEGORY_LIST in the same order as COST_CATEGORIES', () => {
|
||||
expect(COST_CATEGORY_LIST.map(m => m.key)).toEqual([...COST_CATEGORIES])
|
||||
})
|
||||
})
|
||||
|
||||
describe('catMeta', () => {
|
||||
it('resolves fuel and parking directly', () => {
|
||||
expect(catMeta('fuel').key).toBe('fuel')
|
||||
expect(catMeta('parking').key).toBe('parking')
|
||||
})
|
||||
|
||||
it('maps legacy/free-text aliases to the new categories', () => {
|
||||
expect(catMeta('gas').key).toBe('fuel')
|
||||
expect(catMeta('petrol').key).toBe('fuel')
|
||||
expect(catMeta('Parking').key).toBe('parking')
|
||||
expect(catMeta('car park').key).toBe('parking')
|
||||
})
|
||||
|
||||
it('resolves a parking booking the same way whichever path created the expense', () => {
|
||||
expect(catMeta(typeToCostCategory('parking')).key).toBe('parking')
|
||||
expect(catMeta('parking').key).toBe(typeToCostCategory('parking'))
|
||||
})
|
||||
|
||||
it('falls back to other for unknown categories', () => {
|
||||
expect(catMeta('made-up-category').key).toBe('other')
|
||||
expect(catMeta(null).key).toBe('other')
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Hotel, Utensils, ShoppingCart, Bus, Plane, Ticket, Camera, ShoppingBag, FileText, HeartPulse, Coins, MoreHorizontal } from 'lucide-react'
|
||||
import { Hotel, Utensils, ShoppingCart, Bus, Plane, Ticket, Camera, ShoppingBag, FileText, HeartPulse, Coins, MoreHorizontal, Fuel, ParkingCircle } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { COST_CATEGORIES, type CostCategory } from '@trek/shared'
|
||||
|
||||
@@ -27,6 +27,8 @@ export const COST_CAT_META: Record<CostCategory, CostCategoryMeta> = {
|
||||
fees: { key: 'fees', labelKey: 'costs.cat.fees', Icon: FileText, color: '#475569' },
|
||||
health: { key: 'health', labelKey: 'costs.cat.health', Icon: HeartPulse, color: '#dc2626' },
|
||||
tips: { key: 'tips', labelKey: 'costs.cat.tips', Icon: Coins, color: '#d97706' },
|
||||
fuel: { key: 'fuel', labelKey: 'costs.cat.fuel', Icon: Fuel, color: '#f59e0b' },
|
||||
parking: { key: 'parking', labelKey: 'costs.cat.parking', Icon: ParkingCircle, color: '#3b82f6' },
|
||||
other: { key: 'other', labelKey: 'costs.cat.other', Icon: MoreHorizontal, color: '#6b7280' },
|
||||
}
|
||||
|
||||
@@ -51,6 +53,8 @@ const LEGACY_CATEGORY_MAP: Record<string, CostCategory> = {
|
||||
fee: 'fees', fees: 'fees',
|
||||
health: 'health', medical: 'health',
|
||||
tip: 'tips', tips: 'tips',
|
||||
gas: 'fuel', fuel: 'fuel', petrol: 'fuel',
|
||||
parking: 'parking', parkings: 'parking', 'car park': 'parking',
|
||||
other: 'other', misc: 'other',
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ describe('CollabChat', () => {
|
||||
|
||||
it('FE-COMP-CHAT-002: shows empty state when no messages', async () => {
|
||||
render(<CollabChat {...defaultProps} />);
|
||||
await screen.findByText('Start the conversation');
|
||||
expect(await screen.findByText('Start the conversation')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CHAT-003: shows message input placeholder', async () => {
|
||||
@@ -85,7 +85,7 @@ describe('CollabChat', () => {
|
||||
)
|
||||
);
|
||||
render(<CollabChat {...defaultProps} />);
|
||||
await screen.findByText('Hello world!');
|
||||
expect(await screen.findByText('Hello world!')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CHAT-006: typing in input updates text field', async () => {
|
||||
@@ -124,9 +124,13 @@ describe('CollabChat', () => {
|
||||
expect(screen.getByPlaceholderText('Type a message...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CHAT-009: shows hint text in empty state', async () => {
|
||||
it('FE-COMP-CHAT-009: shows guidance in empty state', async () => {
|
||||
render(<CollabChat {...defaultProps} />);
|
||||
await screen.findByText(/Share ideas, plans/i);
|
||||
// The empty state now renders the shared EmptyState: a chat-scene mascot
|
||||
// plus the single "Start the conversation" title (the separate hint
|
||||
// paragraph was dropped in the mobile rewrite).
|
||||
await screen.findByText('Start the conversation');
|
||||
expect(document.querySelector('svg.trek--chat')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CHAT-010: chat container renders', () => {
|
||||
@@ -595,7 +599,7 @@ describe('CollabChat', () => {
|
||||
await screen.findByText('New 100');
|
||||
const loadMoreBtn = screen.getByRole('button', { name: /load/i });
|
||||
await user.click(loadMoreBtn);
|
||||
await screen.findByText('Older message');
|
||||
expect(await screen.findByText('Older message')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CHAT-033: clicking delete on own message marks it as deleted', async () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import ReactDOM from 'react-dom'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { ArrowUp, Reply, Smile, X } from 'lucide-react'
|
||||
import type { User } from '../../types'
|
||||
import { useCollabChat } from './useCollabChat'
|
||||
@@ -39,7 +39,7 @@ export default function CollabChat({ tripId, currentUser }: CollabChatProps) {
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>
|
||||
<strong>{replyTo.username}</strong>: {(replyTo.text || '').slice(0, 60)}
|
||||
</span>
|
||||
<button onClick={() => setReplyTo(null)} style={{
|
||||
<button type="button" onClick={() => setReplyTo(null)} style={{
|
||||
background: 'none', border: 'none', cursor: 'pointer', padding: 2, color: 'var(--text-faint)',
|
||||
display: 'flex', flexShrink: 0,
|
||||
}}>
|
||||
@@ -51,7 +51,7 @@ export default function CollabChat({ tripId, currentUser }: CollabChatProps) {
|
||||
<div style={{ display: 'flex', alignItems: 'flex-end', gap: 6 }}>
|
||||
{/* Emoji button */}
|
||||
{canEdit && (
|
||||
<button ref={emojiBtnRef} onClick={() => setShowEmoji(!showEmoji)} style={{
|
||||
<button type="button" ref={emojiBtnRef} onClick={() => setShowEmoji(!showEmoji)} style={{
|
||||
width: 34, height: 34, borderRadius: '50%', border: 'none',
|
||||
background: showEmoji ? 'var(--bg-hover)' : 'transparent',
|
||||
color: 'var(--text-muted)', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
@@ -80,7 +80,7 @@ export default function CollabChat({ tripId, currentUser }: CollabChatProps) {
|
||||
|
||||
{/* Send */}
|
||||
{canEdit && (
|
||||
<button onClick={handleSend} disabled={!text.trim() || sending} style={{
|
||||
<button type="button" onClick={handleSend} disabled={!text.trim() || sending} style={{
|
||||
width: 34, height: 34, borderRadius: '50%', border: 'none',
|
||||
background: text.trim() ? '#007AFF' : 'var(--border-primary)',
|
||||
color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
@@ -97,7 +97,7 @@ export default function CollabChat({ tripId, currentUser }: CollabChatProps) {
|
||||
{showEmoji && <EmojiPicker onSelect={handleEmojiSelect} onClose={() => setShowEmoji(false)} anchorRef={emojiBtnRef} containerRef={containerRef} />}
|
||||
|
||||
{/* Reaction quick menu (right-click) */}
|
||||
{reactMenu && ReactDOM.createPortal(
|
||||
{reactMenu && createPortal(
|
||||
<ReactionMenu x={reactMenu.x} y={reactMenu.y} onReact={(emoji) => handleReact(reactMenu.msgId, emoji)} onClose={() => setReactMenu(null)} />,
|
||||
document.body
|
||||
)}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect, useRef } from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { EMOJI_CATEGORIES } from './CollabChat.constants'
|
||||
import { TwemojiImg } from './CollabChatTwemojiImg'
|
||||
|
||||
@@ -37,7 +37,7 @@ export function EmojiPicker({ onSelect, onClose, anchorRef, containerRef }: Emoj
|
||||
return () => document.removeEventListener('mousedown', close)
|
||||
}, [onClose, anchorRef])
|
||||
|
||||
return ReactDOM.createPortal(
|
||||
return createPortal(
|
||||
<div ref={ref} style={{
|
||||
position: 'fixed', bottom: pos.bottom, left: pos.left, zIndex: 10000,
|
||||
background: 'var(--bg-card)', border: '1px solid var(--border-faint)', borderRadius: 16,
|
||||
@@ -46,7 +46,7 @@ export function EmojiPicker({ onSelect, onClose, anchorRef, containerRef }: Emoj
|
||||
{/* Category tabs */}
|
||||
<div style={{ display: 'flex', borderBottom: '1px solid var(--border-faint)', padding: '6px 8px', gap: 2 }}>
|
||||
{Object.keys(EMOJI_CATEGORIES).map(c => (
|
||||
<button key={c} onClick={() => setCat(c)} style={{
|
||||
<button type="button" key={c} onClick={() => setCat(c)} style={{
|
||||
flex: 1, padding: '4px 0', borderRadius: 6, border: 'none', cursor: 'pointer',
|
||||
background: cat === c ? 'var(--bg-hover)' : 'transparent',
|
||||
color: 'var(--text-primary)', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, fontFamily: 'inherit',
|
||||
@@ -58,7 +58,7 @@ export function EmojiPicker({ onSelect, onClose, anchorRef, containerRef }: Emoj
|
||||
{/* Emoji grid */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(10, 1fr)', gap: 2, padding: 8 }}>
|
||||
{EMOJI_CATEGORIES[cat].map((emoji, i) => (
|
||||
<button key={i} onClick={() => onSelect(emoji)} style={{
|
||||
<button type="button" key={i} onClick={() => onSelect(emoji)} style={{
|
||||
width: 28, height: 28, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
background: 'none', border: 'none', cursor: 'pointer', borderRadius: 6,
|
||||
padding: 2, transition: 'transform 0.1s',
|
||||
|
||||
@@ -2,7 +2,12 @@ import { useState, useEffect } from 'react'
|
||||
import { collabApi } from '../../api/client'
|
||||
|
||||
/* ── Link Preview ── */
|
||||
const previewCache = {}
|
||||
// linkPreview is trip-scoped on the server, so the cache key has to be too.
|
||||
// Capped as well: a long chat session would otherwise keep every preview it ever
|
||||
// rendered for as long as the tab lives.
|
||||
const previewCache = new Map()
|
||||
const cacheKey = (tripId: number, url: string): string => `${tripId} ${url}`
|
||||
const MAX_CACHED_PREVIEWS = 200
|
||||
|
||||
interface LinkPreviewProps {
|
||||
url: string
|
||||
@@ -12,17 +17,23 @@ interface LinkPreviewProps {
|
||||
}
|
||||
|
||||
export function LinkPreview({ url, tripId, own, onLoad }: LinkPreviewProps) {
|
||||
const [data, setData] = useState(previewCache[url] || null)
|
||||
const [loading, setLoading] = useState(!previewCache[url])
|
||||
const [data, setData] = useState(previewCache.get(cacheKey(tripId, url)) || null)
|
||||
const [loading, setLoading] = useState(!previewCache.has(cacheKey(tripId, url)))
|
||||
|
||||
useEffect(() => {
|
||||
if (previewCache[url]) return
|
||||
const key = cacheKey(tripId, url)
|
||||
const cached = previewCache.get(key)
|
||||
if (cached) { setData(cached); setLoading(false); return }
|
||||
let current = true
|
||||
collabApi.linkPreview(tripId, url).then(d => {
|
||||
previewCache[url] = d
|
||||
if (previewCache.size >= MAX_CACHED_PREVIEWS) previewCache.delete(previewCache.keys().next().value)
|
||||
previewCache.set(key, d)
|
||||
if (!current) return
|
||||
setData(d)
|
||||
setLoading(false)
|
||||
if (d?.title || d?.description || d?.image) onLoad?.()
|
||||
}).catch(() => setLoading(false))
|
||||
}).catch(() => { if (current) setLoading(false) })
|
||||
return () => { current = false }
|
||||
}, [url, tripId])
|
||||
|
||||
if (loading || !data || (!data.title && !data.description && !data.image)) return null
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
// FE-W5CCM-001 to FE-W5CCM-024
|
||||
// ChatMessages is a pure presentational component — every piece of state arrives
|
||||
// as a prop from useCollabChat, so the tests drive it directly instead of going
|
||||
// through CollabChat (that path is covered in CollabChat.test.tsx).
|
||||
|
||||
vi.mock('./CollabChatLinkPreview', () => ({
|
||||
LinkPreview: ({ url, onLoad }: { url: string; onLoad?: () => void }) => (
|
||||
<button type="button" data-testid={`preview-${url}`} onClick={() => onLoad?.()}>
|
||||
preview
|
||||
</button>
|
||||
),
|
||||
}))
|
||||
|
||||
import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'
|
||||
import { ChatMessages } from './CollabChatMessages'
|
||||
|
||||
interface ChatMsg {
|
||||
id: number
|
||||
user_id: number
|
||||
username: string
|
||||
text: string
|
||||
created_at: string
|
||||
user_avatar?: string | null
|
||||
reply_text?: string | null
|
||||
reply_username?: string | null
|
||||
reply_to?: number | null
|
||||
reactions?: { emoji: string; count: number; users: { user_id: number; username: string }[] }[]
|
||||
_deleted?: boolean
|
||||
}
|
||||
|
||||
const currentUser = { id: 1, username: 'me' }
|
||||
|
||||
function buildMsg(overrides: Partial<ChatMsg> = {}): ChatMsg {
|
||||
return {
|
||||
id: 1,
|
||||
user_id: 2,
|
||||
username: 'alice',
|
||||
text: 'hello',
|
||||
created_at: '2025-06-01T10:00:00.000Z',
|
||||
reactions: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
interface Handles {
|
||||
setHoveredId: ReturnType<typeof vi.fn>
|
||||
setReplyTo: ReturnType<typeof vi.fn>
|
||||
setReactMenu: ReturnType<typeof vi.fn>
|
||||
handleDelete: ReturnType<typeof vi.fn>
|
||||
handleReact: ReturnType<typeof vi.fn>
|
||||
handleLoadMore: ReturnType<typeof vi.fn>
|
||||
scrollToBottom: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
function renderMessages(
|
||||
messages: ChatMsg[],
|
||||
overrides: Record<string, unknown> = {},
|
||||
): Handles {
|
||||
const handles: Handles = {
|
||||
setHoveredId: vi.fn(),
|
||||
setReplyTo: vi.fn(),
|
||||
setReactMenu: vi.fn(),
|
||||
handleDelete: vi.fn(),
|
||||
handleReact: vi.fn(),
|
||||
handleLoadMore: vi.fn(),
|
||||
scrollToBottom: vi.fn(),
|
||||
}
|
||||
const props = {
|
||||
currentUser,
|
||||
tripId: 1,
|
||||
t: (key: string) => key,
|
||||
is12h: false,
|
||||
canEdit: true,
|
||||
messages,
|
||||
loading: false,
|
||||
hasMore: false,
|
||||
loadingMore: false,
|
||||
hoveredId: null,
|
||||
deletingIds: new Set<number>(),
|
||||
scrollRef: { current: null },
|
||||
isAtBottom: { current: false },
|
||||
checkAtBottom: vi.fn(),
|
||||
isOwn: (m: ChatMsg) => String(m.user_id) === String(currentUser.id),
|
||||
isEmojiOnly: (text: string) => /^\p{Extended_Pictographic}$/u.test(text),
|
||||
...handles,
|
||||
...overrides,
|
||||
}
|
||||
render(<ChatMessages {...props} />)
|
||||
return handles
|
||||
}
|
||||
|
||||
describe('ChatMessages', () => {
|
||||
it('FE-W5CCM-001: renders the empty state when there are no messages', () => {
|
||||
renderMessages([])
|
||||
expect(screen.getByText('collab.chat.empty')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CCM-002: the load-more button reports its loading state and calls back', () => {
|
||||
const { handleLoadMore } = renderMessages([buildMsg()], { hasMore: true })
|
||||
const btn = screen.getByRole('button', { name: 'collab.chat.loadMore' })
|
||||
fireEvent.click(btn)
|
||||
expect(handleLoadMore).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-W5CCM-003: the load-more button is disabled and shows an ellipsis while loading', () => {
|
||||
renderMessages([buildMsg()], { hasMore: true, loadingMore: true })
|
||||
const btn = screen.getByText('...').closest('button')
|
||||
expect(btn).toBeDisabled()
|
||||
})
|
||||
|
||||
it('FE-W5CCM-004: a deleted message renders the placeholder line with its author', () => {
|
||||
renderMessages([buildMsg({ _deleted: true })])
|
||||
expect(screen.getByText(/collab\.chat\.deletedMessage/)).toBeInTheDocument()
|
||||
expect(screen.queryByText('hello')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CCM-005: the deleted placeholder falls back to English when the key is missing', () => {
|
||||
renderMessages([buildMsg({ _deleted: true })], {
|
||||
t: (key: string) => (key === 'collab.chat.deletedMessage' ? '' : key),
|
||||
})
|
||||
expect(screen.getByText(/deleted a message/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CCM-006: a message not at the end of its group keeps the rounded tail', () => {
|
||||
renderMessages([
|
||||
buildMsg({ id: 1, user_id: 1, username: 'me', text: 'first' }),
|
||||
buildMsg({ id: 2, user_id: 1, username: 'me', text: 'second' }),
|
||||
])
|
||||
const first = screen.getByText('first').closest('div[style]')!
|
||||
const last = screen.getByText('second').closest('div[style]')!
|
||||
expect(first.getAttribute('style')).toContain('border-radius: 18px 18px 18px 18px')
|
||||
expect(last.getAttribute('style')).toContain('border-radius: 18px 18px 4px 18px')
|
||||
})
|
||||
|
||||
it('FE-W5CCM-007: the avatar image is rendered for a foreign author who has one', () => {
|
||||
renderMessages([buildMsg({ user_avatar: '/uploads/avatars/alice.png' })])
|
||||
const avatar = document.querySelector('img[src="/uploads/avatars/alice.png"]')
|
||||
expect(avatar).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CCM-008: the avatar initial falls back to a question mark without a username', () => {
|
||||
renderMessages([buildMsg({ username: '' })])
|
||||
expect(screen.getByText('?')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CCM-009: hovering a bubble reports the hovered id and clears it on leave', () => {
|
||||
const { setHoveredId } = renderMessages([buildMsg({ id: 7 })])
|
||||
const bubble = screen.getByText('hello').closest('div[style="position: relative;"]')!
|
||||
fireEvent.mouseEnter(bubble)
|
||||
expect(setHoveredId).toHaveBeenCalledWith(7)
|
||||
fireEvent.mouseLeave(bubble)
|
||||
expect(setHoveredId).toHaveBeenLastCalledWith(null)
|
||||
})
|
||||
|
||||
it('FE-W5CCM-010: the hover actions become visible for the hovered message only', () => {
|
||||
renderMessages(
|
||||
[buildMsg({ id: 1, text: 'one' }), buildMsg({ id: 2, text: 'two' })],
|
||||
{ hoveredId: 1 },
|
||||
)
|
||||
const actions = screen.getAllByTitle('collab.chat.reply').map(b => b.parentElement!)
|
||||
expect(actions[0].getAttribute('style')).toContain('opacity: 1')
|
||||
expect(actions[1].getAttribute('style')).toContain('opacity: 0')
|
||||
})
|
||||
|
||||
it('FE-W5CCM-011: right-clicking a bubble opens the reaction menu at the cursor', () => {
|
||||
const { setReactMenu } = renderMessages([buildMsg({ id: 9 })])
|
||||
const bubble = screen.getByText('hello').closest('div[style="position: relative;"]')!
|
||||
fireEvent.contextMenu(bubble, { clientX: 120, clientY: 240 })
|
||||
expect(setReactMenu).toHaveBeenCalledWith({ msgId: 9, x: 120, y: 240 })
|
||||
})
|
||||
|
||||
it('FE-W5CCM-012: right-clicking does nothing without edit rights', () => {
|
||||
const { setReactMenu } = renderMessages([buildMsg()], { canEdit: false })
|
||||
const bubble = screen.getByText('hello').closest('div[style="position: relative;"]')!
|
||||
fireEvent.contextMenu(bubble, { clientX: 10, clientY: 20 })
|
||||
expect(setReactMenu).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W5CCM-013: a single tap only records the tap, a double tap opens the reaction menu', () => {
|
||||
const { setReactMenu } = renderMessages([buildMsg({ id: 4 })])
|
||||
const bubble = screen.getByText('hello').closest('div[style="position: relative;"]') as HTMLElement
|
||||
fireEvent.touchEnd(bubble, { changedTouches: [{ clientX: 5, clientY: 6 }] })
|
||||
expect(setReactMenu).not.toHaveBeenCalled()
|
||||
expect(bubble.dataset.lastTap).toBeTruthy()
|
||||
|
||||
fireEvent.touchEnd(bubble, { changedTouches: [{ clientX: 33, clientY: 44 }] })
|
||||
expect(setReactMenu).toHaveBeenCalledWith({ msgId: 4, x: 33, y: 44 })
|
||||
})
|
||||
|
||||
it('FE-W5CCM-014: a double tap without touch coordinates does not open the menu', () => {
|
||||
const { setReactMenu } = renderMessages([buildMsg()])
|
||||
const bubble = screen.getByText('hello').closest('div[style="position: relative;"]') as HTMLElement
|
||||
fireEvent.touchEnd(bubble, { changedTouches: [] })
|
||||
fireEvent.touchEnd(bubble, { changedTouches: [] })
|
||||
expect(setReactMenu).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W5CCM-015: a double tap is ignored without edit rights', () => {
|
||||
const { setReactMenu } = renderMessages([buildMsg()], { canEdit: false })
|
||||
const bubble = screen.getByText('hello').closest('div[style="position: relative;"]') as HTMLElement
|
||||
fireEvent.touchEnd(bubble, { changedTouches: [{ clientX: 1, clientY: 2 }] })
|
||||
fireEvent.touchEnd(bubble, { changedTouches: [{ clientX: 1, clientY: 2 }] })
|
||||
expect(setReactMenu).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W5CCM-016: an own reply quote shows the quoted author and a truncated body', () => {
|
||||
const longQuote = 'q'.repeat(120)
|
||||
renderMessages([
|
||||
buildMsg({ user_id: 1, username: 'me', reply_username: 'alice', reply_text: longQuote }),
|
||||
])
|
||||
expect(screen.getByText('alice')).toBeInTheDocument()
|
||||
expect(screen.getByText('q'.repeat(80))).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CCM-017: a reply without stored quote data renders empty quote fields', () => {
|
||||
renderMessages([buildMsg({ reply_to: 55, reply_text: null, reply_username: null })])
|
||||
const quote = screen.getByText('hello').closest('div[style]')!.parentElement!
|
||||
// The quote block renders before the message text with both fields blank
|
||||
expect(quote.textContent).toBe('hello')
|
||||
})
|
||||
|
||||
it('FE-W5CCM-018: a resolved link preview scrolls down when the view is pinned to the bottom', async () => {
|
||||
const { scrollToBottom } = renderMessages(
|
||||
[buildMsg({ text: 'look at https://example.com/a' })],
|
||||
{ isAtBottom: { current: true } },
|
||||
)
|
||||
fireEvent.click(screen.getByTestId('preview-https://example.com/a'))
|
||||
await waitFor(() => expect(scrollToBottom).toHaveBeenCalledWith('smooth'))
|
||||
})
|
||||
|
||||
it('FE-W5CCM-019: a resolved link preview does not scroll when the user scrolled up', async () => {
|
||||
const { scrollToBottom } = renderMessages(
|
||||
[buildMsg({ text: 'look at https://example.com/b' })],
|
||||
{ isAtBottom: { current: false } },
|
||||
)
|
||||
fireEvent.click(screen.getByTestId('preview-https://example.com/b'))
|
||||
await new Promise(r => setTimeout(r, 80))
|
||||
expect(scrollToBottom).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W5CCM-020: the reply and delete buttons react to hover and fire their handlers', () => {
|
||||
const { setReplyTo, handleDelete } = renderMessages([
|
||||
buildMsg({ id: 3, user_id: 1, username: 'me', text: 'mine' }),
|
||||
])
|
||||
const replyBtn = screen.getByTitle('collab.chat.reply')
|
||||
fireEvent.mouseEnter(replyBtn)
|
||||
expect(replyBtn.style.transform).toBe('scale(1.2)')
|
||||
fireEvent.mouseLeave(replyBtn)
|
||||
expect(replyBtn.style.transform).toBe('scale(1)')
|
||||
fireEvent.click(replyBtn)
|
||||
expect(setReplyTo).toHaveBeenCalledWith(expect.objectContaining({ id: 3 }))
|
||||
|
||||
const deleteBtn = screen.getByTitle('common.delete')
|
||||
fireEvent.mouseEnter(deleteBtn)
|
||||
expect(deleteBtn.style.background).toBe('rgb(239, 68, 68)')
|
||||
fireEvent.mouseLeave(deleteBtn)
|
||||
expect(deleteBtn.style.background).toBe('var(--accent)')
|
||||
fireEvent.click(deleteBtn)
|
||||
expect(handleDelete).toHaveBeenCalledWith(3)
|
||||
})
|
||||
|
||||
it('FE-W5CCM-021: clicking a reaction badge on an own message reacts again', () => {
|
||||
const { handleReact } = renderMessages([
|
||||
buildMsg({
|
||||
id: 8,
|
||||
user_id: 1,
|
||||
username: 'me',
|
||||
reactions: [{ emoji: '🔥', count: 2, users: [{ user_id: 1, username: 'me' }] }],
|
||||
}),
|
||||
])
|
||||
fireEvent.click(screen.getByAltText('🔥').closest('button')!)
|
||||
expect(handleReact).toHaveBeenCalledWith(8, '🔥')
|
||||
})
|
||||
|
||||
it('FE-W5CCM-022: reaction badges are inert without edit rights', () => {
|
||||
const { handleReact } = renderMessages(
|
||||
[
|
||||
buildMsg({
|
||||
reactions: [{ emoji: '👍', count: 1, users: [{ user_id: 2, username: 'alice' }] }],
|
||||
}),
|
||||
],
|
||||
{ canEdit: false },
|
||||
)
|
||||
fireEvent.click(screen.getByAltText('👍').closest('button')!)
|
||||
expect(handleReact).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W5CCM-023: a message being deleted collapses instead of disappearing instantly', () => {
|
||||
renderMessages([buildMsg({ id: 12 })], { deletingIds: new Set([12]) })
|
||||
const row = screen.getByText('hello').closest('div[style*="row"]')!
|
||||
expect(row.getAttribute('style')).toContain('opacity: 0')
|
||||
})
|
||||
|
||||
it('FE-W5CCM-024: a single emoji message renders without a bubble background', () => {
|
||||
renderMessages([buildMsg({ text: '🎉' })])
|
||||
const big = screen.getByText('🎉')
|
||||
expect(big.getAttribute('style')).toContain('font-size: calc(40px')
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,11 @@
|
||||
import React from 'react'
|
||||
import { Trash2, Reply, ChevronUp, MessageCircle } from 'lucide-react'
|
||||
import { Trash2, Reply, ChevronUp } from 'lucide-react'
|
||||
import { URL_REGEX } from './CollabChat.constants'
|
||||
import { formatTime, formatDateSeparator, shouldShowDateSeparator } from './CollabChat.helpers'
|
||||
import { MessageText } from './CollabChatMessageText'
|
||||
import { LinkPreview } from './CollabChatLinkPreview'
|
||||
import { ReactionBadge } from './CollabChatReactionBadge'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
|
||||
export function ChatMessages(props: any) {
|
||||
const { currentUser, tripId, t, is12h, can, trip, canEdit, messages, setMessages, loading, setLoading, hasMore, setHasMore, loadingMore, setLoadingMore, text, setText, replyTo, setReplyTo, hoveredId, setHoveredId, sending, setSending, showEmoji, setShowEmoji, reactMenu, setReactMenu, deletingIds, setDeletingIds, deleteTimersRef, containerRef, messagesRef, scrollRef, textareaRef, emojiBtnRef, isAtBottom, scrollToBottom, checkAtBottom, handleLoadMore, handleTextChange, handleSend, handleKeyDown, handleDelete, handleReact, handleEmojiSelect, isOwn, isEmojiOnly } = props
|
||||
@@ -12,11 +13,10 @@ export function ChatMessages(props: any) {
|
||||
<>
|
||||
{/* Messages */}
|
||||
{messages.length === 0 ? (
|
||||
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8, color: 'var(--text-faint)', padding: 32, textAlign: 'center' }}>
|
||||
<MessageCircle size={40} strokeWidth={1.2} style={{ opacity: 0.4 }} />
|
||||
<span style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{t('collab.chat.empty')}</span>
|
||||
<span style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', opacity: 0.6, fontFamily: 'var(--font-subtext)' }}>{t('collab.chat.emptyDesc') || ''}</span>
|
||||
</div>
|
||||
// flex-1, like the message list it stands in for: without it the empty
|
||||
// state was only as tall as its own content and the composer rode up to
|
||||
// sit right under the mascot, with the rest of the panel left blank.
|
||||
<EmptyState scene="chat" title={t('collab.chat.empty')} className="min-h-0 flex-1" />
|
||||
) : (
|
||||
<div ref={scrollRef} onScroll={checkAtBottom} className="chat-scroll" style={{
|
||||
flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '8px 14px 4px', WebkitOverflowScrolling: 'touch',
|
||||
@@ -24,7 +24,7 @@ export function ChatMessages(props: any) {
|
||||
}}>
|
||||
{hasMore && (
|
||||
<div style={{ display: 'flex', justifyContent: 'center', padding: '4px 0 10px' }}>
|
||||
<button onClick={handleLoadMore} disabled={loadingMore} style={{
|
||||
<button type="button" onClick={handleLoadMore} disabled={loadingMore} style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600,
|
||||
color: 'var(--text-muted)', background: 'var(--bg-secondary)', border: '1px solid var(--border-faint)',
|
||||
borderRadius: 99, padding: '5px 14px', cursor: 'pointer', fontFamily: 'inherit',
|
||||
@@ -181,7 +181,7 @@ export function ChatMessages(props: any) {
|
||||
transition: 'opacity .1s',
|
||||
...(own ? { left: -6 } : { right: -6 }),
|
||||
}}>
|
||||
<button onClick={() => setReplyTo(msg)} title={t('collab.chat.reply')} style={{
|
||||
<button type="button" onClick={() => setReplyTo(msg)} title={t('collab.chat.reply')} style={{
|
||||
width: 24, height: 24, borderRadius: '50%', border: 'none',
|
||||
background: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
cursor: 'pointer', color: 'var(--accent-text)', padding: 0,
|
||||
@@ -193,7 +193,7 @@ export function ChatMessages(props: any) {
|
||||
<Reply size={11} />
|
||||
</button>
|
||||
{own && canEdit && (
|
||||
<button onClick={() => handleDelete(msg.id)} title={t('common.delete')} style={{
|
||||
<button type="button" onClick={() => handleDelete(msg.id)} title={t('common.delete')} style={{
|
||||
width: 24, height: 24, borderRadius: '50%', border: 'none',
|
||||
background: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
cursor: 'pointer', color: 'var(--accent-text)', padding: 0,
|
||||
@@ -221,12 +221,9 @@ export function ChatMessages(props: any) {
|
||||
borderRadius: 99, background: 'var(--bg-card)',
|
||||
boxShadow: '0 1px 6px rgba(0,0,0,0.12)', border: '1px solid var(--border-faint)',
|
||||
}}>
|
||||
{msg.reactions.map(r => {
|
||||
const myReaction = r.users.some(u => String(u.user_id) === String(currentUser.id))
|
||||
return (
|
||||
<ReactionBadge key={r.emoji} reaction={r} currentUserId={currentUser.id} onReact={() => { if (canEdit) handleReact(msg.id, r.emoji) }} />
|
||||
)
|
||||
})}
|
||||
{msg.reactions.map(r => (
|
||||
<ReactionBadge key={r.emoji} reaction={r} currentUserId={currentUser.id} onReact={() => { if (canEdit) handleReact(msg.id, r.emoji) }} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useRef } from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { TwemojiImg } from './CollabChatTwemojiImg'
|
||||
import type { ChatReaction } from './CollabChat.types'
|
||||
|
||||
@@ -18,7 +18,7 @@ export function ReactionBadge({ reaction, currentUserId, onReact }: ReactionBadg
|
||||
|
||||
return (
|
||||
<>
|
||||
<button ref={ref} onClick={onReact}
|
||||
<button type="button" ref={ref} onClick={onReact}
|
||||
onMouseEnter={() => {
|
||||
if (ref.current) {
|
||||
const rect = ref.current.getBoundingClientRect()
|
||||
@@ -36,7 +36,7 @@ export function ReactionBadge({ reaction, currentUserId, onReact }: ReactionBadg
|
||||
<TwemojiImg emoji={reaction.emoji} size={16} />
|
||||
{reaction.count > 1 && <span style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 700, color: 'var(--text-muted)', minWidth: 8 }}>{reaction.count}</span>}
|
||||
</button>
|
||||
{hover && names && ReactDOM.createPortal(
|
||||
{hover && names && createPortal(
|
||||
<div style={{
|
||||
position: 'fixed', top: pos.top, left: pos.left, transform: 'translate(-50%, -100%)',
|
||||
pointerEvents: 'none', zIndex: 10000, whiteSpace: 'nowrap',
|
||||
|
||||
@@ -31,7 +31,7 @@ export function ReactionMenu({ x, y, onReact, onClose }: ReactionMenuProps) {
|
||||
display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 2, width: menuWidth,
|
||||
}}>
|
||||
{QUICK_REACTIONS.map(emoji => (
|
||||
<button key={emoji} onClick={() => onReact(emoji)} style={{
|
||||
<button type="button" key={emoji} onClick={() => onReact(emoji)} style={{
|
||||
width: 30, height: 30, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
background: 'none', border: 'none', cursor: 'pointer', borderRadius: '50%',
|
||||
padding: 3, transition: 'transform 0.1s, background 0.1s',
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
// FE-W4CCS-001 to FE-W4CCS-019
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'
|
||||
import type { ChatReaction } from './CollabChat.types'
|
||||
import type { NoteAuthor } from './CollabNotes.types'
|
||||
|
||||
const linkPreview = vi.fn(async (_tripId: number, _url: string) => ({ title: 'TREK', image: null as string | null }))
|
||||
vi.mock('../../api/client', () => ({ collabApi: { linkPreview: (tripId: number, url: string) => linkPreview(tripId, url) } }))
|
||||
|
||||
import { TwemojiImg } from './CollabChatTwemojiImg'
|
||||
import { ReactionBadge } from './CollabChatReactionBadge'
|
||||
import { UserAvatar } from './CollabNotesUserAvatar'
|
||||
import { WebsiteThumbnail } from './CollabNotesWebsiteThumbnail'
|
||||
import { LinkPreview } from './CollabChatLinkPreview'
|
||||
|
||||
function reaction(overrides: Partial<ChatReaction> = {}): ChatReaction {
|
||||
return { emoji: '👍', count: 1, users: [{ id: 1, username: 'ada' }], ...overrides } as unknown as ChatReaction
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
linkPreview.mockReset()
|
||||
linkPreview.mockResolvedValue({ title: 'TREK', image: null })
|
||||
})
|
||||
|
||||
describe('TwemojiImg', () => {
|
||||
it('FE-W4CCS-001: renders the twemoji asset for the codepoint', () => {
|
||||
const { container } = render(<TwemojiImg emoji="👍" />)
|
||||
const img = container.querySelector('img') as HTMLImageElement
|
||||
|
||||
expect(img).toHaveAttribute('alt', '👍')
|
||||
expect(img.getAttribute('src')).toContain('/1f44d.png')
|
||||
expect(img).toHaveStyle({ width: '20px', height: '20px' })
|
||||
})
|
||||
|
||||
it('FE-W4CCS-002: strips the variation selector from a multi-codepoint emoji', () => {
|
||||
const { container } = render(<TwemojiImg emoji="❤️" size={16} />)
|
||||
|
||||
expect((container.querySelector('img') as HTMLImageElement).getAttribute('src')).toContain('/2764.png')
|
||||
})
|
||||
|
||||
it('FE-W4CCS-003: falls back to the plain glyph when the asset fails to load', () => {
|
||||
const { container } = render(<TwemojiImg emoji="👍" size={24} />)
|
||||
|
||||
fireEvent.error(container.querySelector('img')!)
|
||||
|
||||
expect(container.querySelector('img')).toBeNull()
|
||||
expect(screen.getByText('👍')).toHaveStyle({ fontSize: '24px' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReactionBadge', () => {
|
||||
it('FE-W4CCS-004: hides the counter for a single reactor', () => {
|
||||
render(<ReactionBadge reaction={reaction()} currentUserId={1} onReact={() => {}} />)
|
||||
|
||||
expect(screen.queryByText('1')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4CCS-005: shows the counter once more than one person reacted', () => {
|
||||
render(
|
||||
<ReactionBadge
|
||||
reaction={reaction({ count: 3, users: [{ id: 1, username: 'ada' }, { id: 2, username: 'bob' }] } as Partial<ChatReaction>)}
|
||||
currentUserId={1}
|
||||
onReact={() => {}}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('3')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4CCS-006: clicking toggles the own reaction', () => {
|
||||
const onReact = vi.fn()
|
||||
render(<ReactionBadge reaction={reaction()} currentUserId={1} onReact={onReact} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button'))
|
||||
|
||||
expect(onReact).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('FE-W4CCS-007: hovering portals the list of reactors and leaving removes it', () => {
|
||||
render(
|
||||
<ReactionBadge
|
||||
reaction={reaction({ users: [{ id: 1, username: 'ada' }, { id: 2, username: 'bob' }] } as Partial<ChatReaction>)}
|
||||
currentUserId={1}
|
||||
onReact={() => {}}
|
||||
/>,
|
||||
)
|
||||
const badge = screen.getByRole('button')
|
||||
|
||||
fireEvent.mouseEnter(badge)
|
||||
expect(screen.getByText('ada, bob')).toBeInTheDocument()
|
||||
|
||||
fireEvent.mouseLeave(badge)
|
||||
expect(screen.queryByText('ada, bob')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4CCS-008: shows no tooltip when nobody is named', () => {
|
||||
render(<ReactionBadge reaction={reaction({ users: [] } as Partial<ChatReaction>)} currentUserId={1} onReact={() => {}} />)
|
||||
|
||||
fireEvent.mouseEnter(screen.getByRole('button'))
|
||||
|
||||
expect(document.body.querySelectorAll('[style*="translate(-50%, -100%)"]')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('UserAvatar', () => {
|
||||
it('FE-W4CCS-009: renders nothing without a user', () => {
|
||||
const { container } = render(<UserAvatar user={null} />)
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('FE-W4CCS-010: renders the avatar image when one is set', () => {
|
||||
const { container } = render(<UserAvatar user={{ username: 'ada', avatar: '/uploads/avatars/ada.png' } as NoteAuthor} size={20} />)
|
||||
const img = container.querySelector('img') as HTMLImageElement
|
||||
|
||||
expect(img).toHaveAttribute('src', '/uploads/avatars/ada.png')
|
||||
expect(img).toHaveAttribute('alt', 'ada')
|
||||
expect(img).toHaveStyle({ width: '20px' })
|
||||
})
|
||||
|
||||
it('FE-W4CCS-011: falls back to the first letter, and to ? without a name', () => {
|
||||
const { unmount } = render(<UserAvatar user={{ username: 'ada', avatar: null } as NoteAuthor} />)
|
||||
expect(screen.getByText('a')).toBeInTheDocument()
|
||||
unmount()
|
||||
|
||||
render(<UserAvatar user={{ username: '', avatar: null } as NoteAuthor} />)
|
||||
expect(screen.getByText('?')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('WebsiteThumbnail', () => {
|
||||
it('FE-W4CCS-012: shows the domain until an OG image arrives', async () => {
|
||||
render(<WebsiteThumbnail url="https://www.liketrek.com/docs" tripId={4} color="#000" />)
|
||||
|
||||
expect(screen.getByText('liketrek.com')).toBeInTheDocument()
|
||||
await waitFor(() => expect(screen.getByRole('link')).toHaveAttribute('title', 'TREK'))
|
||||
expect(linkPreview).toHaveBeenCalledWith(4, 'https://www.liketrek.com/docs')
|
||||
})
|
||||
|
||||
it('FE-W4CCS-013: renders the OG image once the preview resolves', async () => {
|
||||
linkPreview.mockResolvedValue({ title: 'Docs', image: 'https://cdn.example/og.png' })
|
||||
const { container } = render(<WebsiteThumbnail url="https://example.com/a" tripId={4} color="#000" />)
|
||||
|
||||
await waitFor(() => expect(container.querySelector('img')).not.toBeNull())
|
||||
expect(container.querySelector('img')).toHaveAttribute('src', 'https://cdn.example/og.png')
|
||||
|
||||
// A broken OG image falls back to the domain chip.
|
||||
fireEvent.error(container.querySelector('img')!)
|
||||
expect(screen.getByText('example.com')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W4CCS-014: keeps the domain chip when the preview request fails', async () => {
|
||||
linkPreview.mockRejectedValue(new Error('blocked'))
|
||||
render(<WebsiteThumbnail url="https://blocked.example/a" tripId={4} color="#000" />)
|
||||
|
||||
expect(screen.getByText('blocked.example')).toBeInTheDocument()
|
||||
await waitFor(() => expect(linkPreview).toHaveBeenCalled())
|
||||
expect(screen.getByRole('link')).toHaveAttribute('title', 'https://blocked.example/a')
|
||||
})
|
||||
|
||||
it('FE-W4CCS-017: a url that is not http(s) is shown but neither linked nor previewed', async () => {
|
||||
const { unmount } = render(<WebsiteThumbnail url="javascript:alert(1)" tripId={4} color="#000" />)
|
||||
|
||||
expect(screen.queryByRole('link')).toBeNull()
|
||||
expect(screen.getByTitle('javascript:alert(1)')).toBeInTheDocument()
|
||||
unmount()
|
||||
|
||||
render(<WebsiteThumbnail url="not a url" tripId={4} color="#000" />)
|
||||
expect(screen.getByText('link')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('link')).toBeNull()
|
||||
expect(linkPreview).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W4CCS-015: caches per trip, because the preview endpoint is trip-scoped', async () => {
|
||||
linkPreview.mockResolvedValue({ title: 'Trip 4', image: null })
|
||||
const shared = 'https://example.com/shared'
|
||||
const first = render(<WebsiteThumbnail url={shared} tripId={4} color="#000" />)
|
||||
await waitFor(() => expect(screen.getByRole('link')).toHaveAttribute('title', 'Trip 4'))
|
||||
first.unmount()
|
||||
|
||||
linkPreview.mockResolvedValue({ title: 'Trip 9', image: null })
|
||||
render(<WebsiteThumbnail url={shared} tripId={9} color="#000" />)
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('link')).toHaveAttribute('title', 'Trip 9'))
|
||||
expect(linkPreview).toHaveBeenCalledTimes(2)
|
||||
expect(linkPreview).toHaveBeenLastCalledWith(9, shared)
|
||||
})
|
||||
|
||||
it('FE-W4CCS-016: a broken OG image does not poison the next url', async () => {
|
||||
linkPreview.mockResolvedValue({ title: 'A', image: 'https://cdn.example/a.png' })
|
||||
const { container, rerender } = render(<WebsiteThumbnail url="https://a.example/x" tripId={4} color="#000" />)
|
||||
await waitFor(() => expect(container.querySelector('img')).not.toBeNull())
|
||||
fireEvent.error(container.querySelector('img')!)
|
||||
expect(container.querySelector('img')).toBeNull()
|
||||
|
||||
linkPreview.mockResolvedValue({ title: 'B', image: 'https://cdn.example/b.png' })
|
||||
rerender(<WebsiteThumbnail url="https://b.example/y" tripId={4} color="#000" />)
|
||||
|
||||
await waitFor(() => expect(container.querySelector('img')).not.toBeNull())
|
||||
expect(container.querySelector('img')).toHaveAttribute('src', 'https://cdn.example/b.png')
|
||||
})
|
||||
})
|
||||
|
||||
describe('LinkPreview', () => {
|
||||
it('FE-W4CCS-018: caches per trip, because the preview endpoint is trip-scoped', async () => {
|
||||
const shared = 'https://example.com/preview'
|
||||
linkPreview.mockResolvedValue({ title: 'Trip 4', image: null })
|
||||
const first = render(<LinkPreview url={shared} tripId={4} own={false} onLoad={undefined} />)
|
||||
expect(await screen.findByText('Trip 4')).toBeInTheDocument()
|
||||
first.unmount()
|
||||
|
||||
linkPreview.mockResolvedValue({ title: 'Trip 9', image: null })
|
||||
render(<LinkPreview url={shared} tripId={9} own={false} onLoad={undefined} />)
|
||||
|
||||
expect(await screen.findByText('Trip 9')).toBeInTheDocument()
|
||||
expect(linkPreview).toHaveBeenCalledTimes(2)
|
||||
expect(linkPreview).toHaveBeenLastCalledWith(9, shared)
|
||||
})
|
||||
|
||||
it('FE-W4CCS-019: a preview that resolves after the url changed is not shown', async () => {
|
||||
let resolveFirst: (v: { title: string; image: string | null }) => void = () => {}
|
||||
linkPreview.mockImplementationOnce(() => new Promise(res => { resolveFirst = res }))
|
||||
const { rerender } = render(<LinkPreview url="https://slow.example/a" tripId={4} own={false} onLoad={undefined} />)
|
||||
|
||||
linkPreview.mockResolvedValue({ title: 'Second', image: null })
|
||||
rerender(<LinkPreview url="https://fast.example/b" tripId={4} own={false} onLoad={undefined} />)
|
||||
expect(await screen.findByText('Second')).toBeInTheDocument()
|
||||
|
||||
resolveFirst({ title: 'First', image: null })
|
||||
await waitFor(() => expect(screen.queryByText('First')).toBeNull())
|
||||
expect(screen.getByText('Second')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
// FE-W4CNH-001 to FE-W4CNH-008
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { formatTimestamp } from './CollabNotes.helpers'
|
||||
|
||||
// The helper feeds t() with a key and params; echo them so the branches are visible.
|
||||
const t = (key: string, params?: Record<string, number>) =>
|
||||
params ? `${key}:${Object.values(params)[0]}` : key
|
||||
|
||||
const NOW = new Date('2026-06-15T12:00:00Z')
|
||||
|
||||
beforeAll(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(NOW)
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
function ago(minutes: number): string {
|
||||
return new Date(NOW.getTime() - minutes * 60_000).toISOString().replace('Z', '')
|
||||
}
|
||||
|
||||
describe('formatTimestamp', () => {
|
||||
it('FE-W4CNH-001: renders an empty string for a missing timestamp', () => {
|
||||
expect(formatTimestamp(null, t, 'en')).toBe('')
|
||||
expect(formatTimestamp('', t, 'en')).toBe('')
|
||||
})
|
||||
|
||||
it('FE-W4CNH-002: labels the last minute as just now', () => {
|
||||
expect(formatTimestamp(ago(0), t, 'en')).toBe('collab.chat.justNow')
|
||||
})
|
||||
|
||||
it('FE-W4CNH-003: counts minutes below the hour', () => {
|
||||
expect(formatTimestamp(ago(5), t, 'en')).toBe('collab.chat.minutesAgo:5')
|
||||
expect(formatTimestamp(ago(59), t, 'en')).toBe('collab.chat.minutesAgo:59')
|
||||
})
|
||||
|
||||
it('FE-W4CNH-004: counts hours below the day', () => {
|
||||
expect(formatTimestamp(ago(60), t, 'en')).toBe('collab.chat.hoursAgo:1')
|
||||
expect(formatTimestamp(ago(60 * 23), t, 'en')).toBe('collab.chat.hoursAgo:23')
|
||||
})
|
||||
|
||||
it('FE-W4CNH-005: counts days below a week', () => {
|
||||
expect(formatTimestamp(ago(60 * 24), t, 'en')).toBe('collab.notes.daysAgo:1')
|
||||
expect(formatTimestamp(ago(60 * 24 * 6), t, 'en')).toBe('collab.notes.daysAgo:6')
|
||||
})
|
||||
|
||||
it('FE-W4CNH-006: falls back to a localized short date beyond a week', () => {
|
||||
expect(formatTimestamp(ago(60 * 24 * 10), t, 'en-US')).toBe('Jun 5')
|
||||
})
|
||||
|
||||
it('FE-W4CNH-007: treats a naive timestamp as UTC and accepts an explicit Z', () => {
|
||||
const withZ = new Date(NOW.getTime() - 5 * 60_000).toISOString()
|
||||
expect(formatTimestamp(withZ, t, 'en')).toBe('collab.chat.minutesAgo:5')
|
||||
})
|
||||
|
||||
it('FE-W4CNH-008: falls back to English labels when the translation is missing', () => {
|
||||
const empty = () => ''
|
||||
expect(formatTimestamp(ago(0), empty, 'en')).toBe('just now')
|
||||
expect(formatTimestamp(ago(5), empty, 'en')).toBe('5m ago')
|
||||
expect(formatTimestamp(ago(120), empty, 'en')).toBe('2h ago')
|
||||
expect(formatTimestamp(ago(60 * 24 * 2), empty, 'en')).toBe('2d ago')
|
||||
})
|
||||
})
|
||||
@@ -10,7 +10,7 @@ vi.mock('../../api/websocket', () => ({
|
||||
removeListener: vi.fn(),
|
||||
}));
|
||||
|
||||
import { render, screen, waitFor, act } from '../../../tests/helpers/render';
|
||||
import { render, screen, waitFor, act, fireEvent, within } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
@@ -19,6 +19,7 @@ import { useTripStore } from '../../store/tripStore';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildUser, buildTrip } from '../../../tests/helpers/factories';
|
||||
import CollabNotes from './CollabNotes';
|
||||
import { addListener } from '../../api/websocket';
|
||||
|
||||
const currentUser = buildUser({ id: 1, username: 'testuser' });
|
||||
|
||||
@@ -46,7 +47,7 @@ describe('CollabNotes', () => {
|
||||
|
||||
it('FE-COMP-NOTES-002: shows empty state when no notes', async () => {
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('No notes yet');
|
||||
expect(await screen.findByText('No notes yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTES-003: shows New Note button', async () => {
|
||||
@@ -69,7 +70,7 @@ describe('CollabNotes', () => {
|
||||
)
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Packing Tips');
|
||||
expect(await screen.findByText('Packing Tips')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTES-005: clicking New Note opens modal', async () => {
|
||||
@@ -78,7 +79,7 @@ describe('CollabNotes', () => {
|
||||
await screen.findByText('No notes yet');
|
||||
await user.click(screen.getByText('New Note'));
|
||||
// Modal opens with a title input — placeholder is "Note title" (no ellipsis)
|
||||
await screen.findByPlaceholderText('Note title');
|
||||
expect(await screen.findByPlaceholderText('Note title')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTES-006: note title is shown in the grid', async () => {
|
||||
@@ -95,7 +96,7 @@ describe('CollabNotes', () => {
|
||||
)
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('My Checklist');
|
||||
expect(await screen.findByText('My Checklist')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTES-007: multiple notes all render', async () => {
|
||||
@@ -116,8 +117,11 @@ describe('CollabNotes', () => {
|
||||
|
||||
it('FE-COMP-NOTES-008: Notes title heading is shown', async () => {
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
// The loading panel renders its own copy of the heading and swaps the whole
|
||||
// node out once the fetch settles, so wait for the loaded state first.
|
||||
await screen.findByText('No notes yet');
|
||||
// collab.notes.title = "Notes"
|
||||
await screen.findByText('Notes');
|
||||
expect(screen.getByText('Notes')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTES-009: create note calls POST API', async () => {
|
||||
@@ -235,7 +239,7 @@ describe('CollabNotes', () => {
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Editable Note');
|
||||
await user.click(screen.getByTitle('Edit'));
|
||||
await screen.findByDisplayValue('Editable Note');
|
||||
expect(await screen.findByDisplayValue('Editable Note')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTES-016: category filter hides notes from other categories', async () => {
|
||||
@@ -270,6 +274,7 @@ describe('CollabNotes', () => {
|
||||
const listener = calls[calls.length - 1][0];
|
||||
act(() => {
|
||||
listener({
|
||||
tripId: 1,
|
||||
type: 'collab:note:created',
|
||||
note: {
|
||||
id: 50, trip_id: 1, user_id: 1, author_username: 'testuser', author_avatar: null,
|
||||
@@ -278,7 +283,7 @@ describe('CollabNotes', () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
await screen.findByText('Live Note');
|
||||
expect(await screen.findByText('Live Note')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTES-018: WebSocket collab:note:deleted event removes note', async () => {
|
||||
@@ -300,7 +305,7 @@ describe('CollabNotes', () => {
|
||||
const calls = (addListener as ReturnType<typeof vi.fn>).mock.calls;
|
||||
const listener = calls[calls.length - 1][0];
|
||||
act(() => {
|
||||
listener({ type: 'collab:note:deleted', noteId: 7 });
|
||||
listener({ tripId: 1, type: 'collab:note:deleted', noteId: 7 });
|
||||
});
|
||||
await waitFor(() => expect(screen.queryByText('WS Delete')).not.toBeInTheDocument());
|
||||
});
|
||||
@@ -401,7 +406,7 @@ describe('CollabNotes', () => {
|
||||
await screen.findByText('No notes yet');
|
||||
await user.click(screen.getByTitle('Manage Categories'));
|
||||
// The modal header renders "Category Settings" or similar
|
||||
await screen.findByText('Manage Categories', { selector: 'h3' });
|
||||
expect(await screen.findByText('Manage Categories', { selector: 'h3' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTES-025: CategorySettingsModal shows no categories message when empty', async () => {
|
||||
@@ -409,7 +414,7 @@ describe('CollabNotes', () => {
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('No notes yet');
|
||||
await user.click(screen.getByTitle('Manage Categories'));
|
||||
await screen.findByText('No categories yet');
|
||||
expect(await screen.findByText('No categories yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTES-026: CategorySettingsModal add new category', async () => {
|
||||
@@ -424,7 +429,7 @@ describe('CollabNotes', () => {
|
||||
const addBtn = newCatInput.nextElementSibling as HTMLElement;
|
||||
await user.click(addBtn);
|
||||
// "Transport" category appears in the modal
|
||||
await screen.findByText('Transport');
|
||||
expect(await screen.findByText('Transport')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTES-027: CategorySettingsModal close button dismisses it', async () => {
|
||||
@@ -462,6 +467,7 @@ describe('CollabNotes', () => {
|
||||
const listener = calls[calls.length - 1][0];
|
||||
act(() => {
|
||||
listener({
|
||||
tripId: 1,
|
||||
type: 'collab:note:updated',
|
||||
note: {
|
||||
id: 5, trip_id: 1, user_id: 1, author_username: 'testuser', author_avatar: null,
|
||||
@@ -671,7 +677,7 @@ describe('CollabNotes', () => {
|
||||
// Click the PDF badge to open FilePreviewPortal
|
||||
await user.click(screen.getByText('PDF'));
|
||||
// FilePreviewPortal renders the file name in the header
|
||||
await screen.findByText('document.pdf');
|
||||
expect(await screen.findByText('document.pdf')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTES-037: note with website shows website thumbnail component', async () => {
|
||||
@@ -852,7 +858,7 @@ describe('CollabNotes', () => {
|
||||
await user.click(screen.getByTitle('Manage Categories'));
|
||||
await screen.findByText('Manage Categories', { selector: 'h3' });
|
||||
// Find the "Transport" category name span and click to edit
|
||||
const categoryNameSpan = screen.getAllByText('Transport').find(el => el.tagName === 'SPAN' && el.title === 'Click to rename');
|
||||
const categoryNameSpan = screen.getAllByText('Transport').find(el => el.tagName === 'BUTTON' && el.title === 'Click to rename');
|
||||
if (categoryNameSpan) {
|
||||
await user.click(categoryNameSpan);
|
||||
// Now an input with value "Transport" should appear
|
||||
@@ -974,7 +980,7 @@ describe('CollabNotes', () => {
|
||||
await screen.findByText('Manage Categories', { selector: 'h3' });
|
||||
|
||||
// Find and click the "OldCat" category name span to enter edit mode
|
||||
const oldCatSpan = screen.getAllByText('OldCat').find(el => el.tagName === 'SPAN' && el.title === 'Click to rename');
|
||||
const oldCatSpan = screen.getAllByText('OldCat').find(el => el.tagName === 'BUTTON' && el.title === 'Click to rename');
|
||||
if (oldCatSpan) {
|
||||
await user.click(oldCatSpan);
|
||||
const editInput = screen.getByDisplayValue('OldCat');
|
||||
@@ -1268,3 +1274,642 @@ describe('CollabNotes', () => {
|
||||
expect(document.body.innerHTML.indexOf('Pinned')).toBeLessThan(document.body.innerHTML.indexOf('Unpinned'));
|
||||
});
|
||||
});
|
||||
|
||||
// FE-W5CNT-001 to FE-W5CNT-029
|
||||
// Fills in the load/error/attachment/category branches of useCollabNotes and the
|
||||
// view modal that the smoke tests above do not reach.
|
||||
|
||||
type AddToast = NonNullable<typeof window.__addToast>;
|
||||
|
||||
const buildNote = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 1,
|
||||
trip_id: 1,
|
||||
user_id: 1,
|
||||
author_username: 'testuser',
|
||||
author_avatar: null,
|
||||
title: 'A note',
|
||||
content: 'Body text',
|
||||
category: null,
|
||||
website: null,
|
||||
color: '#3b82f6',
|
||||
pinned: false,
|
||||
files: [],
|
||||
attachments: [],
|
||||
created_at: '2025-06-01T10:00:00.000Z',
|
||||
updated_at: '2025-06-01T10:00:00.000Z',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function serveNotes(payload: unknown) {
|
||||
server.use(http.get('/api/trips/1/collab/notes', () => HttpResponse.json(payload)));
|
||||
}
|
||||
|
||||
/** Serves a different payload per GET so reload-after-upload can be observed. */
|
||||
function serveNotesSequence(payloads: unknown[]) {
|
||||
let call = 0;
|
||||
server.use(
|
||||
http.get('/api/trips/1/collab/notes', () => {
|
||||
const payload = payloads[Math.min(call, payloads.length - 1)];
|
||||
call += 1;
|
||||
return HttpResponse.json(payload);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function pasteFile(name: string, type = 'image/png') {
|
||||
const file = new File(['x'], name, { type });
|
||||
fireEvent.paste(document.querySelector('form')!, {
|
||||
clipboardData: { items: [{ type, getAsFile: () => file }] },
|
||||
});
|
||||
}
|
||||
|
||||
function wsHandler(): (msg: Record<string, unknown>) => void {
|
||||
return (addListener as ReturnType<typeof vi.fn>).mock.calls[0][0];
|
||||
}
|
||||
|
||||
describe('CollabNotes details', () => {
|
||||
let addToast: ReturnType<typeof vi.fn<AddToast>>;
|
||||
let filesChanged: number;
|
||||
let onFilesChanged: () => void;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
addToast = vi.fn<AddToast>(() => 0);
|
||||
window.__addToast = addToast;
|
||||
filesChanged = 0;
|
||||
onFilesChanged = () => { filesChanged += 1; };
|
||||
window.addEventListener('collab-files-changed', onFilesChanged);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
window.removeEventListener('collab-files-changed', onFilesChanged);
|
||||
delete window.__addToast;
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-001: a corrupt category cache in localStorage is ignored', async () => {
|
||||
localStorage.setItem('collab-cats-1', '{not json');
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
expect(await screen.findByText('No notes yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-002: a category without a stored colour falls back to the first palette entry', async () => {
|
||||
serveNotes({ notes: [buildNote({ category: 'Ideas', color: null })] });
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('A note');
|
||||
// The card chip is a span, the filter pill above the grid is a button
|
||||
const chip = screen.getAllByText('Ideas').find(el => el.tagName === 'SPAN')!;
|
||||
expect(chip.style.color).toBe('rgb(99, 102, 241)');
|
||||
});
|
||||
|
||||
it('FE-W5CNT-003: without a trip id nothing is fetched and the panel stays in its loading state', () => {
|
||||
render(<CollabNotes tripId={0} currentUser={currentUser} />);
|
||||
expect(screen.getByRole('heading', { name: 'Notes' })).toBeInTheDocument();
|
||||
expect(screen.queryByText('New Note')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-004: notes served as a bare array are rendered', async () => {
|
||||
serveNotes([buildNote({ title: 'Array note' })]);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
expect(await screen.findByText('Array note')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-005: an empty payload yields an empty list', async () => {
|
||||
serveNotes(null);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
expect(await screen.findByText('No notes yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-006: a failing load falls back to the empty state', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips/1/collab/notes', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
expect(await screen.findByText('No notes yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-007: a WebSocket create for a note already in the list does not duplicate it', async () => {
|
||||
serveNotes({ notes: [buildNote({ id: 4, title: 'Already here' })] });
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Already here');
|
||||
const handler = wsHandler();
|
||||
await act(async () => {
|
||||
handler({ tripId: 1, type: 'collab:note:created', note: buildNote({ id: 4, title: 'Already here' }) });
|
||||
});
|
||||
expect(screen.getAllByText('Already here')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-W5CNT-008: a WebSocket update only touches the matching note', async () => {
|
||||
serveNotes({
|
||||
notes: [buildNote({ id: 1, title: 'First' }), buildNote({ id: 2, title: 'Second' })],
|
||||
});
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Second');
|
||||
const handler = wsHandler();
|
||||
await act(async () => {
|
||||
handler({ tripId: 1, type: 'collab:note:updated', note: { id: 2, title: 'Second renamed' } });
|
||||
});
|
||||
expect(await screen.findByText('Second renamed')).toBeInTheDocument();
|
||||
expect(screen.getByText('First')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-009: a WebSocket delete accepts a plain id and ignores events without one', async () => {
|
||||
serveNotes({ notes: [buildNote({ id: 9, title: 'Doomed' })] });
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Doomed');
|
||||
const handler = wsHandler();
|
||||
await act(async () => { handler({ tripId: 1, type: 'collab:note:deleted' }); });
|
||||
expect(screen.getByText('Doomed')).toBeInTheDocument();
|
||||
await act(async () => { handler({ tripId: 1, type: 'collab:note:deleted', id: 9 }); });
|
||||
await waitFor(() => expect(screen.queryByText('Doomed')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-W5CNT-010: an unwrapped create response is prepended to the list', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('/api/trips/1/collab/notes', () =>
|
||||
HttpResponse.json(buildNote({ id: 20, title: 'Fresh note' })),
|
||||
),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('No notes yet');
|
||||
await user.click(screen.getByText('New Note'));
|
||||
await user.type(await screen.findByPlaceholderText('Note title'), 'Fresh note');
|
||||
await user.click(screen.getByRole('button', { name: 'Create' }));
|
||||
expect(await screen.findByText('Fresh note')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-011: an empty create response leaves the list untouched', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/trips/1/collab/notes', () => HttpResponse.json(null)));
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('No notes yet');
|
||||
await user.click(screen.getByText('New Note'));
|
||||
await user.type(await screen.findByPlaceholderText('Note title'), 'Ghost note');
|
||||
await user.click(screen.getByRole('button', { name: 'Create' }));
|
||||
await waitFor(() => expect(screen.queryByPlaceholderText('Note title')).not.toBeInTheDocument());
|
||||
expect(screen.getByText('No notes yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-012: a failing create reports an error and keeps the modal open', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('/api/trips/1/collab/notes', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('No notes yet');
|
||||
await user.click(screen.getByText('New Note'));
|
||||
await user.type(await screen.findByPlaceholderText('Note title'), 'Doomed note');
|
||||
await user.click(screen.getByRole('button', { name: 'Create' }));
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));
|
||||
expect(screen.getByPlaceholderText('Note title')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-013: a pasted attachment is uploaded and the list is reloaded afterwards', async () => {
|
||||
const user = userEvent.setup();
|
||||
let uploaded = 0;
|
||||
serveNotesSequence([
|
||||
{ notes: [] },
|
||||
{ notes: [buildNote({ id: 30, title: 'With file' })] },
|
||||
]);
|
||||
server.use(
|
||||
http.post('/api/trips/1/collab/notes', () =>
|
||||
HttpResponse.json({ note: buildNote({ id: 30, title: 'With file' }) }),
|
||||
),
|
||||
http.post('/api/trips/1/collab/notes/30/files', () => {
|
||||
uploaded += 1;
|
||||
return HttpResponse.json({ file: { id: 1 } });
|
||||
}),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('No notes yet');
|
||||
await user.click(screen.getByText('New Note'));
|
||||
await user.type(await screen.findByPlaceholderText('Note title'), 'With file');
|
||||
pasteFile('screenshot.png');
|
||||
await user.click(screen.getByRole('button', { name: 'Create' }));
|
||||
await screen.findByText('With file');
|
||||
expect(uploaded).toBe(1);
|
||||
expect(filesChanged).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-W5CNT-014: a failing upload reports an error and the array-shaped reload is ignored', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotesSequence([{ notes: [] }, [buildNote({ id: 31, title: 'Never shown' })]]);
|
||||
server.use(
|
||||
http.post('/api/trips/1/collab/notes', () =>
|
||||
HttpResponse.json({ note: buildNote({ id: 31, title: 'Upload fails' }) }),
|
||||
),
|
||||
http.post('/api/trips/1/collab/notes/31/files', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('No notes yet');
|
||||
await user.click(screen.getByText('New Note'));
|
||||
await user.type(await screen.findByPlaceholderText('Note title'), 'Upload fails');
|
||||
pasteFile('broken.png');
|
||||
await user.click(screen.getByRole('button', { name: 'Create' }));
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));
|
||||
await waitFor(() => expect(filesChanged).toBe(1));
|
||||
expect(screen.queryByText('Never shown')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-015: pinning a note applies the unwrapped response to that note only', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotes({
|
||||
notes: [buildNote({ id: 1, title: 'Pin me' }), buildNote({ id: 2, title: 'Leave me' })],
|
||||
});
|
||||
server.use(
|
||||
http.put('/api/trips/1/collab/notes/1', () =>
|
||||
HttpResponse.json(buildNote({ id: 1, title: 'Pinned now', pinned: true })),
|
||||
),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Pin me');
|
||||
const pinBtn = screen.getAllByTitle('Pin')[0];
|
||||
await user.click(pinBtn);
|
||||
await screen.findByText('Pinned now');
|
||||
expect(screen.getByText('Leave me')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-016: an empty update response leaves the note as it was', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotes({ notes: [buildNote({ id: 1, title: 'Unchanged' })] });
|
||||
server.use(http.put('/api/trips/1/collab/notes/1', () => HttpResponse.json(null)));
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Unchanged');
|
||||
await user.click(screen.getByTitle('Pin'));
|
||||
await waitFor(() => expect(screen.getByText('Unchanged')).toBeInTheDocument());
|
||||
expect(screen.getByTitle('Pin')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-017: a failing edit reports an error and keeps the edit modal open', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotes({ notes: [buildNote({ id: 3, title: 'Edit me' })] });
|
||||
server.use(
|
||||
http.put('/api/trips/1/collab/notes/3', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Edit me');
|
||||
await user.click(screen.getByTitle('Edit'));
|
||||
const titleInput = await screen.findByDisplayValue('Edit me');
|
||||
await user.type(titleInput, ' v2');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));
|
||||
expect(screen.getByDisplayValue('Edit me v2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-018: saving a new category colour rewrites every note in that category', async () => {
|
||||
const user = userEvent.setup();
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
serveNotes({ notes: [buildNote({ id: 1, title: 'Sushi', category: 'Food', color: '#ef4444' })] });
|
||||
server.use(
|
||||
http.put('/api/trips/1/collab/notes/1', async ({ request }) => {
|
||||
bodies.push((await request.json()) as Record<string, unknown>);
|
||||
return HttpResponse.json({ note: buildNote({ id: 1, title: 'Sushi', category: 'Food', color: '#10b981' }) });
|
||||
}),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Sushi');
|
||||
await user.click(screen.getByTitle('Manage Categories'));
|
||||
const label = (await screen.findAllByText('Food')).find(el => el.title === 'Click to rename')!;
|
||||
const swatches = label.parentElement!.querySelectorAll('button');
|
||||
await user.click(swatches[3]);
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(bodies).toEqual([{ color: '#10b981' }]));
|
||||
});
|
||||
|
||||
it('FE-W5CNT-019: attaching a file while editing uploads it and refreshes the note', async () => {
|
||||
const user = userEvent.setup();
|
||||
let uploaded = 0;
|
||||
serveNotesSequence([
|
||||
{ notes: [buildNote({ id: 3, title: 'Edit me' })] },
|
||||
{ notes: [buildNote({ id: 3, title: 'Edited', attachments: [] })] },
|
||||
]);
|
||||
server.use(
|
||||
http.put('/api/trips/1/collab/notes/3', () =>
|
||||
HttpResponse.json({ note: buildNote({ id: 3, title: 'Edited' }) }),
|
||||
),
|
||||
http.post('/api/trips/1/collab/notes/3/files', () => {
|
||||
uploaded += 1;
|
||||
return HttpResponse.json({ file: { id: 2 } });
|
||||
}),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Edit me');
|
||||
await user.click(screen.getByTitle('Edit'));
|
||||
await screen.findByDisplayValue('Edit me');
|
||||
pasteFile('attachment.png');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await screen.findByText('Edited');
|
||||
expect(uploaded).toBe(1);
|
||||
expect(filesChanged).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-W5CNT-020: a failing upload during an edit reports an error', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotesSequence([
|
||||
{ notes: [buildNote({ id: 3, title: 'Edit me' })] },
|
||||
[buildNote({ id: 3, title: 'Ignored reload' })],
|
||||
]);
|
||||
server.use(
|
||||
http.put('/api/trips/1/collab/notes/3', () =>
|
||||
HttpResponse.json({ note: buildNote({ id: 3, title: 'Edit me' }) }),
|
||||
),
|
||||
http.post('/api/trips/1/collab/notes/3/files', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Edit me');
|
||||
await user.click(screen.getByTitle('Edit'));
|
||||
await screen.findByDisplayValue('Edit me');
|
||||
pasteFile('nope.png');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));
|
||||
expect(screen.queryByText('Ignored reload')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-021: a failing attachment removal reports an error', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotes({
|
||||
notes: [buildNote({
|
||||
id: 3,
|
||||
title: 'Has file',
|
||||
attachments: [{ id: 9, filename: 's.pdf', original_name: 'plan.pdf', mime_type: 'application/pdf', url: '/uploads/plan.pdf' }],
|
||||
})],
|
||||
});
|
||||
server.use(
|
||||
http.delete('/api/trips/1/collab/notes/3/files/9', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Has file');
|
||||
await user.click(screen.getByTitle('Edit'));
|
||||
const chip = (await screen.findByText('plan.pdf')).closest('div')!;
|
||||
await user.click(chip.querySelector('button')!);
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));
|
||||
expect(filesChanged).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-W5CNT-022: pinned notes sort first and notes without timestamps sort last', async () => {
|
||||
serveNotes({
|
||||
notes: [
|
||||
buildNote({ id: 1, title: 'No timestamps', updated_at: null, created_at: null }),
|
||||
buildNote({ id: 2, title: 'Pinned one', pinned: true }),
|
||||
buildNote({ id: 3, title: 'Created only', updated_at: null, created_at: '2025-06-02T10:00:00.000Z' }),
|
||||
buildNote({ id: 4, title: 'Also undated', updated_at: null, created_at: null }),
|
||||
],
|
||||
});
|
||||
const known = ['No timestamps', 'Pinned one', 'Created only', 'Also undated'];
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Pinned one');
|
||||
const titles = Array.from(document.querySelectorAll('span'))
|
||||
.filter(el => el.childElementCount === 0)
|
||||
.map(el => el.textContent)
|
||||
.filter(text => known.includes(text ?? ''));
|
||||
expect(titles).toEqual(['Pinned one', 'Created only', 'No timestamps', 'Also undated']);
|
||||
});
|
||||
|
||||
it('FE-W5CNT-023: clicking the active category pill clears the filter again', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotes({
|
||||
notes: [
|
||||
buildNote({ id: 1, title: 'Food note', category: 'Food', color: '#ef4444' }),
|
||||
buildNote({ id: 2, title: 'Plain note' }),
|
||||
],
|
||||
});
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Plain note');
|
||||
const pill = screen.getAllByRole('button').find(b => b.textContent === 'Food')!;
|
||||
await user.click(pill);
|
||||
await waitFor(() => expect(screen.queryByText('Plain note')).not.toBeInTheDocument());
|
||||
await user.click(pill);
|
||||
expect(await screen.findByText('Plain note')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-024: a narrow viewport lays the grid out in a single column', async () => {
|
||||
const original = window.innerWidth;
|
||||
Object.defineProperty(window, 'innerWidth', { value: 500, writable: true, configurable: true });
|
||||
try {
|
||||
serveNotes({ notes: [buildNote({ title: 'Mobile note' })] });
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Mobile note');
|
||||
const grid = document.querySelector('[style*="grid-template-columns"]') as HTMLElement;
|
||||
expect(grid.style.gridTemplateColumns).toBe('1fr');
|
||||
} finally {
|
||||
Object.defineProperty(window, 'innerWidth', { value: original, writable: true, configurable: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-W5CNT-025: the expanded note closes on a backdrop click and its buttons highlight on hover', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotes({ notes: [buildNote({ id: 5, title: 'Long note', content: 'Full body', category: 'Food', color: '#ef4444' })] });
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Long note');
|
||||
await user.click(screen.getByTitle('collab.notes.expand'));
|
||||
const modal = await waitFor(() => {
|
||||
const md = document.querySelector('.collab-note-md-full')
|
||||
if (!md) throw new Error('view modal not open yet')
|
||||
return md.closest('div[style*="position: fixed"]') as HTMLElement
|
||||
});
|
||||
expect(within(modal).getByText('Full body')).toBeInTheDocument();
|
||||
|
||||
const [editBtn, closeBtn] = Array.from(modal.querySelectorAll('button'));
|
||||
fireEvent.mouseEnter(editBtn);
|
||||
expect(editBtn.style.color).toBe('var(--text-primary)');
|
||||
fireEvent.mouseLeave(editBtn);
|
||||
expect(editBtn.style.color).toBe('var(--text-faint)');
|
||||
fireEvent.mouseEnter(closeBtn);
|
||||
expect(closeBtn.style.color).toBe('var(--text-primary)');
|
||||
fireEvent.mouseLeave(closeBtn);
|
||||
expect(closeBtn.style.color).toBe('var(--text-faint)');
|
||||
|
||||
fireEvent.click(modal);
|
||||
await waitFor(() => expect(document.querySelector('.collab-note-md-full')).toBeNull());
|
||||
});
|
||||
|
||||
it('FE-W5CNT-026: attachments in the expanded note open the preview and react to hover', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotes({
|
||||
notes: [buildNote({
|
||||
id: 6,
|
||||
title: 'Trip docs',
|
||||
content: 'See attachments',
|
||||
attachments: [
|
||||
{ id: 1, filename: 'a.png', original_name: 'map.png', mime_type: 'image/png', url: '/uploads/map.png' },
|
||||
{ id: 2, filename: 'b.zip', original_name: 'itinerary.zip', mime_type: 'application/zip', url: '/uploads/itinerary.zip' },
|
||||
{ id: 3, filename: 'c', url: '/uploads/c' },
|
||||
],
|
||||
})],
|
||||
});
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Trip docs');
|
||||
await user.click(screen.getByTitle('collab.notes.expand'));
|
||||
const modal = await waitFor(() => {
|
||||
const md = document.querySelector('.collab-note-md-full')
|
||||
if (!md) throw new Error('view modal not open yet')
|
||||
return md.closest('div[style*="position: fixed"]') as HTMLElement
|
||||
});
|
||||
|
||||
// Unknown mime type and missing name fall back to a "?" tile
|
||||
expect(within(modal).getByText('?')).toBeInTheDocument();
|
||||
|
||||
const zipTile = within(modal).getByTitle('itinerary.zip');
|
||||
expect(zipTile.style.background).toBe('var(--bg-secondary)');
|
||||
expect(within(modal).getByText('ZIP')).toBeInTheDocument();
|
||||
fireEvent.mouseEnter(zipTile);
|
||||
expect(zipTile.style.transform).toBe('scale(1.06)');
|
||||
fireEvent.mouseLeave(zipTile);
|
||||
expect(zipTile.style.transform).toBe('scale(1)');
|
||||
fireEvent.click(zipTile);
|
||||
// FilePreviewPortal shows a download action for non-image files
|
||||
expect(await screen.findByText('Download itinerary.zip')).toBeInTheDocument();
|
||||
|
||||
const image = await waitFor(() => {
|
||||
const img = modal.querySelector('img[alt="map.png"]') as HTMLImageElement | null;
|
||||
if (!img) throw new Error('image attachment not rendered yet');
|
||||
return img;
|
||||
});
|
||||
// The clickable thumbnail is a real button wrapped around the image, so the
|
||||
// hover transform lands on that button.
|
||||
const imageTile = image.closest('button') as HTMLElement;
|
||||
fireEvent.mouseEnter(imageTile);
|
||||
expect(imageTile.style.transform).toBe('scale(1.06)');
|
||||
fireEvent.mouseLeave(imageTile);
|
||||
expect(imageTile.style.transform).toBe('scale(1)');
|
||||
fireEvent.click(image);
|
||||
await waitFor(() => expect(screen.queryByText('Download itinerary.zip')).not.toBeInTheDocument());
|
||||
});
|
||||
it('FE-W5CNT-027: a create response for a note already in the list is not added twice', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotes({ notes: [buildNote({ id: 20, title: 'Fresh note' })] });
|
||||
server.use(
|
||||
http.post('/api/trips/1/collab/notes', () =>
|
||||
HttpResponse.json({ note: buildNote({ id: 20, title: 'Fresh note' }) }),
|
||||
),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Fresh note');
|
||||
await user.click(screen.getByText('New Note'));
|
||||
await user.type(await screen.findByPlaceholderText('Note title'), 'Fresh note');
|
||||
await user.click(screen.getByRole('button', { name: 'Create' }));
|
||||
await waitFor(() => expect(screen.queryByPlaceholderText('Note title')).not.toBeInTheDocument());
|
||||
expect(screen.getAllByText('Fresh note')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-W5CNT-028: a second note created elsewhere is prepended to the existing list', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotes({ notes: [buildNote({ id: 20, title: 'Older note' })] });
|
||||
server.use(
|
||||
http.post('/api/trips/1/collab/notes', () =>
|
||||
HttpResponse.json({ note: buildNote({ id: 21, title: 'Newer note' }) }),
|
||||
),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Older note');
|
||||
await user.click(screen.getByText('New Note'));
|
||||
await user.type(await screen.findByPlaceholderText('Note title'), 'Newer note');
|
||||
await user.click(screen.getByRole('button', { name: 'Create' }));
|
||||
await screen.findByText('Newer note');
|
||||
expect(screen.getByText('Older note')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-030: a WebSocket event for another trip is ignored', async () => {
|
||||
serveNotes({ notes: [] });
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('No notes yet');
|
||||
const handler = wsHandler();
|
||||
await act(async () => {
|
||||
handler({ tripId: 2, type: 'collab:note:created', note: buildNote({ id: 60, title: 'Other trip note' }) });
|
||||
});
|
||||
expect(screen.queryByText('Other trip note')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-031: a rejected rename still renames the rest and re-reads the list', async () => {
|
||||
const user = userEvent.setup();
|
||||
const puts: string[] = [];
|
||||
serveNotesSequence([
|
||||
{ notes: [buildNote({ id: 1, title: 'First note', category: 'OldCat' }), buildNote({ id: 2, title: 'Second note', category: 'OldCat' })] },
|
||||
{ notes: [buildNote({ id: 1, title: 'First note', category: 'OldCat' }), buildNote({ id: 2, title: 'Second note', category: 'NewCat' })] },
|
||||
]);
|
||||
server.use(
|
||||
http.put('/api/trips/1/collab/notes/1', () => {
|
||||
puts.push('1');
|
||||
return new HttpResponse(null, { status: 500 });
|
||||
}),
|
||||
http.put('/api/trips/1/collab/notes/2', () => {
|
||||
puts.push('2');
|
||||
return HttpResponse.json({ note: buildNote({ id: 2, title: 'Second note', category: 'NewCat' }) });
|
||||
}),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('First note');
|
||||
|
||||
await user.click(screen.getByTitle('Manage Categories'));
|
||||
await screen.findByText('Manage Categories', { selector: 'h3' });
|
||||
const oldCat = screen.getAllByText('OldCat').find(el => el.tagName === 'BUTTON' && el.title === 'Click to rename')!;
|
||||
await user.click(oldCat);
|
||||
const editInput = screen.getByDisplayValue('OldCat');
|
||||
await user.clear(editInput);
|
||||
await user.type(editInput, 'NewCat');
|
||||
await user.keyboard('{Enter}');
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/i }));
|
||||
|
||||
// The rejected note must not stop the second one, but the modal stays open —
|
||||
// half a rename is not a saved rename.
|
||||
await waitFor(() => expect(puts).toEqual(['1', '2']));
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));
|
||||
expect(screen.getByText('Manage Categories', { selector: 'h3' })).toBeInTheDocument();
|
||||
// Re-read: the note the server refused is still shown under its old category.
|
||||
const header = screen.getByText('Manage Categories', { selector: 'h3' }).parentElement!;
|
||||
await user.click(within(header).getByRole('button'));
|
||||
await waitFor(() => expect(screen.getAllByText('NewCat').length).toBeGreaterThan(0));
|
||||
expect(screen.getAllByText('OldCat').length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('FE-W5CNT-029: a failing delete reports an error and keeps the note in the list', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotes({ notes: [buildNote({ id: 30, title: 'Stubborn note' })] });
|
||||
server.use(
|
||||
http.delete('/api/trips/1/collab/notes/30', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('Stubborn note');
|
||||
|
||||
await user.click(screen.getByTitle('Delete'));
|
||||
const dialog = (await screen.findByText('Delete note?')).closest('div.trek-modal-enter') as HTMLElement;
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Delete' }));
|
||||
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));
|
||||
expect(screen.getByText('Stubborn note')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CNT-032: a rejected category rename keeps the settings modal open and reports once', async () => {
|
||||
const user = userEvent.setup();
|
||||
serveNotes({
|
||||
notes: [
|
||||
buildNote({ id: 1, title: 'First note', category: 'OldCat' }),
|
||||
buildNote({ id: 2, title: 'Second note', category: 'OldCat' }),
|
||||
],
|
||||
});
|
||||
server.use(
|
||||
http.put('/api/trips/1/collab/notes/:id', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
render(<CollabNotes {...defaultProps} />);
|
||||
await screen.findByText('First note');
|
||||
await user.click(screen.getByTitle('Manage Categories'));
|
||||
await screen.findByText('Manage Categories', { selector: 'h3' });
|
||||
|
||||
const oldCat = screen.getAllByText('OldCat').find(el => el.tagName === 'BUTTON' && el.title === 'Click to rename')!;
|
||||
await user.click(oldCat);
|
||||
const editInput = screen.getByDisplayValue('OldCat');
|
||||
await user.clear(editInput);
|
||||
await user.type(editInput, 'NewCat');
|
||||
await user.keyboard('{Enter}');
|
||||
await screen.findByText('NewCat');
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/i }));
|
||||
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));
|
||||
// Nothing was renamed, so the modal must not act like it was saved…
|
||||
expect(screen.getByText('Manage Categories', { selector: 'h3' })).toBeInTheDocument();
|
||||
// …and both rejected writes are one message, not one each.
|
||||
expect(addToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback, useMemo } from 'react'
|
||||
import Markdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import remarkBreaks from 'remark-breaks'
|
||||
import ReactDOM from 'react-dom'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { Plus, Pencil, X, StickyNote, Settings } from 'lucide-react'
|
||||
import { collabApi } from '../../api/client'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
@@ -11,6 +11,7 @@ import { addListener, removeListener } from '../../api/websocket'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import ConfirmDialog from '../shared/ConfirmDialog'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
import type { User } from '../../types'
|
||||
import type { CollabNote } from './CollabNotes.types'
|
||||
import { FONT, NOTE_COLORS } from './CollabNotes.constants'
|
||||
@@ -88,6 +89,9 @@ function useCollabNotes({ tripId, currentUser }: CollabNotesProps) {
|
||||
if (!tripId) return
|
||||
|
||||
const handler = (msg) => {
|
||||
// The panel is not remounted on a trip change, so an event still in flight
|
||||
// from the trip we just left must not land in this list.
|
||||
if (String(msg?.tripId) !== String(tripId)) return
|
||||
if (msg.type === 'collab:note:created' && msg.note) {
|
||||
setNotes(prev => {
|
||||
if (prev.some(n => n.id === msg.note.id)) return prev
|
||||
@@ -144,12 +148,13 @@ function useCollabNotes({ tripId, currentUser }: CollabNotesProps) {
|
||||
}
|
||||
}, [tripId, toast, t])
|
||||
|
||||
const handleUpdateNote = useCallback(async (noteId, data) => {
|
||||
const handleUpdateNote = useCallback(async (noteId, data, opts: { silent?: boolean } = {}) => {
|
||||
let result
|
||||
try {
|
||||
result = await collabApi.updateNote(tripId, noteId, data)
|
||||
} catch (err) {
|
||||
toast.error(t('common.error'))
|
||||
// A batch of writes reports once for the whole run instead of once per note.
|
||||
if (!opts.silent) toast.error(t('common.error'))
|
||||
throw err
|
||||
}
|
||||
const updated = result?.note || result
|
||||
@@ -160,16 +165,28 @@ function useCollabNotes({ tripId, currentUser }: CollabNotesProps) {
|
||||
}
|
||||
}, [tripId, toast, t])
|
||||
|
||||
// A colour or a rename is N single-note writes; if one of them is rejected the
|
||||
// rest still have to run, and the list has to be re-read so it stops showing a
|
||||
// change the server never took. Reporting the failure is the caller's job.
|
||||
const resyncNotes = useCallback(async () => {
|
||||
try {
|
||||
const fresh = await collabApi.getNotes(tripId)
|
||||
setNotes(fresh?.notes || fresh || [])
|
||||
} catch {}
|
||||
}, [tripId])
|
||||
|
||||
const saveCategoryColors = useCallback(async (newMap) => {
|
||||
let failed = 0
|
||||
// Update notes with changed colors
|
||||
for (const [cat, color] of Object.entries(newMap)) {
|
||||
const notesInCat = notes.filter(n => n.category === cat)
|
||||
if (notesInCat.length > 0 && categoryColors[cat] !== color) {
|
||||
for (const n of notesInCat) {
|
||||
await handleUpdateNote(n.id, { color })
|
||||
try { await handleUpdateNote(n.id, { color }) } catch { failed++ }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failed > 0) await resyncNotes()
|
||||
// Save all categories (including empty ones) to localStorage
|
||||
const emptyCats = {}
|
||||
for (const [cat, color] of Object.entries(newMap)) {
|
||||
@@ -178,7 +195,23 @@ function useCollabNotes({ tripId, currentUser }: CollabNotesProps) {
|
||||
}
|
||||
}
|
||||
saveEmptyCategories(emptyCats)
|
||||
}, [categoryColors, notes, handleUpdateNote])
|
||||
}, [categoryColors, notes, handleUpdateNote, resyncNotes])
|
||||
|
||||
const renameCategory = useCallback(async (oldName, newName) => {
|
||||
// Update all notes with this category in DB
|
||||
const toUpdate = notes.filter(n => n.category === oldName)
|
||||
let failed = 0
|
||||
for (const n of toUpdate) {
|
||||
try { await handleUpdateNote(n.id, { category: newName }, { silent: true }) } catch { failed++ }
|
||||
}
|
||||
// The rest still had to run, but a partial rename is not a saved rename: the
|
||||
// settings modal has to stay open on the rejection instead of closing on it.
|
||||
if (failed > 0) {
|
||||
await resyncNotes()
|
||||
toast.error(t('common.error'))
|
||||
throw new Error(`rename failed for ${failed} of ${toUpdate.length} notes`)
|
||||
}
|
||||
}, [notes, handleUpdateNote, resyncNotes, toast, t])
|
||||
|
||||
const handleEditSubmit = useCallback(async (data) => {
|
||||
if (!editingNote) return
|
||||
@@ -231,7 +264,7 @@ function useCollabNotes({ tripId, currentUser }: CollabNotesProps) {
|
||||
notes, loading, showNewModal, setShowNewModal, editingNote, setEditingNote,
|
||||
viewingNote, setViewingNote, previewFile, setPreviewFile, showSettings, setShowSettings,
|
||||
activeCategory, setActiveCategory, categoryColors, getCategoryColor,
|
||||
handleCreateNote, handleUpdateNote, saveCategoryColors, handleEditSubmit,
|
||||
handleCreateNote, handleUpdateNote, saveCategoryColors, renameCategory, handleEditSubmit,
|
||||
handleDeleteNoteFile, handleDeleteNote, categories, sortedNotes,
|
||||
pendingDeleteNoteId, setPendingDeleteNoteId,
|
||||
}
|
||||
@@ -270,13 +303,13 @@ function CollabNotesHeader({ t, canEdit, setShowSettings, setShowNewModal }: Not
|
||||
{t('collab.notes.title')}
|
||||
</h3>
|
||||
<div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
|
||||
{canEdit && <button onClick={() => setShowSettings(true)} title={t('collab.notes.categorySettings') || 'Categories'}
|
||||
{canEdit && <button type="button" onClick={() => setShowSettings(true)} title={t('collab.notes.categorySettings')}
|
||||
style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 28, height: 28, borderRadius: 8, border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--text-faint)', transition: 'color 0.12s' }}
|
||||
onMouseEnter={e => e.currentTarget.style.color = 'var(--text-primary)'}
|
||||
onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>
|
||||
<Settings size={14} />
|
||||
</button>}
|
||||
{canEdit && <button onClick={() => setShowNewModal(true)}
|
||||
{canEdit && <button type="button" onClick={() => setShowNewModal(true)}
|
||||
style={{ display: 'inline-flex', alignItems: 'center', gap: 4, borderRadius: 99, padding: '6px 12px', background: 'var(--accent)', color: 'var(--accent-text)', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600, fontFamily: FONT, border: 'none', cursor: 'pointer', whiteSpace: 'nowrap' }}>
|
||||
<Plus size={12} />
|
||||
{t('collab.notes.new')}
|
||||
@@ -289,7 +322,7 @@ function CollabNotesHeader({ t, canEdit, setShowSettings, setShowNewModal }: Not
|
||||
function CollabCategoryPills({ categories, activeCategory, setActiveCategory, t }: NotesState) {
|
||||
return (
|
||||
<div style={{ display: 'flex', gap: 4, padding: '8px 12px 0', overflowX: 'auto', flexShrink: 0 }}>
|
||||
<button
|
||||
<button type="button"
|
||||
onClick={() => setActiveCategory(null)}
|
||||
style={{
|
||||
flexShrink: 0, borderRadius: 99, padding: '3px 10px', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, fontFamily: FONT,
|
||||
@@ -302,7 +335,7 @@ function CollabCategoryPills({ categories, activeCategory, setActiveCategory, t
|
||||
{t('collab.notes.all')}
|
||||
</button>
|
||||
{categories.map(cat => (
|
||||
<button
|
||||
<button type="button"
|
||||
key={cat}
|
||||
onClick={() => setActiveCategory(prev => prev === cat ? null : cat)}
|
||||
style={{
|
||||
@@ -329,18 +362,7 @@ function CollabNotesGrid(S: NotesState) {
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: 12 }}>
|
||||
{sortedNotes.length === 0 ? (
|
||||
/* ── Empty state ── */
|
||||
<div style={{
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
|
||||
padding: '48px 20px', textAlign: 'center', height: '100%',
|
||||
}}>
|
||||
<Pencil size={36} color="var(--text-faint)" style={{ marginBottom: 12 }} />
|
||||
<div style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4, fontFamily: FONT }}>
|
||||
{t('collab.notes.empty')}
|
||||
</div>
|
||||
<div style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'var(--text-faint)', fontFamily: FONT }}>
|
||||
{t('collab.notes.emptyDesc') || 'Create a note to get started'}
|
||||
</div>
|
||||
</div>
|
||||
<EmptyState scene="notes" title={t('collab.notes.empty')} />
|
||||
) : (
|
||||
/* ── Notes grid — 2 columns ── */
|
||||
<div style={{
|
||||
@@ -373,7 +395,7 @@ function CollabNotesGrid(S: NotesState) {
|
||||
function ViewNoteModal(S: NotesState) {
|
||||
const { viewingNote, setViewingNote, canEdit, setEditingNote, getCategoryColor, t, setPreviewFile } = S
|
||||
if (!viewingNote) return null
|
||||
return ReactDOM.createPortal(
|
||||
return createPortal(
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
|
||||
@@ -381,7 +403,8 @@ function ViewNoteModal(S: NotesState) {
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
zIndex: 10000, padding: 16,
|
||||
}}
|
||||
onClick={() => setViewingNote(null)}
|
||||
role="presentation"
|
||||
onClick={e => { if (e.target === e.currentTarget) setViewingNote(null) }}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
@@ -390,7 +413,6 @@ function ViewNoteModal(S: NotesState) {
|
||||
width: 'min(700px, calc(100vw - 32px))', maxHeight: '80vh',
|
||||
overflow: 'hidden', display: 'flex', flexDirection: 'column',
|
||||
}}
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
<div style={{
|
||||
padding: '16px 20px 12px', borderBottom: '1px solid var(--border-primary)',
|
||||
@@ -408,13 +430,13 @@ function ViewNoteModal(S: NotesState) {
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
|
||||
{canEdit && <button onClick={() => { setViewingNote(null); setEditingNote(viewingNote) }}
|
||||
{canEdit && <button type="button" onClick={() => { setViewingNote(null); setEditingNote(viewingNote) }}
|
||||
style={{ padding: 6, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex', borderRadius: 6 }}
|
||||
onMouseEnter={e => e.currentTarget.style.color = 'var(--text-primary)'}
|
||||
onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>
|
||||
<Pencil size={16} />
|
||||
</button>}
|
||||
<button onClick={() => setViewingNote(null)}
|
||||
<button type="button" onClick={() => setViewingNote(null)}
|
||||
style={{ padding: 6, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex', borderRadius: 6 }}
|
||||
onMouseEnter={e => e.currentTarget.style.color = 'var(--text-primary)'}
|
||||
onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>
|
||||
@@ -440,17 +462,18 @@ function ViewNoteModal(S: NotesState) {
|
||||
onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.06)'; e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = 'none' }} />
|
||||
) : (
|
||||
<div title={a.original_name} onClick={() => setPreviewFile(a)}
|
||||
<button type="button" title={a.original_name} onClick={() => setPreviewFile(a)}
|
||||
style={{
|
||||
width: 64, height: 64, borderRadius: 8, cursor: 'pointer',
|
||||
background: a.mime_type === 'application/pdf' ? '#ef44441a' : 'var(--bg-secondary)',
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 1,
|
||||
transition: 'transform 0.12s, box-shadow 0.12s',
|
||||
border: 'none', padding: 0, fontFamily: 'inherit',
|
||||
}}
|
||||
onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.06)'; e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = 'none' }}>
|
||||
<span style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 700, color: a.mime_type === 'application/pdf' ? '#ef4444' : 'var(--text-muted)', letterSpacing: 0.3 }}>{ext}</span>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
<span style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', textAlign: 'center', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', width: '100%' }}>{a.original_name}</span>
|
||||
</div>
|
||||
@@ -472,7 +495,7 @@ export default function CollabNotes(props: CollabNotesProps) {
|
||||
loading, tripId, t, categories, categoryColors, getCategoryColor, notes,
|
||||
viewingNote, showNewModal, editingNote, previewFile, showSettings,
|
||||
setShowNewModal, setEditingNote, setPreviewFile, setShowSettings,
|
||||
handleCreateNote, handleEditSubmit, handleDeleteNoteFile, saveCategoryColors, handleUpdateNote,
|
||||
handleCreateNote, handleEditSubmit, handleDeleteNoteFile, saveCategoryColors, renameCategory, handleUpdateNote,
|
||||
handleDeleteNote, pendingDeleteNoteId, setPendingDeleteNoteId,
|
||||
} = S
|
||||
|
||||
@@ -521,13 +544,7 @@ export default function CollabNotes(props: CollabNotesProps) {
|
||||
categories={categories}
|
||||
categoryColors={categoryColors}
|
||||
onSave={saveCategoryColors}
|
||||
onRenameCategory={async (oldName, newName) => {
|
||||
// Update all notes with this category in DB
|
||||
const toUpdate = notes.filter(n => n.category === oldName)
|
||||
for (const n of toUpdate) {
|
||||
await handleUpdateNote(n.id, { category: newName })
|
||||
}
|
||||
}}
|
||||
onRenameCategory={renameCategory}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
@@ -536,7 +553,8 @@ export default function CollabNotes(props: CollabNotesProps) {
|
||||
<ConfirmDialog
|
||||
isOpen={pendingDeleteNoteId !== null}
|
||||
onClose={() => setPendingDeleteNoteId(null)}
|
||||
onConfirm={() => { if (pendingDeleteNoteId !== null) handleDeleteNote(pendingDeleteNoteId) }}
|
||||
// Hand the promise back so the dialog absorbs the rethrow of a failed DELETE.
|
||||
onConfirm={() => (pendingDeleteNoteId !== null ? handleDeleteNote(pendingDeleteNoteId) : undefined)}
|
||||
title={t('collab.notes.confirmDeleteTitle')}
|
||||
message={t('collab.notes.confirmDeleteBody')}
|
||||
/>
|
||||
|
||||
@@ -1,10 +1,22 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { getAuthUrl } from '../../api/authUrl'
|
||||
|
||||
export function AuthedImg({ src, style, onClick, onMouseEnter, onMouseLeave, alt }: { src: string; style?: React.CSSProperties; onClick?: () => void; onMouseEnter?: React.MouseEventHandler<HTMLImageElement>; onMouseLeave?: React.MouseEventHandler<HTMLImageElement>; alt?: string }) {
|
||||
export function AuthedImg({ src, style, onClick, onMouseEnter, onMouseLeave, alt }: { src: string; style?: React.CSSProperties; onClick?: () => void; onMouseEnter?: React.MouseEventHandler<HTMLElement>; onMouseLeave?: React.MouseEventHandler<HTMLElement>; alt?: string }) {
|
||||
const [authSrc, setAuthSrc] = useState('')
|
||||
useEffect(() => {
|
||||
getAuthUrl(src, 'download').then(setAuthSrc)
|
||||
}, [src])
|
||||
return authSrc ? <img src={authSrc} alt={alt} style={style} onClick={onClick} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} /> : null
|
||||
if (!authSrc) return null
|
||||
// A clickable thumbnail gets a real button around the image so it is
|
||||
// reachable by keyboard. The caller's style stays on the outer box, so the
|
||||
// hover transform/transition still animates the element that carries them.
|
||||
if (onClick) {
|
||||
return (
|
||||
<button type="button" onClick={onClick} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}
|
||||
style={{ ...style, padding: 0, border: 'none', background: 'none', display: 'block' }}>
|
||||
<img src={authSrc} alt={alt} style={{ ...style, width: '100%', height: '100%', display: 'block' }} />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
return <img src={authSrc} alt={alt} style={style} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} />
|
||||
}
|
||||
|
||||
@@ -80,26 +80,26 @@ export function NoteCard({ note, currentUser, canEdit, onUpdate, onDelete, onEdi
|
||||
display: 'flex', gap: 2,
|
||||
}}>
|
||||
{note.content && (
|
||||
<button onClick={() => onView?.(note)} title={t('collab.notes.expand') || 'Expand'}
|
||||
<button type="button" onClick={() => onView?.(note)} title={t('collab.notes.expand') || 'Expand'}
|
||||
style={{ padding: 3, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex' }}
|
||||
onMouseEnter={e => e.currentTarget.style.color = 'var(--text-primary)'}
|
||||
onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>
|
||||
<Maximize2 size={10} />
|
||||
</button>
|
||||
)}
|
||||
{canEdit && <button onClick={handleTogglePin} title={note.pinned ? t('collab.notes.unpin') : t('collab.notes.pin')}
|
||||
{canEdit && <button type="button" onClick={handleTogglePin} title={note.pinned ? t('collab.notes.unpin') : t('collab.notes.pin')}
|
||||
style={{ padding: 3, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex' }}
|
||||
onMouseEnter={e => e.currentTarget.style.color = color}
|
||||
onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>
|
||||
{note.pinned ? <PinOff size={10} /> : <Pin size={10} />}
|
||||
</button>}
|
||||
{canEdit && <button onClick={() => onEdit?.(note)} title={t('collab.notes.edit')}
|
||||
{canEdit && <button type="button" onClick={() => onEdit?.(note)} title={t('collab.notes.edit')}
|
||||
style={{ padding: 3, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex' }}
|
||||
onMouseEnter={e => e.currentTarget.style.color = 'var(--text-primary)'}
|
||||
onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>
|
||||
<Pencil size={10} />
|
||||
</button>}
|
||||
{canEdit && <button onClick={handleDelete} title={t('collab.notes.delete')}
|
||||
{canEdit && <button type="button" onClick={handleDelete} title={t('collab.notes.delete')}
|
||||
style={{ padding: 3, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex' }}
|
||||
onMouseEnter={e => e.currentTarget.style.color = '#ef4444'}
|
||||
onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>
|
||||
@@ -171,17 +171,18 @@ export function NoteCard({ note, currentUser, canEdit, onUpdate, onDelete, onEdi
|
||||
onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.08)'; e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = 'none' }} />
|
||||
) : (
|
||||
<div key={a.id} title={a.original_name} onClick={() => onPreviewFile?.(a)}
|
||||
<button type="button" key={a.id} title={a.original_name} aria-label={a.original_name} onClick={() => onPreviewFile?.(a)}
|
||||
style={{
|
||||
width: 48, height: 48, borderRadius: 8, cursor: 'pointer',
|
||||
background: a.mime_type === 'application/pdf' ? '#ef44441a' : 'var(--bg-secondary)',
|
||||
border: 'none', padding: 0, fontFamily: 'inherit',
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 1,
|
||||
transition: 'transform 0.12s, box-shadow 0.12s',
|
||||
}}
|
||||
onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.08)'; e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = 'none' }}>
|
||||
<span style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))', fontWeight: 700, color: a.mime_type === 'application/pdf' ? '#ef4444' : 'var(--text-muted)', letterSpacing: 0.3 }}>{ext}</span>
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{(note.attachments?.length || 0) > (note.website ? 1 : 2) && (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import ReactDOM from 'react-dom'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useState } from 'react'
|
||||
import { Plus, Trash2, X } from 'lucide-react'
|
||||
import { FONT, NOTE_COLORS } from './CollabNotes.constants'
|
||||
@@ -48,9 +48,14 @@ export function CategorySettingsModal({ onClose, categories, categoryColors, onS
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
// Apply renames to notes in DB
|
||||
for (const [oldName, newName] of Object.entries(renames)) {
|
||||
if (oldName !== newName) await onRenameCategory(oldName, newName)
|
||||
// Apply renames to notes in DB. A rejected rename keeps the modal open — closing
|
||||
// it would look like the rename went through; the caller has already reported it.
|
||||
try {
|
||||
for (const [oldName, newName] of Object.entries(renames)) {
|
||||
if (oldName !== newName) await onRenameCategory(oldName, newName)
|
||||
}
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
await onSave(localColors)
|
||||
onClose()
|
||||
@@ -59,22 +64,22 @@ export function CategorySettingsModal({ onClose, categories, categoryColors, onS
|
||||
// Merge existing categories from notes with saved colors
|
||||
const allCats = [...new Set([...categories, ...Object.keys(localColors)])]
|
||||
|
||||
return ReactDOM.createPortal(
|
||||
return createPortal(
|
||||
<div style={{
|
||||
position: 'fixed', inset: 0, background: 'var(--overlay-bg, rgba(0,0,0,0.35))',
|
||||
backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999, padding: 16, fontFamily: FONT,
|
||||
}} onClick={onClose}>
|
||||
}} role="presentation" onClick={onClose}>
|
||||
<div style={{
|
||||
background: 'var(--bg-card)', borderRadius: 16, width: '100%', maxWidth: 420,
|
||||
maxHeight: '80vh', overflow: 'auto', border: '1px solid var(--border-faint)',
|
||||
}} onClick={e => e.stopPropagation()}>
|
||||
}} role="presentation" onClick={e => e.stopPropagation()}>
|
||||
{/* Header */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px 12px', borderBottom: '1px solid var(--border-faint)' }}>
|
||||
<h3 style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 700, color: 'var(--text-primary)', margin: 0 }}>
|
||||
{t('collab.notes.categorySettings') || 'Category Settings'}
|
||||
</h3>
|
||||
<button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', padding: 2, display: 'flex' }}>
|
||||
<button type="button" onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', padding: 2, display: 'flex' }}>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
@@ -91,7 +96,7 @@ export function CategorySettingsModal({ onClose, categories, categoryColors, onS
|
||||
{/* Color swatches */}
|
||||
<div style={{ display: 'flex', gap: 4 }}>
|
||||
{NOTE_COLORS.map(c => (
|
||||
<button key={c.value} onClick={() => handleColorChange(cat, c.value)} style={{
|
||||
<button type="button" key={c.value} onClick={() => handleColorChange(cat, c.value)} style={{
|
||||
width: 20, height: 20, borderRadius: 6, background: c.value, border: 'none', cursor: 'pointer', padding: 0,
|
||||
outline: (localColors[cat] || NOTE_COLORS[0].value) === c.value ? '2px solid var(--text-primary)' : '2px solid transparent',
|
||||
outlineOffset: 1, transition: 'transform 0.1s',
|
||||
@@ -102,7 +107,7 @@ export function CategorySettingsModal({ onClose, categories, categoryColors, onS
|
||||
{/* Category name — editable */}
|
||||
<EditableCatName name={cat} onRename={(newName) => handleRenameCategory(cat, newName)} />
|
||||
{/* Delete */}
|
||||
<button onClick={() => handleRemoveCategory(cat)} style={{
|
||||
<button type="button" onClick={() => handleRemoveCategory(cat)} style={{
|
||||
background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', padding: 3, display: 'flex',
|
||||
}}
|
||||
onMouseEnter={e => e.currentTarget.style.color = '#ef4444'}
|
||||
@@ -121,7 +126,7 @@ export function CategorySettingsModal({ onClose, categories, categoryColors, onS
|
||||
flex: 1, border: '1px solid var(--border-primary)', borderRadius: 10, padding: '8px 12px',
|
||||
fontSize: 'calc(13px * var(--fs-scale-body, 1))', background: 'var(--bg-input)', color: 'var(--text-primary)', fontFamily: 'inherit', outline: 'none',
|
||||
}} />
|
||||
<button onClick={handleAddCategory} disabled={!newCatName.trim()} style={{
|
||||
<button type="button" onClick={handleAddCategory} disabled={!newCatName.trim()} style={{
|
||||
background: newCatName.trim() ? 'var(--accent)' : 'var(--border-primary)', color: 'var(--accent-text)',
|
||||
border: 'none', borderRadius: 10, padding: '8px 14px', cursor: newCatName.trim() ? 'pointer' : 'default',
|
||||
display: 'flex', alignItems: 'center', flexShrink: 0,
|
||||
@@ -131,7 +136,7 @@ export function CategorySettingsModal({ onClose, categories, categoryColors, onS
|
||||
</div>
|
||||
|
||||
{/* Save */}
|
||||
<button onClick={handleSave} style={{
|
||||
<button type="button" onClick={handleSave} style={{
|
||||
width: '100%', borderRadius: 99, padding: '9px 14px', background: 'var(--accent)', color: 'var(--accent-text)',
|
||||
fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600, border: 'none', cursor: 'pointer', marginTop: 8,
|
||||
}}>
|
||||
|
||||
@@ -25,10 +25,10 @@ export function EditableCatName({ name, onRename }: EditableCatNameProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<span onClick={() => { setValue(name); setEditing(true) }}
|
||||
style={{ flex: 1, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-primary)', cursor: 'pointer', padding: '2px 0' }}
|
||||
<button type="button" onClick={() => { setValue(name); setEditing(true) }}
|
||||
style={{ flex: 1, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-primary)', cursor: 'pointer', padding: '2px 0', background: 'none', border: 'none', textAlign: 'left', fontFamily: 'inherit' }}
|
||||
title="Click to rename">
|
||||
{name}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import ReactDOM from 'react-dom'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { X, ExternalLink, Loader2 } from 'lucide-react'
|
||||
import { getAuthUrl } from '../../api/authUrl'
|
||||
@@ -27,11 +27,11 @@ export function FilePreviewPortal({ file, onClose }: FilePreviewPortalProps) {
|
||||
|
||||
const openInNewTab = () => openFile(rawUrl).catch(() => {})
|
||||
|
||||
return ReactDOM.createPortal(
|
||||
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.88)', zIndex: 10000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }} onClick={onClose}>
|
||||
return createPortal(
|
||||
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.88)', zIndex: 10000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }} role="presentation" onClick={onClose}>
|
||||
{isImage ? (
|
||||
/* Image lightbox — floating controls */
|
||||
<div style={{ position: 'relative', maxWidth: '90vw', maxHeight: '90vh' }} onClick={e => e.stopPropagation()}>
|
||||
<div style={{ position: 'relative', maxWidth: '90vw', maxHeight: '90vh' }} role="presentation" onClick={e => e.stopPropagation()}>
|
||||
{authUrl
|
||||
? <img src={authUrl} alt={file.original_name} style={{ maxWidth: '90vw', maxHeight: '90vh', objectFit: 'contain', borderRadius: 8, display: 'block' }} />
|
||||
: <Loader2 size={32} className="animate-spin text-[rgba(255,255,255,0.5)]" />
|
||||
@@ -39,30 +39,30 @@ export function FilePreviewPortal({ file, onClose }: FilePreviewPortalProps) {
|
||||
<div style={{ position: 'absolute', top: -36, left: 0, right: 0, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 4px' }}>
|
||||
<span style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'rgba(255,255,255,0.7)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '70%' }}>{file.original_name}</span>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button onClick={openInNewTab} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'rgba(255,255,255,0.7)', display: 'flex', padding: 0 }}><ExternalLink size={15} /></button>
|
||||
<button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'rgba(255,255,255,0.7)', display: 'flex', padding: 0 }}><X size={17} /></button>
|
||||
<button type="button" onClick={openInNewTab} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'rgba(255,255,255,0.7)', display: 'flex', padding: 0 }}><ExternalLink size={15} /></button>
|
||||
<button type="button" onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'rgba(255,255,255,0.7)', display: 'flex', padding: 0 }}><X size={17} /></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
/* Document viewer — card with header */
|
||||
<div style={{ width: '100%', maxWidth: 950, height: '94vh', display: 'flex', flexDirection: 'column', background: 'var(--bg-card)', borderRadius: 12, overflow: 'hidden', boxShadow: '0 20px 60px rgba(0,0,0,0.3)' }} onClick={e => e.stopPropagation()}>
|
||||
<div style={{ width: '100%', maxWidth: 950, height: '94vh', display: 'flex', flexDirection: 'column', background: 'var(--bg-card)', borderRadius: 12, overflow: 'hidden', boxShadow: '0 20px 60px rgba(0,0,0,0.3)' }} role="presentation" onClick={e => e.stopPropagation()}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 16px', borderBottom: '1px solid var(--border-primary)', flexShrink: 0 }}>
|
||||
<span style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>{file.original_name}</span>
|
||||
<div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
|
||||
<button onClick={openInNewTab} style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 3, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-muted)', padding: 0 }}><ExternalLink size={13} /></button>
|
||||
<button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex', padding: 2 }}><X size={18} /></button>
|
||||
<button type="button" onClick={openInNewTab} style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 3, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-muted)', padding: 0 }}><ExternalLink size={13} /></button>
|
||||
<button type="button" onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex', padding: 2 }}><X size={18} /></button>
|
||||
</div>
|
||||
</div>
|
||||
{(isPdf || isTxt) ? (
|
||||
<object data={authUrl ? `${authUrl}#view=FitH` : ''} type={file.mime_type} style={{ flex: 1, width: '100%', border: 'none', background: '#fff' }} title={file.original_name}>
|
||||
<p style={{ padding: 24, textAlign: 'center', color: 'var(--text-muted)' }}>
|
||||
<button onClick={openInNewTab} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-primary)', textDecoration: 'underline', fontSize: 'calc(14px * var(--fs-scale-body, 1))', padding: 0 }}>Download</button>
|
||||
<button type="button" onClick={openInNewTab} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-primary)', textDecoration: 'underline', fontSize: 'calc(14px * var(--fs-scale-body, 1))', padding: 0 }}>Download</button>
|
||||
</p>
|
||||
</object>
|
||||
) : (
|
||||
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40 }}>
|
||||
<button onClick={openInNewTab} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-primary)', textDecoration: 'underline', fontSize: 'calc(14px * var(--fs-scale-body, 1))', padding: 0 }}>Download {file.original_name}</button>
|
||||
<button type="button" onClick={openInNewTab} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-primary)', textDecoration: 'underline', fontSize: 'calc(14px * var(--fs-scale-body, 1))', padding: 0 }}>Download {file.original_name}</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
// FE-W5CNF-001 to FE-W5CNF-021
|
||||
// NoteFormModal takes everything it needs as props, so the tests drive it
|
||||
// directly rather than through CollabNotes.
|
||||
|
||||
import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { usePermissionsStore } from '../../store/permissionsStore'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
import { buildUser, buildTrip } from '../../../tests/helpers/factories'
|
||||
import { NoteFormModal } from './CollabNotesFormModal'
|
||||
import type { CollabNote, NoteFile } from './CollabNotes.types'
|
||||
|
||||
const identity = (key: string) => key
|
||||
|
||||
function buildAttachment(overrides: Partial<NoteFile> = {}): NoteFile {
|
||||
return {
|
||||
id: 1,
|
||||
filename: 'stored.png',
|
||||
original_name: 'photo.png',
|
||||
mime_type: 'image/png',
|
||||
url: '/uploads/collab/photo.png',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function buildNote(overrides: Partial<CollabNote> = {}): CollabNote {
|
||||
return {
|
||||
id: 42,
|
||||
trip_id: 1,
|
||||
title: 'Existing note',
|
||||
content: 'Existing content',
|
||||
category: 'Food',
|
||||
website: 'https://example.com',
|
||||
pinned: false,
|
||||
color: '#6366f1',
|
||||
username: 'tester',
|
||||
avatar_url: null,
|
||||
avatar: null,
|
||||
user_id: 1,
|
||||
created_at: '2025-06-01T10:00:00.000Z',
|
||||
attachments: [],
|
||||
...overrides,
|
||||
} as CollabNote
|
||||
}
|
||||
|
||||
interface ModalOverrides {
|
||||
note?: CollabNote | null
|
||||
onClose?: () => void
|
||||
onSubmit?: (data: Record<string, unknown>) => Promise<void>
|
||||
onDeleteFile?: (noteId: number, fileId: number) => Promise<void>
|
||||
existingCategories?: string[]
|
||||
categoryColors?: Record<string, string>
|
||||
t?: (key: string) => string
|
||||
}
|
||||
|
||||
function renderModal(overrides: ModalOverrides = {}) {
|
||||
const onSubmit = overrides.onSubmit ?? vi.fn(async () => {})
|
||||
const onClose = overrides.onClose ?? vi.fn(() => {})
|
||||
render(
|
||||
<NoteFormModal
|
||||
note={overrides.note ?? null}
|
||||
tripId={1}
|
||||
onClose={onClose}
|
||||
onSubmit={onSubmit as unknown as React.ComponentProps<typeof NoteFormModal>['onSubmit']}
|
||||
onDeleteFile={overrides.onDeleteFile}
|
||||
existingCategories={overrides.existingCategories ?? []}
|
||||
categoryColors={overrides.categoryColors as Record<string, string>}
|
||||
getCategoryColor={(cat: string) => (cat === 'Food' ? '#ef4444' : '#6366f1')}
|
||||
t={overrides.t ?? identity}
|
||||
/>,
|
||||
)
|
||||
return { onSubmit, onClose }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores()
|
||||
seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true })
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1, user_id: 1 }) })
|
||||
})
|
||||
|
||||
describe('NoteFormModal', () => {
|
||||
it('FE-W5CNF-001: falls back to an empty color map when none is supplied', () => {
|
||||
renderModal({ existingCategories: ['Food'] })
|
||||
expect(screen.getByRole('button', { name: 'Food' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-002: submitting with a blank title does nothing', async () => {
|
||||
const { onSubmit, onClose } = renderModal()
|
||||
const form = document.querySelector('form')!
|
||||
fireEvent.submit(form)
|
||||
await waitFor(() => expect(onSubmit).not.toHaveBeenCalled())
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-003: a filled-in note is submitted trimmed and the modal closes', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onSubmit, onClose } = renderModal({ existingCategories: ['Food'] })
|
||||
await user.type(screen.getByPlaceholderText('collab.notes.titlePlaceholder'), ' Dinner ')
|
||||
await user.type(screen.getByPlaceholderText('collab.notes.contentPlaceholder'), 'Book a table')
|
||||
await user.type(screen.getByPlaceholderText('collab.notes.websitePlaceholder'), ' https://trek.test ')
|
||||
await user.click(screen.getByRole('button', { name: 'collab.notes.create' }))
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
|
||||
expect(onSubmit).toHaveBeenCalledWith({
|
||||
title: 'Dinner',
|
||||
content: 'Book a table',
|
||||
category: 'Food',
|
||||
color: '#ef4444',
|
||||
website: 'https://trek.test',
|
||||
_pendingFiles: [],
|
||||
})
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-004: a note without a category submits null instead of an empty string', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onSubmit } = renderModal()
|
||||
await user.type(screen.getByPlaceholderText('collab.notes.titlePlaceholder'), 'Loose note')
|
||||
await user.click(screen.getByRole('button', { name: 'collab.notes.create' }))
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalled())
|
||||
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ category: null, website: null }))
|
||||
})
|
||||
|
||||
it('FE-W5CNF-005: a rejected submit keeps the modal open and re-enables the button', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onSubmit = vi.fn(async () => { throw new Error('boom') })
|
||||
const { onClose } = renderModal({ onSubmit })
|
||||
await user.type(screen.getByPlaceholderText('collab.notes.titlePlaceholder'), 'Fails')
|
||||
const submit = screen.getByRole('button', { name: 'collab.notes.create' })
|
||||
await user.click(submit)
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalled())
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
expect(submit).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-006: edit mode prefills the fields and uses the save label', () => {
|
||||
renderModal({ note: buildNote() })
|
||||
expect(screen.getByDisplayValue('Existing note')).toBeInTheDocument()
|
||||
expect(screen.getByDisplayValue('Existing content')).toBeInTheDocument()
|
||||
expect(screen.getByDisplayValue('https://example.com')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'collab.notes.save' })).toBeInTheDocument()
|
||||
expect(screen.getByText('collab.notes.edit')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-007: the close button calls back without submitting', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onClose, onSubmit } = renderModal()
|
||||
const header = screen.getByText('collab.notes.new').parentElement!
|
||||
await user.click(header.querySelector('button')!)
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
expect(onSubmit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-008: picking another category marks it active and submits it', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onSubmit } = renderModal({
|
||||
existingCategories: ['Food'],
|
||||
categoryColors: { Sights: '#6366f1' },
|
||||
})
|
||||
const sights = screen.getByRole('button', { name: 'Sights' })
|
||||
expect(sights.style.background).toBe('transparent')
|
||||
await user.click(sights)
|
||||
expect(sights.style.background).toBe('rgba(99, 102, 241, 0.094)')
|
||||
await user.type(screen.getByPlaceholderText('collab.notes.titlePlaceholder'), 'Museum')
|
||||
await user.click(screen.getByRole('button', { name: 'collab.notes.create' }))
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalled())
|
||||
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ category: 'Sights' }))
|
||||
})
|
||||
|
||||
it('FE-W5CNF-009: pasting an image attaches it as a pending file', () => {
|
||||
renderModal()
|
||||
const file = new File(['x'], 'pasted.png', { type: 'image/png' })
|
||||
fireEvent.paste(document.querySelector('form')!, {
|
||||
clipboardData: { items: [{ type: 'image/png', getAsFile: () => file }] },
|
||||
})
|
||||
expect(screen.getByText('pasted.png')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-010: pasting a PDF after a non-file item attaches the PDF', () => {
|
||||
renderModal()
|
||||
const file = new File(['%PDF'], 'itinerary.pdf', { type: 'application/pdf' })
|
||||
fireEvent.paste(document.querySelector('form')!, {
|
||||
clipboardData: {
|
||||
items: [
|
||||
{ type: 'text/plain', getAsFile: () => null },
|
||||
{ type: 'application/pdf', getAsFile: () => file },
|
||||
],
|
||||
},
|
||||
})
|
||||
expect(screen.getByText('itinerary.pdf')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-011: a paste whose item yields no file attaches nothing', () => {
|
||||
renderModal()
|
||||
fireEvent.paste(document.querySelector('form')!, {
|
||||
clipboardData: { items: [{ type: 'image/png', getAsFile: () => null }] },
|
||||
})
|
||||
expect(screen.queryByText(/\.png$/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-012: a paste without clipboard items is ignored', () => {
|
||||
renderModal()
|
||||
fireEvent.paste(document.querySelector('form')!, { clipboardData: {} })
|
||||
expect(screen.getByPlaceholderText('collab.notes.titlePlaceholder')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-013: without upload rights the file section is hidden and paste is ignored', () => {
|
||||
seedStore(usePermissionsStore, { permissions: { file_upload: 'admin' } })
|
||||
renderModal()
|
||||
expect(screen.queryByText('collab.notes.attachFiles')).not.toBeInTheDocument()
|
||||
const file = new File(['x'], 'blocked.png', { type: 'image/png' })
|
||||
fireEvent.paste(document.querySelector('form')!, {
|
||||
clipboardData: { items: [{ type: 'image/png', getAsFile: () => file }] },
|
||||
})
|
||||
expect(screen.queryByText('blocked.png')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-014: choosing files through the picker lists them and long names are truncated', () => {
|
||||
renderModal()
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement
|
||||
const longName = 'an-extremely-long-attachment-name.pdf'
|
||||
fireEvent.change(input, {
|
||||
target: {
|
||||
files: [
|
||||
new File(['a'], 'short.png', { type: 'image/png' }),
|
||||
new File(['b'], longName, { type: 'application/pdf' }),
|
||||
],
|
||||
},
|
||||
})
|
||||
expect(screen.getByText('short.png')).toBeInTheDocument()
|
||||
expect(screen.getByText(`${longName.slice(0, 17)}...`)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-015: an empty file selection changes nothing', () => {
|
||||
renderModal()
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement
|
||||
fireEvent.change(input, { target: { files: [] } })
|
||||
expect(screen.queryByText(/\.png$/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-016: a pending file can be removed again', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderModal()
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement
|
||||
fireEvent.change(input, { target: { files: [new File(['a'], 'remove-me.png', { type: 'image/png' })] } })
|
||||
const chip = screen.getByText('remove-me.png').closest('div')!
|
||||
await user.click(chip.querySelector('button')!)
|
||||
expect(screen.queryByText('remove-me.png')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-017: the add button opens the hidden file picker', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderModal()
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement
|
||||
const clickSpy = vi.spyOn(input, 'click').mockImplementation(() => {})
|
||||
await user.click(screen.getByRole('button', { name: 'files.attach' }))
|
||||
expect(clickSpy).toHaveBeenCalled()
|
||||
clickSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-018: the add button falls back to an English label', () => {
|
||||
renderModal({ t: (key: string) => (key === 'files.attach' ? '' : key) })
|
||||
expect(screen.getByRole('button', { name: 'Add' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-019: deleting an existing attachment calls back and drops the chip', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onDeleteFile = vi.fn(async () => {})
|
||||
renderModal({
|
||||
note: buildNote({
|
||||
attachments: [
|
||||
buildAttachment({ id: 7, original_name: 'a-really-long-attachment-name.pdf', mime_type: 'application/pdf' }),
|
||||
],
|
||||
}),
|
||||
onDeleteFile,
|
||||
})
|
||||
const chip = screen.getByText('a-really-long-att...').closest('div')!
|
||||
await user.click(chip.querySelector('button')!)
|
||||
await waitFor(() => expect(onDeleteFile).toHaveBeenCalledWith(42, 7))
|
||||
expect(screen.queryByText('a-really-long-att...')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-020: an attachment without a delete handler stays in the list', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderModal({ note: buildNote({ attachments: [buildAttachment({ id: 9 })] }) })
|
||||
const chip = screen.getByText('photo.png').closest('div')!
|
||||
await user.click(chip.querySelector('button')!)
|
||||
expect(screen.getByText('photo.png')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CNF-021: an attachment without an original name renders an empty label', () => {
|
||||
renderModal({
|
||||
note: buildNote({
|
||||
attachments: [buildAttachment({ id: 11, original_name: undefined as unknown as string, mime_type: 'text/plain' })],
|
||||
}),
|
||||
})
|
||||
const section = screen.getByText('collab.notes.attachFiles').parentElement!
|
||||
expect(section.querySelectorAll('img').length).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import ReactDOM from 'react-dom'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useState, useRef } from 'react'
|
||||
import { Plus, X } from 'lucide-react'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
@@ -67,7 +67,7 @@ export function NoteFormModal({ onClose, onSubmit, onDeleteFile, existingCategor
|
||||
|
||||
const canSubmit = title.trim() && !submitting
|
||||
|
||||
return ReactDOM.createPortal(
|
||||
return createPortal(
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
@@ -84,6 +84,7 @@ export function NoteFormModal({ onClose, onSubmit, onDeleteFile, existingCategor
|
||||
}}
|
||||
>
|
||||
<form
|
||||
role="presentation"
|
||||
style={{
|
||||
background: 'var(--bg-card)',
|
||||
borderRadius: 16,
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { ExternalLink } from 'lucide-react'
|
||||
import { collabApi } from '../../api/client'
|
||||
import { safeExternalHref } from '../../utils/safeUrl'
|
||||
|
||||
// ── Website Thumbnail (fetches OG image) ────────────────────────────────────
|
||||
const ogCache = {}
|
||||
interface OgPreview { title?: string; image?: string }
|
||||
|
||||
// linkPreview is trip-scoped on the server, so the cache key has to be too.
|
||||
// Capped like the chat preview's: a long session would otherwise keep every
|
||||
// thumbnail it ever rendered for as long as the tab lives. The separator is a
|
||||
// space because a trip id has none and a URL cannot contain a raw one - it used
|
||||
// to be a NUL, which made git treat this whole file as binary and its diffs
|
||||
// unreadable.
|
||||
const ogCache = new Map<string, OgPreview>()
|
||||
const cacheKey = (tripId: number, url: string): string => `${tripId} ${url}`
|
||||
const MAX_CACHED_PREVIEWS = 200
|
||||
|
||||
interface WebsiteThumbnailProps {
|
||||
url: string
|
||||
@@ -12,36 +23,60 @@ interface WebsiteThumbnailProps {
|
||||
}
|
||||
|
||||
export function WebsiteThumbnail({ url, tripId, color }: WebsiteThumbnailProps) {
|
||||
const [data, setData] = useState(ogCache[url] || null)
|
||||
const [data, setData] = useState<OgPreview | null>(null)
|
||||
const [failed, setFailed] = useState(false)
|
||||
// The note contract takes any string, so a stored javascript: URL would run in
|
||||
// this origin the moment someone clicks the tile. Refuse those, and leave a
|
||||
// bare host linkable - people paste them here the same way they do on a
|
||||
// booking. The tile still renders either way; it just is not a link.
|
||||
const href = safeExternalHref(url)
|
||||
|
||||
useEffect(() => {
|
||||
if (ogCache[url]) { setData(ogCache[url]); return }
|
||||
collabApi.linkPreview(tripId, url).then(d => { ogCache[url] = d; setData(d) }).catch(() => setFailed(true))
|
||||
}, [url, tripId])
|
||||
if (!href) return
|
||||
const key = cacheKey(tripId, url)
|
||||
setFailed(false)
|
||||
const cached = ogCache.get(key)
|
||||
if (cached) { setData(cached); return }
|
||||
setData(null)
|
||||
let current = true
|
||||
collabApi.linkPreview(tripId, url)
|
||||
.then(d => {
|
||||
if (ogCache.size >= MAX_CACHED_PREVIEWS) ogCache.delete(ogCache.keys().next().value!)
|
||||
ogCache.set(key, d)
|
||||
if (current) setData(d)
|
||||
})
|
||||
.catch(() => { if (current) setFailed(true) })
|
||||
return () => { current = false }
|
||||
}, [url, tripId, href])
|
||||
|
||||
const domain = (() => { try { return new URL(url).hostname.replace('www.', '') } catch { return 'link' } })()
|
||||
|
||||
const tileStyle = {
|
||||
width: 48, height: 48, borderRadius: 8, cursor: href ? 'pointer' : 'default', overflow: 'hidden',
|
||||
background: data?.image ? 'none' : 'var(--bg-tertiary)', border: 'none',
|
||||
display: 'flex', flexDirection: 'column' as const, alignItems: 'center', justifyContent: 'center', gap: 2,
|
||||
textDecoration: 'none', transition: 'transform 0.12s, box-shadow 0.12s', flexShrink: 0,
|
||||
}
|
||||
|
||||
const tile = data?.image && !failed ? (
|
||||
<img src={data.image} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} onError={() => setFailed(true)} />
|
||||
) : (
|
||||
<>
|
||||
<ExternalLink size={14} color="var(--text-muted)" />
|
||||
<span style={{ fontSize: 'calc(7px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-muted)', maxWidth: 42, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', textAlign: 'center' }}>
|
||||
{domain}
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
|
||||
if (!href) return <span title={data?.title || url} style={tileStyle}>{tile}</span>
|
||||
|
||||
return (
|
||||
<a href={url} target="_blank" rel="noopener noreferrer" title={data?.title || url}
|
||||
style={{
|
||||
width: 48, height: 48, borderRadius: 8, cursor: 'pointer', overflow: 'hidden',
|
||||
background: data?.image ? 'none' : 'var(--bg-tertiary)', border: 'none',
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 2,
|
||||
textDecoration: 'none', transition: 'transform 0.12s, box-shadow 0.12s', flexShrink: 0,
|
||||
}}
|
||||
<a href={href} target="_blank" rel="noopener noreferrer" title={data?.title || url}
|
||||
style={tileStyle}
|
||||
onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.08)'; e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = 'none' }}>
|
||||
{data?.image && !failed ? (
|
||||
<img src={data.image} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} onError={() => setFailed(true)} />
|
||||
) : (
|
||||
<>
|
||||
<ExternalLink size={14} color="var(--text-muted)" />
|
||||
<span style={{ fontSize: 'calc(7px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-muted)', maxWidth: 42, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', textAlign: 'center' }}>
|
||||
{domain}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{tile}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -143,3 +143,125 @@ describe('CollabPanel', () => {
|
||||
expect(screen.queryByTestId('collab-notes')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
// FE-W5CPN-001 to FE-W5CPN-013
|
||||
// The desktop branch picks a different layout for every combination of enabled
|
||||
// collab features, so each combination gets its own case.
|
||||
const allOff = { chat: false, notes: false, polls: false, whatsnext: false }
|
||||
|
||||
describe('CollabPanel feature combinations', () => {
|
||||
beforeEach(() => {
|
||||
originalInnerWidth = window.innerWidth
|
||||
resetAllStores()
|
||||
seedStore(useAuthStore, { user: buildUser() })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(window, 'innerWidth', { value: originalInnerWidth, writable: true, configurable: true })
|
||||
})
|
||||
|
||||
it('FE-W5CPN-001: renders nothing when every collab feature is disabled', () => {
|
||||
setViewport(1280)
|
||||
const { container } = render(<CollabPanel tripId={1} collabFeatures={allOff} />)
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CPN-002: chat alone fills the whole desktop panel', () => {
|
||||
setViewport(1280)
|
||||
render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, chat: true }} />)
|
||||
expect(screen.getByTestId('collab-chat')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-notes')).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-polls')).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId('whats-next')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CPN-003: chat plus notes puts the notes card next to the chat column', () => {
|
||||
setViewport(1280)
|
||||
render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, chat: true, notes: true }} />)
|
||||
expect(screen.getByTestId('collab-chat')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('collab-notes')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-polls')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CPN-004: chat plus polls renders the polls card as the only right panel', () => {
|
||||
setViewport(1280)
|
||||
render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, chat: true, polls: true }} />)
|
||||
expect(screen.getByTestId('collab-polls')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-notes')).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId('whats-next')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("FE-W5CPN-005: chat plus what's next renders the widget as the only right panel", () => {
|
||||
setViewport(1280)
|
||||
render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, chat: true, whatsnext: true }} />)
|
||||
expect(screen.getByTestId('whats-next')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-notes')).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-polls')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CPN-006: chat plus notes and polls stacks both right panels', () => {
|
||||
setViewport(1280)
|
||||
render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, chat: true, notes: true, polls: true }} />)
|
||||
expect(screen.getByTestId('collab-notes')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('collab-polls')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('whats-next')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("FE-W5CPN-007: chat plus polls and what's next stacks those two", () => {
|
||||
setViewport(1280)
|
||||
render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, chat: true, polls: true, whatsnext: true }} />)
|
||||
expect(screen.getByTestId('collab-polls')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('whats-next')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-notes')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CPN-008: notes alone fills the panel when chat is off', () => {
|
||||
setViewport(1280)
|
||||
render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, notes: true }} />)
|
||||
expect(screen.getByTestId('collab-notes')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-chat')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CPN-009: polls alone fills the panel when chat is off', () => {
|
||||
setViewport(1280)
|
||||
render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, polls: true }} />)
|
||||
expect(screen.getByTestId('collab-polls')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-chat')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("FE-W5CPN-010: what's next alone fills the panel when chat is off", () => {
|
||||
setViewport(1280)
|
||||
render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, whatsnext: true }} />)
|
||||
expect(screen.getByTestId('whats-next')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-chat')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CPN-011: notes and polls share the width side by side when chat is off', () => {
|
||||
setViewport(1280)
|
||||
render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, notes: true, polls: true }} />)
|
||||
expect(screen.getByTestId('collab-notes')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('collab-polls')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-chat')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("FE-W5CPN-012: polls and what's next share the width when chat is off", () => {
|
||||
setViewport(1280)
|
||||
render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, polls: true, whatsnext: true }} />)
|
||||
expect(screen.getByTestId('collab-polls')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('whats-next')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-notes')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5CPN-013: mobile falls back to the first tab when the active one gets disabled', () => {
|
||||
setViewport(375)
|
||||
const { rerender } = render(<CollabPanel tripId={1} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /polls/i }))
|
||||
expect(screen.getByTestId('collab-polls')).toBeInTheDocument()
|
||||
|
||||
rerender(<CollabPanel tripId={1} collabFeatures={{ ...allOff, notes: true, whatsnext: true }} />)
|
||||
expect(screen.getByTestId('collab-notes')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('collab-polls')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /polls/i })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -39,10 +39,10 @@ interface CollabPanelProps {
|
||||
}
|
||||
|
||||
const ALL_TABS = [
|
||||
{ id: 'chat', featureKey: 'chat' as const, labelKey: 'collab.tabs.chat', fallback: 'Chat', icon: MessageCircle },
|
||||
{ id: 'notes', featureKey: 'notes' as const, labelKey: 'collab.tabs.notes', fallback: 'Notes', icon: StickyNote },
|
||||
{ id: 'polls', featureKey: 'polls' as const, labelKey: 'collab.tabs.polls', fallback: 'Polls', icon: BarChart3 },
|
||||
{ id: 'next', featureKey: 'whatsnext' as const, labelKey: 'collab.whatsNext.title', fallback: "What's Next", icon: Sparkles },
|
||||
{ id: 'chat', featureKey: 'chat' as const, labelKey: 'collab.tabs.chat', icon: MessageCircle },
|
||||
{ id: 'notes', featureKey: 'notes' as const, labelKey: 'collab.tabs.notes', icon: StickyNote },
|
||||
{ id: 'polls', featureKey: 'polls' as const, labelKey: 'collab.tabs.polls', icon: BarChart3 },
|
||||
{ id: 'next', featureKey: 'whatsnext' as const, labelKey: 'collab.whatsNext.title', icon: Sparkles },
|
||||
]
|
||||
|
||||
export default function CollabPanel({ tripId, tripMembers = [], collabFeatures }: CollabPanelProps) {
|
||||
@@ -55,7 +55,7 @@ export default function CollabPanel({ tripId, tripMembers = [], collabFeatures }
|
||||
const tabs = useMemo(() =>
|
||||
ALL_TABS.filter(tab => features[tab.featureKey]).map(tab => ({
|
||||
...tab,
|
||||
label: t(tab.labelKey) || tab.fallback,
|
||||
label: t(tab.labelKey),
|
||||
})),
|
||||
[features, t])
|
||||
|
||||
@@ -170,7 +170,7 @@ export default function CollabPanel({ tripId, tripMembers = [], collabFeatures }
|
||||
{tabs.map(tab => {
|
||||
const active = mobileTab === tab.id
|
||||
return (
|
||||
<button key={tab.id} onClick={() => setMobileTab(tab.id)} style={{
|
||||
<button type="button" key={tab.id} onClick={() => setMobileTab(tab.id)} style={{
|
||||
flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
|
||||
padding: '8px 0', borderRadius: 10, border: 'none', cursor: 'pointer',
|
||||
background: active ? 'var(--accent)' : 'transparent',
|
||||
|
||||
@@ -10,9 +10,9 @@ vi.mock('../../api/websocket', () => ({
|
||||
removeListener: vi.fn(),
|
||||
}));
|
||||
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import { render, screen, waitFor, fireEvent, act } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { http, HttpResponse, delay } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
@@ -30,7 +30,7 @@ const buildPoll = (overrides: Record<string, unknown> = {}) => ({
|
||||
{ id: 1, text: 'Paris', label: 'Paris', voters: [] },
|
||||
{ id: 2, text: 'Rome', label: 'Rome', voters: [] },
|
||||
],
|
||||
multi_choice: false,
|
||||
multiple_choice: false,
|
||||
is_closed: false,
|
||||
deadline: null,
|
||||
created_by: 1,
|
||||
@@ -55,7 +55,7 @@ beforeEach(() => {
|
||||
describe('CollabPolls', () => {
|
||||
it('FE-COMP-POLLS-001: renders empty state when no polls exist', async () => {
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText(/no polls yet|collab\.polls\.empty/i);
|
||||
expect(await screen.findByText(/no polls yet|collab\.polls\.empty/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-POLLS-002: shows loading spinner initially', async () => {
|
||||
@@ -79,7 +79,7 @@ describe('CollabPolls', () => {
|
||||
),
|
||||
);
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Best destination?');
|
||||
expect(await screen.findByText('Best destination?')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-POLLS-004: renders poll options', async () => {
|
||||
@@ -108,7 +108,7 @@ describe('CollabPolls', () => {
|
||||
await screen.findByText(/no polls yet|collab\.polls\.empty/i);
|
||||
await user.click(screen.getByRole('button', { name: /new/i }));
|
||||
// Modal has a question placeholder input
|
||||
await screen.findByPlaceholderText(/what should we do/i);
|
||||
expect(await screen.findByPlaceholderText(/what should we do/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-POLLS-007: create modal requires question and at least 2 options to enable submit', async () => {
|
||||
@@ -153,7 +153,7 @@ describe('CollabPolls', () => {
|
||||
await user.type(optionInputs[1], 'Japanese');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /create|collab\.polls\.create/i }));
|
||||
await screen.findByText('Where to eat?');
|
||||
expect(await screen.findByText('Where to eat?')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-POLLS-009: voting on an option calls POST vote API', async () => {
|
||||
@@ -188,7 +188,7 @@ describe('CollabPolls', () => {
|
||||
),
|
||||
);
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText(/closed/i);
|
||||
expect(await screen.findByText(/closed/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-POLLS-011: closed poll options are disabled (cannot vote)', async () => {
|
||||
@@ -234,9 +234,9 @@ describe('CollabPolls', () => {
|
||||
|
||||
// Get the WS listener that was registered
|
||||
const listener = (addListener as ReturnType<typeof vi.fn>).mock.calls[0][0];
|
||||
listener({ type: 'collab:poll:created', poll: buildPoll({ id: 77, question: 'Live poll?' }) });
|
||||
listener({ tripId: 1, type: 'collab:poll:created', poll: buildPoll({ id: 77, question: 'Live poll?' }) });
|
||||
|
||||
await screen.findByText('Live poll?');
|
||||
expect(await screen.findByText('Live poll?')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-POLLS-014: WebSocket collab:poll:deleted event removes poll', async () => {
|
||||
@@ -249,7 +249,7 @@ describe('CollabPolls', () => {
|
||||
await screen.findByText('Best destination?');
|
||||
|
||||
const listener = (addListener as ReturnType<typeof vi.fn>).mock.calls[0][0];
|
||||
listener({ type: 'collab:poll:deleted', pollId: 3 });
|
||||
listener({ tripId: 1, type: 'collab:poll:deleted', pollId: 3 });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByText('Best destination?')).not.toBeInTheDocument(),
|
||||
@@ -273,3 +273,462 @@ describe('CollabPolls', () => {
|
||||
expect(optionInputs).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
// FE-W5CPL-001 to FE-W5CPL-028
|
||||
// Covers the deadline maths, the voter chips, the error paths of every mutation
|
||||
// and the WebSocket handler branches that the smoke tests above skip.
|
||||
|
||||
type AddToast = NonNullable<typeof window.__addToast>;
|
||||
|
||||
const MINUTE = 60_000;
|
||||
const HOUR = 60 * MINUTE;
|
||||
const DAY = 24 * HOUR;
|
||||
|
||||
/** A deadline `ms` in the future, with a small buffer so the clock can tick. */
|
||||
const inFuture = (ms: number) => new Date(Date.now() + ms + 10_000).toISOString();
|
||||
|
||||
function servePolls(polls: unknown) {
|
||||
server.use(http.get('/api/trips/1/collab/polls', () => HttpResponse.json(polls)));
|
||||
}
|
||||
|
||||
/** Grabs the WS handler CollabPolls registered on mount. */
|
||||
function wsHandler(): (msg: Record<string, unknown>) => void {
|
||||
return (addListener as ReturnType<typeof vi.fn>).mock.calls[0][0];
|
||||
}
|
||||
|
||||
describe('CollabPolls details', () => {
|
||||
let addToast: ReturnType<typeof vi.fn<AddToast>>;
|
||||
|
||||
beforeEach(() => {
|
||||
addToast = vi.fn<AddToast>(() => 0);
|
||||
window.__addToast = addToast;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete window.__addToast;
|
||||
});
|
||||
|
||||
it('FE-W5CPL-001: a deadline more than a day away is shown in days and hours', async () => {
|
||||
servePolls({ polls: [buildPoll({ deadline: inFuture(2 * DAY + 3 * HOUR) })] });
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
expect(await screen.findByText('2d 3h')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-002: a deadline within the day is shown in hours and minutes', async () => {
|
||||
servePolls({ polls: [buildPoll({ deadline: inFuture(5 * HOUR + 30 * MINUTE) })] });
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
expect(await screen.findByText('5h 30m')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-003: a deadline within the hour is shown in minutes', async () => {
|
||||
servePolls({ polls: [buildPoll({ deadline: inFuture(45 * MINUTE) })] });
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
expect(await screen.findByText('45m')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-004: a passed deadline closes the poll and drops the countdown', async () => {
|
||||
servePolls({ polls: [buildPoll({ deadline: '2020-01-01T00:00:00.000Z' })] });
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Best destination?');
|
||||
expect(screen.getByText(/closed/i)).toBeInTheDocument();
|
||||
expect(screen.getByText('Paris').closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-005: a poll served as a bare array is rendered', async () => {
|
||||
servePolls([buildPoll({ question: 'Array shaped?' })]);
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
expect(await screen.findByText('Array shaped?')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-006: options without a voters array count as zero votes', async () => {
|
||||
servePolls({ polls: [{ ...buildPoll(), options: [{ id: 1, text: 'Solo' }] }] });
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Solo');
|
||||
expect(screen.getByText('0 votes')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-007: a poll without an options array still renders its question', async () => {
|
||||
servePolls({ polls: [{ ...buildPoll(), options: undefined }] });
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Best destination?');
|
||||
expect(screen.queryByText('Paris')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-008: plain string options are rendered as their own label', async () => {
|
||||
servePolls({ polls: [{ ...buildPoll(), options: ['Yes', 'No'] }] });
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Yes');
|
||||
expect(screen.getByText('No')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-009: a multiple-choice poll shows the multi badge and a single vote label', async () => {
|
||||
servePolls({
|
||||
polls: [buildPoll({
|
||||
multiple_choice: true,
|
||||
options: [
|
||||
{ id: 1, text: 'Paris', voters: [{ user_id: 9, username: 'bob', avatar_url: null }] },
|
||||
{ id: 2, text: 'Rome', voters: [] },
|
||||
],
|
||||
})],
|
||||
});
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Best destination?');
|
||||
expect(screen.getByText('Multiple choice')).toBeInTheDocument();
|
||||
expect(screen.getByText('1 vote')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-010: once the user voted the results, avatars and tooltip appear', async () => {
|
||||
servePolls({
|
||||
polls: [buildPoll({
|
||||
options: [
|
||||
{
|
||||
id: 1, text: 'Paris',
|
||||
voters: [
|
||||
{ user_id: 1, username: 'testuser', avatar_url: null },
|
||||
{ user_id: 2, username: 'alice', avatar_url: '/uploads/avatars/alice.png' },
|
||||
],
|
||||
},
|
||||
{ id: 2, text: 'Rome', voters: [] },
|
||||
],
|
||||
})],
|
||||
});
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Paris');
|
||||
expect(screen.getByText('100%')).toBeInTheDocument();
|
||||
expect(screen.getByText('0%')).toBeInTheDocument();
|
||||
expect(document.querySelector('img[src="/uploads/avatars/alice.png"]')).toBeInTheDocument();
|
||||
|
||||
const chip = screen.getByText('T');
|
||||
fireEvent.mouseEnter(chip);
|
||||
expect(await screen.findByText('testuser')).toBeInTheDocument();
|
||||
fireEvent.mouseLeave(chip);
|
||||
await waitFor(() => expect(screen.queryByText('testuser')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-W5CPL-011: a voter without a username falls back to a question mark', async () => {
|
||||
servePolls({
|
||||
polls: [buildPoll({
|
||||
is_closed: true,
|
||||
options: [
|
||||
{ id: 1, text: 'Paris', voters: [{ user_id: null, username: '', avatar_url: null }] },
|
||||
{ id: 2, text: 'Rome', voters: [] },
|
||||
],
|
||||
})],
|
||||
});
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Paris');
|
||||
expect(screen.getByText('?')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-012: hovering an open option scales it, a closed one stays put', async () => {
|
||||
servePolls({ polls: [buildPoll({ id: 1 }), buildPoll({ id: 2, question: 'Done?', is_closed: true })] });
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Done?');
|
||||
const [openOption, closedOption] = screen.getAllByText('Paris').map(el => el.closest('button')!);
|
||||
fireEvent.mouseEnter(openOption);
|
||||
expect(openOption.style.transform).toBe('scale(1.01)');
|
||||
fireEvent.mouseLeave(openOption);
|
||||
expect(openOption.style.transform).toBe('scale(1)');
|
||||
|
||||
fireEvent.mouseEnter(closedOption);
|
||||
expect(closedOption.style.transform).toBe('');
|
||||
});
|
||||
|
||||
it('FE-W5CPL-013: the closed section heading only appears next to active polls', async () => {
|
||||
servePolls({
|
||||
polls: [
|
||||
buildPoll({ id: 1, question: 'Still open?' }),
|
||||
buildPoll({ id: 2, question: 'Already done?', is_closed: true }),
|
||||
],
|
||||
});
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Still open?');
|
||||
expect(screen.getByText('Already done?')).toBeInTheDocument();
|
||||
// One "Closed" badge on the poll itself plus the section heading above it
|
||||
expect(screen.getAllByText('Closed')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-W5CPL-014: closing a poll marks it closed and leaves the other one open', async () => {
|
||||
let closeCalled = false;
|
||||
servePolls({ polls: [buildPoll({ id: 5 }), buildPoll({ id: 6, question: 'Stays open?' })] });
|
||||
server.use(
|
||||
http.put('/api/trips/1/collab/polls/5/close', () => {
|
||||
closeCalled = true;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Stays open?');
|
||||
|
||||
// Both action buttons highlight on hover
|
||||
const closeBtn = screen.getAllByTitle('Close')[0];
|
||||
fireEvent.mouseEnter(closeBtn);
|
||||
expect(closeBtn.style.color).toBe('var(--text-primary)');
|
||||
fireEvent.mouseLeave(closeBtn);
|
||||
expect(closeBtn.style.color).toBe('var(--text-faint)');
|
||||
const deleteBtn = screen.getAllByTitle('Delete')[0];
|
||||
fireEvent.mouseEnter(deleteBtn);
|
||||
expect(deleteBtn.style.color).toBe('rgb(239, 68, 68)');
|
||||
fireEvent.mouseLeave(deleteBtn);
|
||||
expect(deleteBtn.style.color).toBe('var(--text-faint)');
|
||||
|
||||
await user.click(closeBtn);
|
||||
await waitFor(() => expect(closeCalled).toBe(true));
|
||||
await waitFor(() => expect(screen.getAllByText('Closed')).toHaveLength(2));
|
||||
expect(screen.getAllByTitle('Close')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-W5CPL-027: a failing poll request falls back to the empty state', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips/1/collab/polls', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
expect(await screen.findByText(/no polls yet|collab\.polls\.empty/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-028: a payload without a polls key yields an empty list', async () => {
|
||||
servePolls({});
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
expect(await screen.findByText(/no polls yet|collab\.polls\.empty/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-015: a failing close shows an error and leaves the poll open', async () => {
|
||||
servePolls({ polls: [buildPoll({ id: 5 })] });
|
||||
server.use(
|
||||
http.put('/api/trips/1/collab/polls/5/close', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Best destination?');
|
||||
await user.click(screen.getByTitle(/close/i));
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));
|
||||
expect(screen.getByTitle(/close/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-016: a failing delete shows an error and keeps the poll', async () => {
|
||||
servePolls({ polls: [buildPoll({ id: 6 })] });
|
||||
server.use(
|
||||
http.delete('/api/trips/1/collab/polls/6', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Best destination?');
|
||||
await user.click(screen.getByTitle(/delete/i));
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));
|
||||
expect(screen.getByText('Best destination?')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-017: a failing vote shows an error and leaves the tally alone', async () => {
|
||||
servePolls({ polls: [buildPoll({ id: 7 })] });
|
||||
server.use(
|
||||
http.post('/api/trips/1/collab/polls/7/vote', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Paris');
|
||||
await user.click(screen.getByText('Paris'));
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));
|
||||
expect(screen.queryByText('100%')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-018: an unwrapped vote response only replaces the poll that was voted on', async () => {
|
||||
servePolls({ polls: [buildPoll({ id: 7 }), buildPoll({ id: 8, question: 'Untouched?' })] });
|
||||
server.use(
|
||||
http.post('/api/trips/1/collab/polls/7/vote', () =>
|
||||
HttpResponse.json(buildPoll({
|
||||
id: 7,
|
||||
question: 'Voted!',
|
||||
options: [
|
||||
{ id: 1, text: 'Paris', voters: [{ user_id: 1, username: 'testuser', avatar_url: null }] },
|
||||
{ id: 2, text: 'Rome', voters: [] },
|
||||
],
|
||||
})),
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Untouched?');
|
||||
await user.click(screen.getAllByText('Paris')[0]);
|
||||
await screen.findByText('Voted!');
|
||||
expect(screen.getByText('Untouched?')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-019: a failing create shows an error and keeps the modal open', async () => {
|
||||
server.use(
|
||||
http.post('/api/trips/1/collab/polls', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText(/no polls yet|collab\.polls\.empty/i);
|
||||
await user.click(screen.getByRole('button', { name: /new/i }));
|
||||
await user.type(screen.getByPlaceholderText(/what should we do/i), 'Fails?');
|
||||
const optionInputs = screen.getAllByPlaceholderText(/option/i);
|
||||
await user.type(optionInputs[0], 'A');
|
||||
await user.type(optionInputs[1], 'B');
|
||||
await user.click(screen.getByRole('button', { name: /create|collab\.polls\.create/i }));
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));
|
||||
expect(screen.getByPlaceholderText(/what should we do/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-020: creating a poll that is already in the list does not duplicate it', async () => {
|
||||
servePolls({ polls: [buildPoll({ id: 12, question: 'Same poll' })] });
|
||||
server.use(
|
||||
http.post('/api/trips/1/collab/polls', () =>
|
||||
HttpResponse.json(buildPoll({ id: 12, question: 'Same poll' })),
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Same poll');
|
||||
await user.click(screen.getByRole('button', { name: /new/i }));
|
||||
await user.type(screen.getByPlaceholderText(/what should we do/i), 'Same poll');
|
||||
const optionInputs = screen.getAllByPlaceholderText(/option/i);
|
||||
await user.type(optionInputs[0], 'A');
|
||||
await user.type(optionInputs[1], 'B');
|
||||
await user.click(screen.getByRole('button', { name: /create|collab\.polls\.create/i }));
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByPlaceholderText(/what should we do/i)).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(screen.getAllByText('Same poll')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-W5CPL-021: submitting the create form without enough options is a no-op', async () => {
|
||||
let postCalled = false;
|
||||
server.use(
|
||||
http.post('/api/trips/1/collab/polls', () => {
|
||||
postCalled = true;
|
||||
return HttpResponse.json({ poll: buildPoll() });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText(/no polls yet|collab\.polls\.empty/i);
|
||||
await user.click(screen.getByRole('button', { name: /new/i }));
|
||||
await user.type(screen.getByPlaceholderText(/what should we do/i), 'Not enough');
|
||||
fireEvent.submit(screen.getByPlaceholderText(/what should we do/i).closest('form')!);
|
||||
await waitFor(() => expect(screen.getByPlaceholderText(/what should we do/i)).toBeInTheDocument());
|
||||
expect(postCalled).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-W5CPL-022: an extra option can be removed again', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText(/no polls yet|collab\.polls\.empty/i);
|
||||
await user.click(screen.getByRole('button', { name: /new/i }));
|
||||
await user.click(screen.getByText(/add option/i));
|
||||
expect(screen.getAllByPlaceholderText(/option/i)).toHaveLength(3);
|
||||
|
||||
const thirdRow = screen.getAllByPlaceholderText(/option/i)[2].parentElement!;
|
||||
await user.click(thirdRow.querySelector('button')!);
|
||||
expect(screen.getAllByPlaceholderText(/option/i)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-W5CPL-023: the multi-choice toggle flips and is sent along on create', async () => {
|
||||
let body: Record<string, unknown> | null = null;
|
||||
server.use(
|
||||
http.post('/api/trips/1/collab/polls', async ({ request }) => {
|
||||
body = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ poll: buildPoll({ id: 30, question: 'Multi?' }) });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText(/no polls yet|collab\.polls\.empty/i);
|
||||
await user.click(screen.getByRole('button', { name: /new/i }));
|
||||
|
||||
const toggle = screen.getByText(/multiple|multi/i).previousElementSibling as HTMLElement;
|
||||
expect(toggle.style.background).toBe('var(--border-primary)');
|
||||
await user.click(toggle);
|
||||
expect(toggle.style.background).toBe('rgb(0, 122, 255)');
|
||||
|
||||
await user.type(screen.getByPlaceholderText(/what should we do/i), 'Multi?');
|
||||
const optionInputs = screen.getAllByPlaceholderText(/option/i);
|
||||
await user.type(optionInputs[0], 'A');
|
||||
await user.type(optionInputs[1], 'B');
|
||||
await user.click(screen.getByRole('button', { name: /create|collab\.polls\.create/i }));
|
||||
await screen.findByText('Multi?');
|
||||
expect(body).toMatchObject({ multiple_choice: true, options: ['A', 'B'] });
|
||||
});
|
||||
|
||||
it('FE-W5CPL-024: WebSocket events without a type or a known id are ignored', async () => {
|
||||
servePolls({ polls: [buildPoll({ id: 40 })] });
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Best destination?');
|
||||
const handler = wsHandler();
|
||||
await act(async () => {
|
||||
handler({});
|
||||
handler({ tripId: 1, type: 'collab:poll:deleted' });
|
||||
handler({ tripId: 1, type: 'collab:poll:created', poll: { id: 40, question: 'Best destination?' } });
|
||||
});
|
||||
expect(screen.getAllByText('Best destination?')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-W5CPL-025: WebSocket vote and close events update only the matching poll', async () => {
|
||||
servePolls({ polls: [buildPoll({ id: 41 }), buildPoll({ id: 42, question: 'Other poll' })] });
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('Other poll');
|
||||
const handler = wsHandler();
|
||||
|
||||
await act(async () => {
|
||||
handler({ tripId: 1, type: 'collab:poll:voted', poll: buildPoll({ id: 41, question: 'Voted live' }) });
|
||||
});
|
||||
expect(await screen.findByText('Voted live')).toBeInTheDocument();
|
||||
expect(screen.getByText('Other poll')).toBeInTheDocument();
|
||||
|
||||
await act(async () => {
|
||||
handler({ tripId: 1, type: 'collab:poll:closed', poll: { id: 41 } });
|
||||
});
|
||||
await waitFor(() => expect(screen.getAllByText('Closed')).toHaveLength(2));
|
||||
|
||||
await act(async () => {
|
||||
handler({ tripId: 1, type: 'collab:poll:deleted', poll: { id: 42 } });
|
||||
});
|
||||
await waitFor(() => expect(screen.queryByText('Other poll')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-W5CPL-027: a WebSocket event for another trip is ignored', async () => {
|
||||
servePolls({ polls: [] });
|
||||
render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText(/no polls yet|collab.polls.empty/i);
|
||||
const handler = wsHandler();
|
||||
await act(async () => {
|
||||
handler({ tripId: 2, type: 'collab:poll:created', poll: buildPoll({ id: 88, question: 'Other trip poll?' }) });
|
||||
});
|
||||
expect(screen.queryByText('Other trip poll?')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-028: a slow load for the trip we left does not overwrite the new one', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips/1/collab/polls', async () => {
|
||||
await delay(80);
|
||||
return HttpResponse.json({ polls: [buildPoll({ id: 1, question: 'Trip one poll?' })] });
|
||||
}),
|
||||
http.get('/api/trips/2/collab/polls', () =>
|
||||
HttpResponse.json({ polls: [buildPoll({ id: 2, question: 'Trip two poll?' })] }),
|
||||
),
|
||||
);
|
||||
const { rerender } = render(<CollabPolls {...defaultProps} />);
|
||||
rerender(<CollabPolls tripId={2} currentUser={currentUser} />);
|
||||
|
||||
await screen.findByText('Trip two poll?');
|
||||
await act(async () => { await delay(150); });
|
||||
expect(screen.queryByText('Trip one poll?')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Trip two poll?')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5CPL-026: a poll with a live deadline starts the countdown ticker', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
||||
try {
|
||||
servePolls({ polls: [buildPoll({ deadline: inFuture(90 * MINUTE) })] });
|
||||
const { unmount } = render(<CollabPolls {...defaultProps} />);
|
||||
await screen.findByText('1h 30m');
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(31_000); });
|
||||
expect(screen.getByText('1h 29m')).toBeInTheDocument();
|
||||
unmount();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,8 @@ import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import ReactDOM from 'react-dom'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
import { createPortal } from 'react-dom'
|
||||
import type { User } from '../../types'
|
||||
|
||||
interface PollVoter {
|
||||
@@ -25,7 +26,7 @@ interface Poll {
|
||||
id: number
|
||||
question: string
|
||||
options: PollOption[]
|
||||
multi_choice: boolean
|
||||
multiple_choice: boolean
|
||||
is_closed: boolean
|
||||
deadline: string | null
|
||||
created_by: number
|
||||
@@ -58,7 +59,7 @@ function totalVotes(poll) {
|
||||
// ── Create Poll Modal ────────────────────────────────────────────────────────
|
||||
interface CreatePollModalProps {
|
||||
onClose: () => void
|
||||
onCreate: (data: { question: string; options: string[]; multi_choice: boolean }) => Promise<void>
|
||||
onCreate: (data: { question: string; options: string[]; multiple_choice: boolean }) => Promise<void>
|
||||
t: (key: string) => string
|
||||
}
|
||||
|
||||
@@ -79,14 +80,16 @@ function CreatePollModal({ onClose, onCreate, t }: CreatePollModalProps) {
|
||||
if (!canSubmit) return
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await onCreate({ question: question.trim(), options: options.filter(o => o.trim()), multi_choice: multiChoice })
|
||||
// `multiple_choice` is the field the server reads (nest/collab/collab.service.ts);
|
||||
// the old `multi_choice` name was silently dropped, losing desktop multi-choice.
|
||||
await onCreate({ question: question.trim(), options: options.filter(o => o.trim()), multiple_choice: multiChoice })
|
||||
onClose()
|
||||
} catch {} finally { setSubmitting(false) }
|
||||
}
|
||||
|
||||
return ReactDOM.createPortal(
|
||||
<div style={{ position: 'fixed', inset: 0, background: 'var(--overlay-bg, rgba(0,0,0,0.35))', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999, padding: 16, fontFamily: FONT }} onClick={onClose}>
|
||||
<form style={{ background: 'var(--bg-card)', borderRadius: 16, width: '100%', maxWidth: 400, maxHeight: '90vh', overflow: 'auto', border: '1px solid var(--border-faint)' }} onClick={e => e.stopPropagation()} onSubmit={handleSubmit}>
|
||||
return createPortal(
|
||||
<div role="presentation" style={{ position: 'fixed', inset: 0, background: 'var(--overlay-bg, rgba(0,0,0,0.35))', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999, padding: 16, fontFamily: FONT }} onClick={e => { if (e.target === e.currentTarget) onClose() }}>
|
||||
<form style={{ background: 'var(--bg-card)', borderRadius: 16, width: '100%', maxWidth: 400, maxHeight: '90vh', overflow: 'auto', border: '1px solid var(--border-faint)' }} onSubmit={handleSubmit}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px 12px', borderBottom: '1px solid var(--border-faint)' }}>
|
||||
<h3 style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 700, color: 'var(--text-primary)', margin: 0 }}>{t('collab.polls.new')}</h3>
|
||||
<button type="button" onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', padding: 2, display: 'flex' }}><X size={16} /></button>
|
||||
@@ -95,7 +98,7 @@ function CreatePollModal({ onClose, onCreate, t }: CreatePollModalProps) {
|
||||
{/* Question */}
|
||||
<div>
|
||||
<div style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4 }}>{t('collab.polls.question')}</div>
|
||||
<input autoFocus value={question} onChange={e => setQuestion(e.target.value)} placeholder={t('collab.polls.questionPlaceholder') || 'Ask a question...'} style={{ width: '100%', border: '1px solid var(--border-primary)', borderRadius: 10, padding: '8px 12px', fontSize: 'calc(13px * var(--fs-scale-body, 1))', background: 'var(--bg-input)', color: 'var(--text-primary)', fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' }} />
|
||||
<input autoFocus value={question} onChange={e => setQuestion(e.target.value)} placeholder={t('collab.polls.questionPlaceholder')} style={{ width: '100%', border: '1px solid var(--border-primary)', borderRadius: 10, padding: '8px 12px', fontSize: 'calc(13px * var(--fs-scale-body, 1))', background: 'var(--bg-input)', color: 'var(--text-primary)', fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' }} />
|
||||
</div>
|
||||
|
||||
{/* Options */}
|
||||
@@ -119,13 +122,13 @@ function CreatePollModal({ onClose, onCreate, t }: CreatePollModalProps) {
|
||||
|
||||
{/* Multi choice toggle */}
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}>
|
||||
<div onClick={() => setMultiChoice(!multiChoice)} style={{
|
||||
width: 36, height: 20, borderRadius: 10, padding: 2, cursor: 'pointer',
|
||||
<button type="button" role="switch" aria-checked={multiChoice} onClick={() => setMultiChoice(!multiChoice)} style={{
|
||||
width: 36, height: 20, borderRadius: 10, padding: 2, cursor: 'pointer', border: 'none',
|
||||
background: multiChoice ? '#007AFF' : 'var(--border-primary)', transition: 'background 0.2s',
|
||||
display: 'flex', alignItems: 'center',
|
||||
}}>
|
||||
<div style={{ width: 16, height: 16, borderRadius: '50%', background: '#fff', transition: 'transform 0.2s', transform: multiChoice ? 'translateX(16px)' : 'translateX(0)' }} />
|
||||
</div>
|
||||
</button>
|
||||
<span style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'var(--text-muted)', fontFamily: FONT }}>{t('collab.polls.multiChoice')}</span>
|
||||
</label>
|
||||
|
||||
@@ -171,9 +174,9 @@ function VoterChip({ voter, offset }: VoterChipProps) {
|
||||
fontSize: 'calc(7px * var(--fs-scale-caption, 1))', fontWeight: 700, color: 'var(--text-muted)', overflow: 'hidden',
|
||||
border: '1.5px solid var(--bg-card)', marginLeft: offset ? -5 : 0, flexShrink: 0,
|
||||
}}>
|
||||
{voter.avatar_url ? <img src={voter.avatar_url} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : (voter.username || '?')[0].toUpperCase()}
|
||||
{voter.avatar_url ? <img src={voter.avatar_url} alt={voter.username || ''} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : (voter.username || '?')[0].toUpperCase()}
|
||||
</div>
|
||||
{hover && ReactDOM.createPortal(
|
||||
{hover && createPortal(
|
||||
<div style={{
|
||||
position: 'fixed', top: pos.top, left: pos.left, transform: 'translate(-50%, -100%)',
|
||||
pointerEvents: 'none', zIndex: 10000, whiteSpace: 'nowrap',
|
||||
@@ -205,6 +208,8 @@ function PollCard({ poll, currentUser, canEdit, onVote, onClose, onDelete, t }:
|
||||
const isClosed = poll.is_closed || isExpired(poll.deadline)
|
||||
const remaining = timeRemaining(poll.deadline)
|
||||
const hasVoted = (poll.options || []).some(o => (o.voters || []).some(v => String(v.user_id) === String(currentUser.id)))
|
||||
// Highest vote count across the options; 0 for a poll without options.
|
||||
const topCount = (poll.options || []).reduce((max, o) => Math.max(max, o.voters?.length || 0), 0)
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
@@ -231,7 +236,7 @@ function PollCard({ poll, currentUser, canEdit, onVote, onClose, onDelete, t }:
|
||||
<Clock size={8} /> {remaining}
|
||||
</span>
|
||||
)}
|
||||
{poll.multi_choice && (
|
||||
{poll.multiple_choice && (
|
||||
<span style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)', background: 'var(--bg-tertiary)', padding: '2px 7px', borderRadius: 99 }}>
|
||||
{t('collab.polls.multiChoice')}
|
||||
</span>
|
||||
@@ -245,14 +250,14 @@ function PollCard({ poll, currentUser, canEdit, onVote, onClose, onDelete, t }:
|
||||
{canEdit && (
|
||||
<div style={{ display: 'flex', gap: 2, flexShrink: 0 }}>
|
||||
{!isClosed && (
|
||||
<button onClick={() => onClose(poll.id)} title={t('collab.polls.close')}
|
||||
<button type="button" onClick={() => onClose(poll.id)} title={t('collab.polls.close')}
|
||||
style={{ padding: 4, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex', borderRadius: 6 }}
|
||||
onMouseEnter={e => e.currentTarget.style.color = 'var(--text-primary)'}
|
||||
onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>
|
||||
<Lock size={12} />
|
||||
</button>
|
||||
)}
|
||||
<button onClick={() => onDelete(poll.id)} title={t('collab.polls.delete')}
|
||||
<button type="button" onClick={() => onDelete(poll.id)} title={t('collab.polls.delete')}
|
||||
style={{ padding: 4, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex', borderRadius: 6 }}
|
||||
onMouseEnter={e => e.currentTarget.style.color = '#ef4444'}
|
||||
onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>
|
||||
@@ -268,10 +273,12 @@ function PollCard({ poll, currentUser, canEdit, onVote, onClose, onDelete, t }:
|
||||
const count = opt.voters?.length || 0
|
||||
const pct = total > 0 ? Math.round((count / total) * 100) : 0
|
||||
const myVote = (opt.voters || []).some(v => String(v.user_id) === String(currentUser.id))
|
||||
const isWinner = isClosed && count === Math.max(...(poll.options || []).map(o => o.voters?.length || 0)) && count > 0
|
||||
const isWinner = isClosed && count > 0 && count === topCount
|
||||
|
||||
return (
|
||||
<button key={idx} onClick={() => !isClosed && onVote(poll.id, idx)}
|
||||
// React dispatches no mouse events on a disabled control, so the
|
||||
// handlers below need no isClosed guard of their own.
|
||||
<button type="button" key={idx} onClick={() => onVote(poll.id, idx)}
|
||||
disabled={isClosed}
|
||||
style={{
|
||||
position: 'relative', display: 'flex', alignItems: 'center', gap: 8,
|
||||
@@ -279,7 +286,7 @@ function PollCard({ poll, currentUser, canEdit, onVote, onClose, onDelete, t }:
|
||||
background: 'var(--bg-secondary)', fontFamily: FONT, textAlign: 'left', width: '100%',
|
||||
overflow: 'hidden', transition: 'transform 0.1s',
|
||||
}}
|
||||
onMouseEnter={e => { if (!isClosed) e.currentTarget.style.transform = 'scale(1.01)' }}
|
||||
onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.01)' }}
|
||||
onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
|
||||
>
|
||||
{/* Progress bar background */}
|
||||
@@ -352,15 +359,25 @@ export default function CollabPolls({ tripId, currentUser }: CollabPollsProps) {
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
collabApi.getPolls(tripId).then(data => {
|
||||
setPolls(Array.isArray(data) ? data : data.polls || [])
|
||||
}).catch(() => {}).finally(() => setLoading(false))
|
||||
if (!cancelled) setPolls(Array.isArray(data) ? data : data.polls || [])
|
||||
}).catch(() => {
|
||||
if (!cancelled) setPolls([])
|
||||
}).finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [tripId])
|
||||
|
||||
// WebSocket
|
||||
useEffect(() => {
|
||||
const handler = (msg) => {
|
||||
if (!msg?.type) return
|
||||
// The panel is not remounted on a trip change, so an event still in flight
|
||||
// from the trip we just left must not land in this list.
|
||||
if (String(msg.tripId) !== String(tripId)) return
|
||||
if (msg.type === 'collab:poll:created' && msg.poll) {
|
||||
setPolls(prev => prev.some(p => p.id === msg.poll.id) ? prev : [msg.poll, ...prev])
|
||||
}
|
||||
@@ -377,7 +394,7 @@ export default function CollabPolls({ tripId, currentUser }: CollabPollsProps) {
|
||||
}
|
||||
addListener(handler)
|
||||
return () => removeListener(handler)
|
||||
}, [])
|
||||
}, [tripId])
|
||||
|
||||
const handleCreate = useCallback(async (data) => {
|
||||
try {
|
||||
@@ -448,7 +465,7 @@ export default function CollabPolls({ tripId, currentUser }: CollabPollsProps) {
|
||||
{t('collab.polls.title')}
|
||||
</h3>
|
||||
{canEdit && (
|
||||
<button onClick={() => setShowForm(true)} style={{
|
||||
<button type="button" onClick={() => setShowForm(true)} style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: 4, borderRadius: 99, padding: '6px 12px',
|
||||
background: 'var(--accent)', color: 'var(--accent-text)', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600,
|
||||
fontFamily: FONT, border: 'none', cursor: 'pointer',
|
||||
@@ -461,11 +478,7 @@ export default function CollabPolls({ tripId, currentUser }: CollabPollsProps) {
|
||||
{/* Content */}
|
||||
<div className="chat-scroll" style={{ flex: 1, overflowY: 'auto', padding: '0 12px 12px' }}>
|
||||
{polls.length === 0 ? (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '48px 20px', textAlign: 'center', height: '100%' }}>
|
||||
<BarChart3 size={36} color="var(--text-faint)" strokeWidth={1.3} style={{ marginBottom: 12 }} />
|
||||
<div style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>{t('collab.polls.empty')}</div>
|
||||
<div style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'var(--text-faint)' }}>{t('collab.polls.emptyHint')}</div>
|
||||
</div>
|
||||
<EmptyState scene="polls" title={t('collab.polls.empty')} />
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
{activePolls.length > 0 && activePolls.map(poll => (
|
||||
@@ -475,7 +488,7 @@ export default function CollabPolls({ tripId, currentUser }: CollabPollsProps) {
|
||||
<>
|
||||
{activePolls.length > 0 && (
|
||||
<div style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.3, padding: '8px 0 2px' }}>
|
||||
{t('collab.polls.closedSection') || 'Closed'}
|
||||
{t('collab.polls.closedSection')}
|
||||
</div>
|
||||
)}
|
||||
{closedPolls.map(poll => (
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user