mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-06-19 13:21:46 +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>
613 lines
26 KiB
TypeScript
613 lines
26 KiB
TypeScript
/**
|
|
* Reservations integration tests.
|
|
* Covers RESV-001 to RESV-007.
|
|
*/
|
|
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';
|
|
|
|
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, createTrip, createDay, createPlace, createReservation, addTripMember } from '../helpers/factories';
|
|
import { authCookie } from '../helpers/auth';
|
|
|
|
let nestApp: INestApplication;
|
|
let app: Application;
|
|
|
|
beforeAll(async () => {
|
|
createTables(testDb);
|
|
runMigrations(testDb);
|
|
nestApp = await buildApp();
|
|
app = nestApp.getHttpAdapter().getInstance();
|
|
});
|
|
|
|
beforeEach(() => {
|
|
resetTestDb(testDb);
|
|
resetRateLimits(nestApp);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await nestApp.close();
|
|
testDb.close();
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Create reservation
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
describe('Create reservation', () => {
|
|
it('RESV-001 — POST /api/trips/:tripId/reservations creates a reservation', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
const res = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'Hotel Check-in', type: 'hotel' });
|
|
expect(res.status).toBe(201);
|
|
expect(res.body.reservation.title).toBe('Hotel Check-in');
|
|
expect(res.body.reservation.type).toBe('hotel');
|
|
});
|
|
|
|
it('RESV-001 — POST without title returns 400', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
const res = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ type: 'hotel' });
|
|
expect(res.status).toBe(400);
|
|
});
|
|
|
|
it('RESV-001 — non-member cannot create reservation', async () => {
|
|
const { user: owner } = createUser(testDb);
|
|
const { user: other } = createUser(testDb);
|
|
const trip = createTrip(testDb, owner.id);
|
|
|
|
const res = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(other.id))
|
|
.send({ title: 'Hotel', type: 'hotel' });
|
|
expect(res.status).toBe(404);
|
|
});
|
|
|
|
it('RESV-002 — POST with create_accommodation creates an accommodation record', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id, { date: '2025-06-01' });
|
|
|
|
const res = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'Grand Hotel', type: 'hotel', day_id: day.id, create_accommodation: true });
|
|
expect(res.status).toBe(201);
|
|
expect(res.body.reservation).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// List reservations
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
describe('List reservations', () => {
|
|
it('RESV-003 — GET /api/trips/:tripId/reservations returns all reservations', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
createReservation(testDb, trip.id, { title: 'Flight Out', type: 'flight' });
|
|
createReservation(testDb, trip.id, { title: 'Hotel Stay', type: 'hotel' });
|
|
|
|
const res = await request(app)
|
|
.get(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id));
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.reservations).toHaveLength(2);
|
|
});
|
|
|
|
it('RESV-003 — returns empty array when no reservations exist', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
const res = await request(app)
|
|
.get(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id));
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.reservations).toHaveLength(0);
|
|
});
|
|
|
|
it('RESV-007 — non-member cannot list reservations', 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}/reservations`)
|
|
.set('Cookie', authCookie(other.id));
|
|
expect(res.status).toBe(404);
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Update reservation
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
describe('Update reservation', () => {
|
|
it('RESV-004 — PUT updates reservation fields', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const resv = createReservation(testDb, trip.id, { title: 'Old Flight', type: 'flight' });
|
|
|
|
const res = await request(app)
|
|
.put(`/api/trips/${trip.id}/reservations/${resv.id}`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'New Flight', confirmation_number: 'ABC123' });
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.reservation.title).toBe('New Flight');
|
|
expect(res.body.reservation.confirmation_number).toBe('ABC123');
|
|
});
|
|
|
|
it('RESV-004b — PUT with day_id null derives day_id from reservation_time so it stays in the Plan (#1237)', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
createDay(testDb, trip.id, { date: '2025-09-01' });
|
|
const day2 = createDay(testDb, trip.id, { date: '2025-09-02' });
|
|
const resv = createReservation(testDb, trip.id, { title: 'Event', type: 'event' });
|
|
|
|
const res = await request(app)
|
|
.put(`/api/trips/${trip.id}/reservations/${resv.id}`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'Event', type: 'event', day_id: null, reservation_time: '2025-09-02' });
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.reservation.day_id).toBe(day2.id);
|
|
});
|
|
|
|
it('RESV-004c — re-dating a booking moves it to the matching day (start + end) (#1237)', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day1 = createDay(testDb, trip.id, { date: '2025-10-01' });
|
|
const day3 = createDay(testDb, trip.id, { date: '2025-10-03' });
|
|
|
|
// Booking sits on day 1 (start + end).
|
|
const created = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'Event', type: 'event', day_id: day1.id, reservation_time: '2025-10-01T09:00', reservation_end_time: '2025-10-01T10:00' });
|
|
const rid = created.body.reservation.id;
|
|
|
|
// Re-date to day 3 WITHOUT sending day_id (the modal omits it) — both ends follow.
|
|
const res = await request(app)
|
|
.put(`/api/trips/${trip.id}/reservations/${rid}`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'Event', type: 'event', reservation_time: '2025-10-03T00:00', reservation_end_time: '2025-10-03T14:00' });
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.reservation.day_id).toBe(day3.id);
|
|
expect(res.body.reservation.end_day_id).toBe(day3.id);
|
|
});
|
|
|
|
it('RESV-004 — PUT on non-existent reservation returns 404', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
const res = await request(app)
|
|
.put(`/api/trips/${trip.id}/reservations/99999`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'Updated' });
|
|
expect(res.status).toBe(404);
|
|
});
|
|
|
|
it('RESV-010 — PUT syncs check-in/out times to linked accommodation', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day1 = createDay(testDb, trip.id, { date: '2025-08-01' });
|
|
const day2 = createDay(testDb, trip.id, { date: '2025-08-03' });
|
|
const place = createPlace(testDb, trip.id, { name: 'Sync Hotel' });
|
|
|
|
// Create reservation with linked accommodation
|
|
const createRes = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({
|
|
title: 'Hotel Booking',
|
|
type: 'hotel',
|
|
day_id: day1.id,
|
|
create_accommodation: { place_id: place.id, start_day_id: day1.id, end_day_id: day2.id },
|
|
});
|
|
expect(createRes.status).toBe(201);
|
|
const resvId = createRes.body.reservation.id;
|
|
|
|
// Update with metadata containing check-in/out times and confirmation_number
|
|
const updateRes = await request(app)
|
|
.put(`/api/trips/${trip.id}/reservations/${resvId}`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({
|
|
metadata: { check_in_time: '15:00', check_out_time: '11:00' },
|
|
confirmation_number: 'HTL-XYZ-999',
|
|
});
|
|
expect(updateRes.status).toBe(200);
|
|
|
|
// Verify accommodation was updated with check-in/out
|
|
const accom = testDb.prepare('SELECT * FROM day_accommodations WHERE trip_id = ?').get(trip.id) as any;
|
|
expect(accom.check_in).toBe('15:00');
|
|
expect(accom.check_out).toBe('11:00');
|
|
expect(accom.confirmation).toBe('HTL-XYZ-999');
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Delete reservation
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
describe('Delete reservation', () => {
|
|
it('RESV-005 — DELETE removes reservation', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const resv = createReservation(testDb, trip.id, { title: 'Flight', type: 'flight' });
|
|
|
|
const del = await request(app)
|
|
.delete(`/api/trips/${trip.id}/reservations/${resv.id}`)
|
|
.set('Cookie', authCookie(user.id));
|
|
expect(del.status).toBe(200);
|
|
expect(del.body.success).toBe(true);
|
|
|
|
const list = await request(app)
|
|
.get(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id));
|
|
expect(list.body.reservations).toHaveLength(0);
|
|
});
|
|
|
|
it('RESV-005 — DELETE non-existent reservation returns 404', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
const res = await request(app)
|
|
.delete(`/api/trips/${trip.id}/reservations/99999`)
|
|
.set('Cookie', authCookie(user.id));
|
|
expect(res.status).toBe(404);
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Batch update positions
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
describe('Batch update positions', () => {
|
|
it('RESV-006 — PUT /positions updates reservation sort order', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const r1 = createReservation(testDb, trip.id, { title: 'First', type: 'flight' });
|
|
const r2 = createReservation(testDb, trip.id, { title: 'Second', type: 'hotel' });
|
|
|
|
const res = await request(app)
|
|
.put(`/api/trips/${trip.id}/reservations/positions`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ positions: [{ id: r2.id, position: 0 }, { id: r1.id, position: 1 }] });
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.success).toBe(true);
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Budget entry auto-create / auto-update
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
describe('Reservation budget entry integration', () => {
|
|
it('RESV-011 — POST with create_budget_entry auto-creates a linked budget item', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
const res = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({
|
|
title: 'Flight to Paris',
|
|
type: 'flight',
|
|
create_budget_entry: { total_price: 250, category: 'Transport' },
|
|
});
|
|
expect(res.status).toBe(201);
|
|
|
|
const budgetItem = testDb
|
|
.prepare('SELECT * FROM budget_items WHERE trip_id = ? AND reservation_id = ?')
|
|
.get(trip.id, res.body.reservation.id) as any;
|
|
expect(budgetItem).toBeDefined();
|
|
expect(budgetItem.total_price).toBe(250);
|
|
expect(budgetItem.name).toBe('Flight to Paris');
|
|
});
|
|
|
|
it('RESV-011b — POST with create_budget_entry.total_price = 0 skips budget creation', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
const res = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({
|
|
title: 'Free Entry',
|
|
type: 'activity',
|
|
create_budget_entry: { total_price: 0 },
|
|
});
|
|
expect(res.status).toBe(201);
|
|
|
|
const budgetItems = testDb
|
|
.prepare('SELECT * FROM budget_items WHERE trip_id = ?')
|
|
.all(trip.id) as any[];
|
|
expect(budgetItems).toHaveLength(0);
|
|
});
|
|
|
|
it('RESV-012 — PUT with create_budget_entry creates a new budget item when none exists', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const resv = createReservation(testDb, trip.id, { title: 'Hotel Stay', type: 'hotel' });
|
|
|
|
const res = await request(app)
|
|
.put(`/api/trips/${trip.id}/reservations/${resv.id}`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ create_budget_entry: { total_price: 300, category: 'Accommodation' } });
|
|
expect(res.status).toBe(200);
|
|
|
|
const budgetItem = testDb
|
|
.prepare('SELECT * FROM budget_items WHERE trip_id = ? AND reservation_id = ?')
|
|
.get(trip.id, resv.id) as any;
|
|
expect(budgetItem).toBeDefined();
|
|
expect(budgetItem.total_price).toBe(300);
|
|
});
|
|
|
|
it('RESV-013 — PUT with create_budget_entry updates existing linked budget item', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
// Create reservation with budget entry via POST
|
|
const createRes = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({
|
|
title: 'Car Rental',
|
|
type: 'transport',
|
|
create_budget_entry: { total_price: 100, category: 'Transport' },
|
|
});
|
|
expect(createRes.status).toBe(201);
|
|
const resvId = createRes.body.reservation.id;
|
|
|
|
// Update with a new price — should update the existing budget item
|
|
const updateRes = await request(app)
|
|
.put(`/api/trips/${trip.id}/reservations/${resvId}`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ create_budget_entry: { total_price: 150, category: 'Transport' } });
|
|
expect(updateRes.status).toBe(200);
|
|
|
|
const items = testDb
|
|
.prepare('SELECT * FROM budget_items WHERE trip_id = ? AND reservation_id = ?')
|
|
.all(trip.id, resvId) as any[];
|
|
expect(items).toHaveLength(1);
|
|
expect(items[0].total_price).toBe(150);
|
|
});
|
|
|
|
it('RESV-014 — PUT without create_budget_entry keeps the existing linked budget item', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
// Create with budget entry
|
|
const createRes = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({
|
|
title: 'Taxi',
|
|
type: 'transport',
|
|
create_budget_entry: { total_price: 50, category: 'Transport' },
|
|
});
|
|
expect(createRes.status).toBe(201);
|
|
const resvId = createRes.body.reservation.id;
|
|
|
|
const before = testDb
|
|
.prepare('SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?')
|
|
.get(trip.id, resvId);
|
|
expect(before).toBeDefined();
|
|
|
|
// Update WITHOUT create_budget_entry — the booking edit must NOT touch its
|
|
// linked expense (expenses are managed from the Costs section now).
|
|
const updateRes = await request(app)
|
|
.put(`/api/trips/${trip.id}/reservations/${resvId}`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'Taxi Updated' });
|
|
expect(updateRes.status).toBe(200);
|
|
|
|
const after = testDb
|
|
.prepare('SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?')
|
|
.get(trip.id, resvId);
|
|
expect(after).toBeDefined();
|
|
});
|
|
|
|
it('RESV-014b — PUT with create_budget_entry total_price 0 removes the linked budget item', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
const createRes = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({
|
|
title: 'Taxi',
|
|
type: 'transport',
|
|
create_budget_entry: { total_price: 50, category: 'Transport' },
|
|
});
|
|
expect(createRes.status).toBe(201);
|
|
const resvId = createRes.body.reservation.id;
|
|
|
|
// Explicit clear (total_price 0) still removes the linked item.
|
|
const updateRes = await request(app)
|
|
.put(`/api/trips/${trip.id}/reservations/${resvId}`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'Taxi', create_budget_entry: { total_price: 0 } });
|
|
expect(updateRes.status).toBe(200);
|
|
|
|
const after = testDb
|
|
.prepare('SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?')
|
|
.get(trip.id, resvId);
|
|
expect(after).toBeUndefined();
|
|
});
|
|
|
|
it('RESV-014c — changing the booking type updates the linked expense category', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
const createRes = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'Booking', type: 'other', create_budget_entry: { total_price: 50, category: 'other' } });
|
|
const resvId = createRes.body.reservation.id;
|
|
|
|
// Change the type other -> hotel (no create_budget_entry).
|
|
await request(app)
|
|
.put(`/api/trips/${trip.id}/reservations/${resvId}`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'Booking', type: 'hotel' });
|
|
|
|
const item = testDb
|
|
.prepare('SELECT category FROM budget_items WHERE trip_id = ? AND reservation_id = ?')
|
|
.get(trip.id, resvId) as { category: string };
|
|
expect(item.category).toBe('accommodation');
|
|
});
|
|
|
|
it('RESV-014d — a manually-picked expense category survives a booking type change', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
const createRes = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'Booking', type: 'other', create_budget_entry: { total_price: 50, category: 'other' } });
|
|
const resvId = createRes.body.reservation.id;
|
|
|
|
// Simulate a manual category pick in the Costs editor.
|
|
testDb.prepare('UPDATE budget_items SET category = ? WHERE trip_id = ? AND reservation_id = ?').run('fees', trip.id, resvId);
|
|
|
|
await request(app)
|
|
.put(`/api/trips/${trip.id}/reservations/${resvId}`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({ title: 'Booking', type: 'hotel' });
|
|
|
|
const item = testDb
|
|
.prepare('SELECT category FROM budget_items WHERE trip_id = ? AND reservation_id = ?')
|
|
.get(trip.id, resvId) as { category: string };
|
|
expect(item.category).toBe('fees');
|
|
});
|
|
});
|
|
|
|
describe('Reservation accommodation delete', () => {
|
|
it('RESV-009 — DELETE reservation linked to accommodation also removes the accommodation', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day1 = createDay(testDb, trip.id, { date: '2025-07-01' });
|
|
const day2 = createDay(testDb, trip.id, { date: '2025-07-03' });
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel Belle' });
|
|
|
|
// Create a reservation via API with create_accommodation as an object
|
|
const createRes = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({
|
|
title: 'Hotel Belle Stay',
|
|
type: 'hotel',
|
|
day_id: day1.id,
|
|
create_accommodation: {
|
|
place_id: place.id,
|
|
start_day_id: day1.id,
|
|
end_day_id: day2.id,
|
|
},
|
|
});
|
|
expect(createRes.status).toBe(201);
|
|
const reservationId = createRes.body.reservation.id;
|
|
|
|
// Verify accommodation was created
|
|
const accom = testDb.prepare(
|
|
'SELECT id FROM day_accommodations WHERE trip_id = ?'
|
|
).get(trip.id) as any;
|
|
expect(accom).toBeDefined();
|
|
|
|
// Delete reservation — should also remove the accommodation
|
|
const delRes = await request(app)
|
|
.delete(`/api/trips/${trip.id}/reservations/${reservationId}`)
|
|
.set('Cookie', authCookie(user.id));
|
|
expect(delRes.status).toBe(200);
|
|
|
|
const accomAfter = testDb.prepare(
|
|
'SELECT id FROM day_accommodations WHERE id = ?'
|
|
).get(accom.id);
|
|
expect(accomAfter).toBeUndefined();
|
|
});
|
|
|
|
it('RESV-009b — DELETE reservation linked to accommodation also removes its linked budget item (issue #933)', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day1 = createDay(testDb, trip.id, { date: '2025-08-01' });
|
|
const day2 = createDay(testDb, trip.id, { date: '2025-08-03' });
|
|
const place = createPlace(testDb, trip.id, { name: 'Seaside Resort' });
|
|
|
|
const createRes = await request(app)
|
|
.post(`/api/trips/${trip.id}/reservations`)
|
|
.set('Cookie', authCookie(user.id))
|
|
.send({
|
|
title: 'Seaside Resort Stay',
|
|
type: 'hotel',
|
|
day_id: day1.id,
|
|
create_accommodation: { place_id: place.id, start_day_id: day1.id, end_day_id: day2.id },
|
|
create_budget_entry: { total_price: 320, category: 'Accommodation' },
|
|
});
|
|
expect(createRes.status).toBe(201);
|
|
const reservationId = createRes.body.reservation.id;
|
|
|
|
const budgetBefore = testDb.prepare(
|
|
'SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?'
|
|
).get(trip.id, reservationId);
|
|
expect(budgetBefore).toBeDefined();
|
|
|
|
// Delete via the reservation endpoint
|
|
const delRes = await request(app)
|
|
.delete(`/api/trips/${trip.id}/reservations/${reservationId}`)
|
|
.set('Cookie', authCookie(user.id));
|
|
expect(delRes.status).toBe(200);
|
|
|
|
const budgetAfter = testDb.prepare(
|
|
'SELECT id FROM budget_items WHERE trip_id = ?'
|
|
).get(trip.id);
|
|
expect(budgetAfter).toBeUndefined();
|
|
});
|
|
});
|