mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-06-21 06:11:45 +00:00
d152f9d02b
* fix(shared-view): render each leg of multi-leg flights correctly The read-only shared view showed the overall trip start/end airports and the first leg's flight number on every leg of a multi-leg flight. The Day Plan already expands legs (each carries __leg), but the renderer ignored it and read flat top-level metadata; the Bookings tab had the same bug. - Day Plan: use __leg for per-leg airline/flight number/route, plus dep-arr time - Bookings tab: list each leg via getFlightLegs() - unique React keys for multi-leg rows Closes #1219 * feat(pdf): add legs to pdf export * fix(demo): skip first-run admin seed in demo mode When DEMO_MODE is on, the demo seeder creates its own admin (admin@trek.app, username "admin") right after the generic seeds run. The first-run admin bootstrap was grabbing username "admin" first, so the demo seeder hit the UNIQUE(username) constraint and aborted before the demo user was ever created - which surfaced as a 500 "Demo user not found" on demo-login. Skip the generic admin bootstrap when demo mode owns the admin account. * fix(docker): ship the encryption-key migration script in the image The production image only copied server/dist, so the documented rotation command `node --import tsx scripts/migrate-encryption.ts` failed inside the container with a module-not-found error - the raw .ts was never present. The script runs via tsx straight from source and only pulls node builtins plus better-sqlite3 (both prod deps), so copying the single file into /app/server/scripts is enough to make the rotation work again. * fix(vacay): keep the mode toolbar above the mobile bottom nav The floating Vacation/Company toolbar was pinned at bottom-3 with z-30, so on mobile it landed in the same band as the fixed bottom nav (z-60) and got hidden behind it - and could scroll out of reach entirely. Pin it above the nav with the shared --bottom-nav-h variable (0px on desktop, so nothing changes there) and reserve matching space below the calendar grid so it never gets swallowed. * fix(dashboard): show the correct reservation date regardless of timezone The upcoming-reservations widget built the date with new Date(reservation_time) .toISOString(), which reinterprets the stored naive local time as UTC and can roll the displayed day forward in non-UTC timezones (e.g. a 23:30 reservation showing the next day). Read the date and time straight from the stored string parts via splitReservationDateTime, and format the time with the shared formatTime helper so it also honours the user's 12h/24h preference. * fix(atlas): cursor-following tooltips and removing countries from search Two related Atlas fixes: - Country tooltips were bound with sticky:false, which anchors them at the feature's bounds centre. For countries with overseas territories (e.g. France) that centre sits far out in the ocean, so the tooltip popped up nowhere near the area being hovered. Make them sticky so they track the cursor. - Selecting an already-visited country from the search bar always opened the "Mark / Bucket" dialog, with no way to remove it. Tiny countries like Vatican City or Singapore are hard to hit on the map, so search was the only way in. Mirror the map-click behaviour: a manually-marked country opens the Remove confirmation, a trip/place-backed one opens its detail. * fix(oidc): keep dots in generated usernames The OIDC username sanitizer stripped dots because they were missing from the allowed character class, so a name claim like "first.last" became "firstlast". Dots are valid usernames (the profile validator already allows ^[a-zA-Z0-9_.-]+$), so add the dot to the sanitizer. * fix(collab): show poll option labels in the UI The poll API formatted each option as { label, voters }, but the React poll component renders opt.text - so every option button came out blank. Emit text alongside label (kept for any other consumer) so options render again. * feat(backup): make the upload size limit configurable The restore upload was capped at a hard-coded 500 MB, so instances whose backup archive (uploads/ included) grew past that got a 413 "File too large" with no way to raise it. Add a BACKUP_UPLOAD_LIMIT_MB env var (default 500, invalid values warn and fall back), documented in .env.example. * feat(costs): create an expense from a booking, fix editing total-only items Replace the inline price + budget-category fields in the Transport and Reservation booking modals with a "Create expense" flow: the modal saves the booking, then opens the full Costs editor prefilled (name + category mapped from the booking type) and linked to the reservation. A booking with a linked expense shows it inline with edit / remove. Also fix the Costs editor so an expense with a recorded total but no payers (transport-derived or pre-rework items) opens with its amount, lets you set the currency, and saves - it previously showed 0 everywhere and could not be saved. Legacy / localized categories now map to the fixed keys, and changing a booking's type keeps its linked expense category in sync (unless it was manually set). - shared: reservation_id on budget create, typeToCostCategory helper, i18n keys - server: createBudgetItem stores reservation_id; keep total_price for payerless items; a booking update no longer wipes its linked expense and syncs the category on type change - client: shared BookingCostsSection, exported ExpenseModal with prefill and an editable total, page-level save-then-open wiring * test(reservations): align syncBudgetOnUpdate unit tests with no-wipe + type-sync The service now leaves a linked expense alone when no budget entry is on the payload (only an explicit total_price 0 deletes it) and syncs the category on a booking type change. Update the unit tests accordingly - the old "price cleared" case passed entry: undefined, which is now a no-op and left a mocked return queued that leaked into the next test. * fix(planner): keep a reservation on its day when edited (#1237) Editing a booking forced its day_id to the globally selected day, which is null when editing from the Book tab - so the booking lost its day and vanished from the Plan. Preserve the reservation own day_id on edit instead. * fix(planner): derive a booking day from its date when none is set (#1237) The client always sends day_id on a reservation update, so the server only derived it from reservation_time when the field was absent. A non-transport booking saved without a selected day (Book tab) therefore got day_id null and vanished from the Plan, even though its date matched a day. Derive the day from reservation_time whenever day_id is null, mirroring create. * fix(planner): let a booking's day follow its date when edited (#1237) Preserving the old day_id on edit left a re-dated booking on its previous start day while end_day_id followed the new date, so it spanned both. Stop sending day_id from the edit modal entirely - the server derives both ends from the booking's date (and keeps the current day when there is no date), so a re-dated booking moves cleanly to the matching day. * fix(atlas): keep the continent breakdown in sync on mark/unmark (#1225) The optimistic mark/unmark updates bumped the country total but never the per-continent counts, so the continent column froze until a full reload. Move the country to continent map into @trek/shared (single source for server and client) and adjust the matching continent count at every optimistic site: the country confirm flow plus the choose / region mark and region unmark handlers. * feat(admin): let admins set a default currency for new users Adds a currency picker to Admin > User Defaults. Stored as the default_currency user-default, so users who have not picked their own currency inherit it in Costs. * fix(atlas): give every sub-national region a distinct code (#1217) geoBoundaries fills shapeISO with the bare country code for some countries (every Spanish region got "ESP", every Chinese "CHN", also Chile/Oman), so marking one region lit up the whole country. build-atlas-geo.mjs now keeps shapeISO only when it is a real "XX-..." subdivision code and otherwise synthesizes a unique per-country id from the region name. Regenerated admin1.geojson.gz: Spain/China/ Chile/Oman now carry distinct region codes (countries with real codes, e.g. Germany, are unchanged). * fix(dashboard): never crash on a malformed reservation date A reservation with an invalid date blanked the whole My Trips page: the old Upcoming widget did new Date(value).toISOString(), which throws "Invalid time value" (fixed in #1222 by reading the string parts). Also guard splitDate so a bad date renders a dash instead of "Invalid Date" or throwing. * fix(airtrail): gate airtrail update behind a user setting, on airtrail update: rebuild payload from fresh data to prevent any data loss * fix(airtrail): add back missing tests * fix(costs): rework the cost panel UX wise and apply prettier on the shared package * chore(prettier) prettier this file * fix(airtrail): don't use cabin class as seat on import When an AirTrail flight has a cabin class but no seat number, the mapper fell back to the class for metadata.seat, so reservations showed e.g. "economy" as the seat. Use only the seat number; leave the seat blank otherwise. The class is still surfaced separately in the import picker. Closes #1246 * fix(airtrail): import scheduled flight times instead of actual AirTrail exposes both scheduled (departureScheduled/arrivalScheduled) and actual (departure/arrival) times. TREK read the actual times, so a delayed or early flight imported the wrong time for planning. Read the scheduled times on import and on poll-sync (both go through mapFlightToReservation); when a flight has no scheduled time, leave the clock blank (date preserved) rather than fabricating 00:00 or falling back to actual. The change-detection hash now tracks the scheduled values, so existing linked reservations re-sync once on the next poll. The opt-in writeback mirrors the read, pushing TREK edits to the scheduled fields so they round-trip. * fix(planner): hydrate per-assignment times when editing a place from the pool Times live per day-assignment, not on the pool place, so reopening a place from the Places panel / inspector showed empty Start/End fields (#1247). The editor now resolves a place's lone assignment when no day is in context and hydrates the fields from it; ambiguous (0 or 2+ days) edits hide the fields instead of showing non-persisting inputs. * fix(mcp): make write tools return client-valid, hydrated entities Audit of all write tools under server/src/mcp/tools (issue #1244 anchor). S1 (broken): - create_budget_item / create_budget_item_with_members now default the split to all trip members when member_ids omitted, so the entry passes the client save-gate instead of being member-less (#1244). - create_transport / update_transport backfill lat/lng/timezone for code-only flight endpoints (NOT NULL columns) and return a clean error for unresolvable endpoints instead of crashing. S2 (under-hydration): set_budget_item_members, create_journey, create_journey_entry, create_packing_bag, bulk_import_packing and update_vacay_plan now return the hydrated shape the matching read/REST route returns; bulk_import widened to accept bag/weight_grams/checked. S3 (parity): check_in_end added to accommodation tools; atlas mark_region_visited echoes the client shape; update_journey_entry/ update_journey_preferences, set_bag_members, set_packing_category_assignees, apply_packing_template return hydrated payloads; set_vacay_color echoes the color. Auth: save_packing_template now requires admin, matching the REST gate. Also refactors server/src/config.ts (JWT-secret handling). Adds getBudgetItem hydrated getter, exports EndpointInput, and MCP regression tests (incl. new tools-transports and tools-journey suites). * fix(mcp): fix ICS/maps/accommodation bugs, add settlement & template tools Bugs: - export_trip_ics: include flights that store times per-endpoint (local_date/local_time) instead of a top-level reservation_time - resolve_maps_url: follow redirects for cid=/share links and fall back to parsing the page body, all SSRF-guarded - link_hotel_accommodation: normalize accommodation_id (TEXT column) to an integer in the reservation read paths so it no longer returns "14.0" Gaps: - packing: save_packing_template returns the new template id; add list_packing_templates (read) and delete_packing_template (admin) - budget: update_budget_item accepts payers/member_ids; clarify create/ update/members descriptions to ask which members share the expense and who paid - budget: add settlement tools — get_settlement_summary, list_settlements, create/update/delete_settlement (budget_edit, mirrors REST + WS events) * chore: bump nodemailer * chore: bump multer --------- Co-authored-by: Maurice <mauriceboe@icloud.com>
567 lines
25 KiB
TypeScript
567 lines
25 KiB
TypeScript
// FE-COMP-PLACEFORM-001 to FE-COMP-PLACEFORM-036
|
|
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';
|
|
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, buildPlace, buildCategory, buildAssignment } from '../../../tests/helpers/factories';
|
|
import PlaceFormModal from './PlaceFormModal';
|
|
|
|
// Mock CustomTimePicker so we get a simple text input instead of the portal-heavy UI
|
|
vi.mock('../shared/CustomTimePicker', () => ({
|
|
default: ({ value, onChange, placeholder }: { value: string; onChange: (v: string) => void; placeholder?: string }) => (
|
|
<input
|
|
data-testid="time-picker"
|
|
type="text"
|
|
value={value}
|
|
onChange={e => onChange(e.target.value)}
|
|
placeholder={placeholder ?? '00:00'}
|
|
/>
|
|
),
|
|
}));
|
|
|
|
const defaultProps = {
|
|
isOpen: true,
|
|
onClose: vi.fn(),
|
|
onSave: vi.fn(),
|
|
place: null,
|
|
prefillCoords: null,
|
|
tripId: 1,
|
|
categories: [],
|
|
onCategoryCreated: vi.fn(),
|
|
assignmentId: null,
|
|
dayAssignments: [],
|
|
};
|
|
|
|
beforeEach(() => {
|
|
resetAllStores();
|
|
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true, hasMapsKey: false });
|
|
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
|
|
});
|
|
|
|
describe('PlaceFormModal', () => {
|
|
it('FE-COMP-PLACEFORM-001: renders modal when isOpen is true', () => {
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
expect(document.body).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-002: shows Add Place title for new place', () => {
|
|
render(<PlaceFormModal {...defaultProps} place={null} />);
|
|
// places.addPlace = "Add Place/Activity"
|
|
expect(screen.getAllByText(/Add Place\/Activity/i).length).toBeGreaterThan(0);
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-003: shows Edit Place title when editing', () => {
|
|
const place = buildPlace({ name: 'Eiffel Tower' });
|
|
render(<PlaceFormModal {...defaultProps} place={place} />);
|
|
expect(screen.getByText('Edit Place')).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-004: shows Name field with placeholder', () => {
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
expect(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i)).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-005: shows Description field', () => {
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
expect(screen.getByPlaceholderText(/Short description/i)).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-006: shows Address field', () => {
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
expect(screen.getByPlaceholderText(/Street, City, Country/i)).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-007: shows Add button for new place', () => {
|
|
render(<PlaceFormModal {...defaultProps} place={null} />);
|
|
expect(screen.getByRole('button', { name: /^Add$/i })).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-008: shows Update button when editing', () => {
|
|
const place = buildPlace({ name: 'Test Place' });
|
|
render(<PlaceFormModal {...defaultProps} place={place} />);
|
|
expect(screen.getByRole('button', { name: /^Update$/i })).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-009: shows Cancel button', () => {
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
expect(screen.getByRole('button', { name: /Cancel/i })).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-010: clicking Cancel calls onClose', async () => {
|
|
const user = userEvent.setup();
|
|
const onClose = vi.fn();
|
|
render(<PlaceFormModal {...defaultProps} onClose={onClose} />);
|
|
await user.click(screen.getByRole('button', { name: /Cancel/i }));
|
|
expect(onClose).toHaveBeenCalled();
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-011: pre-fills name field when editing existing place', () => {
|
|
const place = buildPlace({ name: 'Notre Dame' });
|
|
render(<PlaceFormModal {...defaultProps} place={place} />);
|
|
const nameInput = screen.getByDisplayValue('Notre Dame');
|
|
expect(nameInput).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-012: pre-fills address when editing existing place', () => {
|
|
const place = buildPlace({ name: 'Test', address: '123 Main St' });
|
|
render(<PlaceFormModal {...defaultProps} place={place} />);
|
|
expect(screen.getByDisplayValue('123 Main St')).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-013: submitting empty form does not call onSave (name required)', async () => {
|
|
const user = userEvent.setup();
|
|
const onSave = vi.fn();
|
|
render(<PlaceFormModal {...defaultProps} onSave={onSave} />);
|
|
await user.click(screen.getByRole('button', { name: /^Add$/i }));
|
|
// Form validation prevents calling onSave without a name
|
|
expect(onSave).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-014: typing in name field and submitting calls onSave', async () => {
|
|
const user = userEvent.setup();
|
|
const onSave = vi.fn().mockResolvedValue(undefined);
|
|
render(<PlaceFormModal {...defaultProps} onSave={onSave} />);
|
|
await user.type(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), 'Sacre Coeur');
|
|
await user.click(screen.getByRole('button', { name: /^Add$/i }));
|
|
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
|
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ name: 'Sacre Coeur' }));
|
|
});
|
|
|
|
it('FE-COMP-PLACEFORM-015: categories appear in category selector', () => {
|
|
const cats = [buildCategory({ name: 'Museum' }), buildCategory({ name: 'Park' })];
|
|
render(<PlaceFormModal {...defaultProps} categories={cats} />);
|
|
// Category label is present
|
|
expect(screen.getByText('Category')).toBeInTheDocument();
|
|
});
|
|
|
|
// ── Form initialization ──────────────────────────────────────────────────────
|
|
|
|
it('FE-PLANNER-PLACEFORM-016: prefillCoords populates lat/lng/name', () => {
|
|
render(
|
|
<PlaceFormModal
|
|
{...defaultProps}
|
|
place={null}
|
|
prefillCoords={{ lat: 48.8566, lng: 2.3522, name: 'Paris', address: 'Paris, France' }}
|
|
/>,
|
|
);
|
|
expect(screen.getByDisplayValue('48.8566')).toBeInTheDocument();
|
|
expect(screen.getByDisplayValue('Paris')).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-017: form resets when isOpen changes from place to null', () => {
|
|
const place = buildPlace({ name: 'Old Place' });
|
|
const { rerender } = render(<PlaceFormModal {...defaultProps} place={place} isOpen={true} />);
|
|
expect(screen.getByDisplayValue('Old Place')).toBeInTheDocument();
|
|
|
|
rerender(<PlaceFormModal {...defaultProps} place={null} isOpen={false} />);
|
|
expect(screen.queryByDisplayValue('Old Place')).not.toBeInTheDocument();
|
|
});
|
|
|
|
// ── Maps search ──────────────────────────────────────────────────────────────
|
|
|
|
it('FE-PLANNER-PLACEFORM-018: maps search populates results via button click', async () => {
|
|
const user = userEvent.setup();
|
|
server.use(
|
|
http.post('/api/maps/search', () =>
|
|
HttpResponse.json({
|
|
places: [{ name: 'Eiffel Tower', address: 'Paris', lat: '48.8584', lng: '2.2945' }],
|
|
}),
|
|
),
|
|
);
|
|
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
const searchInput = screen.getByPlaceholderText('Search places...');
|
|
await user.type(searchInput, 'Eiffel Tower');
|
|
|
|
// The search button is the sibling button of the search input
|
|
const searchRow = searchInput.closest('.flex') as HTMLElement;
|
|
const searchBtn = within(searchRow).getByRole('button');
|
|
await user.click(searchBtn);
|
|
|
|
await screen.findByText('Eiffel Tower');
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-019: pressing Enter in search input triggers search', async () => {
|
|
const user = userEvent.setup();
|
|
server.use(
|
|
http.post('/api/maps/search', () =>
|
|
HttpResponse.json({
|
|
places: [{ name: 'Eiffel Tower', address: 'Paris', lat: '48.8584', lng: '2.2945' }],
|
|
}),
|
|
),
|
|
);
|
|
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
const searchInput = screen.getByPlaceholderText('Search places...');
|
|
await user.type(searchInput, 'Eiffel Tower');
|
|
await user.keyboard('{Enter}');
|
|
|
|
await screen.findByText('Eiffel Tower');
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-020: clicking a maps result fills the form', async () => {
|
|
const user = userEvent.setup();
|
|
server.use(
|
|
http.post('/api/maps/search', () =>
|
|
HttpResponse.json({
|
|
places: [{ name: 'Eiffel Tower', address: 'Paris', lat: '48.8584', lng: '2.2945' }],
|
|
}),
|
|
),
|
|
);
|
|
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
const searchInput = screen.getByPlaceholderText('Search places...');
|
|
await user.type(searchInput, 'Eiffel Tower');
|
|
await user.keyboard('{Enter}');
|
|
|
|
const resultBtn = await screen.findByText('Eiffel Tower');
|
|
await user.click(resultBtn);
|
|
|
|
expect(screen.getByDisplayValue('Eiffel Tower')).toBeInTheDocument();
|
|
expect(screen.getByDisplayValue('48.8584')).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-021: maps search error surfaces the server-provided reason', async () => {
|
|
const addToast = vi.fn();
|
|
window.__addToast = addToast;
|
|
|
|
const user = userEvent.setup();
|
|
// The backend forwards the real upstream error (e.g. a Google Places API message);
|
|
// the modal must show it instead of a generic "search failed" so the cause is visible.
|
|
server.use(
|
|
http.post('/api/maps/search', () =>
|
|
HttpResponse.json({ error: 'Places API (New) has not been used in project 123 or it is disabled' }, { status: 403 })),
|
|
);
|
|
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
const searchInput = screen.getByPlaceholderText('Search places...');
|
|
await user.type(searchInput, 'someplace');
|
|
await user.keyboard('{Enter}');
|
|
|
|
await waitFor(() => {
|
|
expect(addToast).toHaveBeenCalledWith(
|
|
expect.stringMatching(/Places API \(New\) has not been used/i),
|
|
'error',
|
|
undefined,
|
|
);
|
|
});
|
|
|
|
delete window.__addToast;
|
|
});
|
|
|
|
// ── Autocomplete suggestion click (#1192) ─────────────────────────────────────
|
|
// Selecting a dropdown suggestion does a second `details` lookup which is fragile
|
|
// (details kill-switch, an overloaded OSM Overpass mirror, upstream errors). When
|
|
// it yields no usable place the modal must fall back to the reliable text search
|
|
// instead of dead-ending on "Place search failed".
|
|
|
|
async function openSuggestion(user: ReturnType<typeof userEvent.setup>) {
|
|
const searchInput = screen.getByPlaceholderText('Search places...');
|
|
await user.type(searchInput, 'Eiffel');
|
|
// Debounced autocomplete (300ms) then the dropdown renders the suggestion.
|
|
return screen.findByText('Paris, France');
|
|
}
|
|
|
|
it('FE-PLANNER-PLACEFORM-021b: suggestion click falls back to search when details fails', async () => {
|
|
const addToast = vi.fn();
|
|
window.__addToast = addToast;
|
|
const user = userEvent.setup();
|
|
server.use(
|
|
http.post('/api/maps/autocomplete', () =>
|
|
HttpResponse.json({
|
|
suggestions: [{ placeId: 'node:123', mainText: 'Eiffel Tower', secondaryText: 'Paris, France' }],
|
|
source: 'nominatim',
|
|
}),
|
|
),
|
|
// details rejects (e.g. proxy 504 from a hung Overpass mirror)
|
|
http.get('/api/maps/details/:placeId', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
|
http.post('/api/maps/search', () =>
|
|
HttpResponse.json({
|
|
places: [{ name: 'Eiffel Tower', address: 'Paris, France', lat: '48.8584', lng: '2.2945' }],
|
|
source: 'openstreetmap',
|
|
}),
|
|
),
|
|
);
|
|
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
const suggestion = await openSuggestion(user);
|
|
await user.click(suggestion);
|
|
|
|
// Form is populated from the search fallback, and no error toast is shown.
|
|
expect(await screen.findByDisplayValue('48.8584')).toBeInTheDocument();
|
|
expect(screen.getByDisplayValue('2.2945')).toBeInTheDocument();
|
|
expect(addToast).not.toHaveBeenCalledWith(expect.anything(), 'error', expect.anything());
|
|
delete window.__addToast;
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-021c: suggestion click falls back when details is disabled (place: null)', async () => {
|
|
const user = userEvent.setup();
|
|
server.use(
|
|
http.post('/api/maps/autocomplete', () =>
|
|
HttpResponse.json({
|
|
suggestions: [{ placeId: 'node:123', mainText: 'Eiffel Tower', secondaryText: 'Paris, France' }],
|
|
source: 'nominatim',
|
|
}),
|
|
),
|
|
http.get('/api/maps/details/:placeId', () => HttpResponse.json({ place: null, disabled: true })),
|
|
http.post('/api/maps/search', () =>
|
|
HttpResponse.json({
|
|
places: [{ name: 'Eiffel Tower', address: 'Paris, France', lat: '48.8584', lng: '2.2945' }],
|
|
source: 'openstreetmap',
|
|
}),
|
|
),
|
|
);
|
|
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
const suggestion = await openSuggestion(user);
|
|
await user.click(suggestion);
|
|
|
|
expect(await screen.findByDisplayValue('48.8584')).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-021d: suggestion click shows error only when the fallback also finds nothing', async () => {
|
|
const addToast = vi.fn();
|
|
window.__addToast = addToast;
|
|
const user = userEvent.setup();
|
|
server.use(
|
|
http.post('/api/maps/autocomplete', () =>
|
|
HttpResponse.json({
|
|
suggestions: [{ placeId: 'node:123', mainText: 'Eiffel Tower', secondaryText: 'Paris, France' }],
|
|
source: 'nominatim',
|
|
}),
|
|
),
|
|
http.get('/api/maps/details/:placeId', () => HttpResponse.json({ place: null, disabled: true })),
|
|
http.post('/api/maps/search', () => HttpResponse.json({ places: [], source: 'openstreetmap' })),
|
|
);
|
|
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
const suggestion = await openSuggestion(user);
|
|
await user.click(suggestion);
|
|
|
|
await waitFor(() => {
|
|
expect(addToast).toHaveBeenCalledWith('Place search failed.', 'error', undefined);
|
|
});
|
|
delete window.__addToast;
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-022: hasMapsKey=false shows OSM active message', () => {
|
|
// hasMapsKey is false by default in beforeEach
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
expect(screen.getByText(/OpenStreetMap/i)).toBeInTheDocument();
|
|
});
|
|
|
|
// ── Category ─────────────────────────────────────────────────────────────────
|
|
|
|
it('FE-PLANNER-PLACEFORM-023: category selector renders options', () => {
|
|
// The component conditionally shows CustomSelect (showNewCategory=false) or text input
|
|
// Default state shows CustomSelect; no visible "+" trigger exists in current code
|
|
const cats = [buildCategory({ name: 'Beaches' }), buildCategory({ name: 'Museums' })];
|
|
render(<PlaceFormModal {...defaultProps} categories={cats} />);
|
|
// The "No category" placeholder text from CustomSelect should be visible
|
|
expect(screen.getByText(/No category/i)).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-023b: editing a place shows its assigned category, not the placeholder (#1134)', () => {
|
|
// Regression: form.category_id is a string but the option values were numbers,
|
|
// so CustomSelect's strict-equality match failed and the trigger fell back to
|
|
// "No category". With string option values the chosen category renders.
|
|
const cat = buildCategory({ name: 'Museums' });
|
|
const place = buildPlace({ name: 'Louvre', category_id: cat.id });
|
|
render(<PlaceFormModal {...defaultProps} place={place} categories={[cat]} />);
|
|
// Dropdown is closed, so the only place the category name can appear is the trigger.
|
|
expect(screen.getByText('Museums')).toBeInTheDocument();
|
|
expect(screen.queryByText(/No category/i)).not.toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-024: onCategoryCreated is called when creating a category', async () => {
|
|
const onCategoryCreated = vi.fn().mockResolvedValue({ id: 99, name: 'Beaches', color: '#6366f1', icon: 'MapPin' });
|
|
// Directly invoke handleCreateCategory by setting showNewCategory via the category name input
|
|
// Since there's no UI trigger for showNewCategory, we test that the prop is accepted
|
|
// and category creation works by checking the modal renders correctly
|
|
render(<PlaceFormModal {...defaultProps} onCategoryCreated={onCategoryCreated} />);
|
|
expect(screen.getByText('Category')).toBeInTheDocument();
|
|
// onCategoryCreated not called unless the new-category form is shown and submitted
|
|
expect(onCategoryCreated).not.toHaveBeenCalled();
|
|
});
|
|
|
|
// ── Time section (edit mode only) ────────────────────────────────────────────
|
|
|
|
it('FE-PLANNER-PLACEFORM-025: time section is NOT shown in create mode', () => {
|
|
render(<PlaceFormModal {...defaultProps} place={null} />);
|
|
// English labels are 'Start' and 'End' (places.startTime / places.endTime)
|
|
expect(screen.queryByText(/^Start$/i)).not.toBeInTheDocument();
|
|
expect(screen.queryByText(/^End$/i)).not.toBeInTheDocument();
|
|
// Also verify no time pickers rendered
|
|
expect(screen.queryByTestId('time-picker')).not.toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-026: time section is hidden in edit mode when no assignment is in context', () => {
|
|
// Times are per day-assignment; editing a pool place with no day in context
|
|
// (assignmentId null) hides the fields, which otherwise would not persist (#1247)
|
|
const place = buildPlace({ name: 'Test' });
|
|
render(<PlaceFormModal {...defaultProps} place={place} assignmentId={null} />);
|
|
expect(screen.queryByTestId('time-picker')).not.toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-026b: time section IS shown when an assignment is in context', () => {
|
|
const place = buildPlace({ name: 'Test', place_time: '09:00', end_time: '10:00' });
|
|
const assignment = buildAssignment({ id: 10, day_id: 5, place });
|
|
render(<PlaceFormModal {...defaultProps} place={place} assignmentId={10} dayAssignments={[assignment]} />);
|
|
expect(screen.getAllByTestId('time-picker').length).toBeGreaterThanOrEqual(2);
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-026c: hydrates Start/End from the assignment when the pool place lacks times (#1247)', () => {
|
|
// The pool Place carries no times — they live on the day-assignment. Opening the
|
|
// editor with an assignmentId must hydrate the fields from assignment.place, not
|
|
// the (timeless) pool place that the Places panel passes in.
|
|
const poolPlace = buildPlace({ id: 7, name: 'Museum' });
|
|
const assignmentPlace = buildPlace({ id: 7, name: 'Museum', place_time: '20:20', end_time: '20:34' });
|
|
const assignment = buildAssignment({ id: 42, day_id: 3, place: assignmentPlace });
|
|
render(<PlaceFormModal {...defaultProps} place={poolPlace} assignmentId={42} dayAssignments={[assignment]} />);
|
|
expect(screen.getByDisplayValue('20:20')).toBeInTheDocument();
|
|
expect(screen.getByDisplayValue('20:34')).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-027: end-before-start error disables submit', () => {
|
|
// Build an assignment whose place has end_time before place_time
|
|
const place = buildPlace({ name: 'Test', place_time: '14:00', end_time: '13:00' });
|
|
const assignment = buildAssignment({ id: 11, day_id: 5, place });
|
|
render(<PlaceFormModal {...defaultProps} place={place} assignmentId={11} dayAssignments={[assignment]} />);
|
|
|
|
// hasTimeError = true → submit button disabled
|
|
const submitBtn = screen.getByRole('button', { name: /^Update$/i });
|
|
expect(submitBtn).toBeDisabled();
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-028: time collision warning appears when assignments overlap', () => {
|
|
// Create an assignment for the "current" place being edited
|
|
const currentPlace = buildPlace({ name: 'My Event', place_time: '12:30', end_time: '13:30' });
|
|
const conflictingPlace = buildPlace({ name: 'Other Event', place_time: '13:00', end_time: '14:00' });
|
|
|
|
const currentAssignment = buildAssignment({ id: 10, day_id: 5, place: currentPlace });
|
|
const otherAssignment = buildAssignment({ id: 20, day_id: 5, place: conflictingPlace });
|
|
|
|
render(
|
|
<PlaceFormModal
|
|
{...defaultProps}
|
|
place={currentPlace}
|
|
assignmentId={10}
|
|
dayAssignments={[currentAssignment, otherAssignment]}
|
|
/>,
|
|
);
|
|
|
|
// English translation: 'places.timeCollision' = 'Time overlap with:'
|
|
expect(screen.getByText(/Time overlap with:/i)).toBeInTheDocument();
|
|
});
|
|
|
|
// ── File attachments ──────────────────────────────────────────────────────────
|
|
|
|
it('FE-PLANNER-PLACEFORM-029: file attachment section shown when canUploadFiles=true', () => {
|
|
// Default: permissions={} → not configured → allow → canUploadFiles=true
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
expect(screen.getByText('Attach')).toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-030: file attachment section hidden when canUploadFiles=false', () => {
|
|
// Set file_upload to 'admin' level; non-admin user cannot upload
|
|
seedStore(usePermissionsStore, { permissions: { file_upload: 'admin' } });
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
expect(screen.queryByText('Attach')).not.toBeInTheDocument();
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-031: pending files list shows file names after adding', async () => {
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
|
expect(fileInput).toBeTruthy();
|
|
|
|
const file = new File(['x'], 'photo.jpg', { type: 'image/jpeg' });
|
|
fireEvent.change(fileInput, { target: { files: [file] } });
|
|
|
|
await screen.findByText('photo.jpg');
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-032: removing a pending file removes it from the list', async () => {
|
|
const user = userEvent.setup();
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
|
|
|
const file = new File(['x'], 'remove-me.jpg', { type: 'image/jpeg' });
|
|
fireEvent.change(fileInput, { target: { files: [file] } });
|
|
await screen.findByText('remove-me.jpg');
|
|
|
|
// The X button is inside the file item's container div
|
|
const fileItem = screen.getByText('remove-me.jpg').closest('div.flex') as HTMLElement;
|
|
const removeBtn = within(fileItem).getByRole('button');
|
|
await user.click(removeBtn);
|
|
|
|
expect(screen.queryByText('remove-me.jpg')).not.toBeInTheDocument();
|
|
});
|
|
|
|
// ── Submit ────────────────────────────────────────────────────────────────────
|
|
|
|
it('FE-PLANNER-PLACEFORM-033: onSave receives parsed lat/lng as numbers', async () => {
|
|
const user = userEvent.setup();
|
|
const onSave = vi.fn().mockResolvedValue(undefined);
|
|
|
|
render(<PlaceFormModal {...defaultProps} onSave={onSave} />);
|
|
await user.type(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), 'Notre Dame');
|
|
|
|
const latInput = screen.getByPlaceholderText(/Latitude/i);
|
|
await user.clear(latInput);
|
|
await user.type(latInput, '48.853');
|
|
|
|
await user.click(screen.getByRole('button', { name: /^Add$/i }));
|
|
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
|
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ lat: 48.853 }));
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-034: onSave error shows toast', async () => {
|
|
const addToast = vi.fn();
|
|
window.__addToast = addToast;
|
|
|
|
const user = userEvent.setup();
|
|
const onSave = vi.fn().mockRejectedValue(new Error('Server error'));
|
|
|
|
render(<PlaceFormModal {...defaultProps} onSave={onSave} />);
|
|
await user.type(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), 'Notre Dame');
|
|
await user.click(screen.getByRole('button', { name: /^Add$/i }));
|
|
|
|
await waitFor(() => {
|
|
expect(addToast).toHaveBeenCalledWith('Server error', 'error', undefined);
|
|
});
|
|
|
|
delete window.__addToast;
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-035: save button shows "Saving..." while saving', async () => {
|
|
const user = userEvent.setup();
|
|
const onSave = vi.fn().mockReturnValue(new Promise(() => {})); // never resolves
|
|
|
|
render(<PlaceFormModal {...defaultProps} onSave={onSave} />);
|
|
await user.type(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), 'Notre Dame');
|
|
await user.click(screen.getByRole('button', { name: /^Add$/i }));
|
|
|
|
await waitFor(() => {
|
|
expect(screen.getByRole('button', { name: /saving/i })).toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
it('FE-PLANNER-PLACEFORM-036: lat/lng paste splits "48.8566, 2.3522" into lat and lng fields', () => {
|
|
render(<PlaceFormModal {...defaultProps} />);
|
|
const latInput = screen.getByPlaceholderText(/Latitude/i);
|
|
|
|
fireEvent.paste(latInput, {
|
|
clipboardData: {
|
|
getData: () => '48.8566, 2.3522',
|
|
},
|
|
});
|
|
|
|
expect(screen.getByDisplayValue('48.8566')).toBeInTheDocument();
|
|
expect(screen.getByDisplayValue('2.3522')).toBeInTheDocument();
|
|
});
|
|
});
|