mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-18 21:16:47 +00:00
9dd0a851ca
* fix(mcp): accept per-leg times on create_transport and update_transport metadata was pinned to Record<string, string>, so a legs array could not get through and a multi-leg flight built over MCP lost every intermediate time. The booking ended up with correct endpoints and no legs, which every reader then treats as a single segment. legs is now a real, typed parameter with its contract in @trek/shared, shaped exactly the way the planner form and the importers write metadata.legs. The folding checks what the readers depend on: one leg fewer than endpoints (the AirTrail dedupe builds its signatures on that), day ids that belong to the trip, airport codes that agree with their endpoint, and the times, where a stopover endpoint carries the departure and the last one the arrival. metadata keeps its type and its replace semantics. Segments smuggled through metadata.legs as a JSON string used to be stored and then ignored by everything that read them; they are refused now and point at the legs parameter instead. Closes #1914 * fix(atlas): refuse a bucket list entry that is already on the list Nothing gave a bucket entry an identity, so the same country could be added as often as it was clicked. A wish is now identified by name, country, target date and, where it has them, coordinates. A different target date is a different wish and still lands, which is what the report asked for; two real places sharing a name stay separate because their coordinates differ. Empty string and NULL are normalised on both sides of the comparison, otherwise the dateless case, which is the one that was reported, would slip through. Deliberately no unique index and no migration. better-sqlite3 is synchronous and the server is a single process, so the race an index would guard against cannot happen here, and an index would have needed a destructive dedupe of existing rows first. create_bucket_list_item had no target_date parameter at all, so over MCP the allowed "same place, other date" case was unreachable. It takes one now. The plugin RPC reports the duplicate as bad params instead of letting it surface as an internal error. Closes #1898 * fix(settings): keep a free-form LLM endpoint in admin hands Any account could name the address the server calls, and the guard in front of it deliberately allows loopback and LAN so a self-hosted Ollama works. That is a reasonable trade for whoever runs the instance, because the network is theirs. It is not one for an arbitrary account, which could aim a request from inside that network at a target only it chose and read how the target answered. A free base URL, and the local provider that is one by another name, now come only from an admin controlled source: the addon config, the instance-wide defaults, or an admin's own settings. OpenAI and Anthropic stay available to everyone, because they go to a fixed address with the user's own key. The resolver is where this is enforced, since it is the single point both the booking import and the plugin host pass through, and the only one that also covers values already sitting in the database. The write path refuses as well, so nothing is stored that would never be read. The hint text promised something users no longer have, so it changed with it. Closes #1772 * fix(calendar): span a date-only booking to its end date A DATE event without DTEND is exactly one day per RFC 5545, so a multi-day booking that carries an end date still collapsed onto its first day. It gets an exclusive DTEND now, built the same way the stay branch already builds one. A booking without an end date serialises byte for byte as before. While in here: the stays query joins reservations on the accommodation, and two bookings pointed at the same stay fanned it out into two events sharing one UID. Duplicate UIDs in a feed are undefined behaviour and calendar clients pick one at random. The same "at most one booking per stay" assumption sat in the accommodations service, where it was worse than cosmetic: accommodation_id carries no foreign key, so deleting a stay took only the first booking and left the second pointing at something that no longer existed. Both the sync and the delete walk all of them now. The callers keep reading linkedReservationId; the list is additional. Refs #1869 * fix(vacay): say that the region is required, because it is The placeholder called the region optional while the add button stayed disabled until one was picked. The wording predates multiple calendars per plan, which is what introduced the gate. Only the value of the existing key changed, in all locales, so the key set stays identical. Two things the same screen got wrong were in the way of a clean answer: The button was clickable while the region list was still loading, which put the user in exactly the state the wording describes, and it is the state the report was filed from. It waits for the list now. Changing the country on an existing calendar kept the previous country's regions on screen, so a German region could be picked for the Netherlands. The list is cleared with the country, which only works in combination with the loading gate: without it, the empty list would happen to enable the button instead. Closes #1813 * fix(collections): let a saved place's address be corrected The edit form offered name, category and labels, and the address only on the way in. The cause was not the form: the update contract never declared address, so the validation pipe stripped it and the UPDATE had no column for it. Coordinates were pulled through for #1435 and the address was missed. It travels the whole chain now, contract to service to both forms. No migration, the column has always been there. The mobile add sheet had no address input at all, showing whatever the search result carried as read-only, so editing would have worked while creating still would not. It has one. The MCP tool description had drifted further than the address, never having mentioned the coordinates either. Both are in it now. Closes #1870 * fix(collections): keep the place search usable after the first save The add dialog stays open on purpose so several places can be added in a row, but after a save it gave no way back into the search. A search with no results was silent, with no empty state and no toast, so typing another name and pressing enter looked like nothing happened. The reporter described both halves and it is the silent search that matches "nothing happens" most closely. There is an empty state now, using a key that already existed in every locale and was unused. The search row is sticky inside the dialog body, so it stays reachable after the save instead of sitting above the scroll position. Also fixed while in here: refreshing the collection after each add reset the select mode, the selection and the label filter. In the very flow this dialog is built for, the user quietly lost all three. Closes #1921 * fix(vacay): make the phone year grid and the dock button do what they look like Two separate faults met on this screen. Tapping a day in the year grid did nothing unless the edit mode was already on, and the only way into it was a floating button that looks exactly like the one the dock draws in the same spot. A tap now opens that month in the editor, where the cells are big enough to hit. At 390px the grid cells are around 21px, which is too small to be mutating data with in the first place. The dock's plus was not wired for this route, so it fell through to creating a trip on the dashboard. Two different actions were stacked in one place, and the wrong one was on top whenever the screen had not painted yet, which includes the time its chunk is still loading. The dock leaves the slot to the screen now, and holds the geometry so the tab groups stay symmetric. Closes #1811 * fix(budget): settle in whole cents so balances stop drifting The report is a balance that moves on its own, with nothing added, edited or removed, on a trip where everything is in euro. Two mechanisms were behind it and both are real. The display currency is a fourth value, a per-user setting, so "everything is in euro" never covered it. Each balance was converted and rounded on its own, and the set no longer summed to zero: at 0.855 and 0.9312 it came out one cent over, at 0.94 it came out even. That cent appears and disappears with the six hour rate cache alone, which is exactly the symptom. The flows were rounded separately from the balances, so the two never had to agree. And a receipt line nobody was ticked for counted toward the total, and therefore toward the payer's credit, while landing in no share. That difference is permanent, and the client sent it that way. The settlement converts once, at the edge, and does integer arithmetic after that. Equal splits distribute the credited cents by largest remainder rather than the entered total, so credits and debits of one expense cancel exactly even in a foreign currency. Display conversion goes through the same largest-remainder allocation, so the sum survives it. With that, the 0.01 epsilon can go. It could never create a cent, but it stranded them: a one cent balance was filtered out of the flows while staying visible in the list, which is the "settle up offers nothing" half of the report. Closes #1382 * fix(journey): reach the book export and the suggestion toggle on a phone Below 1024px the hero card is dropped, and it held the only way to either action. The floating bar that replaces it was never given them. It has them now, and the hero is unmounted rather than hidden, so there is no second invisible copy of the same controls in the document. The bar's own buttons moved onto the appearance tokens while they were being touched. The phone screen never had either action at all and now carries both. The book itself was hardwired to English, cover and dates included, while the keys for it had been sitting in every locale unused. It takes the page's translator and locale, sets the document language, and prints mood and weather, which were on screen but never in the book. Closes #1848 * fix(journey): offer the connected photo providers in the phone entry editor The desktop editor grew an external photo source in #1632; the phone editor that came out of the mobile rewrite never did, so editing an entry on a phone had no way to Immich or Synology. It mirrors the desktop mechanics, including the part that is easy to miss: a save that creates the entry and then fails on the photos keeps the sheet open, and without remembering what was just created the retry creates a second entry. The sheet no longer kicks off its own addon load. The list is loaded once on boot and this only reacts to it; a second load races the other consumers and overwrites the store when it lands. Closes #1808 * fix(mobile): let the document scroll so Safari can collapse its URL bar iOS Safari only shrinks its address bar when the document scrolls, and TREK's never did: the root was locked and the mobile shell put a scroll container inside it. On the bottom tab layout that costs about a sixth of the viewport, permanently. Below 768px the document is the scroller again and the full-bleed screens measure their own height instead of leaning on the shell. That makes the body scroll locks real for the first time on a phone, and they were not ready for it. Three of them reset the overflow unconditionally, one of those on every run of its effect rather than on unmount, so a system notice could hand the page back while a sheet was still open. They all go through one reference counted lock now, which is the part that had to land first. Worth knowing for the issue: this reaches the flow screens. The trip planner, the journal, the atlas and the vacay screen keep their own full-height scrollers and still will not collapse the bar. Closes #1809 * fix(mobile): keep the screen gradient visible behind the translucent cards The gradient layer introduced with the scroll change sat at z-index -10. A negative layer paints above the canvas but below the backgrounds of ordinary blocks, and body carries an opaque one, so the gradient was hidden behind it. The mobile cards are translucent and take their depth from what is behind them, so every surface ended up compositing against a single flat colour and the whole phone UI read as one tone. The layer is positioned at z-index 0 now and the content above it at 10, which puts both over body's background. Same visual as before the scroll change, and the shell still owns no scroll container. * test(reservations): teach the accommodation delete stub about the id lists The RPC walks every linked booking since the delete stopped stopping at the first one. The stub still answered with the two singular fields, so the loop had nothing to iterate and the cascade events never fired. * fix(settings): move the free-form LLM endpoint out of user settings entirely Hiding it from non-admins closed the hole, but it left the option sitting in the admin's own personal settings, which is not what was asked for and not where it belongs: an instance has exactly one address it calls out to, and there was a second, invisible place to set it. The provider list is now the two hosted ones for everybody, the endpoint field is gone, and the resolver takes the address from the admin-controlled instance defaults for every caller including an admin. It no longer reads the users table at all. The write path refuses the keys for everyone, so nothing can be stored that would never be read. The endpoint is configured on the addon in the admin settings, which already carries provider, model, base URL and key, plus the Ollama model list. Nothing is lost, it just has one home now. Behaviour change worth a release note: an admin who set a personal Ollama endpoint has to move it to the addon config. A non-admin was already in that position after the previous commit. Refs #1772 * fix(journey): make the book preview usable on a phone The preview document carried no viewport, so a phone laid it out at its default 980px while the page is A4 landscape and about 1123px wide. It spilled out of the frame, which reads as being zoomed far in. Declaring the real width lets the browser scale the page to fit. Printing is unaffected, it goes by @page. The preview chrome had the same problem in miniature: a title and two labels on one row, sized inline, which does not fit a phone and fits translated labels even less. It moved to a stylesheet, and below 640px the card goes full-bleed, the decorative title steps aside and the two actions share the width. Refs #1848 * fix(mobile): stop the shell trapping the screens' own overlays Lifting the background layer into the positioned range meant the content wrapper had to be positioned too, and a positioned wrapper with a z-index is a stacking context. Every fixed overlay a screen renders inside it got clamped to that level: the vacay view/edit FAB sits at z-50 precisely so it beats the dock at z-40, and it disappeared behind it. The layer goes back to a negative z-index and the wrapper back to no positioning at all. What it needed in the first place was for body to stop painting over it, which is one line in the phone media block rather than a new stacking context. * fix(mobile): let the phone background override actually win A media query adds no specificity, so the themed body rule further down the file kept winning on source order and painted over the shell's background layer. The override is on html body now. The gradient was back to being invisible, which is the flat single-tone phone UI again. * fix(vacay): draw today's ring around the day instead of replacing it On the phone, today short-circuited the day-cell matrix and returned a ring on an empty cell. A vacation day or a company holiday logged for today was stored and counted in the totals, but the cell showed nothing, so it read as if the tap had not taken. Today is an annotation now, layered like the school band and the shared-calendar rings, which is how the desktop month card has always treated it. The strong ink stays only where the cell has no fill of its own, since --m-ink is light in dark mode and would disappear on a pastel. * fix(map): stop serving a stale GL style document from the service worker The Workbox rule for Mapbox matched every URL under api.mapbox.com, and the style document lives there too. Under StaleWhileRevalidate the map was built from the previous revision on every load, with the refresh landing one load too late, so a style republished in Studio with different label languages kept rendering the old ones. The network tab showed a 200 throughout, because the service worker's own answer is a real 200, which is why this looked like the app rewriting text-field at runtime. The style now has its own rule ahead of the tile rules, on NetworkFirst so it is current whenever the network is, and still cached so the map opens offline. Its own small cache too: sharing an LRU with three thousand tiles made the staleness come and go at random. OpenFreeMap styles had the same problem and are covered by the same rule. Closes #1924
600 lines
28 KiB
TypeScript
600 lines
28 KiB
TypeScript
/**
|
|
* Unit tests for AccommodationsService. DAY-SVC-016..026, 029 and 035 moved here
|
|
* 1:1 with the SQL they cover when accommodations became their own domain; the
|
|
* case ids are unchanged so the diff reads as a move. Real in-memory SQLite.
|
|
*/
|
|
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
|
|
|
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');
|
|
return {
|
|
testDb: db,
|
|
dbMock: {
|
|
db,
|
|
closeDb: () => {},
|
|
reinitialize: () => {},
|
|
getPlaceWithTags: () => null,
|
|
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),
|
|
},
|
|
};
|
|
});
|
|
|
|
vi.mock('../../../src/db/database', () => dbMock);
|
|
const { broadcast } = vi.hoisted(() => ({ broadcast: vi.fn() }));
|
|
vi.mock('../../../src/websocket', () => ({ broadcast }));
|
|
|
|
import { createTables } from '../../../src/db/schema';
|
|
import { runMigrations } from '../../../src/db/migrations';
|
|
import { resetTestDb } from '../../helpers/test-db';
|
|
import { createUser, createTrip, createDay, createPlace, createDayAccommodation, addTripMember } from '../../helpers/factories';
|
|
import { DatabaseService } from '../../../src/nest/database/database.service';
|
|
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
|
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
|
|
import { AccommodationsService } from '../../../src/nest/accommodations/accommodations.service';
|
|
import { AccommodationsModule } from '../../../src/nest/accommodations/accommodations.module';
|
|
import { AccommodationsController } from '../../../src/nest/accommodations/accommodations.controller';
|
|
import { expectRegisteredProvider, expectRegisteredController } from '../../helpers/module-providers';
|
|
|
|
// Named `svc` so the moved cases read exactly as they did on DaysService.
|
|
const svc = new AccommodationsService(
|
|
new DatabaseService(testDb),
|
|
new PermissionsService(new DatabaseService(testDb)),
|
|
new RealtimeService(),
|
|
);
|
|
|
|
beforeAll(() => {
|
|
createTables(testDb);
|
|
runMigrations(testDb);
|
|
});
|
|
|
|
beforeEach(() => {
|
|
resetTestDb(testDb);
|
|
});
|
|
|
|
afterAll(() => {
|
|
testDb.close();
|
|
});
|
|
|
|
describe('validateAccommodationRefs', () => {
|
|
it('DAY-SVC-016 — returns no errors when all refs are valid', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const errors = svc.validateAccommodationRefs(trip.id, place.id, day.id, day.id);
|
|
expect(errors).toHaveLength(0);
|
|
});
|
|
|
|
it('DAY-SVC-017 — returns error when place does not exist in trip', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const errors = svc.validateAccommodationRefs(trip.id, 99999, day.id, day.id);
|
|
expect(errors.some((e: any) => e.field === 'place_id')).toBe(true);
|
|
});
|
|
|
|
it('DAY-SVC-018 — returns error when start_day_id is invalid', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const errors = svc.validateAccommodationRefs(trip.id, place.id, 99999, day.id);
|
|
expect(errors.some((e: any) => e.field === 'start_day_id')).toBe(true);
|
|
});
|
|
|
|
it('ACC-003 — reports every bad ref, end_day_id included', () => {
|
|
// The controller only surfaces errors[0], so an unchecked end_day_id would let a
|
|
// stay point at a day from another trip and never be reported.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const errors = svc.validateAccommodationRefs(trip.id, 99999, 99998, 99997);
|
|
expect(errors.map((e: any) => e.field)).toEqual(['place_id', 'start_day_id', 'end_day_id']);
|
|
});
|
|
|
|
it('ACC-004 — skips the refs the caller left undefined', () => {
|
|
// The plugin update path (accommodations.rpc) passes only the fields it changes.
|
|
// If an absent ref were validated, every partial update would 403 "Place not found".
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
expect(svc.validateAccommodationRefs(trip.id)).toHaveLength(0);
|
|
expect(svc.validateAccommodationRefs(trip.id, undefined, undefined, undefined)).toHaveLength(0);
|
|
});
|
|
});
|
|
|
|
describe('createAccommodation', () => {
|
|
it('DAY-SVC-019 — creates accommodation and returns it with place info', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Grand Hotel' }) as any;
|
|
|
|
const accom = svc.createAccommodation(trip.id, {
|
|
place_id: place.id,
|
|
start_day_id: day.id,
|
|
end_day_id: day.id,
|
|
check_in: '15:00',
|
|
check_out: '11:00',
|
|
}) as any;
|
|
|
|
expect(accom).toBeDefined();
|
|
expect(accom.place_name).toBe('Grand Hotel');
|
|
});
|
|
|
|
it('DAY-SVC-020 — auto-creates a linked reservation', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'City Hotel' }) as any;
|
|
|
|
const accom = svc.createAccommodation(trip.id, {
|
|
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
|
|
}) as any;
|
|
|
|
const reservation = testDb.prepare('SELECT * FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
|
|
expect(reservation).toBeDefined();
|
|
expect(reservation.type).toBe('hotel');
|
|
expect(reservation.status).toBe('confirmed');
|
|
});
|
|
|
|
it('ACC-005 — titles the partner reservation "Hotel" when the stay has no place', () => {
|
|
// day_accommodations.place_id is nullable (ON DELETE SET NULL) while
|
|
// reservations.title is NOT NULL: without the fallback the reservation insert
|
|
// fails and takes the whole transaction — and the stay — down with it.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
|
|
const accom = svc.createAccommodation(trip.id, {
|
|
place_id: null as unknown as number, start_day_id: day.id, end_day_id: day.id,
|
|
}) as any;
|
|
|
|
expect(accom.place_name).toBeNull();
|
|
const reservation = testDb.prepare('SELECT title FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
|
|
expect(reservation.title).toBe('Hotel');
|
|
});
|
|
});
|
|
|
|
describe('getAccommodation', () => {
|
|
it('DAY-SVC-021 — returns accommodation for valid id and trip', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const accom = createDayAccommodation(testDb, trip.id, place.id, day.id, day.id) as any;
|
|
const found = svc.getAccommodation(accom.id, trip.id) as any;
|
|
expect(found).toBeDefined();
|
|
expect(found.id).toBe(accom.id);
|
|
});
|
|
|
|
it('DAY-SVC-022 — returns undefined for non-existent accommodation', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
expect(svc.getAccommodation(99999, trip.id)).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe('updateAccommodation', () => {
|
|
it('DAY-SVC-023 — updates check-in and check-out times', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const accom = svc.createAccommodation(trip.id, {
|
|
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
|
|
}) as any;
|
|
|
|
const existing = svc.getAccommodation(accom.id, trip.id)!;
|
|
const updated = svc.updateAccommodation(accom.id, existing as any, { check_in: '16:00', check_out: '12:00' }) as any;
|
|
expect(updated).toBeDefined();
|
|
|
|
// Verify linked reservation metadata was synced
|
|
const reservation = testDb.prepare('SELECT * FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
|
|
expect(reservation).toBeDefined();
|
|
const meta = JSON.parse(reservation.metadata || '{}');
|
|
expect(meta.check_in_time).toBe('16:00');
|
|
expect(meta.check_out_time).toBe('12:00');
|
|
});
|
|
|
|
it('DAY-SVC-024 — preserves existing fields when not updated', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const accom = svc.createAccommodation(trip.id, {
|
|
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
|
|
confirmation: 'ABC123',
|
|
}) as any;
|
|
|
|
const existing = svc.getAccommodation(accom.id, trip.id)!;
|
|
svc.updateAccommodation(accom.id, existing as any, { check_in: '14:00' });
|
|
|
|
const row = svc.getAccommodation(accom.id, trip.id) as any;
|
|
expect(row.confirmation).toBe('ABC123');
|
|
});
|
|
|
|
it('ACC-006 — updates a stay that has no linked reservation', () => {
|
|
// Stays imported before the auto-reservation existed have no partner row. The sync
|
|
// block must be skipped for them, not throw on a missing reservation.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
// The factory writes the stay row directly, without the partner reservation.
|
|
const accom = createDayAccommodation(testDb, trip.id, place.id, day.id, day.id) as any;
|
|
|
|
const existing = svc.getAccommodation(accom.id, trip.id)!;
|
|
const updated = svc.updateAccommodation(accom.id, existing as any, { check_in: '15:00' }) as any;
|
|
|
|
expect(updated.check_in).toBe('15:00');
|
|
expect(testDb.prepare('SELECT COUNT(*) as n FROM reservations WHERE accommodation_id = ?').get(accom.id)).toMatchObject({ n: 0 });
|
|
});
|
|
|
|
it('ACC-007 — merges into the reservation metadata instead of replacing it', () => {
|
|
// The stay is created with a check-in, so the reservation already carries metadata.
|
|
// An update that only moves the check-out must parse and extend that object —
|
|
// writing a fresh one would silently drop the check-in window.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const accom = svc.createAccommodation(trip.id, {
|
|
place_id: place.id, start_day_id: day.id, end_day_id: day.id, check_in: '15:00',
|
|
}) as any;
|
|
|
|
const existing = svc.getAccommodation(accom.id, trip.id)!;
|
|
svc.updateAccommodation(accom.id, existing as any, { check_in_end: '20:00', check_out: '11:00' });
|
|
|
|
const reservation = testDb.prepare('SELECT metadata FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
|
|
expect(JSON.parse(reservation.metadata)).toEqual({
|
|
check_in_time: '15:00', check_in_end_time: '20:00', check_out_time: '11:00',
|
|
});
|
|
});
|
|
|
|
it('ACC-008 — leaves the reservation confirmation number alone when the stay has none', () => {
|
|
// COALESCE(?, confirmation_number): a stay without a confirmation must not null out
|
|
// a number that was typed on the reservation itself.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const accom = svc.createAccommodation(trip.id, {
|
|
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
|
|
}) as any;
|
|
testDb.prepare('UPDATE reservations SET confirmation_number = ? WHERE accommodation_id = ?').run('RES-9', accom.id);
|
|
|
|
const existing = svc.getAccommodation(accom.id, trip.id)!;
|
|
svc.updateAccommodation(accom.id, existing as any, { check_in: '15:00' });
|
|
|
|
const reservation = testDb.prepare('SELECT confirmation_number FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
|
|
expect(reservation.confirmation_number).toBe('RES-9');
|
|
});
|
|
});
|
|
|
|
describe('deleteAccommodation', () => {
|
|
it('DAY-SVC-025 — deletes accommodation and its linked reservation', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const accom = svc.createAccommodation(trip.id, {
|
|
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
|
|
}) as any;
|
|
|
|
const reservation = testDb.prepare('SELECT id FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
|
|
|
|
const result = svc.deleteAccommodation(accom.id);
|
|
expect(result.linkedReservationId).toBe(reservation.id);
|
|
|
|
// Accommodation is gone
|
|
expect(svc.getAccommodation(accom.id, trip.id)).toBeUndefined();
|
|
|
|
// Reservation is gone
|
|
const deletedRes = testDb.prepare('SELECT id FROM reservations WHERE id = ?').get(reservation.id);
|
|
expect(deletedRes).toBeUndefined();
|
|
});
|
|
|
|
it('DAY-SVC-026 — returns null linkedReservationId when no reservation was linked', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const accom = createDayAccommodation(testDb, trip.id, place.id, day.id, day.id) as any;
|
|
|
|
// Remove the auto-created reservation so there's no linked one
|
|
testDb.prepare('DELETE FROM reservations WHERE accommodation_id = ?').run(accom.id);
|
|
|
|
const result = svc.deleteAccommodation(accom.id);
|
|
expect(result.linkedReservationId).toBeNull();
|
|
});
|
|
|
|
it('ACC-009 — also deletes the budget item that hangs off the linked reservation', () => {
|
|
// The cost row references the reservation, not the stay, so the delete has to
|
|
// cascade twice. Skipping the second hop strands a budget line whose reservation
|
|
// is gone, and the costs view can no longer reach it to remove it.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const accom = svc.createAccommodation(trip.id, {
|
|
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
|
|
}) as any;
|
|
|
|
const reservation = testDb.prepare('SELECT id FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
|
|
const budgetItemId = testDb.prepare(
|
|
'INSERT INTO budget_items (trip_id, name, category, total_price, reservation_id) VALUES (?, ?, ?, ?, ?)'
|
|
).run(trip.id, 'Hotel stay', 'Accommodation', 240, reservation.id).lastInsertRowid as number;
|
|
|
|
const result = svc.deleteAccommodation(accom.id);
|
|
|
|
expect(result).toEqual({
|
|
linkedReservationId: reservation.id,
|
|
deletedBudgetItemId: budgetItemId,
|
|
linkedReservationIds: [reservation.id],
|
|
deletedBudgetItemIds: [budgetItemId],
|
|
});
|
|
expect(testDb.prepare('SELECT id FROM budget_items WHERE id = ?').get(budgetItemId)).toBeUndefined();
|
|
});
|
|
|
|
it('ACC-010 — a second booking pointed at the same stay goes too, instead of being orphaned', () => {
|
|
// reservations.accommodation_id carries no foreign key and no unique constraint,
|
|
// and the booking form lets a hotel booking pick an existing stay. Deleting only
|
|
// the first left the second behind, referencing a stay that no longer exists.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const accom = svc.createAccommodation(trip.id, {
|
|
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
|
|
}) as any;
|
|
|
|
const first = testDb.prepare('SELECT id FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
|
|
const second = testDb.prepare(
|
|
'INSERT INTO reservations (trip_id, type, title, accommodation_id) VALUES (?, ?, ?, ?)'
|
|
).run(trip.id, 'hotel', 'Second booking', accom.id).lastInsertRowid as number;
|
|
|
|
const result = svc.deleteAccommodation(accom.id);
|
|
|
|
expect(result.linkedReservationIds).toEqual([first.id, second]);
|
|
expect(result.linkedReservationId).toBe(first.id);
|
|
expect(testDb.prepare('SELECT COUNT(*) as n FROM reservations WHERE accommodation_id = ?').get(accom.id)).toMatchObject({ n: 0 });
|
|
});
|
|
|
|
it('ACC-011 — updating the stay syncs the times onto every linked booking', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const accom = svc.createAccommodation(trip.id, {
|
|
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
|
|
}) as any;
|
|
testDb.prepare(
|
|
'INSERT INTO reservations (trip_id, type, title, accommodation_id) VALUES (?, ?, ?, ?)'
|
|
).run(trip.id, 'hotel', 'Second booking', accom.id);
|
|
|
|
const existing = testDb.prepare('SELECT * FROM day_accommodations WHERE id = ?').get(accom.id) as any;
|
|
svc.updateAccommodation(accom.id, existing, { check_in: '15:00', check_out: '11:00' });
|
|
|
|
const rows = testDb.prepare('SELECT metadata FROM reservations WHERE accommodation_id = ?').all(accom.id) as Array<{ metadata: string | null }>;
|
|
expect(rows).toHaveLength(2);
|
|
for (const row of rows) {
|
|
expect(JSON.parse(row.metadata || '{}')).toMatchObject({ check_in_time: '15:00', check_out_time: '11:00' });
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('listAccommodations', () => {
|
|
it('DAY-SVC-029 — listAccommodations returns the hydrated stays', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id);
|
|
const place = createPlace(testDb, trip.id, { name: 'Ryokan' });
|
|
createDayAccommodation(testDb, trip.id, place.id, day.id, day.id);
|
|
const rows = svc.listAccommodations(trip.id) as { place_name: string }[];
|
|
expect(rows).toHaveLength(1);
|
|
expect(rows[0].place_name).toBe('Ryokan');
|
|
});
|
|
});
|
|
|
|
describe('quirk fixes', () => {
|
|
it('DAY-SVC-035 — deleteAccommodation is atomic: a failed stay delete keeps the linked reservation', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id);
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' });
|
|
const accom = svc.createAccommodation(trip.id, {
|
|
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
|
|
}) as { id: number };
|
|
testDb.exec("CREATE TRIGGER boom BEFORE DELETE ON day_accommodations BEGIN SELECT RAISE(ABORT, 'boom'); END");
|
|
try {
|
|
expect(() => svc.deleteAccommodation(accom.id)).toThrow();
|
|
// The earlier reservation delete inside the transaction rolled back.
|
|
expect(testDb.prepare('SELECT COUNT(*) as n FROM reservations WHERE accommodation_id = ?').get(accom.id)).toMatchObject({ n: 1 });
|
|
} finally {
|
|
testDb.exec('DROP TRIGGER boom');
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('route-facing delegators', () => {
|
|
// list/validateRefs/get/create/update/remove are what the controller, the plugin RPC
|
|
// and trip-read-model call; the MCP tools call the long names. Both sets have to land
|
|
// on the same SQL, and the short ones get raw route params — strings where the long
|
|
// ones get numbers.
|
|
|
|
it('ACC-010 — list() returns what listAccommodations() returns, for a string and a number trip id', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Pension Alpen' }) as any;
|
|
createDayAccommodation(testDb, trip.id, place.id, day.id, day.id);
|
|
|
|
expect(svc.list(String(trip.id))).toEqual(svc.listAccommodations(trip.id));
|
|
expect((svc.list(trip.id) as any[])[0].place_name).toBe('Pension Alpen');
|
|
});
|
|
|
|
it('ACC-011 — validateRefs() returns the same errors validateAccommodationRefs() does', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
|
|
expect(svc.validateRefs(trip.id, place.id, day.id, day.id)).toHaveLength(0);
|
|
// The controller 404s with errors[0].message, so the shape matters, not just the count.
|
|
expect(svc.validateRefs(trip.id, 99999, day.id, day.id)).toEqual([{ field: 'place_id', message: 'Place not found' }]);
|
|
});
|
|
|
|
it('ACC-012 — create() writes the stay, get() reads it back trip-scoped', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const otherTrip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
|
|
// Both ids arrive from the route as strings.
|
|
const created = svc.create(String(trip.id), {
|
|
place_id: place.id, start_day_id: day.id, end_day_id: day.id, confirmation: 'XY-1',
|
|
}) as any;
|
|
|
|
expect(svc.get(String(created.id), String(trip.id))).toMatchObject({ id: created.id, confirmation: 'XY-1' });
|
|
// Trip-scoped: a stay must not be readable through another trip's URL.
|
|
expect(svc.get(created.id, otherTrip.id)).toBeUndefined();
|
|
});
|
|
|
|
it('ACC-013 — update() syncs the partner reservation even when the id is a string', () => {
|
|
// updateAccommodation looks the reservation up with Number(id); if that coercion
|
|
// regresses, the REST path silently stops syncing check-in times.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const accom = svc.create(trip.id, { place_id: place.id, start_day_id: day.id, end_day_id: day.id }) as any;
|
|
|
|
const existing = svc.get(accom.id, trip.id)!;
|
|
const updated = svc.update(String(accom.id), existing as any, { check_in: '16:00', notes: 'late arrival' }) as any;
|
|
|
|
expect(updated).toMatchObject({ check_in: '16:00', notes: 'late arrival' });
|
|
const reservation = testDb.prepare('SELECT metadata FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
|
|
expect(JSON.parse(reservation.metadata).check_in_time).toBe('16:00');
|
|
});
|
|
|
|
it('ACC-014 — remove() reports the partner reservation it took with it', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const day = createDay(testDb, trip.id) as any;
|
|
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
|
|
const accom = svc.create(trip.id, { place_id: place.id, start_day_id: day.id, end_day_id: day.id }) as any;
|
|
const reservation = testDb.prepare('SELECT id FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
|
|
|
|
// The controller broadcasts reservation:deleted off this return value.
|
|
expect(svc.remove(String(accom.id))).toEqual({
|
|
linkedReservationId: reservation.id,
|
|
deletedBudgetItemId: null,
|
|
linkedReservationIds: [reservation.id],
|
|
deletedBudgetItemIds: [],
|
|
});
|
|
expect(svc.get(accom.id, trip.id)).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe('trip access and edit permission', () => {
|
|
it('ACC-015 — verifyTripAccess resolves the trip from a string id and from a number', () => {
|
|
// The REST path hands over the raw :tripId param, the MCP tools the parsed number.
|
|
// Without the Number() coercion one of the two callers stops finding its trip.
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
|
|
expect(svc.verifyTripAccess(String(trip.id), user.id)).toMatchObject({ id: trip.id, user_id: user.id });
|
|
expect(svc.verifyTripAccess(trip.id, user.id)).toMatchObject({ id: trip.id, user_id: user.id });
|
|
});
|
|
|
|
it('ACC-016 — verifyTripAccess returns nothing for a user who is neither owner nor member', () => {
|
|
const { user: owner } = createUser(testDb);
|
|
const { user: stranger } = createUser(testDb);
|
|
const trip = createTrip(testDb, owner.id);
|
|
|
|
expect(svc.verifyTripAccess(trip.id, stranger.id)).toBeUndefined();
|
|
});
|
|
|
|
it('ACC-017 — canEdit lets the owner through on the default day_edit level', () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const access = svc.verifyTripAccess(trip.id, user.id)!;
|
|
|
|
expect(svc.canEdit(access, user as any)).toBe(true);
|
|
});
|
|
|
|
it('ACC-018 — canEdit lets a member through: it derives isMember from the trip owner id', () => {
|
|
// day_edit defaults to trip_member. canEdit passes `trip.user_id !== user.id` as the
|
|
// isMember flag, so inverting that comparison would lock every invited traveller out
|
|
// of the day plan while the owner still edits fine.
|
|
const { user: owner } = createUser(testDb);
|
|
const { user: member } = createUser(testDb);
|
|
const trip = createTrip(testDb, owner.id);
|
|
addTripMember(testDb, trip.id, member.id);
|
|
const access = svc.verifyTripAccess(trip.id, member.id)!;
|
|
|
|
expect(svc.canEdit(access, member as any)).toBe(true);
|
|
});
|
|
|
|
it('ACC-019 — canEdit denies a member once day_edit is raised to trip_owner', () => {
|
|
const { user: owner } = createUser(testDb);
|
|
const { user: member } = createUser(testDb);
|
|
const trip = createTrip(testDb, owner.id);
|
|
addTripMember(testDb, trip.id, member.id);
|
|
const permissions = new PermissionsService(new DatabaseService(testDb));
|
|
|
|
try {
|
|
permissions.savePermissions({ day_edit: 'trip_owner' });
|
|
expect(svc.canEdit(svc.verifyTripAccess(trip.id, member.id)!, member as any)).toBe(false);
|
|
// The owner keeps the right, otherwise the setting would lock out the whole trip.
|
|
expect(svc.canEdit(svc.verifyTripAccess(trip.id, owner.id)!, owner as any)).toBe(true);
|
|
} finally {
|
|
// The permission cache is module-scoped and outlives resetTestDb — drop the row and
|
|
// the cache together, or every later case in this file inherits the raised level.
|
|
testDb.prepare("DELETE FROM app_settings WHERE key = 'perm_day_edit'").run();
|
|
permissions.invalidatePermissionsCache();
|
|
}
|
|
});
|
|
|
|
it('ACC-020 — broadcast forwards the socket id so the originating client is not echoed', () => {
|
|
// The X-Socket-Id contract: the facade must pass the id straight through as the
|
|
// fourth argument. Dropping it makes the sender apply its own change twice.
|
|
broadcast.mockClear();
|
|
|
|
svc.broadcast('5', 'accommodation:deleted', { accommodationId: 9 }, 'sock-1');
|
|
expect(broadcast).toHaveBeenCalledWith('5', 'accommodation:deleted', { accommodationId: 9 }, 'sock-1');
|
|
|
|
svc.broadcast('5', 'accommodation:updated', { accommodation: { id: 9 } }, undefined);
|
|
expect(broadcast).toHaveBeenLastCalledWith('5', 'accommodation:updated', { accommodation: { id: 9 } }, undefined);
|
|
});
|
|
});
|
|
|
|
describe('AccommodationsService wiring', () => {
|
|
it('ACC-001: the module carries the controller, the service and the RPC surface', () => {
|
|
expectRegisteredController(AccommodationsModule, AccommodationsController);
|
|
expectRegisteredProvider(AccommodationsModule, AccommodationsService);
|
|
const exports = Reflect.getMetadata('exports', AccommodationsModule) as unknown[];
|
|
expect(Array.isArray(exports)).toBe(true);
|
|
expect(exports).toEqual(expect.arrayContaining([AccommodationsService]));
|
|
});
|
|
|
|
it('ACC-002: it does not import the days or reservations modules', () => {
|
|
const imports = (Reflect.getMetadata('imports', AccommodationsModule) as { name?: string }[]) ?? [];
|
|
expect(Array.isArray(imports)).toBe(true);
|
|
const names = imports.map((m) => m?.name);
|
|
expect(names).not.toContain('DaysModule');
|
|
expect(names).not.toContain('ReservationsModule');
|
|
});
|
|
});
|