mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-06-19 21:31:46 +00:00
20791a29a7
* Migrate TREK 3 to NestJS + React 19 with a shared Zod contract layer
Brownfield strangler migration of the backend onto NestJS modules
(auth, trips, days, places, assignments, packing, todo, budget,
reservations, collab, files, photos, journey, share, settings, backup,
oidc, oauth, admin, atlas, vacay, weather, airports, maps, categories,
tags, notifications, system-notices) served through a per-prefix
dispatcher, keeping the existing SQLite/better-sqlite3 DB and JWT
httpOnly cookie auth, with behavioural parity for every route.
Client: React 19 upgrade, "page = wiring container + data hook"
pattern across all pages, per-domain Zustand stores bound to
@trek/shared contracts, and decomposition of the large components
(DayPlanSidebar, PackingListPanel, CollabNotes, FileManager,
MemoriesPanel, PlacesSidebar, CollabChat, SystemNoticeModal,
BudgetPanel, PlaceFormModal, ...) into focused render units backed by
in-file hooks.
Apply the shared global request pipeline (helmet/CSP, CORS, HSTS,
forced HTTPS, the global MFA policy and request logging) to the NestJS
instance as well, so a migrated route is protected identically to the
legacy fallback rather than bypassing it.
* Finish the NestJS migration — drop the legacy Express app
NestJS now serves the whole surface: every /api domain plus the platform
routes (uploads, /mcp, the OAuth/MCP SDK + /.well-known metadata and the
production SPA fallback). Removed server/src/app.ts, all of
server/src/routes/* and the strangler dispatcher; index.ts and the
integration suite share a single buildApp() bootstrap so prod and tests
can't drift.
- Platform/transport routes extracted to nest/platform/platform.routes.ts
and mounted before app.init() — Nest's router answers an unmatched
request with a 404, so a route registered after init is never reached.
The SPA fallback is a NotFoundException filter and the catch-all uses a
RegExp (Express 5's path-to-regexp rejects a bare '*').
- New modules: memories (/api/integrations/memories — the Journey
gallery's Immich/Synology proxy), addons (GET /api/addons) and the
cross-trip GET /api/reservations/upcoming.
- TrekExceptionFilter reproduces the old multer / err.statusCode handling
so upload rejections keep their 400/413 { error } body and non-ASCII
filenames survive (defParamCharset).
- addTripToJourney and the MCP get_journey_share_link tool gained the
trip-access check they were missing.
- Re-pointed the 34 integration tests + the websocket test onto the Nest
app; removed the now-meaningless Express-vs-Nest parity tests and a few
orphaned client components.
* Restore the reset-password rate limit and fix copyTrip reservation links
Two correctness/security gaps the NestJS migration introduced:
- POST /api/auth/reset-password lost its per-IP rate limiter. Restore it
(5 attempts / 15 min on a dedicated bucket, same as the old resetLimiter)
so reset tokens can't be brute-forced unthrottled. Covered by AUTH-019.
- copyTripById did not copy reservations.end_day_id (a day reference — now
remapped through dayMap like day_id) or needs_review, so a duplicated trip
lost multi-day transport end-day links and reset the review flag.
* Clean up dead code, dedupe helpers, fix the reset-password contract
- Remove server exports orphaned by the Express removal: the immich
album-link helpers, seven route-only service exports, getFileByIdFull;
de-export internal-only helpers (utcSuffix).
- De-duplicate verifyTripAccess (9 identical copies -> services/tripAccess.ts)
and avatarUrl (3 -> services/avatarUrl.ts); name the bcrypt cost
(BCRYPT_COST) and the email regex (EMAIL_REGEX). Public API unchanged.
- resetPasswordRequestSchema declared `password`, but the client sends and
the service reads `new_password` — rename it so the contract matches and
the client types resolve.
- Make ATLAS-013 deterministic: stub the admin-1 GeoJSON download instead of
fetching ~4600 features from GitHub during the test (it hung the suite).
* Make the client typecheck runnable (vitest/vite ambient types)
The client had no `typecheck` script and tsc couldn't even start (the
baseUrl deprecation errored out, same as server/shared already silence).
Add `ignoreDeprecations: "6.0"` to match the other workspaces, a `typecheck`
npm script, and a src/vite-env.d.ts referencing vite/client + vitest/globals
so tsc knows the test globals (describe/it/expect/vi). This turns ~3600
phantom "Cannot find name" errors into a real, measurable count (~590 actual
type errors remain, to be worked down). Type-only; no runtime change.
* Derive client domain types from the shared schema contracts
Add entity/response Zod schemas to @trek/shared (place, trip, assignment, day, budget, packing, reservation), each matched against the producing server service, and re-export them from client types.ts instead of the hand-written duplicates that had drifted (name/title, amount/total_price, owner_id/user_id, cover_url/cover_image, ...). Updates the call sites and test fixtures the corrected types surfaced; type-only, no runtime behaviour change.
* chore(db): log swallowed errors in addon-disable migration + guard against destructive migrations
The migration that disables the legacy "memories" addon swallowed any
error in an empty catch, as did ~30 other catch blocks in the migration
runner (column adds, the journey rebuild, index probes). Replace each
silent catch with the existing console.warn('[migrations] ...') log so
failures are visible. Control flow is unchanged: every step stays
non-fatal, nothing new is thrown.
Add a static guardrail test that scans the migration source and fails
when a new destructive statement (DROP TABLE / DROP COLUMN / TRUNCATE /
DELETE FROM / ALTER ... DROP) appears outside a reviewed allowlist, and
when an empty/silent catch block is reintroduced. The existing
destructive statements are all legitimate table rebuilds or
bounded cleanups and are recorded in the allowlist with a reason.
* Re-check SSRF on every redirect hop when resolving short links
Replace the one-shot checkSsrf + fetch(redirect:'follow') in the maps and place short-link resolvers with safeFetchFollow, which follows redirects manually and re-runs checkSsrf against the DNS-pinned IP of each hop (max 5). A redirect to an internal/loopback address is now blocked even when the initial URL is public, while legitimate cross-host redirects (goo.gl -> maps.google.com) still resolve.
* Reject WebSocket tokens minted before a password change
Stamp the user's password_version onto the ephemeral ws token and verify it on connect, closing the socket (4001) when it no longer matches, so a token issued before a password reset can't be replayed. Tokens minted without a version are treated as version 0, matching the JWT pv-claim semantics.
* fix(i18n): guard locale key parity and finish the OAuth consent page strings
Every non-en locale now exposes the exact same flat key set as en. Keys that
had drifted out of sync are backfilled with the English source value (tagged
en-fallback) so t() resolves a real string instead of relying on the silent
runtime fallback; no existing translation was touched and no key was removed.
Add a parity test that imports each aggregated locale bundle and asserts its
key set matches en, with a diagnostic listing of any missing/extra keys. This
complements the file-level check in shared/scripts by guarding the merged
export the app actually serves.
Finish internationalising OAuthAuthorizePage: the ~15 remaining hardcoded
English chrome strings now go through oauth.authorize.* keys (English source
in en, en-fallback placeholders elsewhere). Markup and behaviour are unchanged.
* Add semantic theme color tokens to Tailwind
Map the CSS theme variables from src/index.css (:root light / .dark dark) to named Tailwind utilities — bg-surface, text-content, border-edge, bg-accent and their variants. This gives components a Tailwind-native target for the theme colors so we can replace inline `style={{ ... 'var(--...)' }}` with utility classes without changing the rendered values.
* Surface silent store failures to the user and validate API responses in dev
Reservation toggle, todo/packing toggle and budget reorder were swallowing API errors after rolling back, so the user saw the change silently snap back with no explanation. Route those failures through the existing toast channel (new store/notify.ts bridges to window.__addToast, the same channel SystemNoticeBanner uses); the reservation toggle re-throws so ReservationsPanel's own translated toast finally fires. Also wire the existing parseInDev/checkInDev response validation into the maps and notification-test endpoints to catch contract drift in dev.
* Migrate static theme inline styles to Tailwind utilities and extract page sub-components
Replace the static, color-only inline `style={{ ... 'var(--bg-primary)' ... }}` props with the new semantic Tailwind utilities (bg-surface, text-content, border-edge, ...) wherever the result is byte-identical; dynamic/conditional theme styles and hardcoded status colors are left inline. Extract the Atlas country-search autocomplete, the Admin update banner, and two Journey dialogs into their own presentational components to shrink the oversized page files, keeping behaviour and markup identical.
* Remove the unrouted photos page and its dead photo components
PhotosPage was never wired into the router and its usePhotos hook read a tripStore photos slice that was never implemented; the Photos gallery, lightbox and upload components were only reachable through it. Per-trip photos now live in the Journey gallery (Immich/Synology). Removed the dead page, hook and components — the live Journey PhotoLightbox is a separate component and stays.
* Resolve the remaining client type errors and the trip.title navbar bug
Drive the client typecheck to zero without any/ts-ignore: convert the tripId route param to a number once at the page boundary so it matches the numeric props and store actions it feeds, fix trip.name -> trip.title (the wire field is title, so the old read rendered blank in the files/offline views), and tighten the scattered handler-arity, DOM-cast and untyped-payload sites. No runtime behaviour change.
* Convert the remaining dynamic and hardcoded inline styles to Tailwind utilities
Second styling pass over the components and pages: move conditional theme colors into className ternaries (bg-accent / bg-surface-hover etc.), turn reused CSSProperties constants into className constants, and express static hardcoded hex/rgba colors as Tailwind arbitrary values so the exact rendered colour is preserved. Truly dynamic styling (computed geometry, gradients, multi-part shadows, data-driven colours, the undefined --sidebar/--nav layout vars) stays inline as it cannot be expressed as a static class. Updated three component tests that asserted the old inline active-state styles to assert the equivalent utility class instead.
Verified: client typecheck 0, full client suite green, and a live light/dark render check in the dev server confirms the semantic theme tokens resolve correctly (the earlier 'transparent popups' were a stale dev server that pre-dated the tailwind.config token addition, not a code issue).
* Add eslint flat-config for client and server and gate typecheck, lint and pages in CI
client and server had lint scripts but no eslint config (only shared was linted in CI). Add flat configs mirroring shared's stack (js + typescript-eslint recommended + eslint-config-prettier) plus the client's react-hooks/react-refresh plugins. Pre-existing patterns in this never-linted code (explicit any, require() in the CommonJS server, empty catches, exhaustive-deps) are set to 'warn' rather than 'error' so the gate passes at 0 errors without a repo-wide reformat — these can be ratcheted to errors over time. Wire blocking typecheck + lint + lint:pages steps into the client and server CI jobs (now that both typechecks are clean) and promote the server typecheck from informational to blocking.
* Decompose the remaining God Components into hooks, helpers and sub-components
FE6: split the oversized page and panel components into thin layout shells plus colocated use<Component> hooks, .constants.ts, .helpers.ts (with tests) and presentational sub-components, following the established 'logic in a hook, render in slices' pattern. Behaviour, markup, classes and effect order are unchanged. Largest reductions: PackingListPanel 1598->42, FileManager 1055->36, AdminPage 1525->167, BudgetPanel 1266->146, JourneyDetailPage 2822->547, PlacesSidebar 945->66, CollabChat 861->106, CollabNotes 1417->532. DayPlanSidebar's drag-and-drop render body was left intact (ref-identity sensitive) and only its toolbar/modals/constants were extracted.
* Fix duplicate React keys in the file-assign place list
When a place is assigned to the same day more than once it appeared twice in a day's list, so the place-button key={p.id} collided and React warned about duplicate keys. Key by place id + render index so siblings stay unique. Pre-existing in the old FileManager; behaviour unchanged.
* Format the shared package and drop an unused import to satisfy the lint gate
The i18n and schema changes added code that wasn't prettier-formatted, and place.schema.ts imported categorySchema without using it. Run prettier over shared and remove the import so 'npm run lint' + 'format:check' pass.
* Install all workspaces in the server CI job so SWC's native binary is present
The server vitest config transforms via unplugin-swc, which needs @swc/core's platform-specific native binary. A workspace-scoped 'npm ci --workspace server' skips that optional dependency, so vitest failed to load the config on the Linux runner. Use a full 'npm ci'.
* Re-resolve dependencies with npm install in the server CI job for SWC
Full 'npm ci' still skipped @swc/core's Linux native binary because the committed lockfile was generated on Windows and lacks the Linux optional-dep install metadata. 'npm install' re-resolves and fetches the platform-matching binary, which the server's unplugin-swc transform needs to load vitest.config.ts.
* Install @swc/core's Linux binary explicitly in the server CI job
Neither npm ci nor npm install fetched @swc/core-linux-x64-gnu on the Linux runner because the lockfile was generated on Windows and lacks the Linux optional-dep metadata. Add a step that installs the matching @swc/core-linux-x64-gnu version (no-save, no-lockfile) so unplugin-swc can load the server's vitest config.
* Use legacy-peer-deps when installing the SWC Linux binary in CI
The explicit @swc/core-linux-x64-gnu install re-resolved the tree and hit the pre-existing lucide-react/react-19 peer conflict that the lockfile was generated around. Add --legacy-peer-deps so the step matches the project's resolution and installs the binary.
* Keep the lockfile when installing the SWC binary so other deps stay pinned
Dropping --no-package-lock made npm re-resolve the whole tree and upgrade eslint, whose newer recommended config flagged no-useless-assignment as an error in the server lint step. Keep the lockfile so only @swc/core-linux-x64-gnu is added and every other dependency (incl. eslint) stays at its locked version.
587 lines
23 KiB
TypeScript
587 lines
23 KiB
TypeScript
// FE-COMP-FILEMANAGER-001 to FE-COMP-FILEMANAGER-012
|
|
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';
|
|
import { useAuthStore } from '../../store/authStore';
|
|
import { useTripStore } from '../../store/tripStore';
|
|
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
|
import { buildUser, buildTrip } from '../../../tests/helpers/factories';
|
|
import type { TripFile } from '../../types';
|
|
import FileManager from './FileManager';
|
|
|
|
// Mock getAuthUrl
|
|
vi.mock('../../api/authUrl', () => ({
|
|
getAuthUrl: vi.fn().mockResolvedValue('http://localhost/signed-url'),
|
|
}));
|
|
|
|
// Mock filesApi
|
|
vi.mock('../../api/client', async (importOriginal) => {
|
|
const original = (await importOriginal()) as any;
|
|
return {
|
|
...original,
|
|
filesApi: {
|
|
list: vi.fn().mockResolvedValue({ files: [] }),
|
|
toggleStar: vi.fn().mockResolvedValue({}),
|
|
restore: vi.fn().mockResolvedValue({}),
|
|
permanentDelete: vi.fn().mockResolvedValue({}),
|
|
emptyTrash: vi.fn().mockResolvedValue({}),
|
|
upload: vi.fn().mockResolvedValue({ file: { id: 99 } }),
|
|
update: vi.fn().mockResolvedValue({}),
|
|
addLink: vi.fn().mockResolvedValue({}),
|
|
removeLink: vi.fn().mockResolvedValue({}),
|
|
getLinks: vi.fn().mockResolvedValue({ links: [] }),
|
|
},
|
|
};
|
|
});
|
|
|
|
import { filesApi } from '../../api/client';
|
|
|
|
const buildFile = (overrides: Partial<TripFile> = {}): TripFile => ({
|
|
id: 1,
|
|
trip_id: 1,
|
|
filename: 'report.pdf',
|
|
original_name: 'report.pdf',
|
|
mime_type: 'application/pdf',
|
|
file_size: 51200,
|
|
created_at: '2025-01-10T08:00:00Z',
|
|
url: '/uploads/trips/1/report.pdf',
|
|
starred: 0,
|
|
deleted_at: null,
|
|
place_id: null,
|
|
reservation_id: null,
|
|
uploaded_by: 1,
|
|
uploaded_by_name: 'Alice',
|
|
...overrides,
|
|
});
|
|
|
|
const defaultProps = {
|
|
files: [],
|
|
onUpload: vi.fn().mockResolvedValue({}),
|
|
onDelete: vi.fn().mockResolvedValue(undefined),
|
|
onUpdate: vi.fn().mockResolvedValue(undefined),
|
|
places: [],
|
|
days: [],
|
|
assignments: {},
|
|
reservations: [],
|
|
tripId: 1,
|
|
allowedFileTypes: null,
|
|
};
|
|
|
|
beforeEach(() => {
|
|
resetAllStores();
|
|
vi.clearAllMocks();
|
|
// Seed auth as admin so useCanDo() returns true for all permissions
|
|
seedStore(useAuthStore, { user: buildUser({ role: 'admin' }), isAuthenticated: true });
|
|
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
|
|
|
|
// Default trash endpoint
|
|
server.use(
|
|
http.get('/api/trips/:tripId/files', ({ request }) => {
|
|
const url = new URL(request.url);
|
|
if (url.searchParams.get('trash') === 'true') {
|
|
return HttpResponse.json({ files: [] });
|
|
}
|
|
return HttpResponse.json({ files: [] });
|
|
}),
|
|
);
|
|
|
|
// Stub window.confirm
|
|
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
|
});
|
|
|
|
describe('FileManager', () => {
|
|
it('FE-COMP-FILEMANAGER-001: renders empty state when no files', async () => {
|
|
render(<FileManager {...defaultProps} files={[]} />);
|
|
// The dropzone should be visible (Upload icon area)
|
|
expect(screen.getByText(/drop/i)).toBeInTheDocument();
|
|
// No file rows
|
|
expect(screen.queryByText('report.pdf')).not.toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-002: renders file list when files are provided', async () => {
|
|
render(<FileManager {...defaultProps} files={[buildFile()]} />);
|
|
expect(screen.getByText('report.pdf')).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-003: file type filter tabs are present', async () => {
|
|
render(<FileManager {...defaultProps} files={[buildFile()]} />);
|
|
// Filter tabs should be present — match the button elements specifically
|
|
expect(screen.getByRole('button', { name: /^all$/i })).toBeInTheDocument();
|
|
expect(screen.getByRole('button', { name: /^pdfs$/i })).toBeInTheDocument();
|
|
expect(screen.getByRole('button', { name: /^images$/i })).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-004: images tab filters to image files only', async () => {
|
|
const files = [
|
|
buildFile({ id: 1, mime_type: 'image/jpeg', original_name: 'photo.jpg' }),
|
|
buildFile({ id: 2, mime_type: 'application/pdf', original_name: 'doc.pdf' }),
|
|
];
|
|
render(<FileManager {...defaultProps} files={files} />);
|
|
// Both should be visible initially
|
|
expect(screen.getByText('photo.jpg')).toBeInTheDocument();
|
|
expect(screen.getByText('doc.pdf')).toBeInTheDocument();
|
|
|
|
// Click Images filter tab
|
|
const user = userEvent.setup();
|
|
const imageTab = screen.getByRole('button', { name: /^images$/i });
|
|
await user.click(imageTab);
|
|
|
|
// Only photo should be visible
|
|
expect(screen.getByText('photo.jpg')).toBeInTheDocument();
|
|
expect(screen.queryByText('doc.pdf')).not.toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-005: star button calls filesApi.toggleStar', async () => {
|
|
render(<FileManager {...defaultProps} files={[buildFile()]} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Find the star button by its title
|
|
const starBtn = screen.getByTitle(/star/i);
|
|
await user.click(starBtn);
|
|
|
|
expect(filesApi.toggleStar).toHaveBeenCalledWith(1, 1);
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-006: trash toggle loads and displays trashed files', async () => {
|
|
// filesApi.list is mocked — configure it to return trash files when called with trash=true
|
|
(filesApi.list as ReturnType<typeof vi.fn>).mockImplementation((_tripId, trash) => {
|
|
if (trash) return Promise.resolve({ files: [buildFile({ id: 5, original_name: 'old.pdf', deleted_at: '2025-02-01' })] });
|
|
return Promise.resolve({ files: [] });
|
|
});
|
|
|
|
render(<FileManager {...defaultProps} files={[]} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Click trash toggle button
|
|
const trashBtn = screen.getByText(/trash/i);
|
|
await user.click(trashBtn);
|
|
|
|
// Trashed file should appear
|
|
await screen.findByText('old.pdf');
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-007: restore button calls filesApi.restore', async () => {
|
|
(filesApi.list as ReturnType<typeof vi.fn>).mockImplementation((_tripId, trash) => {
|
|
if (trash) return Promise.resolve({ files: [buildFile({ id: 5, original_name: 'old.pdf', deleted_at: '2025-02-01' })] });
|
|
return Promise.resolve({ files: [] });
|
|
});
|
|
|
|
render(<FileManager {...defaultProps} files={[]} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Open trash
|
|
const trashBtn = screen.getByText(/trash/i);
|
|
await user.click(trashBtn);
|
|
await screen.findByText('old.pdf');
|
|
|
|
// Click restore button
|
|
const restoreBtn = screen.getByTitle(/restore/i);
|
|
await user.click(restoreBtn);
|
|
|
|
expect(filesApi.restore).toHaveBeenCalledWith(1, 5);
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-008: permanent delete calls filesApi.permanentDelete after confirm', async () => {
|
|
(filesApi.list as ReturnType<typeof vi.fn>).mockImplementation((_tripId, trash) => {
|
|
if (trash) return Promise.resolve({ files: [buildFile({ id: 5, original_name: 'old.pdf', deleted_at: '2025-02-01' })] });
|
|
return Promise.resolve({ files: [] });
|
|
});
|
|
|
|
render(<FileManager {...defaultProps} files={[]} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Open trash
|
|
await user.click(screen.getByText(/trash/i));
|
|
await screen.findByText('old.pdf');
|
|
|
|
// Click permanent delete (the Trash2 icon button in trash view)
|
|
const deleteBtn = screen.getByTitle(/delete/i);
|
|
await user.click(deleteBtn);
|
|
|
|
expect(filesApi.permanentDelete).toHaveBeenCalledWith(1, 5);
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-009: empty trash calls filesApi.emptyTrash', async () => {
|
|
(filesApi.list as ReturnType<typeof vi.fn>).mockImplementation((_tripId, trash) => {
|
|
if (trash) return Promise.resolve({ files: [buildFile({ id: 5, original_name: 'old.pdf', deleted_at: '2025-02-01' })] });
|
|
return Promise.resolve({ files: [] });
|
|
});
|
|
|
|
render(<FileManager {...defaultProps} files={[]} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Open trash
|
|
await user.click(screen.getByText(/trash/i));
|
|
await screen.findByText('old.pdf');
|
|
|
|
// Click "Empty Trash" button
|
|
const emptyTrashBtn = await screen.findByText(/empty trash/i);
|
|
await user.click(emptyTrashBtn);
|
|
|
|
expect(filesApi.emptyTrash).toHaveBeenCalledWith(1);
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-010: image file click opens lightbox', async () => {
|
|
const files = [
|
|
buildFile({ id: 1, mime_type: 'image/jpeg', original_name: 'photo.jpg' }),
|
|
];
|
|
render(<FileManager {...defaultProps} files={files} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Click the file name to open lightbox
|
|
await user.click(screen.getByText('photo.jpg'));
|
|
|
|
// Lightbox should appear — it has a fixed position overlay with the filename and a counter
|
|
await waitFor(() => {
|
|
// The lightbox header shows the filename and "1 / 1"
|
|
expect(screen.getByText('1 / 1')).toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-011: escape key closes lightbox', async () => {
|
|
const files = [
|
|
buildFile({ id: 1, mime_type: 'image/jpeg', original_name: 'photo.jpg' }),
|
|
];
|
|
render(<FileManager {...defaultProps} files={files} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Open lightbox
|
|
await user.click(screen.getByText('photo.jpg'));
|
|
await waitFor(() => {
|
|
expect(screen.getByText('1 / 1')).toBeInTheDocument();
|
|
});
|
|
|
|
// Press Escape
|
|
await user.keyboard('{Escape}');
|
|
|
|
// Lightbox should be gone
|
|
await waitFor(() => {
|
|
expect(screen.queryByText('1 / 1')).not.toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-013: soft-delete button calls onDelete', async () => {
|
|
const onDelete = vi.fn().mockResolvedValue(undefined);
|
|
render(<FileManager {...defaultProps} files={[buildFile()]} onDelete={onDelete} />);
|
|
const user = userEvent.setup();
|
|
|
|
// The delete (trash) button on a non-trash row is titled 'Delete'
|
|
const deleteBtn = screen.getByTitle(/delete/i);
|
|
await user.click(deleteBtn);
|
|
|
|
expect(onDelete).toHaveBeenCalledWith(1);
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-014: PDF file click opens preview modal', async () => {
|
|
const files = [buildFile({ id: 1, mime_type: 'application/pdf', original_name: 'report.pdf' })];
|
|
render(<FileManager {...defaultProps} files={files} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Click the file name — for a non-image this opens the PDF preview modal
|
|
await user.click(screen.getByText('report.pdf'));
|
|
|
|
// PDF preview modal should appear with the filename in the header
|
|
await waitFor(() => {
|
|
// The preview modal header shows the filename
|
|
const headers = screen.getAllByText('report.pdf');
|
|
expect(headers.length).toBeGreaterThanOrEqual(2); // in list + in modal header
|
|
});
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-015: file with uploader name shows avatar chip initials', () => {
|
|
const files = [buildFile({ uploaded_by_name: 'Alice Smith' })];
|
|
render(<FileManager {...defaultProps} files={files} />);
|
|
|
|
// The AvatarChip shows the first letter of the name
|
|
expect(screen.getByText('A')).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-016: multiple images in lightbox shows thumbnail strip', async () => {
|
|
const files = [
|
|
buildFile({ id: 1, mime_type: 'image/jpeg', original_name: 'photo1.jpg' }),
|
|
buildFile({ id: 2, mime_type: 'image/jpeg', original_name: 'photo2.jpg' }),
|
|
];
|
|
render(<FileManager {...defaultProps} files={files} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Open lightbox on first image
|
|
await user.click(screen.getByText('photo1.jpg'));
|
|
|
|
// Lightbox shows "1 / 2" counter
|
|
await waitFor(() => {
|
|
expect(screen.getByText('1 / 2')).toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-017: file size is displayed', () => {
|
|
const files = [buildFile({ file_size: 51200 })];
|
|
render(<FileManager {...defaultProps} files={files} />);
|
|
expect(screen.getByText('50.0 KB')).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-018: starred filter shows only starred files', async () => {
|
|
const files = [
|
|
buildFile({ id: 1, original_name: 'starred.pdf', starred: 1 }),
|
|
buildFile({ id: 2, original_name: 'normal.pdf', starred: 0 }),
|
|
];
|
|
render(<FileManager {...defaultProps} files={files} />);
|
|
const user = userEvent.setup();
|
|
|
|
// The starred filter tab only appears when there are starred files
|
|
const starredTab = screen.getByRole('button', { name: '' }); // Star icon button in filter tabs
|
|
await user.click(starredTab);
|
|
|
|
expect(screen.getByText('starred.pdf')).toBeInTheDocument();
|
|
expect(screen.queryByText('normal.pdf')).not.toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-019: clicking assign button opens assign modal', async () => {
|
|
render(<FileManager {...defaultProps} files={[buildFile()]} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Pencil/assign button
|
|
const assignBtn = screen.getByTitle(/assign/i);
|
|
await user.click(assignBtn);
|
|
|
|
// Assign modal should appear (it has a title and a close button)
|
|
await waitFor(() => {
|
|
expect(screen.getByText(/assign/i, { selector: 'div' })).toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-020: assign modal shows places list', async () => {
|
|
const { buildPlace } = await import('../../../tests/helpers/factories');
|
|
const place = buildPlace({ id: 10, name: 'Eiffel Tower' });
|
|
render(<FileManager {...defaultProps} files={[buildFile()]} places={[place]} />);
|
|
const user = userEvent.setup();
|
|
|
|
const assignBtn = screen.getByTitle(/assign/i);
|
|
await user.click(assignBtn);
|
|
|
|
await screen.findByText('Eiffel Tower');
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-021: file description is shown when present', () => {
|
|
const files = [buildFile({ description: 'A very important document' })];
|
|
render(<FileManager {...defaultProps} files={files} />);
|
|
expect(screen.getByText('A very important document')).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-022: PDF preview modal can be closed', async () => {
|
|
const files = [buildFile({ id: 1, mime_type: 'application/pdf', original_name: 'report.pdf' })];
|
|
render(<FileManager {...defaultProps} files={files} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Open preview
|
|
await user.click(screen.getByText('report.pdf'));
|
|
|
|
// Multiple 'report.pdf' elements now (list + modal header)
|
|
await waitFor(() => {
|
|
expect(screen.getAllByText('report.pdf').length).toBeGreaterThanOrEqual(2);
|
|
});
|
|
|
|
// Close via X button in the modal (second X button — first might be something else)
|
|
const closeButtons = screen.getAllByRole('button', { name: '' });
|
|
// Find a close button near the modal header — click the last X-like button
|
|
const xBtn = closeButtons.find(btn => btn.closest('[style*="z-index: 10000"]'));
|
|
if (xBtn) await user.click(xBtn);
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-023: assign modal shows reservations list', async () => {
|
|
const { buildReservation } = await import('../../../tests/helpers/factories');
|
|
const reservation = buildReservation({ id: 20, title: 'Hotel Paris' });
|
|
render(<FileManager {...defaultProps} files={[buildFile()]} reservations={[reservation]} />);
|
|
const user = userEvent.setup();
|
|
|
|
const assignBtn = screen.getByTitle(/assign/i);
|
|
await user.click(assignBtn);
|
|
|
|
await screen.findByText('Hotel Paris');
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-024: clicking a place in assign modal calls filesApi.update', async () => {
|
|
const { buildPlace } = await import('../../../tests/helpers/factories');
|
|
const place = buildPlace({ id: 10, name: 'Louvre Museum' });
|
|
const file = buildFile({ id: 1 });
|
|
const onUpdate = vi.fn().mockResolvedValue(undefined);
|
|
render(<FileManager {...defaultProps} files={[file]} places={[place]} onUpdate={onUpdate} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Open assign modal
|
|
await user.click(screen.getByTitle(/assign/i));
|
|
await screen.findByText('Louvre Museum');
|
|
|
|
// Click on the place button to link it
|
|
await user.click(screen.getByText('Louvre Museum'));
|
|
|
|
expect(filesApi.update).toHaveBeenCalledWith(1, 1, { place_id: 10 });
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-025: clicking a reservation in assign modal calls filesApi.update', async () => {
|
|
const { buildReservation } = await import('../../../tests/helpers/factories');
|
|
const reservation = buildReservation({ id: 20, title: 'Train Ticket' });
|
|
const file = buildFile({ id: 1 });
|
|
render(<FileManager {...defaultProps} files={[file]} reservations={[reservation]} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Open assign modal
|
|
await user.click(screen.getByTitle(/assign/i));
|
|
await screen.findByText('Train Ticket');
|
|
|
|
// Click on the reservation button to link it
|
|
await user.click(screen.getByText('Train Ticket'));
|
|
|
|
expect(filesApi.update).toHaveBeenCalledWith(1, 1, { reservation_id: 20 });
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-026: assign modal with both places and reservations shows both sections', async () => {
|
|
const { buildPlace, buildReservation } = await import('../../../tests/helpers/factories');
|
|
const place = buildPlace({ id: 10, name: 'Notre Dame' });
|
|
const reservation = buildReservation({ id: 20, title: 'Airbnb' });
|
|
render(<FileManager {...defaultProps} files={[buildFile()]} places={[place]} reservations={[reservation]} />);
|
|
const user = userEvent.setup();
|
|
|
|
await user.click(screen.getByTitle(/assign/i));
|
|
await screen.findByText('Notre Dame');
|
|
await screen.findByText('Airbnb');
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-027: paste event uploads file when user can upload', async () => {
|
|
const onUpload = vi.fn().mockResolvedValue({ file: { id: 55 } });
|
|
render(<FileManager {...defaultProps} onUpload={onUpload} />);
|
|
|
|
const container = document.querySelector('.flex.flex-col') as HTMLElement;
|
|
const file = new File(['data'], 'pasted.png', { type: 'image/png' });
|
|
|
|
// Manually build a paste event with a mock clipboardData.items
|
|
const mockItem = { kind: 'file', getAsFile: () => file };
|
|
const pasteEvent = new Event('paste', { bubbles: true });
|
|
Object.defineProperty(pasteEvent, 'clipboardData', {
|
|
value: { items: [mockItem] },
|
|
});
|
|
|
|
await fireEvent(container, pasteEvent);
|
|
|
|
await waitFor(() => {
|
|
expect(onUpload).toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-028: upload with places open assign modal after upload', async () => {
|
|
const { buildPlace } = await import('../../../tests/helpers/factories');
|
|
const place = buildPlace({ id: 10, name: 'Sagrada Familia' });
|
|
const onUpload = vi.fn().mockResolvedValue({ file: { id: 77 } });
|
|
|
|
render(<FileManager {...defaultProps} onUpload={onUpload} places={[place]} />);
|
|
|
|
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
|
const file = new File(['data'], 'photo.jpg', { type: 'image/jpeg' });
|
|
await userEvent.upload(input, file);
|
|
|
|
// After successful upload with places present, assign modal opens
|
|
await waitFor(() => {
|
|
expect(onUpload).toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-029: assign modal with days+assignments shows day group', async () => {
|
|
const { buildPlace, buildDay } = await import('../../../tests/helpers/factories');
|
|
const place = buildPlace({ id: 10, name: 'Arc de Triomphe' });
|
|
const day = buildDay({ id: 5, date: '2025-06-01', day_number: 1 });
|
|
const assignments = { '5': [{ id: 1, day_id: 5, place_id: 10, order_index: 0, place }] };
|
|
|
|
render(<FileManager {...defaultProps} files={[buildFile()]} places={[place]} days={[day]} assignments={assignments} />);
|
|
const user = userEvent.setup();
|
|
|
|
await user.click(screen.getByTitle(/assign/i));
|
|
await screen.findByText('Arc de Triomphe');
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-030: file with linked place shows source badge', async () => {
|
|
const { buildPlace } = await import('../../../tests/helpers/factories');
|
|
const place = buildPlace({ id: 10, name: 'Colosseum' });
|
|
const file = buildFile({ place_id: 10 });
|
|
|
|
render(<FileManager {...defaultProps} files={[file]} places={[place]} />);
|
|
|
|
// Source badge text includes place name
|
|
await screen.findByText(/Colosseum/);
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-031: unlink place from assign modal calls filesApi.update', async () => {
|
|
const { buildPlace } = await import('../../../tests/helpers/factories');
|
|
const place = buildPlace({ id: 10, name: 'Venice Beach' });
|
|
// File already has place_id set to 10 (linked)
|
|
const file = buildFile({ id: 1, place_id: 10 });
|
|
|
|
render(<FileManager {...defaultProps} files={[file]} places={[place]} />);
|
|
const user = userEvent.setup();
|
|
|
|
// Open assign modal
|
|
await user.click(screen.getByTitle(/assign/i));
|
|
await screen.findByText('Venice Beach');
|
|
|
|
// Clicking the linked place should unlink it
|
|
await user.click(screen.getByText('Venice Beach'));
|
|
expect(filesApi.update).toHaveBeenCalledWith(1, 1, { place_id: null });
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-032: unlink reservation from assign modal calls filesApi.update', async () => {
|
|
const { buildReservation } = await import('../../../tests/helpers/factories');
|
|
const reservation = buildReservation({ id: 20, title: 'Museum Pass' });
|
|
// File already has reservation_id set to 20
|
|
const file = buildFile({ id: 1, reservation_id: 20 });
|
|
|
|
render(<FileManager {...defaultProps} files={[file]} reservations={[reservation]} />);
|
|
const user = userEvent.setup();
|
|
|
|
await user.click(screen.getByTitle(/assign/i));
|
|
await screen.findByText('Museum Pass');
|
|
|
|
// Clicking the linked reservation should unlink it
|
|
await user.click(screen.getByText('Museum Pass'));
|
|
expect(filesApi.update).toHaveBeenCalledWith(1, 1, { reservation_id: null });
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-033: opening PDF preview and closing via backdrop', async () => {
|
|
const files = [buildFile({ id: 1, mime_type: 'application/pdf', original_name: 'doc.pdf' })];
|
|
render(<FileManager {...defaultProps} files={files} />);
|
|
const user = userEvent.setup();
|
|
|
|
await user.click(screen.getByText('doc.pdf'));
|
|
|
|
// Modal opens (multiple occurrences of doc.pdf)
|
|
await waitFor(() => {
|
|
expect(screen.getAllByText('doc.pdf').length).toBeGreaterThanOrEqual(2);
|
|
});
|
|
|
|
// Click the backdrop to close
|
|
const backdrop = document.querySelector('[style*="z-index: 10000"]') as HTMLElement;
|
|
if (backdrop) await user.click(backdrop);
|
|
|
|
await waitFor(() => {
|
|
expect(screen.getAllByText('doc.pdf').length).toBeLessThan(2);
|
|
});
|
|
});
|
|
|
|
it('FE-COMP-FILEMANAGER-012: upload via dropzone calls onUpload', async () => {
|
|
const onUpload = vi.fn().mockResolvedValue({ file: { id: 99 } });
|
|
render(<FileManager {...defaultProps} onUpload={onUpload} />);
|
|
|
|
// Find the hidden file input from the dropzone
|
|
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
|
expect(input).toBeTruthy();
|
|
|
|
const file = new File(['hello'], 'test.pdf', { type: 'application/pdf' });
|
|
|
|
await userEvent.upload(input, file);
|
|
|
|
await waitFor(() => {
|
|
expect(onUpload).toHaveBeenCalled();
|
|
const call = onUpload.mock.calls[0];
|
|
expect(call[0]).toBeInstanceOf(FormData);
|
|
});
|
|
});
|
|
});
|