* fix(plugins): prevent arbitrary api access * fix(planner): disable drag & drop on mobile so the places list scrolls (#1432) On touch devices the draggable rows hijack the scroll gesture, so dragging to scroll started an HTML5 drag and popped up the file-import overlay instead of scrolling. Gate the draggable rows and the sidebar file-drop handlers on !isMobile across the places sidebar and the day plan (places, transports, notes), and hide the grip handle — the arrow reorder buttons take over there. * fix(inspector): make the remove-from-day button icon-only on mobile * fix(collections): show the save picker above the mobile place detail * fix(plugins): seal IPC parent/child for good * test(inspector): match the icon-only remove-from-day button * feat(sdk): switch plain ts for clack/prompts interactive session * feat(plugins): force-refresh the registry from the rescan button The registry is cached for 30 min server-side and GitHub serves it with a 5-min CDN cache, so a freshly published plugin could take up to ~35 min to appear. The rescan/reload button now force-pulls the registry: it bypasses the in-memory cache and appends a cache-buster + no-cache headers to beat the CDN, and refreshes the browse grid immediately. * feat(sdk): bump plugin version * fix(stored settings): prevent local storage drop when update not successful * feat(plugins): sideload plugins by uploading a .zip Adds an admin "Upload plugin" button + drag-and-drop to the plugins panel for installing a plugin archive directly — handy for testing a build before it goes to the registry. It reuses the registry install pipeline (slip/bomb-safe extract, strict manifest validation, native-binary scan) via a new POST /admin/plugins/upload, and only skips the registry sha256/signature checks that a sideload can't have. Sideloaded plugins are flagged (source "local:upload", a "Sideloaded" badge, no GitHub link, no auto-update) and always land INACTIVE — replacing a running or active plugin stops it and clears the active flag first, so new code never runs without a fresh activation + permission consent. * fix(planner): keep the day-plan collapse state after fully closing the page The expanded/collapsed days were stored in sessionStorage, which survives a reload but is wiped when the tab or window is closed — so every fresh open re-expanded all days, which is tedious to re-collapse on long (10+ day) trips. Store it in localStorage instead so a collapsed layout sticks until it's changed. * fix(i18n): correct Vietnamese translation of 'Disabled' (#1438) 'Tàn tật' means physically handicapped/disabled-person, not the off/disabled state of a toggle. Replace with 'Tắt' (off), matching the existing 'admin.plugins.stateOff' translation. Affects admin.notifications.none and admin.addons.disabled. * add the code of conduct * fix(plugins): let widgets follow the in-app dark-mode toggle The plugin frame is sandboxed at an opaque origin (no parent DOM access) and we only sent the context — including the theme — once, on trek:ready. So toggling dark mode in TREK left already-mounted widgets on the old theme until a reload. Watch the <html> `dark` class and re-post the context when it flips; plugins already re-apply the theme on trek:context. * fix(plugins): deliver widget context on load so the theme is right on first paint * fix(plugins): give widget cards the native glassy look and auto-height Widget plugins rendered in a plain card with a fixed 180px body, so they looked foreign next to the glassy dashboard tools and taller widgets had their controls clipped. Mirror the native `.tool` surface (glass background/border/blur, uppercase title) and let the body grow to the height the widget reports over trek:resize. * feat(plugins): add read/rwite costs * feat(plugin): better readme/index.js * feat(plugin): better readme/index.js * feat(plugins): hand widgets TREK's theme tokens, formats and display identity Extends trek:context with a non-secret `tokens` map (TREK's resolved CSS design tokens for the current theme), `formats` (currency/date/units/timezone) and a `user` display object (name/avatar/isAdmin — never the email, role only as a boolean). Re-sent on every theme toggle. A widget can now apply the tokens and match the host exactly, in both themes and under a custom appearance, instead of hard-coding a palette that drifts — so plugins feel native, not bolted-on. * feat(plugins): hand plugins the full palette and appearance state The theme context only carried a ~19-token subset read off <html> and only followed the dark-mode toggle. Widen it to the whole global (:root/.dark) palette — surfaces, text, borders, the accent family, semantic + soft fills, shadows, radii and fonts — so a plugin tracks the user's chosen accent scheme, custom accent and high-contrast live, not just light/dark. Also send an `appearance` block (scheme, density, reduced-motion, no-transparency) mirrored from the attributes applyAppearance writes on <html>, and re-post the context whenever any of those actually change (a small signature dedupes unrelated mutations) so plugins restyle in step with the app. * feat(plugins): ship a design kit so plugin UIs look native A plugin's UI is a sandboxed, opaque-origin iframe that can't load TREK's stylesheet — so authors had to re-derive the whole look by hand, and most didn't. Ship it instead: a token-driven stylesheet (glass, hover, buttons, inputs, chips, rows) that consumes the tokens the host already sends and swaps light/dark, plus a small bootstrap that applies those tokens, mirrors the appearance flags, auto-reports the frame height and exposes a `window.trek` helper over the existing bridge. Both are plain strings meant to be inlined (the CSP forbids external assets for an opaque frame); `injectTrekUi` expands a `<!-- trek:ui -->` marker. No new capability — only a native look. * feat(plugins): deliver the design kit — native scaffold + inline on dev/pack A new page/widget scaffolds a native, glassy starter that talks over window.trek. The source keeps a single `<!-- trek:ui -->` line; `dev` (when it serves /ui) and `pack` (as the file enters the archive) expand it into the inlined kit — so the file stays a one-line opt-in and a rebuild always ships the current kit. Existing plugins opt in the same way, by dropping the marker. * feat(plugins): faithful themed host preview in dev `dev` served the plugin UI raw at /ui — top-level, with no host — so the theme, context and bridge never fired and authors couldn't see the design kit render. Add /preview: it embeds /ui in a sandboxed opaque-origin iframe (exactly TREK's isolation) and plays the host — posts trek:context with a theme/accent/appearance toggle, proxies trek:invoke to your /api routes as the dev user, and surfaces resize/notify/navigate. /ui stays as the raw doc for debugging. * docs(plugins): document the design kit, window.trek and the token contract Rewrite the client section of the Plugin Development wiki kit-first: the `<!-- trek:ui -->` marker, the component classes, the `window.trek` bridge, the `/preview` host preview, the full `trek:context` payload (now the whole palette plus an `appearance` block) and how to apply tokens by hand. Add a "Build a native UI" section + the new exports to the SDK README. * feat(budget): add 'Outstanding amount' card * fix(translations): finish translating new keys * feat(plugins): trip-page plugins — a plugin tab inside every trip Adds a `trip-page` plugin type whose sandboxed iframe mounts as a tab in the trip planner (Plan / Transports / … / <plugin>), scoped to the open trip, with no dashboard nav entry. This is the most-asked planner-extension request from discussion #1429 (a plugin that lives in the trip, e.g. SimMesg20's budget planner). It reuses PluginFrame and the existing tab system — the frame already receives the current tripId over trek:context — so there is no bridge or security change: only the manifest type enum (server + SDK), the client feed classification (pluginStore.tripPages), and one render branch in the planner. The SDK scaffolds it with `create --type trip-page`. * fix(apple wallet): support for .pkpasses * feat(plugins): permission-gated write APIs for the planner (#1429) Plugins can now WRITE core planner data, not just read it, through curated, membership-checked methods — so downstream features can live in plugins instead of long-lived core patches. Four new scopes: db:write:places (create/update/delete places), db:write:days (days), db:write:itinerary (assign/unassign a place on a day) and db:write:trips (update trip fields). Each ctx method mirrors costs.create: it validates the input against the SAME @trek/shared schema the web app uses, binds the acting user host-side (a job/onLoad has none, so its writes are refused), checks trip access AND the app's edit permission (place_edit / day_edit / trip_edit), delegates to the real services, broadcasts the same events so open sessions update live, and records the write in the tamper-evident capability audit. No new route, no sandbox or CSP change — the isolation boundary is unchanged; a plugin can only change what its user could change by hand. Consent UI + permission labels in all 22 locales, SDK types + mock host, and the wikis are updated. * docs(plugin): ensure wiki correctness * feat(plugins): plugin metadata on core entities — db:meta (#1429) Plugins can now attach their OWN namespaced key/value data to a trip, place or day without forking the core schema (#1429, request 2). New `db:meta` scope + `ctx.meta.get/set/list/delete`. Storage is one plugin_entity_metadata table (migration 161) keyed (plugin_id, entity_type, entity_id, key) — a plugin only ever sees its own rows. Every call is membership-checked: the entity must belong to a trip the host-bound acting user can access. Quotas guard the shared volume (≤64KB per value, ≤100 keys per entity); rows are purged on uninstall-with-delete-data and recorded in the capability audit. SDK types + mock host, a consent chip + labels in all 22 locales, and the wikis. No new route, no sandbox change. * feat(plugins): place-detail plugin slot in the trip planner (#1429) A widget plugin can declare `capabilities.widget.slot: 'place-detail'` to mount its sandboxed frame inside the trip planner's place-detail panel, scoped to the open place — the frame receives the `placeId` in trek:context alongside the tripId. This is the UI half of the place-detail-providers ask (reviews/ratings/popular times shown on a place). It reuses the existing widget mechanism: PluginFrame gains an optional placeId, the feed/store learn the new slot, and PlaceInspector renders the slot at the foot of its body in trip mode. Admin chip + label in all 22 locales, wiki updated. No sandbox or permission change. * fix(plugins): green the server tests + harden the new capability surface The in-memory uninstall fixture was missing the new plugin_entity_metadata table, so uninstall's DELETE threw "no such table" and failed the server test job. Add the table to the fixture schema. Self-review hardening of the write/metadata surface: - trips.update now reproduces the web UI's per-field gate: is_archived needs trip_archive and cover_image needs trip_cover_upload, not just trip_edit — so a member who may only edit can't archive or re-cover a trip. - Plugin metadata WRITES now also require the entity's edit permission (place_edit/day_edit/trip_edit), not just trip access, so a read-only member can't overwrite or delete metadata another user created. Reads stay access-gated. - Cap the metadata key length (<=256 chars) alongside the value/count quotas — the key was attacker-controlled and uncapped, defeating the disk-DoS guard. * test(plugins): cover the new write/metadata deps to hold the coverage gate The new create-rpc-host write + metadata deps were untested, dropping the src/nest branch coverage below the 80% gate. Add a seeded in-memory core db plus mocked core services to exercise every dep end-to-end: places/days/itinerary create/update/delete + not-found paths, trips.update with the archive/cover per-field gates and the Validation/NotFound/unknown-error mapping, metadata CRUD + key/value/count caps + access checks, the costs deps, and users.getById scoping. Plus rpc-host cases for meta writes on place/day and a no-acting-user refusal. Tests only — no production code change. * fix(costs): freeze FX on every cost + settlement write path (#1445) Settled foreign-currency costs kept re-opening with a few-cent residual when live rates drifted. The #1335 freeze only ran on the REST create/ update path, so two gaps remained: - Foreign-currency items created via MCP create_budget_item or booking- import bypassed the freeze and stored exchange_rate = 1, so settlement re-converted them with live rates. Promote freezeForeignRate into the shared budgetService and call it from every write path. - Settle-up transfers were stored currency-less and re-converted with live rates on each recompute. Add currency + exchange_rate to budget_settlements (migration), freeze the display-currency rate at settle time, and convert with it in calculateSettlement. Legacy rows (currency = NULL / rate = 1) keep live-rate behaviour until re-edited. Also expose guarded cost update/delete to plugins: costs.update and costs.delete under db:write:costs, gated exactly like costs.create (addon + trip access + the acting user's budget_edit permission). updateCost reuses BudgetService.update so a plugin write re-freezes the FX rate too; both broadcast the same budget:updated / budget:deleted events the REST controller emits. Wired through the host, the runtime SDK context and the published trek-plugin-sdk (types + mock host). * feat(plugins): provider hooks — placeDetailProvider, wired (#1429) Turn "hooks" from a declared-but-dead surface into a real host→plugin capability. Add an invoke.hook branch to the child + a supervisor hook registry (providersOf) + PluginRuntimeService.invokeHook, reusing the existing invoke transport and its timeout (a short 5s deadline so a slow provider can't delay a response; a job/onLoad has no user, host-bound as ever). Also fixes a real bug: the in-repo runtime SDK copy was missing the `hooks` field entirely and could not even parse a plugin that declared one — synced it with the published SDK. The first wired hook is placeDetailProvider: a plugin returns extra rows ({label,value?,url?}) for a place, and TREK renders them natively at the foot of the place-detail panel. Consumer is a new, additive, fail-safe endpoint GET /api/place-details/:placeId (membership-checked; any provider that errors or times out is simply skipped — it never breaks the panel). New hook:place-detail- provider scope + consent chip in all 22 locales. SDK types (both copies), a controller test, and the wiki. photoProvider/calendarSource stay reserved but the transport now exists for them. No sandbox or CSP change. * fix(files): handle pkpass in booking uploads and files-tab open (#1447, #1448) Both bugs were client-only; the server already allows .pkpass and serves it as application/vnd.apple.pkpass. #1448: the reservation/transport attachment inputs hard-coded an accept list that omitted pkpass, so macOS grayed it out. Add .pkpass/.pkpasses (+ wallet MIME types) to the accept attribute in both modals. #1447: the files-tab open path routed every non-media/non-markdown file into the in-app PDF preview object. Add isWalletPass() and route wallet passes through the shared blob openFile helper (as bookings already do), which downloads them so the OS hands them to Apple Wallet. * feat(plugins): validation/warning contributions via warningProvider hook (#1429) Second wired provider hook, reusing the invoke.hook infra from the last commit. A plugin implements warningProvider.getWarnings(tripId, ctx) → {level, message, dayId?, placeId?}[] to flag problems on a trip (overpacked day, place closed on its planned date, missing booking, …). TREK surfaces them as a non-blocking overlay banner at the top of the trip planner (the wrapper ignores pointer events so it never covers the map/panels; only the pills are interactive). Consumer is a new additive, fail-safe endpoint GET /api/trip-warnings/:tripId (membership-checked; a provider that errors or times out contributes nothing and never blocks the planner). New hook:trip-warning-provider scope + consent chip in all 22 locales, SDK types (both copies), a controller test, and the wiki. This is the validation half of the scheduling+validation block; feeding durations/travel times back into core recalculation stays out (it would touch core planner computation — deliberately deferred to keep the no-breaking-changes guarantee). * fix(plugins): enforce the hook:* grant on provider dispatch (#1429 audit) The adversarial audit of the #1429 additions found one real (medium) gap: the hook:* permission was never enforced at runtime. providersOf() selected provider plugins purely by the hooks their CODE declares (sup.hooks, reported by the child as Object.keys(def.hooks)) and never intersected that with sup.granted — so a plugin that merely implemented placeDetailProvider/warningProvider got wired in as a provider even when the admin never consented to hook:place-detail-provider / hook:trip-warning-provider. The downstream capability router still held (the hook's ctx can only do what the plugin's OTHER grants allow), but a plugin could obtain an auto-triggered, user-bound execution context on a passive UI browse without the hook being consented — a consent-integrity gap that contradicts the documented invariant. Gate it host-side: a hookName→permission map, and providersOf now returns a plugin only if it is active, implements the hook, AND holds the matching hook:* grant. An unmapped hook resolves to nobody. invokeHook additionally re-checks membership in providersOf (defense-in-depth against a direct caller). Unit test proves the grant/implements/active intersection. * docs(plugins): add the Plugin Cookbook + a trip-doctor example (#1429 eco) Fosters plugin authoring by turning the new #1429 capabilities into copy-paste recipes. New wiki page Plugin-Cookbook (read a trip, write to the itinerary, tag an entity with metadata, contribute native place details, raise trip warnings, broadcast, match the TREK look) linked in the sidebar, plus a complete runnable example — trip-doctor — a hooks-only plugin that showcases warningProvider + placeDetailProvider + ctx.meta with zero UI of its own. Manifest validates against the SDK. Docs/example only; no product code. * fix(collections): don't reset saved-place status to 'idea' on edit (#1437) The update schema reused collectionStatusSchema, whose .default('idea') survives .optional() — so a PATCH that omits status had 'idea' injected by the validation pipe and written to the DB, clobbering 'want'/'visited'. Strip the default on the update field with .removeDefault(), keeping the .catch guard. Add a shared schema regression test and an e2e round-trip. * docs(plugin): ensure plugin scopes are the same everywhere * feat(plugins): read scopes for packing + files (#1429 eco) Extend the read side of the capability model beyond trips/costs: db:read:packing → ctx.packing.list(tripId) and db:read:files → ctx.files.list(tripId). Both mirror the existing trip reads exactly — the host membership-checks the trip against the invocation's user (tripRead) before delegating to the same packingService/ fileService the REST paths use (so bags/assignees hydrate and trash is excluded), and each is a separate scope (packing doesn't unlock files). ctx types in both SDK copies + mock-host, consent labels + cap chips in all 22 locales, rpc-host + create-rpc-host tests, and the wiki (perm table + cookbook recipe). * feat(plugins): core event subscriptions (#1429 eco) A plugin can react to core activity by declaring events: [{ on, handler }] + the events:subscribe grant. websocket.broadcast announces every CORE trip event (name + tripId ONLY, never the payload) through a tiny dependency-free relay (plugin-event-sink); the runtime registers a sink in onModuleInit and the supervisor fans each event out to subscribed, granted, active plugins via a fire-and-forget invoke.event on a short timeout — so a slow subscriber can never block a core write. Safety by construction: handlers run with NO user (like a job) so trip reads are refused — they react to the fact, using the plugin's own ctx.db/ws/outbound; the grant is enforced host-side (deliverEvent checks events:subscribe); plugin:* re- broadcasts are never delivered back, so handlers can't loop; and only the event name + tripId cross the boundary. SDK types (both copies), consent label + cap chip in all 22 locales, supervisor gating + broadcast-tap tests, and the wiki + cookbook. The relay lives in its own module (not websocket) so it doesn't drag `ws` into the runtime and tests that mock ./websocket don't strip the sink. * feat(plugin-sdk): typed ctx returns + native trek.ui DOM helpers (#1429 eco) Two author-DX wins, SDK-only. Typed reads/writes: ctx.trips.getById/getPlaces/getReservations, packing.list, files.list, costs.*, places/days/itinerary writes and users.getById now return proper entity types (Trip, Place, Day, Reservation, PackingItem, TripFile, BudgetItem, Assignment, User) instead of unknown — real autocomplete for authors. Only `id` is guaranteed and every shape keeps an index signature, so it mirrors the raw DB row honestly (no column hidden, no false guarantees). mock-host matches. Native UI helpers: window.trek now carries `trek.ui` — a tiny bundler-free DOM builder (el/button/card/chip/input/mount) that emits the kit's trek-* classes, so a widget builds themed UI with no CSS and no build step. Ships inlined via the same <!-- trek:ui --> marker. Wiki updated. * fix(plugins): scope packing.list to the acting user's #858 visibility (eco audit) The final eco audit found one real (medium) gap: the db:read:packing delegate called packingService.listItems(tripId) with NO userId, which takes the UNFILTERED branch and returns every member's private (is_private=1) packing items — leaking another member's personal/surprise-gift items to a plugin the normal UI/REST hides them from. The handler had the host-bound acting user but dropped it when delegating. Thread it through: tripRead now hands the membership-checked userId to the read callback, packing.list forwards it to listPackingItems(tripId, userId), and the service applies its three-tier #858 filter — a plugin now sees exactly what its user sees. files.list is unaffected (no per-user file visibility). Tests assert the user is passed. The other three audited surfaces (event subscriptions, trek.ui, and the regression sweep of the capability boundary) were clean. * security(plugins): prevent open redirect * fix(plugins): resolve PR #1433 full-audit findings (code + tests) The comprehensive PR audit confirmed 21 findings; this fixes the code/test ones I own: - ctx.users.getById was DEAD: the runtime SDK omitted the _inv tag, so actingUser never bound and every call hit RESOURCE_FORBIDDEN. Add _inv (the test had codified the bug — corrected). - Plugin place writes bypassed the REST STRING_LIMITS (a 100k-char name the web app rejects). Mirror the caps (name 200 / description 2000 / address 500 / notes 2000). - packing.list / files.list were missing from the capability audit log while every other core read is audited — add them to isAuditable + auditResource. - SDK lockstep: CalendarSource.getEvents drifted (published Date vs runtime string); the host->plugin boundary is JSON, so align both to string. - Admin panel didn't know the new trip-page plugin type (unlocalised badge, missing filter) — add it to KNOWN_TYPES + the type filter + a 22-locale label. - Tests for previously-uncovered paths: the child-side invoke.hook/invoke.event dispatch (real fork, hook + event + non-matching-subscription), and invokeHook's defense-in-depth grant re-check. Julien's settlement-FX-refreeze finding is his budget code (flagged, not touched). * docs(plugins): correct the wiki against the shipped capability surface (#1433 audit) Fixes the 11 doc findings from the PR audit — every corrected claim was cross-checked against the code: - Plugin-Development: CSP connect-src is built from granted http:outbound:<host>, not egress[]; dropped the stale "costs.create is the first and only core mutation"; documented costs.update/delete + ctx.packing/ctx.files; the manifest permission table gained the six missing scopes (db:write:places/days/itinerary/trips, db:meta, hook:trip-warning-provider); the widget slot table gained place-detail. - Plugin-Cookbook: days.create no longer passes a title the schema drops; broadcastToUser uses the real (userId, event, data) signature; fixed the broken #the-trek-ui-design-kit anchor and noted window.trek.ui. - Plugin-Permissions: added db:read:packing, db:read:files and events:subscribe; the provider hooks are implemented in `hooks: {...}` on the definition, not on ctx. * fix(unsplash) allow api key usage * fix(guests): scope guest display names per-trip, not globally (#1446) A guest is a per-trip person, but their name lived in the globally UNIQUE users.username, so uniqueGuestUsername() auto-renamed a second "Jake" (on any other trip) to "Jake 2". Add a non-unique users.display_name: a guest now stores the human name there and gets a uuid-based username that is never shown, and every member view (members list, day-assignment participants, budget members/payers, packing recipients/contributors/bags/assignees) COALESCEs display_name over username. Rename updates display_name with no dedup. Real users are unchanged (display_name NULL → COALESCE falls through to username). Migration adds the nullable column; existing guests keep their current username via the COALESCE fallback. This also unblocks ctx.users.getById (the audit's #4 fix), whose projection selects display_name. Tests: two "Jake" guests on two trips both keep the name; the two codified-the-old-behaviour guest tests corrected. * fix(costs): don't re-freeze a settlement's FX rate on an unrelated edit (#1445) The full audit found that updateSettlement called freezeForeignRate without the "currency unchanged" guard the item path has, so any edit of a foreign-currency settlement (e.g. correcting from/to) re-fetched the LIVE rate and overwrote the frozen one — re-opening an already-balanced position with a small residual, the exact drift #1445 was meant to prevent. freezeForeignRate's unchanged-check was item-centric (it queried budget_items), which a settlement (a different table) can't use. Give it an explicit existingCurrency param; updateSettlement now reads the settlement's stored currency and passes it, so an edit that doesn't change the currency keeps the frozen rate (the service UPDATE already preserves exchange_rate when it's left unset). Tests cover both: unchanged currency keeps the rate, a real currency change re-freezes. * feat(plugins): add inter plugin dependency support and addon dependency support * feat(plugins): add inter plugin dependency support and addon dependency support * docs(plugins) inter dependencies --------- Co-authored-by: Maurice <mauriceboe@icloud.com> Co-authored-by: trongbinhnguyen <43725147+trongbinh15@users.noreply.github.com>
1249 lines
52 KiB
TypeScript
1249 lines
52 KiB
TypeScript
/**
|
||
* Trips API integration tests.
|
||
* Covers TRIP-001 through TRIP-022.
|
||
*/
|
||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||
import request from 'supertest';
|
||
import type { Application } from 'express';
|
||
import type { INestApplication } from '@nestjs/common';
|
||
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
// Step 1: Bare in-memory DB — schema applied in beforeAll after mocks register
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
const { testDb, dbMock } = vi.hoisted(() => {
|
||
const Database = require('better-sqlite3');
|
||
const db = new Database(':memory:');
|
||
db.exec('PRAGMA journal_mode = WAL');
|
||
db.exec('PRAGMA foreign_keys = ON');
|
||
db.exec('PRAGMA busy_timeout = 5000');
|
||
|
||
const mock = {
|
||
db,
|
||
closeDb: () => {},
|
||
reinitialize: () => {},
|
||
getPlaceWithTags: (placeId: number) => {
|
||
const place: any = db.prepare(`
|
||
SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
|
||
FROM places p LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?
|
||
`).get(placeId);
|
||
if (!place) return null;
|
||
const tags = db.prepare(`SELECT t.* FROM tags t JOIN place_tags pt ON t.id = pt.tag_id WHERE pt.place_id = ?`).all(placeId);
|
||
return { ...place, category: place.category_id ? { id: place.category_id, name: place.category_name, color: place.category_color, icon: place.category_icon } : null, tags };
|
||
},
|
||
canAccessTrip: (tripId: any, userId: number) =>
|
||
db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId),
|
||
isOwner: (tripId: any, userId: number) =>
|
||
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
|
||
};
|
||
|
||
return { testDb: db, dbMock: mock };
|
||
});
|
||
|
||
vi.mock('../../src/db/database', () => dbMock);
|
||
vi.mock('../../src/config', () => ({
|
||
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
|
||
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
||
updateJwtSecret: () => {},
|
||
SESSION_DURATION: '24h',
|
||
SESSION_DURATION_MS: 86400000,
|
||
SESSION_DURATION_SECONDS: 86400,
|
||
DEFAULT_LANGUAGE: 'en',
|
||
}));
|
||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
|
||
|
||
import { buildApp } from '../../src/bootstrap';
|
||
import { createTables } from '../../src/db/schema';
|
||
import { runMigrations } from '../../src/db/migrations';
|
||
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
|
||
import { createUser, createAdmin, createTrip, addTripMember, createPlace, createReservation, createTag, createDayAccommodation, createBudgetItem, createPackingItem, createDayNote, createDayAssignment } from '../helpers/factories';
|
||
import { authCookie } from '../helpers/auth';
|
||
import { invalidatePermissionsCache } from '../../src/services/permissions';
|
||
|
||
let nestApp: INestApplication;
|
||
let app: Application;
|
||
|
||
beforeAll(async () => {
|
||
createTables(testDb);
|
||
runMigrations(testDb);
|
||
nestApp = await buildApp();
|
||
app = nestApp.getHttpAdapter().getInstance();
|
||
});
|
||
beforeEach(() => {
|
||
resetTestDb(testDb);
|
||
resetRateLimits(nestApp);
|
||
invalidatePermissionsCache();
|
||
});
|
||
afterAll(async () => {
|
||
await nestApp.close();
|
||
testDb.close();
|
||
});
|
||
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
// Create trip (TRIP-001, TRIP-002, TRIP-003)
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
|
||
describe('Create trip', () => {
|
||
it('TRIP-001 — POST /api/trips with start_date/end_date returns 201 and auto-generates days', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
const res = await request(app)
|
||
.post('/api/trips')
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ title: 'Paris Adventure', start_date: '2026-06-01', end_date: '2026-06-05' });
|
||
|
||
expect(res.status).toBe(201);
|
||
expect(res.body.trip).toBeDefined();
|
||
expect(res.body.trip.title).toBe('Paris Adventure');
|
||
|
||
// Verify days were generated (5 days: Jun 1–5)
|
||
const days = testDb.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY date').all(res.body.trip.id) as any[];
|
||
expect(days).toHaveLength(5);
|
||
expect(days[0].date).toBe('2026-06-01');
|
||
expect(days[4].date).toBe('2026-06-05');
|
||
});
|
||
|
||
it('TRIP-002 — POST /api/trips without dates returns 201 and creates 7 dateless placeholder days', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
const res = await request(app)
|
||
.post('/api/trips')
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ title: 'Open-ended Trip' });
|
||
|
||
expect(res.status).toBe(201);
|
||
expect(res.body.trip).toBeDefined();
|
||
expect(res.body.trip.start_date).toBeNull();
|
||
expect(res.body.trip.end_date).toBeNull();
|
||
|
||
// Should have 7 dateless placeholder days
|
||
const days = testDb.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number').all(res.body.trip.id) as any[];
|
||
expect(days).toHaveLength(7);
|
||
expect(days[0].date).toBeNull();
|
||
});
|
||
|
||
it('TRIP-002b — POST /api/trips with day_count creates correct number of dateless days', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
const res = await request(app)
|
||
.post('/api/trips')
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ title: 'Custom Days Trip', day_count: 20 });
|
||
|
||
expect(res.status).toBe(201);
|
||
expect(res.body.trip.start_date).toBeNull();
|
||
expect(res.body.trip.day_count).toBe(20);
|
||
|
||
const days = testDb.prepare('SELECT * FROM days WHERE trip_id = ?').all(res.body.trip.id) as any[];
|
||
expect(days).toHaveLength(20);
|
||
});
|
||
|
||
it('TRIP-001 — POST /api/trips requires a title, returns 400 without one', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
const res = await request(app)
|
||
.post('/api/trips')
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ description: 'No title here' });
|
||
|
||
expect(res.status).toBe(400);
|
||
expect(res.body.error).toMatch(/title/i);
|
||
});
|
||
|
||
it('TRIP-001 — POST /api/trips rejects end_date before start_date with 400', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
const res = await request(app)
|
||
.post('/api/trips')
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ title: 'Bad Dates', start_date: '2026-06-10', end_date: '2026-06-05' });
|
||
|
||
expect(res.status).toBe(400);
|
||
expect(res.body.error).toMatch(/end date/i);
|
||
});
|
||
|
||
it('TRIP-003 — trip_create permission set to admin blocks regular user with 403', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
// Restrict trip creation to admins only
|
||
testDb.prepare("INSERT INTO app_settings (key, value) VALUES ('perm_trip_create', 'admin')").run();
|
||
invalidatePermissionsCache();
|
||
|
||
const res = await request(app)
|
||
.post('/api/trips')
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ title: 'Forbidden Trip' });
|
||
|
||
expect(res.status).toBe(403);
|
||
expect(res.body.error).toMatch(/permission/i);
|
||
});
|
||
|
||
it('TRIP-003 — trip_create permission set to admin allows admin user', async () => {
|
||
const { user: admin } = createAdmin(testDb);
|
||
|
||
testDb.prepare("INSERT INTO app_settings (key, value) VALUES ('perm_trip_create', 'admin')").run();
|
||
invalidatePermissionsCache();
|
||
|
||
const res = await request(app)
|
||
.post('/api/trips')
|
||
.set('Cookie', authCookie(admin.id))
|
||
.send({ title: 'Admin Trip' });
|
||
|
||
expect(res.status).toBe(201);
|
||
});
|
||
|
||
it('TRIP-001 — unauthenticated POST /api/trips returns 401', async () => {
|
||
const res = await request(app).post('/api/trips').send({ title: 'No Auth' });
|
||
expect(res.status).toBe(401);
|
||
});
|
||
});
|
||
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
// List trips (TRIP-004, TRIP-005)
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
|
||
describe('List trips', () => {
|
||
it('TRIP-004 — GET /api/trips returns own trips and member trips, not other users trips', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const { user: stranger } = createUser(testDb);
|
||
|
||
const ownTrip = createTrip(testDb, owner.id, { title: "Owner's Trip" });
|
||
const memberTrip = createTrip(testDb, stranger.id, { title: "Stranger's Trip (member)" });
|
||
createTrip(testDb, stranger.id, { title: "Stranger's Private Trip" });
|
||
|
||
// Add member to one of stranger's trips
|
||
addTripMember(testDb, memberTrip.id, member.id);
|
||
|
||
const ownerRes = await request(app)
|
||
.get('/api/trips')
|
||
.set('Cookie', authCookie(owner.id));
|
||
|
||
expect(ownerRes.status).toBe(200);
|
||
const ownerTripIds = ownerRes.body.trips.map((t: any) => t.id);
|
||
expect(ownerTripIds).toContain(ownTrip.id);
|
||
expect(ownerTripIds).not.toContain(memberTrip.id);
|
||
|
||
const memberRes = await request(app)
|
||
.get('/api/trips')
|
||
.set('Cookie', authCookie(member.id));
|
||
|
||
expect(memberRes.status).toBe(200);
|
||
const memberTripIds = memberRes.body.trips.map((t: any) => t.id);
|
||
expect(memberTripIds).toContain(memberTrip.id);
|
||
expect(memberTripIds).not.toContain(ownTrip.id);
|
||
});
|
||
|
||
it('TRIP-005 — GET /api/trips excludes archived trips by default', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
const activeTrip = createTrip(testDb, user.id, { title: 'Active Trip' });
|
||
const archivedTrip = createTrip(testDb, user.id, { title: 'Archived Trip' });
|
||
|
||
// Archive the second trip directly in the DB
|
||
testDb.prepare('UPDATE trips SET is_archived = 1 WHERE id = ?').run(archivedTrip.id);
|
||
|
||
const res = await request(app)
|
||
.get('/api/trips')
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
expect(res.status).toBe(200);
|
||
const tripIds = res.body.trips.map((t: any) => t.id);
|
||
expect(tripIds).toContain(activeTrip.id);
|
||
expect(tripIds).not.toContain(archivedTrip.id);
|
||
});
|
||
|
||
it('TRIP-005 — GET /api/trips?archived=1 returns only archived trips', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
const activeTrip = createTrip(testDb, user.id, { title: 'Active Trip' });
|
||
const archivedTrip = createTrip(testDb, user.id, { title: 'Archived Trip' });
|
||
|
||
testDb.prepare('UPDATE trips SET is_archived = 1 WHERE id = ?').run(archivedTrip.id);
|
||
|
||
const res = await request(app)
|
||
.get('/api/trips?archived=1')
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
expect(res.status).toBe(200);
|
||
const tripIds = res.body.trips.map((t: any) => t.id);
|
||
expect(tripIds).toContain(archivedTrip.id);
|
||
expect(tripIds).not.toContain(activeTrip.id);
|
||
});
|
||
});
|
||
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
// Get trip (TRIP-006, TRIP-007, TRIP-016, TRIP-017)
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
|
||
describe('Get trip', () => {
|
||
it('TRIP-006 — GET /api/trips/:id for own trip returns 200 with full trip object', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { title: 'My Trip', description: 'A lovely trip' });
|
||
|
||
const res = await request(app)
|
||
.get(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.trip).toBeDefined();
|
||
expect(res.body.trip.id).toBe(trip.id);
|
||
expect(res.body.trip.title).toBe('My Trip');
|
||
expect(res.body.trip.is_owner).toBe(1);
|
||
});
|
||
|
||
it('TRIP-007 — GET /api/trips/:id for another users trip returns 404', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: other } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: "Owner's Trip" });
|
||
|
||
const res = await request(app)
|
||
.get(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(other.id));
|
||
|
||
expect(res.status).toBe(404);
|
||
expect(res.body.error).toMatch(/not found/i);
|
||
});
|
||
|
||
|
||
it('TRIP-017 — Member can access trip → 200', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Shared Trip' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
const res = await request(app)
|
||
.get(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(member.id));
|
||
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.trip.id).toBe(trip.id);
|
||
expect(res.body.trip.is_owner).toBe(0);
|
||
});
|
||
|
||
it('TRIP-006 — GET /api/trips/:id for non-existent trip returns 404', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
const res = await request(app)
|
||
.get('/api/trips/999999')
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
expect(res.status).toBe(404);
|
||
});
|
||
});
|
||
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
// Update trip (TRIP-008, TRIP-009, TRIP-010)
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
|
||
describe('Update trip', () => {
|
||
it('TRIP-008 — PUT /api/trips/:id updates title and description for owner → 200', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { title: 'Original Title' });
|
||
|
||
const res = await request(app)
|
||
.put(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ title: 'Updated Title', description: 'New description' });
|
||
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.trip.title).toBe('Updated Title');
|
||
expect(res.body.trip.description).toBe('New description');
|
||
});
|
||
|
||
it('TRIP-009 — Archive trip (PUT with is_archived:true) removes it from normal list', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { title: 'To Archive' });
|
||
|
||
const archiveRes = await request(app)
|
||
.put(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ is_archived: true });
|
||
|
||
expect(archiveRes.status).toBe(200);
|
||
expect(archiveRes.body.trip.is_archived).toBe(1);
|
||
|
||
// Should not appear in the normal list
|
||
const listRes = await request(app)
|
||
.get('/api/trips')
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
const tripIds = listRes.body.trips.map((t: any) => t.id);
|
||
expect(tripIds).not.toContain(trip.id);
|
||
});
|
||
|
||
it('TRIP-009 — Unarchive trip reappears in normal list', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { title: 'Archived Trip' });
|
||
|
||
// Archive it first
|
||
testDb.prepare('UPDATE trips SET is_archived = 1 WHERE id = ?').run(trip.id);
|
||
|
||
// Unarchive via API
|
||
const unarchiveRes = await request(app)
|
||
.put(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ is_archived: false });
|
||
|
||
expect(unarchiveRes.status).toBe(200);
|
||
expect(unarchiveRes.body.trip.is_archived).toBe(0);
|
||
|
||
// Should appear in the normal list again
|
||
const listRes = await request(app)
|
||
.get('/api/trips')
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
const tripIds = listRes.body.trips.map((t: any) => t.id);
|
||
expect(tripIds).toContain(trip.id);
|
||
});
|
||
|
||
it('TRIP-010 — Archive by trip member is denied when trip_archive is set to trip_owner', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Members Trip' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
// Restrict archiving to trip_owner only (this is actually the default, but set explicitly)
|
||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('perm_trip_archive', 'trip_owner')").run();
|
||
invalidatePermissionsCache();
|
||
|
||
const res = await request(app)
|
||
.put(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(member.id))
|
||
.send({ is_archived: true });
|
||
|
||
expect(res.status).toBe(403);
|
||
expect(res.body.error).toMatch(/permission/i);
|
||
});
|
||
|
||
it('TRIP-008 — Member cannot edit trip title when trip_edit is set to trip_owner', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Original' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
// Default trip_edit is trip_owner — members should be blocked
|
||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('perm_trip_edit', 'trip_owner')").run();
|
||
invalidatePermissionsCache();
|
||
|
||
const res = await request(app)
|
||
.put(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(member.id))
|
||
.send({ title: 'Hacked Title' });
|
||
|
||
expect(res.status).toBe(403);
|
||
});
|
||
|
||
it('TRIP-008 — PUT /api/trips/:id returns 404 for non-existent trip', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
const res = await request(app)
|
||
.put('/api/trips/999999')
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ title: 'Ghost Update' });
|
||
|
||
expect(res.status).toBe(404);
|
||
});
|
||
|
||
it('TRIP-023 — Shifting trip date range preserves day assignments positionally', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { start_date: '2026-08-01', end_date: '2026-08-05' });
|
||
|
||
const days = testDb.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number').all(trip.id) as { id: number; date: string }[];
|
||
expect(days).toHaveLength(5);
|
||
|
||
const place = createPlace(testDb, trip.id);
|
||
const assignment = createDayAssignment(testDb, days[0].id, place.id);
|
||
const note = createDayNote(testDb, days[1].id, trip.id, { text: 'pack sunscreen' });
|
||
|
||
// Shift forward 10 days (zero overlap with original range)
|
||
const res = await request(app)
|
||
.put(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ start_date: '2026-08-11', end_date: '2026-08-15' });
|
||
|
||
expect(res.status).toBe(200);
|
||
|
||
const daysAfter = testDb.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number').all(trip.id) as { id: number; date: string | null }[];
|
||
expect(daysAfter).toHaveLength(5);
|
||
expect(daysAfter.map(d => d.date)).toEqual(['2026-08-11', '2026-08-12', '2026-08-13', '2026-08-14', '2026-08-15']);
|
||
|
||
const assignmentsAfter = testDb.prepare('SELECT * FROM day_assignments WHERE id = ?').get(assignment.id) as { day_id: number } | undefined;
|
||
expect(assignmentsAfter).toBeDefined();
|
||
expect(assignmentsAfter!.day_id).toBe(daysAfter[0].id);
|
||
|
||
const notesAfter = testDb.prepare('SELECT * FROM day_notes WHERE id = ?').get(note.id) as { day_id: number } | undefined;
|
||
expect(notesAfter).toBeDefined();
|
||
expect(notesAfter!.day_id).toBe(daysAfter[1].id);
|
||
});
|
||
|
||
it('TRIP-024 — Shrinking trip date range deletes overflow days and their content', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { start_date: '2026-09-01', end_date: '2026-09-05' });
|
||
|
||
const days = testDb.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number').all(trip.id) as { id: number }[];
|
||
const place = createPlace(testDb, trip.id);
|
||
const a4 = createDayAssignment(testDb, days[3].id, place.id);
|
||
const a5 = createDayAssignment(testDb, days[4].id, place.id);
|
||
|
||
// Shrink from 5 to 3 days
|
||
const res = await request(app)
|
||
.put(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ start_date: '2026-09-01', end_date: '2026-09-03' });
|
||
|
||
expect(res.status).toBe(200);
|
||
|
||
const daysAfter = testDb.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number').all(trip.id) as { id: number; date: string | null }[];
|
||
expect(daysAfter).toHaveLength(3);
|
||
expect(daysAfter.every(d => d.date !== null)).toBe(true);
|
||
|
||
// Overflow days and their assignments deleted
|
||
const all = testDb.prepare('SELECT * FROM day_assignments WHERE id IN (?, ?)').all(a4.id, a5.id) as { id: number }[];
|
||
expect(all).toHaveLength(0);
|
||
});
|
||
});
|
||
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
// Delete trip (TRIP-018, TRIP-019, TRIP-022)
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
|
||
describe('Delete trip', () => {
|
||
it('TRIP-018 — DELETE /api/trips/:id by owner returns 200 and trip is no longer accessible', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { title: 'To Delete' });
|
||
|
||
const deleteRes = await request(app)
|
||
.delete(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
expect(deleteRes.status).toBe(200);
|
||
expect(deleteRes.body.success).toBe(true);
|
||
|
||
// Trip should no longer be accessible
|
||
const getRes = await request(app)
|
||
.get(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
expect(getRes.status).toBe(404);
|
||
});
|
||
|
||
it('TRIP-019 — Regular user cannot delete another users trip → 403', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: other } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: "Owner's Trip" });
|
||
|
||
const res = await request(app)
|
||
.delete(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(other.id));
|
||
|
||
// getTripOwner finds the trip (it exists); checkPermission fails for non-members → 403
|
||
expect(res.status).toBe(403);
|
||
|
||
// Trip still exists
|
||
const tripInDb = testDb.prepare('SELECT id FROM trips WHERE id = ?').get(trip.id);
|
||
expect(tripInDb).toBeDefined();
|
||
});
|
||
|
||
it('TRIP-019 — Trip member cannot delete trip → 403', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Shared Trip' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
const res = await request(app)
|
||
.delete(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(member.id));
|
||
|
||
expect(res.status).toBe(403);
|
||
expect(res.body.error).toMatch(/permission/i);
|
||
});
|
||
|
||
it('TRIP-022 — Trip with places and reservations can be deleted (cascade)', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { title: 'Trip With Data' });
|
||
|
||
// Add associated data
|
||
createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
|
||
createReservation(testDb, trip.id, { title: 'Hotel Booking', type: 'hotel' });
|
||
|
||
const deleteRes = await request(app)
|
||
.delete(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
expect(deleteRes.status).toBe(200);
|
||
expect(deleteRes.body.success).toBe(true);
|
||
|
||
// Verify cascade: places and reservations should be gone
|
||
const places = testDb.prepare('SELECT id FROM places WHERE trip_id = ?').all(trip.id);
|
||
expect(places).toHaveLength(0);
|
||
|
||
const reservations = testDb.prepare('SELECT id FROM reservations WHERE trip_id = ?').all(trip.id);
|
||
expect(reservations).toHaveLength(0);
|
||
});
|
||
|
||
it('TRIP-018 — Admin can delete another users trip', async () => {
|
||
const { user: admin } = createAdmin(testDb);
|
||
const { user: owner } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: "User's Trip" });
|
||
|
||
const res = await request(app)
|
||
.delete(`/api/trips/${trip.id}`)
|
||
.set('Cookie', authCookie(admin.id));
|
||
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.success).toBe(true);
|
||
});
|
||
|
||
it('TRIP-018 — DELETE /api/trips/:id for non-existent trip returns 404', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
const res = await request(app)
|
||
.delete('/api/trips/999999')
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
expect(res.status).toBe(404);
|
||
});
|
||
});
|
||
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
// Members (TRIP-013, TRIP-014, TRIP-015)
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
|
||
describe('Trip members', () => {
|
||
it('TRIP-015 — GET /api/trips/:id/members returns owner and members list', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Team Trip' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
const res = await request(app)
|
||
.get(`/api/trips/${trip.id}/members`)
|
||
.set('Cookie', authCookie(owner.id));
|
||
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.owner).toBeDefined();
|
||
expect(res.body.owner.id).toBe(owner.id);
|
||
expect(Array.isArray(res.body.members)).toBe(true);
|
||
expect(res.body.members.some((m: any) => m.id === member.id)).toBe(true);
|
||
expect(res.body.current_user_id).toBe(owner.id);
|
||
});
|
||
|
||
it('TRIP-013 — POST /api/trips/:id/members adds a member by email → 201', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: invitee } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Team Trip' });
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/members`)
|
||
.set('Cookie', authCookie(owner.id))
|
||
.send({ identifier: invitee.email });
|
||
|
||
expect(res.status).toBe(201);
|
||
expect(res.body.member).toBeDefined();
|
||
expect(res.body.member.email).toBe(invitee.email);
|
||
expect(res.body.member.role).toBe('member');
|
||
|
||
// Verify in DB
|
||
const dbEntry = testDb.prepare('SELECT * FROM trip_members WHERE trip_id = ? AND user_id = ?').get(trip.id, invitee.id);
|
||
expect(dbEntry).toBeDefined();
|
||
});
|
||
|
||
it('TRIP-013 — POST /api/trips/:id/members adds a member by username → 201', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: invitee } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Team Trip' });
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/members`)
|
||
.set('Cookie', authCookie(owner.id))
|
||
.send({ identifier: invitee.username });
|
||
|
||
expect(res.status).toBe(201);
|
||
expect(res.body.member.id).toBe(invitee.id);
|
||
});
|
||
|
||
it('TRIP-013 — Adding a non-existent user returns 404', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Team Trip' });
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/members`)
|
||
.set('Cookie', authCookie(owner.id))
|
||
.send({ identifier: 'nobody@nowhere.example.com' });
|
||
|
||
expect(res.status).toBe(404);
|
||
expect(res.body.error).toMatch(/user not found/i);
|
||
});
|
||
|
||
it('TRIP-013 — Adding a user who is already a member returns 400', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Team Trip' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/members`)
|
||
.set('Cookie', authCookie(owner.id))
|
||
.send({ identifier: member.email });
|
||
|
||
expect(res.status).toBe(400);
|
||
expect(res.body.error).toMatch(/already/i);
|
||
});
|
||
|
||
it('TRIP-013 — Adding a member by whitespace-padded username resolves correctly → 201', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: invitee } = createUser(testDb, { username: 'paddeduser' });
|
||
const trip = createTrip(testDb, owner.id, { title: 'Padded Trip' });
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/members`)
|
||
.set('Cookie', authCookie(owner.id))
|
||
.send({ identifier: ' paddeduser ' });
|
||
|
||
expect(res.status).toBe(201);
|
||
expect(res.body.member.id).toBe(invitee.id);
|
||
});
|
||
|
||
it('TRIP-014 — DELETE /api/trips/:id/members/:userId removes a member → 200', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Team Trip' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
const res = await request(app)
|
||
.delete(`/api/trips/${trip.id}/members/${member.id}`)
|
||
.set('Cookie', authCookie(owner.id));
|
||
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.success).toBe(true);
|
||
|
||
// Verify removal in DB
|
||
const dbEntry = testDb.prepare('SELECT * FROM trip_members WHERE trip_id = ? AND user_id = ?').get(trip.id, member.id);
|
||
expect(dbEntry).toBeUndefined();
|
||
});
|
||
|
||
it('TRIP-014 — Member can remove themselves from a trip → 200', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Team Trip' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
const res = await request(app)
|
||
.delete(`/api/trips/${trip.id}/members/${member.id}`)
|
||
.set('Cookie', authCookie(member.id));
|
||
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.success).toBe(true);
|
||
});
|
||
|
||
it('TRIP-TRANSFER-001 — owner hands the trip to a member; roles swap (#973)', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Team Trip' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/transfer`)
|
||
.set('Cookie', authCookie(owner.id))
|
||
.send({ newOwnerId: member.id });
|
||
|
||
expect(res.status).toBe(201);
|
||
expect(res.body.success).toBe(true);
|
||
|
||
const row = testDb.prepare('SELECT user_id FROM trips WHERE id = ?').get(trip.id) as { user_id: number };
|
||
expect(row.user_id).toBe(member.id);
|
||
const memberRows = (testDb.prepare('SELECT user_id FROM trip_members WHERE trip_id = ?').all(trip.id) as { user_id: number }[]).map(r => r.user_id);
|
||
expect(memberRows).toContain(owner.id);
|
||
expect(memberRows).not.toContain(member.id);
|
||
});
|
||
|
||
it('TRIP-TRANSFER-002 — a non-owner cannot transfer ownership → 403', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Team Trip' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/transfer`)
|
||
.set('Cookie', authCookie(member.id))
|
||
.send({ newOwnerId: member.id });
|
||
|
||
expect(res.status).toBe(403);
|
||
});
|
||
|
||
it('TRIP-TRANSFER-003 — cannot transfer to a non-member → 400', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: stranger } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Team Trip' });
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/transfer`)
|
||
.set('Cookie', authCookie(owner.id))
|
||
.send({ newOwnerId: stranger.id });
|
||
|
||
expect(res.status).toBe(400);
|
||
});
|
||
|
||
it('TRIP-GUEST-001 — owner creates a guest; it appears as a member and is shielded from auth (#1362)', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Camping' });
|
||
|
||
const created = await request(app)
|
||
.post(`/api/trips/${trip.id}/guests`)
|
||
.set('Cookie', authCookie(owner.id))
|
||
.send({ name: 'Grandma' });
|
||
expect(created.status).toBe(201);
|
||
expect(created.body.member.is_guest).toBe(true);
|
||
expect(created.body.member.username).toBe('Grandma');
|
||
const guestId = created.body.member.id;
|
||
|
||
// Surfaces in the members list every assignment picker consumes.
|
||
const members = await request(app).get(`/api/trips/${trip.id}/members`).set('Cookie', authCookie(owner.id));
|
||
const guest = members.body.members.find((m: any) => m.id === guestId);
|
||
expect(guest).toBeTruthy();
|
||
expect(guest.is_guest).toBe(true);
|
||
|
||
// NOT in the global user directory (the member-add picker source).
|
||
const dir = await request(app).get('/api/auth/users').set('Cookie', authCookie(owner.id));
|
||
expect(dir.body.users.some((u: any) => u.id === guestId)).toBe(false);
|
||
|
||
// The synthetic email can never authenticate (resolves as an unknown email).
|
||
const email = (testDb.prepare('SELECT email FROM users WHERE id = ?').get(guestId) as any).email;
|
||
const login = await request(app).post('/api/auth/login').send({ email, password: 'anything' });
|
||
expect(login.status).toBe(401);
|
||
});
|
||
|
||
it('TRIP-GUEST-004 — the same guest name is allowed on two trips (no "Name 2", #1446)', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const tripA = createTrip(testDb, owner.id, { title: 'Trip A' });
|
||
const tripB = createTrip(testDb, owner.id, { title: 'Trip B' });
|
||
|
||
const addJake = (tripId: number) => request(app)
|
||
.post(`/api/trips/${tripId}/guests`).set('Cookie', authCookie(owner.id)).send({ name: 'Jake' });
|
||
|
||
const a = await addJake(tripA.id);
|
||
const b = await addJake(tripB.id);
|
||
expect(a.status).toBe(201);
|
||
expect(b.status).toBe(201);
|
||
// both keep the plain name — the second is NOT auto-renamed to "Jake 2"
|
||
expect(a.body.member.username).toBe('Jake');
|
||
expect(b.body.member.username).toBe('Jake');
|
||
expect(b.body.member.id).not.toBe(a.body.member.id);
|
||
|
||
// and each trip's member list shows "Jake" (not the internal uuid handle)
|
||
const membersB = await request(app).get(`/api/trips/${tripB.id}/members`).set('Cookie', authCookie(owner.id));
|
||
expect(membersB.body.members.find((m: any) => m.id === b.body.member.id).username).toBe('Jake');
|
||
});
|
||
|
||
it('TRIP-GUEST-002 — guest CRUD is owner-only', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Camping' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
// A non-owner member cannot create a guest.
|
||
const denied = await request(app)
|
||
.post(`/api/trips/${trip.id}/guests`)
|
||
.set('Cookie', authCookie(member.id))
|
||
.send({ name: 'Nope' });
|
||
expect(denied.status).toBe(403);
|
||
|
||
const created = await request(app)
|
||
.post(`/api/trips/${trip.id}/guests`)
|
||
.set('Cookie', authCookie(owner.id))
|
||
.send({ name: 'Kid' });
|
||
const guestId = created.body.member.id;
|
||
|
||
// Rename + delete by the owner.
|
||
const renamed = await request(app)
|
||
.put(`/api/trips/${trip.id}/guests/${guestId}`)
|
||
.set('Cookie', authCookie(owner.id))
|
||
.send({ name: 'Junior' });
|
||
expect(renamed.status).toBe(200);
|
||
// #1446: the human name lives in display_name now (username is a non-shown uuid handle)
|
||
expect((testDb.prepare('SELECT display_name FROM users WHERE id = ?').get(guestId) as any).display_name).toBe('Junior');
|
||
|
||
const removed = await request(app)
|
||
.delete(`/api/trips/${trip.id}/guests/${guestId}`)
|
||
.set('Cookie', authCookie(owner.id));
|
||
expect(removed.status).toBe(200);
|
||
expect(testDb.prepare('SELECT id FROM users WHERE id = ?').get(guestId)).toBeUndefined();
|
||
});
|
||
|
||
it('TRIP-GUEST-003 — a guest cannot be invited as a member to any trip (#1362)', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Camping' });
|
||
const otherTrip = createTrip(testDb, owner.id, { title: 'Other' });
|
||
const created = await request(app)
|
||
.post(`/api/trips/${trip.id}/guests`)
|
||
.set('Cookie', authCookie(owner.id))
|
||
.send({ name: 'Eve' });
|
||
const email = (testDb.prepare('SELECT email FROM users WHERE id = ?').get(created.body.member.id) as any).email;
|
||
|
||
const invite = await request(app)
|
||
.post(`/api/trips/${otherTrip.id}/members`)
|
||
.set('Cookie', authCookie(owner.id))
|
||
.send({ identifier: email });
|
||
expect(invite.status).toBe(404);
|
||
});
|
||
|
||
it('TRIP-013 — Non-owner member cannot add other members when member_manage is trip_owner', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const { user: invitee } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Team Trip' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
// Restrict member management to trip_owner (default)
|
||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('perm_member_manage', 'trip_owner')").run();
|
||
invalidatePermissionsCache();
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/members`)
|
||
.set('Cookie', authCookie(member.id))
|
||
.send({ identifier: invitee.email });
|
||
|
||
expect(res.status).toBe(403);
|
||
expect(res.body.error).toMatch(/permission/i);
|
||
});
|
||
|
||
it('TRIP-015 — Non-member cannot list trip members → 404', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: stranger } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Private Trip' });
|
||
|
||
const res = await request(app)
|
||
.get(`/api/trips/${trip.id}/members`)
|
||
.set('Cookie', authCookie(stranger.id));
|
||
|
||
expect(res.status).toBe(404);
|
||
});
|
||
});
|
||
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
// Copy trip (TRIP-023, TRIP-024)
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
|
||
describe('Copy trip', () => {
|
||
it('TRIP-023 — POST /api/trips/:id/copy creates a duplicate trip with 201', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { title: 'Original Trip', description: 'Desc' });
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/copy`)
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({});
|
||
|
||
expect(res.status).toBe(201);
|
||
expect(res.body.trip).toBeDefined();
|
||
expect(res.body.trip.id).not.toBe(trip.id);
|
||
expect(res.body.trip.title).toBe('Original Trip');
|
||
});
|
||
|
||
it('TRIP-023 — copy accepts a custom title for the new trip', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { title: 'Source' });
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/copy`)
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ title: 'Custom Copy' });
|
||
|
||
expect(res.status).toBe(201);
|
||
expect(res.body.trip.title).toBe('Custom Copy');
|
||
});
|
||
|
||
it('TRIP-023 — copied trip belongs to the requesting user', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Shared Trip' });
|
||
addTripMember(testDb, trip.id, member.id);
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/copy`)
|
||
.set('Cookie', authCookie(member.id))
|
||
.send({});
|
||
|
||
expect(res.status).toBe(201);
|
||
const newTrip = testDb.prepare('SELECT * FROM trips WHERE id = ?').get(res.body.trip.id) as any;
|
||
expect(newTrip.user_id).toBe(member.id);
|
||
});
|
||
|
||
it('TRIP-024 — non-member cannot copy a trip → 404', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: stranger } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Private Trip' });
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/copy`)
|
||
.set('Cookie', authCookie(stranger.id))
|
||
.send({});
|
||
|
||
expect(res.status).toBe(404);
|
||
});
|
||
|
||
it('TRIP-024 — copy of non-existent trip returns 404', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
const res = await request(app)
|
||
.post('/api/trips/999999/copy')
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({});
|
||
|
||
expect(res.status).toBe(404);
|
||
});
|
||
});
|
||
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
// ICS export (TRIP-025)
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
|
||
describe('ICS export', () => {
|
||
it('TRIP-025 — GET /api/trips/:id/export.ics returns text/calendar content', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { title: 'Calendar Trip' });
|
||
|
||
const res = await request(app)
|
||
.get(`/api/trips/${trip.id}/export.ics`)
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
expect(res.status).toBe(200);
|
||
expect(res.headers['content-type']).toMatch(/text\/calendar/);
|
||
expect(res.text).toContain('BEGIN:VCALENDAR');
|
||
expect(res.text).toContain('END:VCALENDAR');
|
||
});
|
||
|
||
it('TRIP-025 — non-member cannot export ICS → 404', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: stranger } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id, { title: 'Private Trip' });
|
||
|
||
const res = await request(app)
|
||
.get(`/api/trips/${trip.id}/export.ics`)
|
||
.set('Cookie', authCookie(stranger.id));
|
||
|
||
expect(res.status).toBe(404);
|
||
});
|
||
|
||
it('TRIP-025 — unauthenticated export returns 401', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { title: 'Trip' });
|
||
|
||
const res = await request(app).get(`/api/trips/${trip.id}/export.ics`);
|
||
expect(res.status).toBe(401);
|
||
});
|
||
});
|
||
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
// Copy trip with full data (covers loop bodies in the copy transaction)
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
|
||
describe('Copy trip with data', () => {
|
||
it('TRIP-026 — copy preserves days, places, tags, assignments, accommodations, reservations, budget, packing, notes', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, {
|
||
title: 'Data-Rich Trip',
|
||
start_date: '2025-09-01',
|
||
end_date: '2025-09-03',
|
||
});
|
||
|
||
const days = testDb.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number').all(trip.id) as any[];
|
||
expect(days.length).toBe(3);
|
||
|
||
// Place with a tag
|
||
const place = createPlace(testDb, trip.id, { name: 'Tower Bridge' });
|
||
const tag = createTag(testDb, user.id, { name: 'Landmark' });
|
||
testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(place.id, tag.id);
|
||
|
||
// Day assignment
|
||
testDb.prepare(
|
||
'INSERT INTO day_assignments (day_id, place_id, order_index, notes) VALUES (?, ?, 0, ?)'
|
||
).run(days[0].id, place.id, 'Visit in morning');
|
||
|
||
// Accommodation spanning days 0→1
|
||
createDayAccommodation(testDb, trip.id, place.id, days[0].id, days[1].id);
|
||
|
||
// Reservation on day 0
|
||
createReservation(testDb, trip.id, { title: 'Flight Out', type: 'flight', day_id: days[0].id });
|
||
|
||
// Budget item
|
||
createBudgetItem(testDb, trip.id, { name: 'Flights', total_price: 400 });
|
||
|
||
// Packing item
|
||
createPackingItem(testDb, trip.id, { name: 'Toothbrush' });
|
||
|
||
// Day note
|
||
createDayNote(testDb, days[0].id, trip.id, { text: 'Pack early!' });
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/copy`)
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ title: 'Data-Rich Trip (Copy)' });
|
||
|
||
expect(res.status).toBe(201);
|
||
const newId = res.body.trip.id;
|
||
expect(newId).not.toBe(trip.id);
|
||
|
||
// Days copied
|
||
const newDays = testDb.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number').all(newId) as any[];
|
||
expect(newDays).toHaveLength(3);
|
||
|
||
// Place copied
|
||
const newPlaces = testDb.prepare('SELECT * FROM places WHERE trip_id = ?').all(newId) as any[];
|
||
expect(newPlaces).toHaveLength(1);
|
||
expect(newPlaces[0].name).toBe('Tower Bridge');
|
||
|
||
// Place tag copied
|
||
const newTags = testDb.prepare(
|
||
'SELECT pt.* FROM place_tags pt JOIN places p ON p.id = pt.place_id WHERE p.trip_id = ?'
|
||
).all(newId) as any[];
|
||
expect(newTags).toHaveLength(1);
|
||
|
||
// Assignment copied
|
||
const newAssignments = testDb.prepare(
|
||
'SELECT da.* FROM day_assignments da JOIN days d ON d.id = da.day_id WHERE d.trip_id = ?'
|
||
).all(newId) as any[];
|
||
expect(newAssignments).toHaveLength(1);
|
||
|
||
// Accommodation copied
|
||
const newAccom = testDb.prepare('SELECT * FROM day_accommodations WHERE trip_id = ?').all(newId) as any[];
|
||
expect(newAccom).toHaveLength(1);
|
||
|
||
// Reservation copied
|
||
const newResv = testDb.prepare('SELECT * FROM reservations WHERE trip_id = ?').all(newId) as any[];
|
||
expect(newResv).toHaveLength(1);
|
||
|
||
// Budget copied
|
||
const newBudget = testDb.prepare('SELECT * FROM budget_items WHERE trip_id = ?').all(newId) as any[];
|
||
expect(newBudget).toHaveLength(1);
|
||
|
||
// Packing copied (checked reset to 0)
|
||
const newPacking = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ?').all(newId) as any[];
|
||
expect(newPacking).toHaveLength(1);
|
||
expect(newPacking[0].checked).toBe(0);
|
||
|
||
// Day note copied
|
||
const newNotes = testDb.prepare('SELECT * FROM day_notes WHERE trip_id = ?').all(newId) as any[];
|
||
expect(newNotes).toHaveLength(1);
|
||
expect(newNotes[0].text).toBe('Pack early!');
|
||
});
|
||
|
||
it('TRIP-027 — copy preserves todos (unchecked, unassigned) and budget category order', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { title: 'Todo Trip' });
|
||
|
||
// Two todos: one checked and assigned — both should arrive unchecked and unassigned
|
||
testDb.prepare(
|
||
'INSERT INTO todo_items (trip_id, name, checked, category, sort_order, due_date, description, priority) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
|
||
).run(trip.id, 'Buy tickets', 0, 'Transport', 0, '2026-06-01', 'Check Ryanair', 1);
|
||
testDb.prepare(
|
||
'INSERT INTO todo_items (trip_id, name, checked, category, sort_order, assigned_user_id, priority) VALUES (?, ?, ?, ?, ?, ?, ?)'
|
||
).run(trip.id, 'Book hotel', 1, 'Accommodation', 1, user.id, 0);
|
||
|
||
// Two budget category order rows
|
||
const insOrder = testDb.prepare('INSERT INTO budget_category_order (trip_id, category, sort_order) VALUES (?, ?, ?)');
|
||
insOrder.run(trip.id, 'Transport', 0);
|
||
insOrder.run(trip.id, 'Accommodation', 1);
|
||
|
||
const res = await request(app)
|
||
.post(`/api/trips/${trip.id}/copy`)
|
||
.set('Cookie', authCookie(user.id))
|
||
.send({ title: 'Todo Trip (Copy)' });
|
||
|
||
expect(res.status).toBe(201);
|
||
const newId = res.body.trip.id;
|
||
|
||
// Todos copied with checked reset and assigned_user_id nulled
|
||
const newTodos = testDb.prepare('SELECT * FROM todo_items WHERE trip_id = ? ORDER BY sort_order').all(newId) as any[];
|
||
expect(newTodos).toHaveLength(2);
|
||
expect(newTodos[0].name).toBe('Buy tickets');
|
||
expect(newTodos[0].category).toBe('Transport');
|
||
expect(newTodos[0].checked).toBe(0);
|
||
expect(newTodos[0].assigned_user_id).toBeNull();
|
||
expect(newTodos[0].due_date).toBe('2026-06-01');
|
||
expect(newTodos[0].description).toBe('Check Ryanair');
|
||
expect(newTodos[0].priority).toBe(1);
|
||
expect(newTodos[1].name).toBe('Book hotel');
|
||
expect(newTodos[1].checked).toBe(0);
|
||
expect(newTodos[1].assigned_user_id).toBeNull();
|
||
|
||
// Budget category order copied
|
||
const newOrder = testDb.prepare('SELECT category, sort_order FROM budget_category_order WHERE trip_id = ? ORDER BY sort_order').all(newId) as any[];
|
||
expect(newOrder).toHaveLength(2);
|
||
expect(newOrder[0]).toMatchObject({ category: 'Transport', sort_order: 0 });
|
||
expect(newOrder[1]).toMatchObject({ category: 'Accommodation', sort_order: 1 });
|
||
});
|
||
});
|
||
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
// Bundle endpoint — GET /api/trips/:id/bundle
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
|
||
describe('Trip bundle', () => {
|
||
it('BUNDLE-001 — returns all sub-collections for owned trip', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id, { start_date: '2026-07-01', end_date: '2026-07-03' });
|
||
|
||
const res = await request(app)
|
||
.get(`/api/trips/${trip.id}/bundle`)
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.trip).toBeDefined();
|
||
expect(res.body.trip.id).toBe(trip.id);
|
||
expect(Array.isArray(res.body.days)).toBe(true);
|
||
expect(res.body.days).toHaveLength(3);
|
||
expect(Array.isArray(res.body.places)).toBe(true);
|
||
expect(Array.isArray(res.body.packingItems)).toBe(true);
|
||
expect(Array.isArray(res.body.todoItems)).toBe(true);
|
||
expect(Array.isArray(res.body.budgetItems)).toBe(true);
|
||
expect(Array.isArray(res.body.reservations)).toBe(true);
|
||
expect(Array.isArray(res.body.files)).toBe(true);
|
||
});
|
||
|
||
it('BUNDLE-002 — returns 404 for trip that does not exist', async () => {
|
||
const { user } = createUser(testDb);
|
||
|
||
const res = await request(app)
|
||
.get('/api/trips/999999/bundle')
|
||
.set('Cookie', authCookie(user.id));
|
||
|
||
expect(res.status).toBe(404);
|
||
});
|
||
|
||
it('BUNDLE-003 — returns 404 when user has no access to trip', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: other } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id);
|
||
|
||
const res = await request(app)
|
||
.get(`/api/trips/${trip.id}/bundle`)
|
||
.set('Cookie', authCookie(other.id));
|
||
|
||
expect(res.status).toBe(404);
|
||
});
|
||
|
||
it('BUNDLE-004 — members can fetch bundle', async () => {
|
||
const { user: owner } = createUser(testDb);
|
||
const { user: member } = createUser(testDb);
|
||
const trip = createTrip(testDb, owner.id);
|
||
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(trip.id, member.id);
|
||
|
||
const res = await request(app)
|
||
.get(`/api/trips/${trip.id}/bundle`)
|
||
.set('Cookie', authCookie(member.id));
|
||
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.trip.id).toBe(trip.id);
|
||
});
|
||
|
||
it('BUNDLE-005 — returns 401 when unauthenticated', async () => {
|
||
const { user } = createUser(testDb);
|
||
const trip = createTrip(testDb, user.id);
|
||
|
||
const res = await request(app).get(`/api/trips/${trip.id}/bundle`);
|
||
|
||
expect(res.status).toBe(401);
|
||
});
|
||
});
|